简体   繁体   中英

how to crop mat using contours in opencv for java

I'm using the below code in order to find mat contours of an Image. I found the contours correct. But when I try to crop the image at contours the app crashes. Where am I wrong?

        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();    

        Imgproc.findContours(imageA, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
        for(int i=0; i< contours.size();i++){
            if (Imgproc.contourArea(contours.get(i)) > 50 ){
                Rect rect = Imgproc.boundingRect(contours.get(i));
                if (rect.height > 28){
                    Core.rectangle(image, new Point(rect.x,rect.y), new Point(rect.x+rect.width,rect.y+rect.height),new Scalar(0,0,255));
                    Mat ROI = image.submat(rect.x, rect.x + rect.heigth, rect.x, rect.x + rect.width);

                    Highgui.imwrite("/mnt/sdcard/images/test4.png",ROI);

                }
            }
        }

your submat looks broken:

Mat ROI = image.submat(rect.x, rect.x + rect.heigth, rect.x, rect.x + rect.width);

it should like this (we're in row/col world here):

Mat ROI = image.submat(rect.y, rect.y + rect.heigth, rect.x, rect.x + rect.width);

http://docs.opencv.org/java/org/opencv/core/Mat.html#submat(int,%20int,%20int,%20int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM