如何在opencv android中从选定的轮廓中裁剪图像

时间:2015-11-18 05:33:04

标签: android opencv

在我的项目中,我想从实时相机Feed中选择一个对象,然后仅创建所选区域的 JPEG 文件。因此,在 onCameraFrame 方法中,我在Imgproc.drawContours(mRgba, contours, 0, CONTOUR_COLOR);中设置了参数0,以选择第一个项目,即所选项目。然后我试图为该项目实现一个绑定矩形。

OnCameraFrame()

public Mat onCameraFrame(CvCameraViewFrame inputFrame){         mRgba = inputFrame.rgba();

    if (mIsColorSelected) {
        mDetector.process(mRgba);
        List<MatOfPoint> contours = mDetector.getContours();
        Log.e(TAG, "Contours count: " + contours.size());
        Imgproc.drawContours(mRgba, contours, 0, CONTOUR_COLOR);

        Mat colorLabel = mRgba.submat(4, 68, 4, 68);
        colorLabel.setTo(mBlobColorRgba);



        MatOfPoint2f contour2f = new MatOfPoint2f( contours.get(0).toArray());
        //Processing on mMOP2f1 which is in type MatOfPoint2f
        double approxDistance = Imgproc.arcLength(contour2f, true)*0.02;
        Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true);

        //Convert back to MatOfPoint
        MatOfPoint points = new MatOfPoint( approxCurve.toArray() );

        // Get bounding rect of contour
        Rect rect = Imgproc.boundingRect(points);
        Mat selectedRegion = mRgba.submat(rect);

        Bitmap bmp = null;
        try {

            bmp = Bitmap.createBitmap(selectedRegion.cols(), selectedRegion.rows(), Bitmap.Config.ARGB_8888);
            convertBitmapToImage(bmp);

        } catch (CvException e) {
            Log.d("Exception", e.getMessage());
        }


    }


    return mRgba;
}  

然后将mat对象转换为位图并将其保存为 JPEG 格式

convertBitmapToImage

private void convertBitmapToImage(Bitmap bmp) {

        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/Dummy");
        if (!root.exists()) {
            root.mkdirs();
        } else {
            System.out.print("Exists");
        }

        File f = new File(root, "filename.jpeg");
        //Convert bitmap to byte array
        Bitmap bitmap = bmp;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos);
        byte[] bitmapdata = bos.toByteArray();


        try {

            f.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }



        //write the bytes in file
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }


    } 

但是它会创建一个空白 JPEG 文件

enter image description here

我做错了什么或需要做什么

1 个答案:

答案 0 :(得分:0)

我不检查你的代码,但我认为这个问题与你的bmp有关。 你应该这样使用......

Bitmap bmp = Bitmap.createBitmap(src.cols(), src.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(src, bmp);

是你的convertBitmapToImage方法。 src是您要保存为图像文件的Mat对象。

相关问题