从submat显示图像时出现MattoBitmap错误

时间:2014-05-09 10:54:29

标签: java opencv

我正在使用下面的代码来查找图像的垫轮廓。我发现轮廓正确。但是当我尝试在轮廓处裁剪图像时,应用程序崩溃了。

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);

这是错误日志:

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)

1 个答案:

答案 0 :(得分:1)

可能存在一个问题:

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

创建Mat时,参数为rowscols,因此您应该这样做:

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

但是,错误意味着源图像和目标图像的大小不同。因此,请注意roi.copyTo(image)调用将调整image的大小以匹配感兴趣区域的大小,它可能与原始位图不匹配。

因此,您必须创建与ROI大小相同的位图,然后复制到该位图,或者您必须调整ROI的大小以匹配您的接收位图。

您可以这样做以确保您知道要使用的位图大小:

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);