Search code examples
javaopencvocrtesseract

How can i fix this error ? findcontours(OpenCV)


good night. I'm using this code to find and crop the letters on my image. However, i get this error;

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in cv::Mat::Mat

And i do not know how to fix that. I've already search something about this, but i'm not finding the solution. Can anyone help me ?

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

My programming program are pointing out in this line:

Mat result = original.submat(rect_min);

Solution

  • It is most likely that rect_min has dimensions that either negative, i.e. rect_min.x = rect_min.x - pad; or larger than that of original image, i.e. rect_min.width = rect_min.width + 2*pad; makes rect_min.width > original.width.

    A possible fix is to crop original image with the unmodified rect_min, then, if you want padding, use copyMakeBorder.