我该如何解决这个错误?找到轮廓(OpenCV)

How can i fix this error ? findcontours(OpenCV)

晚安。我正在使用此代码查找和裁剪图像上的字母。但是,我收到此错误;

OpenCV 错误:断言失败(0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 < = roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) 在 cv::Mat::Mat

而且我不知道如何解决这个问题。我已经搜索了一些关于这个的东西,但我没有找到解决方案。谁能帮帮我?

Mat image = Imgcodecs.imread("C:\Users\Me\Desktop\Programs\Image2.png", Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);
// clone the image 
Mat original = image.clone();
// thresholding the image to make a binary image
Imgproc.threshold(image, image, 220, 60, Imgproc.THRESH_BINARY_INV);
// find the center of the image
double[] centers = {(double)image.width()/2, (double)image.height()/2};
Point image_center = new Point(centers);

// finding the contours
ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
Imgproc.findContours(image, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

// finding best bounding rectangle for a contour whose distance is closer to the image center that other ones
double d_min = Double.MAX_VALUE;
Rect rect_min = new Rect();
for (MatOfPoint contour : contours) {
    Rect rec = Imgproc.boundingRect(contour);
    // find the best candidates
    if (rec.height > image.height()/2 & rec.width > image.width()/2)            
        continue;
    Point pt1 = new Point((double)rec.x, (double)rec.y);
    Point center = new Point(rec.x+(double)(rec.width)/2, rec.y + (double)(rec.height)/2);
    double d = Math.sqrt(Math.pow((double)(pt1.x-image_center.x),2) + Math.pow((double)(pt1.y -image_center.y), 2));            
    if (d < d_min)
    {
        d_min = d;
        rect_min = rec;
    }                   
}
// slicing the image for result region
int pad = 5;        
rect_min.x = rect_min.x - pad;
rect_min.y = rect_min.y - pad;

rect_min.width = rect_min.width + 2*pad;
rect_min.height = rect_min.height + 2*pad;

Mat result = original.submat(rect_min);     
Imgcodecs.imwrite("C:\Users\Me\Desktop\Programs\result.png", result);

我的编程程序在这一行指出:

Mat result = original.submat(rect_min);

这意味着 rect_min 的边界超出了原始图像的边界。

也许填充使它如此? 你应该打印出原始图像的大小,然后rect_min的大小就可以查出来了。

很可能 rect_min 的尺寸为负,即 rect_min.x = rect_min.x - pad; 或大于原始图像的尺寸,即 rect_min.width = rect_min.width + 2*pad; 使 rect_min.width > original.width

一个可能的解决方法是使用未修改的 rect_min 裁剪原始图像,然后,如果您想要填充,请使用 copyMakeBorder