Question

I'm using the code below in order to find mat contours of an Image. I found the contours correct. But when I try to crop the image at contour the app crashes.

List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat contour_mat = new Mat();
Imgproc.findContours(image, contours, contour_mat, Imgproc.RETR_LIST,    Imgproc.CHAIN_APPROX_NONE);

Mat roi = null; 
for (int idx = 0; idx < contours.size(); idx++) {
    Mat contour = contours.get(idx);
    double contourarea = Imgproc.contourArea(contour);

if(contourarea>10000){
      Rect rect = Imgproc.boundingRect(contours.get(idx));
                        //to get my target contour
       if (rect.height< 55){

       Core.rectangle(hsv_image, new Point(rect.x,rect.y), new Point(rect.x+rect.width,rect.y+rect.height),new Scalar(0,0,255));
       roi = hsv_image.submat(rect.y, rect.y + rect.height, rect.x, rect.x + rect.width);

               }
            }
          }
Mat image = new Mat(roi.size(), CvType.CV_8UC1);
roi.copyTo(image);
Bitmap bm = Bitmap.createBitmap(image.rows(), image.cols(),  
                              Bitmap.Config.ARGB_8888); 

 Utils.matToBitmap(image, bm);

this is the error log:

05-08 20:07:56.851: E/AndroidRuntime(13331): CvException [org.opencv.core.CvException: /home/reports/ci/slave_desktop/50-SDK/opencv/modules/java/generator/src/cpp/utils.cpp:97: error: (-215) src.dims == 2 && info.height == (uint32_t)src.rows && info.width == (uint32_t)src.cols in function void Java_org_opencv_android_Utils_nMatToBitmap2(JNIEnv*, jclass, jlong, jobject, jboolean)
Was it helpful?

Solution

One problem is possibly here:

Mat image = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC1);

When you create a Mat, the arguments are rows, cols, so you should be doing this:

Mat image = new Mat(bitmap.getHeight(), bitmap.getWidth(), CvType.CV_8UC1);

However, the error implies that the source and destination images are different sizes. So, noting that the roi.copyTo(image) call will resize image to match the size of the region of interest, it may not match your original bitmap.

So, either you have to create a bitmap of the same size as the ROI, and then copy to that, or you have to resize the ROI to match your recieving bitmap.

You can do this to make sure that you know what size bitmap to use:

Mat image = new Mat(roi.size(), CvType.CV_8UC1);

// unsure of syntax for your platform here... but something like ...
Bitmap newBitmap = Bitmap.createBitmap(image.cols(), image.rows(), 
                                           Bitmap.Config.ARGB_8888);

// now copy the image
Utils.matToBitmap(image, newBitmap);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top