Java Code Examples for org.opencv.android.Utils#bitmapToMat()

The following examples show how to use org.opencv.android.Utils#bitmapToMat() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DocumentDetector.java    From CVScanner with GNU General Public License v3.0 6 votes vote down vote up
Document detectDocument(Frame frame){
    Size imageSize = new Size(frame.getMetadata().getWidth(), frame.getMetadata().getHeight());
    Mat src = new Mat();
    Utils.bitmapToMat(frame.getBitmap(), src);
    List<MatOfPoint> contours = CVProcessor.findContours(src);
    src.release();

    if(!contours.isEmpty()){
        CVProcessor.Quadrilateral quad = CVProcessor.getQuadrilateral(contours, imageSize);

        if(quad != null){
            quad.points = CVProcessor.getUpscaledPoints(quad.points, CVProcessor.getScaleRatio(imageSize));
            return new Document(frame, quad);
        }
    }

    return null;
}
 
Example 2
Source File: MainActivity.java    From OCR-Test with Apache License 2.0 6 votes vote down vote up
public Bitmap convertToBlackWhite(Bitmap compressImage)
{
    Log.d("CV", "Before converting to black");
    Mat imageMat = new Mat();
    Utils.bitmapToMat(compressImage, imageMat);
    Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_BGR2GRAY);
    Imgproc.GaussianBlur(imageMat, imageMat, new Size(3, 3), 0);
    //Imgproc.adaptiveThreshold(imageMat, imageMat, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 5, 4);
    //Imgproc.medianBlur(imageMat, imageMat, 3);
    Imgproc.threshold(imageMat, imageMat, 0, 255, Imgproc.THRESH_OTSU);

    Bitmap newBitmap = compressImage;
    Utils.matToBitmap(imageMat, newBitmap);
    imageView.setImageBitmap(newBitmap);
    Log.d("CV", "After converting to black");


    return newBitmap;

}
 
Example 3
Source File: ProcessHelper.java    From OpenCV-android with Apache License 2.0 6 votes vote down vote up
/**
 * 角点检测
 *
 * @param origin   原始bitmap
 * @param callback 回调
 */
public void harris(Bitmap origin, ProcessCallback callback) {
    if (origin == null) {
        return;
    }
    try {
        Bitmap bitmap = Bitmap.createBitmap(origin.getWidth(), origin.getHeight(), Bitmap.Config.RGB_565);
        Utils.bitmapToMat(origin, rgbMat);
        Imgproc.cvtColor(rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);
        Mat corners = new Mat();
        Mat tempDst = new Mat();
        Mat tempDstNorm = new Mat();
        // 找出角点
        Imgproc.cornerHarris(grayMat, tempDst, 2, 3, 0.04);
        // 归一化Harris角点的输出
        Core.normalize(tempDst, tempDstNorm, 0, 255, Core.NORM_MINMAX);
        Core.convertScaleAbs(tempDstNorm, corners);
        // 绘制角点
        Random random = new Random();
        for (int i = 0; i < tempDstNorm.cols(); i++) {
            for (int j = 0; j < tempDstNorm.rows(); j++) {
                double[] value = tempDstNorm.get(j, i);
                if (value[0] > 250) {
                    // 决定了画出哪些角点,值越大选择画出的点就越少
                    Imgproc.circle(corners, new Point(i, j), 5, new Scalar(random.nextInt(255)), 2);
                }
            }
        }
        Utils.matToBitmap(corners, bitmap);
        callback.onSuccess(bitmap);
    } catch (Exception e) {
        callback.onFailed(e.getMessage());
    }
}
 
Example 4
Source File: MainActivity.java    From OpenCV-Android-Object-Detection with MIT License 6 votes vote down vote up
private void initializeOpenCVDependencies() throws IOException {
    mOpenCvCameraView.enableView();
    detector = FeatureDetector.create(FeatureDetector.ORB);
    descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);
    matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
    img1 = new Mat();
    AssetManager assetManager = getAssets();
    InputStream istr = assetManager.open("a.jpeg");
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    Utils.bitmapToMat(bitmap, img1);
    Imgproc.cvtColor(img1, img1, Imgproc.COLOR_RGB2GRAY);
    img1.convertTo(img1, 0); //converting the image to match with the type of the cameras image
    descriptors1 = new Mat();
    keypoints1 = new MatOfKeyPoint();
    detector.detect(img1, keypoints1);
    descriptor.compute(img1, keypoints1, descriptors1);

}
 
Example 5
Source File: PyramidActivity.java    From MOAAP with MIT License 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch(requestCode) {
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK){
                try {
                    final Uri imageUri = imageReturnedIntent.getData();
                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                    src = new Mat(selectedImage.getHeight(), selectedImage.getWidth(), CvType.CV_8UC4);
                    Utils.bitmapToMat(selectedImage, src);
                    srcSelected = true;
                    bGaussianPyrUp.setEnabled(true);
                    bGaussianPyrDown.setEnabled(true);
                    bLaplacianPyr.setEnabled(true);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            break;
    }
}
 
Example 6
Source File: MainActivity.java    From MOAAP with MIT License 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    //Put it there, just in case:)
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch(requestCode) {
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK && read_external_storage_granted){
                try {
                    final Uri imageUri = imageReturnedIntent.getData();
                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                    src = new Mat(selectedImage.getHeight(), selectedImage.getWidth(), CvType.CV_8UC4);
                    Utils.bitmapToMat(selectedImage, src);
                    src_gray = new Mat(selectedImage.getHeight(), selectedImage.getWidth(), CvType.CV_8UC1);
                    switch (ACTION_MODE) {
                        case HomeActivity.GAUSSIAN_BLUR:
                            Imgproc.GaussianBlur(src, src, new Size(9, 9), 0);
                            break;
                        case HomeActivity.MEAN_BLUR:
                            Imgproc.blur(src, src, new Size(9, 9));
                            break;
                        case HomeActivity.MEDIAN_BLUR:
                            Imgproc.medianBlur(src, src, 9);
                            break;
                        case HomeActivity.SHARPEN:
                            Mat kernel = new Mat(3, 3, CvType.CV_16SC1);
                            //int[] values = {0, -1, 0, -1, 5, -1, 0, -1, 0};
                            Log.d("imageType", CvType.typeToString(src.type()) + "");
                            kernel.put(0, 0, 0, -1, 0, -1, 5, -1, 0, -1, 0);
                            Imgproc.filter2D(src, src, src_gray.depth(), kernel);
                            break;
                        case HomeActivity.DILATE:
                            Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY);
                            Imgproc.threshold(src_gray, src_gray, 100, 255, Imgproc.THRESH_BINARY);
                            Mat kernelDilate = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3, 3));
                            Imgproc.dilate(src_gray, src_gray, kernelDilate);
                            Imgproc.cvtColor(src_gray, src, Imgproc.COLOR_GRAY2RGBA, 4);
                            break;
                        case HomeActivity.ERODE:
                            Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY);
                            Imgproc.threshold(src_gray, src_gray, 100, 255, Imgproc.THRESH_BINARY);
                            Mat kernelErode = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
                            Imgproc.erode(src_gray, src_gray, kernelErode);
                            Imgproc.cvtColor(src_gray, src, Imgproc.COLOR_GRAY2RGBA, 4);
                            break;
                        case HomeActivity.THRESHOLD:
                            Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY);
                            Imgproc.threshold(src_gray, src_gray, 100, 255, Imgproc.THRESH_BINARY);
                            Imgproc.cvtColor(src_gray, src, Imgproc.COLOR_GRAY2RGBA, 4);
                            break;
                        case HomeActivity.ADAPTIVE_THRESHOLD:
                            Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY);
                            Imgproc.adaptiveThreshold(src_gray, src_gray, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 3, 0);
                            Imgproc.cvtColor(src_gray, src, Imgproc.COLOR_GRAY2RGBA, 4);
                            break;
                    }
                    Bitmap processedImage = Bitmap.createBitmap(src.cols(), src.rows(), Bitmap.Config.ARGB_8888);
                    Log.i("imageType", CvType.typeToString(src.type()) + "");
                    Utils.matToBitmap(src, processedImage);
                    ivImage.setImageBitmap(selectedImage);
                    ivImageProcessed.setImageBitmap(processedImage);
                    Log.i("process", "process done");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            break;
    }
}
 
