Can't find contours in image using OpenCV FindCountour function(in java)?

345 views Asked by At

Input Image Output Image

Here is my code for finding contours in Java using OpenCV. I first used the image to detect the edges in the image, then I passed that image's location to contour function, but it is not showing any contours. Please take look at it. I also attached the images of input and output to code.

 package test;
 import org.opencv.imgcodecs.Imgcodecs;

 import org.opencv.core.*;
 import org.opencv.imgproc.Imgproc;
 import org.opencv.highgui.Highgui;

 import java.util.*;

 import javax.swing.*;


 public class DMImageFactory {

   public void contours(String location) {

       System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        Mat image =Imgcodecs.imread(location);
        Mat dst=new Mat();

        Core.inRange(image, new Scalar(0,0,0), new Scalar(255,255,255),dst);

        if(dst.empty())
        System.out.print("empty matrix");

        Imshow im = new Imshow("Box1");
        im.showImage(image);

        List<MatOfPoint> contours = new ArrayList<>();
        Mat countour_result = Mat.zeros(image.size(), CvType.CV_8UC3);

       Imgproc.findContours(dst, contours, new Mat(),[enter image description here][1]Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);

       Imgproc.drawContours(countour_result, contours, -1,new 
       Scalar(255,255,255));

       Imgcodecs.imwrite("/Users/pranay/Desktop/test/counterdetection_intermidiate.png",countour_result);

        System.out.print(contours+" ");

         for (MatOfPoint contour: contours) 
        Imgproc.fillPoly(countour_result, Arrays.asList(contour), new Scalar(255,255,255));

       Scalar green = new Scalar(81, 190, 0);

       for (MatOfPoint contour: contours) {
        RotatedRect rotatedRect = Imgproc.minAreaRect(new 
        MatOfPoint2f(contour.toArray()));
      drawRotatedRect(countour_result, rotatedRect, green, 4);
    }


     Imgcodecs.imwrite("/Users/pranay/Desktop/test/counterdetection.png",countour_result);


 }

 public static void drawRotatedRect(Mat image, RotatedRect rotatedRect, 
 Scalar color, int thickness) {
      Point[] vertices = new Point[4];
      rotatedRect.points(vertices);
      MatOfPoint points = new MatOfPoint(vertices);
      Imgproc.drawContours(image, Arrays.asList(points), -1, color, 
      thickness);
    }


 }
1

There are 1 answers

0
user2518618 On

Probably you are drawing all contours on top of each other and the biggest one is drawn last and it covers all other contours.

Try to draw each contour in a new image.