0

when implementing ROI algorithm to binarize images in JAVA by using OpenCV,exception threw. can anybody help me figure out bugs among my code snippets?

System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
String filename = "path/to/image";
Mat image = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR);
int ch = 255, cw = 255; //---small block
int h = image.rows(), w = image.cols(); //---height vs width
Mat gray = new Mat();
Imgproc.cvtColor(image, gray, Imgproc.COLOR_BGR2GRAY); //--to gray

//-----handle every small block
for (int row = 0; row < h; row += ch) {
    for (int col = 0; col < w; col += cw) {
        Rect roi_rect = new Rect(col, row, cw, ch); //------small block:rectangle
        Mat roi = new Mat(gray, roi_rect);
        Imgproc.adaptiveThreshold(roi, roi, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 127, 10); //----binarization
        roi.copyTo(gray.submat(roi_rect));//----replace original block
    }
}

HighGui.imshow("binary", gray); 

exception messages as follows:

OpenCV(4.7.0-dev) Error: Assertion failed (0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols) in cv::Mat::Mat, file C:\GHA-OCV-2\_work\ci-gha-workflow\ci-gha-workflow\opencv\modules\core\src\matrix.cpp, line 776

Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: OpenCV(4.7.0-dev) C:\GHA-OCV-2\_work\ci-gha-workflow\ci-gha-workflow\opencv\modules\core\src\matrix.cpp:776: error: (-215:Assertion failed) 0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols in function 'cv::Mat::Mat']

It threw exception at Mat roi = new Mat(gray, roi_rect). What's wrong with this?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
biotech7
  • 25
  • 4

1 Answers1

0

The violated assertion is:

(
    0 <= _colRange.start &&
    _colRange.start <= _colRange.end &&
    _colRange.end <= m.cols
)

Possibilities:

  • Your ROI has negative size (start > end)
  • your ROI is out of bounds of the parent Mat
  • the parent Mat has zero size (and the ROI does not)

You fix that by figuring out which it is, and then figuring out why that is.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • by setting col < w-cw; row < h-ch respectively, the exception can be avoided , but resulting in few blocks of image intact. so how to shuffle all the image without out- of-range exception? It 's a bit tricky! – biotech7 Jun 08 '23 at 13:25
  • calculate ROI size in each iteration, to be within bounds. will require use of `min()` function and probably subtraction/difference – Christoph Rackwitz Jun 08 '23 at 13:48
  • Christoph Rackwitz, thanks again.I need to give it more thought. – biotech7 Jun 08 '23 at 14:13