Example 7
Source File: FtcTestOpenCv.java    From FtcSamples with MIT License 6 votes vote down vote up
/**
 * This method is called when the camera view is started. It will allocate and initialize
 * some global resources.
 *
 * @param width specifies the width of the camera view.
 * @param height specifies the height of the camera view.
 */
@Override
public void onCameraViewStarted(int width, int height)
{
    faceRects = new MatOfRect();
    totalProcessingTime = 0;
    framesProcessed = 0;

    overlayImage = new Mat();
    Bitmap overlayBitmap =
            BitmapFactory.decodeResource(activity.getResources(), R.drawable.mustache);
    Utils.bitmapToMat(overlayBitmap, overlayImage);
    //
    // Don't allow overlay unless overlay image has the rgba channels.
    //
    if (overlayImage.channels() < 4) doOverlayImage = false;
}
 
Example 8
Source File: ImageProcessor.java    From pasm-yolov3-Android with GNU General Public License v3.0 5 votes vote down vote up
public void loadImage(Bitmap loadedImage, int yoloWidth, int yoloHeight) {
    this.widthRatio = (float)loadedImage.getWidth() / yoloWidth;
    this.heightRatio = (float)loadedImage.getHeight() / yoloHeight;

    Bitmap bmp32 = loadedImage.copy(Bitmap.Config.ARGB_8888, true);
    Utils.bitmapToMat(bmp32, rgbImage);

}
 
Example 9
Source File: Image.java    From RobotHelper with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 模板匹配
 *
 * @param srcImg      //源图像
 * @param templateImg //模板图像
 * @param threshold   //相识度阈值,阈值调小可以一定程度解决不同手机分辨率的问题
 * @return //如果没有找到则返回(-1,-1)点
 */
public static Point matchTemplate(Bitmap srcImg, Bitmap templateImg, double threshold) {

    if (threshold <= 0) {
        threshold = 0.5;
    }


    Mat tpl = new Mat();
    Mat src = new Mat();
    Utils.bitmapToMat(srcImg, src);
    Utils.bitmapToMat(templateImg, tpl);


    int height = src.rows() - tpl.rows() + 1;
    int width = src.cols() - tpl.cols() + 1;
    Mat result = new Mat(height, width, CvType.CV_32FC1);
    int method = Imgproc.TM_CCOEFF_NORMED;
    Imgproc.matchTemplate(src, tpl, result, method);
    Core.MinMaxLocResult minMaxResult = Core.minMaxLoc(result);
    org.opencv.core.Point maxloc = minMaxResult.maxLoc;
    if (minMaxResult.maxVal < threshold) {
        return new Point(-1, -1);
    }
    org.opencv.core.Point minloc = minMaxResult.minLoc;
    org.opencv.core.Point matchloc = null;
    matchloc = maxloc;
    return new Point((int) matchloc.x, (int) matchloc.y);

}
 
Example 10
Source File: ProcessHelper.java    From OpenCV-android with Apache License 2.0 5 votes vote down vote up
/**
 * 灰度处理
 *
 * @param origin   原始bitmap
 * @param callback 回调
 */
public void gray(Bitmap origin, ProcessCallback callback) {
    if (origin == null) {
        return;
    }
    try {
        Bitmap bitmap = Bitmap.createBitmap(origin.getWidth(), origin.getHeight(), Bitmap.Config.RGB_565);
        Utils.bitmapToMat(origin, rgbMat);
        Imgproc.cvtColor(rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);
        Utils.matToBitmap(grayMat, bitmap);
        callback.onSuccess(bitmap);
    } catch (Exception e) {
        callback.onFailed(e.getMessage());
    }
}
 
Example 11
Source File: OpenCVTestCase.java    From OpenTLDAndroid with Apache License 2.0 5 votes vote down vote up
protected static Mat readMatFromFile(final String name){
	// BitmapFactory.decodeResource scales the image which is not great... Geting the image from resources is a BIG PAIN !
	//final Bitmap image = new BitmapDrawable(getContext().getResources(), getContext().getResources().openRawResource(R.drawable.test_grid_frame)).getBitmap();
	final Bitmap image = BitmapFactory.decodeFile("/mnt/sdcard/TLDtest/" + name + ".png");
	final Mat img = new Mat();
	Utils.bitmapToMat(image, img);
	
	return img;		
}
 
