OpenCV错误:断言失败(0< = roi.x&& 0< = roi.width&& roi.x + roi.width< = m.cols&& 0< cv :: Mat :: Mat
中的; = roi.y&& 0< = roi.height&& roi.y + roi.height< = m.rows)我不知道如何解决这个问题。我已经搜索过这个,但我找不到解决方案。任何人都可以帮助我吗?
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);
答案 0 :(得分:1)
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
裁剪原始图像,然后,如果要填充,请使用iterateThroughElements
。
答案 1 :(得分:0)
这意味着rect_min的边界超出了原始图像的边界。
也许衬垫是这样的? 您应该打印出原始图像的大小,以及rect_min的大小来查找。