opencv java How to sort contours from left to right

asked 2020-08-18 13:18:52 -0500

Nagarjuna gravatar image

updated 2020-08-19 12:34:30 -0500

I want to sort contours from left to right.Please help me on this.

Code:

Mat image = Imgcodecs.imread("D:/OCR Images/letters/crop/PAN.png", Imgproc.COLOR_BGR2GRAY);
        image.size();
        Mat resizedImage = new Mat();

        Size size = new Size(1024,600);

        Imgproc.resize( image, resizedImage, size);
        Imgcodecs.imwrite("D:/OCR Images/letters/crop/PAN6_resize.jpg",resizedImage);

        Mat imageHSV = new Mat(resizedImage.size(), CvType.CV_8UC4);        
        Mat imageBlurr = new Mat(image.size(), CvType.CV_8UC4);
        Mat imageA = new Mat(image.size(), CvType.CV_32F);

        Imgproc.cvtColor(image, imageHSV, Imgproc.COLOR_BGR2GRAY);
        Imgproc.GaussianBlur(imageHSV, imageBlurr, new Size(5,5), 0);
        Imgproc.adaptiveThreshold(imageBlurr, imageA, 255,Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY,7, 5);

        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();    
        Imgproc.findContours(imageA, contours, new Mat(), Imgproc.RETR_LIST,Imgproc.CHAIN_APPROX_SIMPLE);
        Imgproc.drawContours(imageBlurr, contours, 5, new Scalar(0,0,255));
        for(int i=0; i< contours.size();i++){

            Rect rect = Imgproc.boundingRect(contours.get(i));

            if ((rect.width > 14 && rect.width < 31) && (rect.height > 27 && rect.height < 31)) {
                Imgcodecs.imwrite("D:/OCR Images/find/pan_" + i + ".jpg", new Mat(image, rect));

            }
             }
edit retag flag offensive close merge delete

Comments

see how to in C++ and try to convert it java ( java usage is similar)

sturkmen gravatar imagesturkmen ( 2020-08-19 10:35:10 -0500 )edit

it's probably slightly more complicated

(since it's a List of MatOfPoints, and you'd likely have to compare center or tl() point of the bounding boxes)

berak gravatar imageberak ( 2020-08-19 12:48:01 -0500 )edit