Example 12
Source File: CameraActivity.java    From Chinese-number-gestures-recognition with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Bitmap scaleImage(Bitmap bitmap, int width, int height)
{

    Mat src = new Mat();
    Mat dst = new Mat();
    Utils.bitmapToMat(bitmap, src);
    //new Size(width, height)
    Imgproc.resize(src, dst, new Size(width,height),0,0,Imgproc.INTER_AREA);
    Bitmap bitmap1 = Bitmap.createBitmap(dst.cols(),dst.rows(),Bitmap.Config.RGB_565);
    Utils.matToBitmap(dst, bitmap1);
    return bitmap1;
}
 
Example 13
Source File: ImageSaveTask.java    From CVScanner with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Override this method to perform a computation on a background thread. The
 * specified parameters are the parameters passed to {@link #execute}
 * by the caller of this task.
 * <p/>
 * This method can call {@link #publishProgress} to publish updates
 * on the UI thread.
 *
 * @param params The parameters of the task.
 * @return A result, defined by the subclass of this task.
 * @see #onPreExecute()
 * @see #onPostExecute
 * @see #publishProgress
 */
@Override
protected String doInBackground(Void... params) {
    Size imageSize = new Size(image.getWidth(), image.getHeight());
    Mat imageMat = new Mat(imageSize, CvType.CV_8UC4);
    Utils.bitmapToMat(image, imageMat);

    image.recycle();

    Mat croppedImage = CVProcessor.fourPointTransform(imageMat, points);
    imageMat.release();

    Mat enhancedImage = CVProcessor.adjustBirghtnessAndContrast(croppedImage, 1);
    croppedImage.release();

    enhancedImage = CVProcessor.sharpenImage(enhancedImage);

    String imagePath = null;
    try {
        imagePath = Util.saveImage(mContext,
                "IMG_CVScanner_" + System.currentTimeMillis(), enhancedImage, false);
        enhancedImage.release();
        Util.setExifRotation(mContext, Util.getUriFromPath(imagePath), rotation);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return imagePath;
}
 
Example 14
Source File: FtcVuforia.java    From FtcSamples with MIT License 5 votes vote down vote up
/**
 * This method gets a frame from the frame queue and returns the image that matches the format specified by the
 * configVideoSource method.
 *
 * @param frame specifies the frame object to hold image.
 * @return true if success, false otherwise.
 */
@Override
public boolean getFrame(Mat frame)
{
    boolean success = false;

    try
    {
        VuforiaLocalizer.CloseableFrame closeableFrame = localizer.getFrameQueue().take();

        for (int i = 0; i < closeableFrame.getNumImages(); i++)
        {
            Image image = closeableFrame.getImage(i);
            if (image.getWidth() == imageWidth && image.getHeight() == imageHeight &&
                    image.getFormat() == PIXEL_FORMAT.RGB565)
            {
                Bitmap bm = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.RGB_565);
                bm.copyPixelsFromBuffer(image.getPixels());
                Utils.bitmapToMat(bm, frame);
                break;
            }
        }

        closeableFrame.close();
        success = true;
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }

    return success;
}
 
Example 15
Source File: PassportDetector.java    From CVScanner with GNU General Public License v3.0 4 votes vote down vote up
Document detectDocument(Frame frame){
    Size imageSize = new Size(frame.getMetadata().getWidth(), frame.getMetadata().getHeight());
    Mat src = new Mat();
    Utils.bitmapToMat(frame.getBitmap(), src);

    int shiftX = 0, shiftY = 0;

    if(frameSizeProvider != null){
        int frameWidth = frameSizeProvider.frameWidth();
        int frameHeight = frameSizeProvider.frameHeight();

        shiftX = Double.valueOf((imageSize.width - frameHeight)/2.0).intValue();
        shiftY = Double.valueOf((imageSize.height - frameWidth)/2.0).intValue();
        Rect rect = new Rect(shiftX, shiftY,
                frameHeight, frameWidth);
        Mat cropped = new Mat(src, rect).clone();
        src.release();
        src = cropped;

        imageSize = new Size(src.cols(), src.rows());
    }

    CVProcessor.Quadrilateral quad = null;

    if(isMRZBasedDetection){
        List<MatOfPoint> contours = CVProcessor.findContoursForMRZ(src);

        if(!contours.isEmpty()){
            quad = CVProcessor.getQuadForPassport(contours, imageSize, frameSizeProvider != null? frameSizeProvider.frameWidth():0);
        }
    }
    else{
        quad = CVProcessor.getQuadForPassport(src, frameSizeProvider != null? frameSizeProvider.frameWidth():0,
                frameSizeProvider != null? frameSizeProvider.frameHeight():0);
    }

    src.release();

    if(quad != null && quad.points != null){
        quad.points = CVProcessor.getUpscaledPoints(quad.points, CVProcessor.getScaleRatio(imageSize));

        //shift back to old coordinates
        for(int i = 0; i < quad.points.length; i++){
            quad.points[i] = shiftPointToOld(quad.points[i], shiftX, shiftY);
        }

        return new Document(frame, quad);
    }

    return null;
}
 
Example 16
Source File: CropImage.java    From reader with MIT License 4 votes vote down vote up
private void makeDefault() {
            HighlightView hv = new HighlightView(mImageView);

            int width = mBitmap.getWidth();
            int height = mBitmap.getHeight();

            Rect imageRect = new Rect(0, 0, width, height);

            // make the default size about 4/5 of the width or height
//            int cropWidth = Math.min(width, height) * 4 / 5;
//            int cropHeight = cropWidth;
            int cropWidth = width;
            int cropHeight = height;

            if (mAspectX != 0 && mAspectY != 0) {
                if (mAspectX > mAspectY) {
                	// �����辩缉���
                    cropHeight = cropWidth * mAspectY ;// mAspectX;
                } else {
                    cropWidth = cropHeight * mAspectX ;// mAspectY;
                }
            }

            int x = (width - cropWidth) / 2;
            int y = (height - cropHeight) / 2;
            
            Mat imgSource = new Mat();
            Utils.bitmapToMat(mBitmap, imgSource);
            //convert the image to black and white 
            Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BGR2GRAY);
            //convert the image to black and white does (8 bit)
            Imgproc.Canny(imgSource, imgSource, 50, 50);

            //apply gaussian blur to smoothen lines of dots
            Imgproc.GaussianBlur(imgSource, imgSource, new  org.opencv.core.Size(5, 5), 5);

            //find the contours
            List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
            Imgproc.findContours(imgSource, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

            double maxArea = -1;
            int maxAreaIdx = -1;
            Log.d("size",Integer.toString(contours.size()));
            MatOfPoint temp_contour = contours.get(0); //the largest is at the index 0 for starting point
            MatOfPoint2f approxCurve = new MatOfPoint2f();
            MatOfPoint largest_contour = contours.get(0);
            //largest_contour.ge
            List<MatOfPoint> largest_contours = new ArrayList<MatOfPoint>();
            //Imgproc.drawContours(imgSource,contours, -1, new Scalar(0, 255, 0), 1);

            for (int idx = 0; idx < contours.size(); idx++) {
                temp_contour = contours.get(idx);
                double contourarea = Imgproc.contourArea(temp_contour);
                //compare this contour to the previous largest contour found
                if (contourarea > maxArea) {
                    //check if this contour is a square
                    MatOfPoint2f new_mat = new MatOfPoint2f( temp_contour.toArray() );
                    int contourSize = (int)temp_contour.total();
                    MatOfPoint2f approxCurve_temp = new MatOfPoint2f();
                    Imgproc.approxPolyDP(new_mat, approxCurve_temp, contourSize*0.05, true);
                    if (approxCurve_temp.total() == 4) {
                        maxArea = contourarea;
                        maxAreaIdx = idx;
                        approxCurve=approxCurve_temp;
                        largest_contour = temp_contour;
                    }
                }
            }

           Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BayerBG2RGB);
           double[] temp_double;
           float x1, y1, x2, y2;
           temp_double = approxCurve.get(0,0);       
           Point p1 = new Point(temp_double[0], temp_double[1]);
           x1 = (float)temp_double[0];
           y1 = (float)temp_double[1];
           //Core.circle(imgSource,p1,55,new Scalar(0,0,255));
           //Imgproc.warpAffine(sourceImage, dummy, rotImage,sourceImage.size());
           temp_double = approxCurve.get(1,0);       
           Point p2 = new Point(temp_double[0], temp_double[1]);
          // Core.circle(imgSource,p2,150,new Scalar(255,255,255));
           temp_double = approxCurve.get(2,0);       
           Point p3 = new Point(temp_double[0], temp_double[1]);
           x2 = (float)temp_double[0];
           y2 = (float)temp_double[1];
           //Core.circle(imgSource,p3,200,new Scalar(255,0,0));
           temp_double = approxCurve.get(3,0);       
           Point p4 = new Point(temp_double[0], temp_double[1]);

            RectF cropRect = new RectF(x, y, x + cropWidth, y + cropHeight);
            //RectF cropRect = new RectF(x1, y1, x2, y2);
         // �����辩缉���
            
            hv.setup(mImageMatrix, imageRect, cropRect, mCircleCrop,false
                     /*mAspectX != 0 && mAspectY != 0*/);
            mImageView.add(hv);
        }
 
Example 17
Source File: MainActivity.java    From effective_android_sample with Apache License 2.0 4 votes vote down vote up
/**
 * OpenCVで
 * @param bmpOrig
 */
private void extractObject(Bitmap bmpOrig) {

    // まずオリジナルのビットマップを表示
    mImageView1.setImageBitmap(bmpOrig);
    // 高さと幅を取得
    int height = bmpOrig.getHeight();
    int width = bmpOrig.getWidth();
    
    // OpenCVオブジェクトの用意
    Mat matOrig = new Mat(height,width,CvType.CV_8UC4); 
    // ビットマップをOpenCVオブジェクトに変換
    Utils.bitmapToMat(bmpOrig, matOrig);
    
    /**
     * グレースケールに変換
     */
    Mat matGray = new Mat(height,width,CvType.CV_8UC1);
    Imgproc.cvtColor(matOrig, matGray, Imgproc.COLOR_RGB2GRAY);
    // 表示
    Bitmap bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(matGray, bmpGray);
    mImageView2.setImageBitmap(bmpGray);

    /**
     * グレースケール→二値化    
     */
    Mat matBlack = new Mat(height,width,CvType.CV_8UC1);
    // 二値化
    Imgproc.threshold(matGray, matBlack, sTH, 255, Imgproc.THRESH_BINARY);
    // 表示
    Bitmap bmpBlack = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(matBlack, bmpBlack);
    mImageView3.setImageBitmap(bmpBlack);

    /**
     * グレースケール→二値化→輪郭塗りつぶし
     */
    // 輪郭を抽出する
    ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat hierarchy = new Mat(matBlack.height(),matBlack.width(),CvType.CV_8UC1);
    int mode = Imgproc.RETR_EXTERNAL;
    int method = Imgproc.CHAIN_APPROX_SIMPLE;

    // 輪郭を抽出する
    Imgproc.findContours(matBlack, contours, hierarchy, mode, method);
    // 輪郭を描く
    Scalar color = new Scalar(255.f, 0.f, 0.f, 0.f);
    Imgproc.drawContours(matBlack, contours, -1, color, 2);
    // 表示
    Bitmap bmpContour = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matBlack, bmpContour);
    mImageView4.setImageBitmap(bmpContour);

    // 抽出した輪郭の内部を塗りつぶす
    Imgproc.drawContours(matBlack, contours, -1, color, -1);
    // 表示
    Bitmap bmpContour2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matBlack, bmpContour2);
    mImageView5.setImageBitmap(bmpContour2);

    
    /**
     * 二値化したマスクを使ってオブジェクトだけをとりだす
     */
    Mat matObject = new Mat(height,width,CvType.CV_8UC4); 
    Core.add(matObject, matOrig, matObject, matBlack);  
    // 表示
    Bitmap bmpObject = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matObject, bmpObject);
    mImageView6.setImageBitmap(bmpObject);

    /**
     * とりだしたオブジェクトに外接する矩形のみをBMPとして抜き出す
     */
    Rect rect = Imgproc.boundingRect(contours.get(0));
    Mat matCut = new Mat(matObject, rect);
    // 表示
    Bitmap bmpCut = Bitmap.createBitmap(matCut.cols(), matCut.rows(), Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matCut, bmpCut);
    mImageView7.setImageBitmap(bmpCut);
}
 
