Imgproc.findContours not returning all contours [closed]

asked 2018-06-17 11:44:37 -0600

Jérémy K gravatar image

updated 2020-12-09 08:18:20 -0600

Small issue again. I'm using the imgproc.findContours in Java:

Imgproc.findContours(imgContours, points, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);

When I use the following canny'ed image: image description

I get following contours: image description

Can someone please explain why the findContours is behaving like this? There's almost no difference in the Canny image between the upper and lower row and the lower contours are fully enclosed, but still it's not returning the contours.. Thanks!

Full code:

private List<Rect> getBoundingBoxes(Mat image, Mat originalImage) {
        Mat imgContours = new Mat(image.rows(), image.cols(), image.type());
        image.copyTo(imgContours);
        Mat imgEdgesFound = originalImage.clone();

        List<MatOfPoint> points = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(imgContours, points, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
        List<Rect> boundingBoxes = new ArrayList<>();

        if (hierarchy.size().height > 0 && hierarchy.size().width > 0) {
            for (int idx = 0; idx >= 0; idx = (int) hierarchy.get(0, idx)[0]) {
                Rect bounds = Imgproc.boundingRect(points.get(idx));
                Imgproc.drawContours(imgEdgesFound, points, idx, new Scalar(250, 0, 0));
                if (bounds.height > Configuration.PictureProcessor.getDigitMinimumHeight() &&
                        bounds.height < Configuration.PictureProcessor.getDigitMaximumHeight() &&
                        bounds.width > Configuration.PictureProcessor.getDigitMinimumWidth() &&
                        bounds.width < bounds.height) {
                    boundingBoxes.add(bounds);
                }
            }
        }

        Collections.sort(boundingBoxes, new BoundingBoxesComparator());

        if (Configuration.PictureProcessor.isDebug()) {
            Imgcodecs.imwrite("output/debug/edgesfound.png", imgEdgesFound);
            logger.info("Number of boundingboxes found: " + boundingBoxes.size());
        }

        return boundingBoxes;
    }

Update: RETR_LIST seems to work, but now I get a lot of duplicates..

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by sturkmen
close date 2020-10-08 00:32:54.331933

Comments

it is not RETR_EXTERNAL but RETR_LIST read doc

LBerger gravatar imageLBerger ( 2018-06-17 12:08:37 -0600 )edit

Hi @LBerger , Thanks for your answer! It indeed helps with getting all the edges, but I get a lot of double points.. Any explanation/quick solution for this?

Jérémy K gravatar imageJérémy K ( 2018-06-17 12:26:40 -0600 )edit

Anyone? Really need help on this.

Jérémy K gravatar imageJérémy K ( 2018-06-19 03:24:17 -0600 )edit