Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

                }
            }
        }
like image 795
kosbou Avatar asked Jan 11 '23 21:01

kosbou


1 Answers

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)

like image 57
berak Avatar answered Jan 17 '23 15:01

berak