Example 18
Source File: MainActivity.java    From MOAAP with MIT License 4 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == ACTION_PICK_PHOTO && resultCode == RESULT_OK && null != data && read_external_storage_granted) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        String picturePath;
        if(cursor == null) {
            Log.i("data", "cannot load any image");
            return;
        }else {
            try {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
            }finally {
                cursor.close();
            }
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        Bitmap temp = BitmapFactory.decodeFile(picturePath, options);

        int orientation = 0;
        try {
            ExifInterface imgParams = new ExifInterface(picturePath);
            orientation = imgParams.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Matrix rotate90 = new Matrix();
        rotate90.postRotate(orientation);
        Bitmap originalBitmap = rotateBitmap(temp,orientation);

        if(originalBitmap != null) {
            Bitmap tempBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
            originalMat = new Mat(tempBitmap.getHeight(),
                    tempBitmap.getWidth(), CvType.CV_8U);
            Utils.bitmapToMat(tempBitmap, originalMat);
            currentBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, false);
            imageView.setImageBitmap(currentBitmap);
        }else {
            Log.i("data", "originalBitmap is empty");
        }
    }
}
 
Example 19
Source File: ProcessHelper.java    From OpenCV-android with Apache License 2.0 4 votes vote down vote up
/**
 * 直线检测
 *
 * @param origin   原始bitmap
 * @param callback 回调
 */
