javaopencvroi

error occurred when binarization based ROI algorithm with OpenCV in JAVA


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?


Solution

  • The violated assertion is:

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

    Possibilities:

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