public void hough(Bitmap origin, ProcessCallback callback) {
    if (origin == null) {
        return;
    }
    try {
        Bitmap bitmap = Bitmap.createBitmap(origin.getWidth(), origin.getHeight(), Bitmap.Config.RGB_565);
        Utils.bitmapToMat(origin, rgbMat);
        Imgproc.cvtColor(rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);
        Mat edges = new Mat();
        Mat src = new Mat(origin.getHeight(), origin.getWidth(), CvType.CV_8UC4);
        Mat lines = new Mat();
        // 拷贝
        Mat origination = new Mat(src.size(), CvType.CV_8UC1);
        src.copyTo(origination);
        // 通过Canny得到边缘图
        Imgproc.cvtColor(origination, grayMat, Imgproc.COLOR_BGR2GRAY);
        Imgproc.Canny(grayMat, edges, 50, 200);
        // 获取直线图
        Imgproc.HoughLinesP(edges, lines, 1, Math.PI / 180, 10, 0, 10);
        Mat houghLines = new Mat();
        houghLines.create(edges.rows(), edges.cols(), CvType.CV_8UC1);
        // 绘制直线
        for (int i = 0; i < lines.rows(); i++) {
            double[] points = lines.get(i, 0);
            if (null != points) {
                double x1, y1, x2, y2;
                x1 = points[0];
                y1 = points[1];
                x2 = points[2];
                y2 = points[3];
                Point pt1 = new Point(x1, y1);
                Point pt2 = new Point(x2, y2);
                Imgproc.line(houghLines, pt1, pt2, new Scalar(55, 100, 195), 3);
            }
        }
        Utils.matToBitmap(houghLines, bitmap);
        callback.onSuccess(bitmap);
    } catch (Exception e) {
        callback.onFailed(e.getMessage());
    }
}
 
Example 20
Source File: ImageUtils.java    From AndroidDocumentScanner with MIT License 4 votes vote down vote up
public static Mat bitmapToMat(Bitmap bitmap) {
    Mat mat = new Mat(bitmap.getHeight(), bitmap.getWidth(), CvType.CV_8U, new Scalar(4));
    Bitmap bitmap32 = bitmap.copy(Bitmap.Config.ARGB_8888, true);
    Utils.bitmapToMat(bitmap32, mat);
    return mat;
}