findContours in opencv Java

asked 2017-11-13 00:37:38 -0600

ChukZ gravatar image

updated 2017-11-13 01:37:48 -0600

if (DETECT_RED_OBJECTS_ONLY) { Imgproc.cvtColor(inputFrame, gray, Imgproc.COLOR_BGR2RGB); } else {

        Imgproc.cvtColor(inputFrame, gray, Imgproc.COLOR_BGR2GRAY);
    }
    Imgproc.cvtColor(inputFrame, dst, Imgproc.COLOR_BGR2RGB);


    // down-scale and upscale the image to filter out the noise
    Imgproc.pyrDown(gray, downscaled, new Size(gray.cols() / 2, gray.rows() / 2));
    Imgproc.pyrUp(downscaled, upscaled, gray.size());

    if (DETECT_RED_OBJECTS_ONLY) {
        // convert the image from RGBA to HSV
        Imgproc.cvtColor(upscaled, hsv, Imgproc.COLOR_RGB2HSV);
        // threshold the image for the lower and upper HSV red range
        Core.inRange(hsv, HSV_LOW_RED1, HSV_LOW_RED2, lowerRedRange);
        Core.inRange(hsv, HSV_HIGH_RED1, HSV_HIGH_RED2, upperRedRange);
        // put the two thresholded images together


        Core.addWeighted(lowerRedRange, 1.0, upperRedRange, 1.0, 0.0, bw);
        // apply canny to get edges only
        System.out.println(bw);
        Imgproc.Canny(bw, bw, 0, 255);
    } else {
        // Use Canny instead of threshold to catch squares with gradient shading
        Imgproc.Canny(upscaled, bw, 0, 255);
    }


    // dilate canny output to remove potential
    // holes between edge segments
    Imgproc.dilate(bw, bw, new Mat(), new Point(-1, 1), 1);

    // find contours and store them all as a list
    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    contourImage = bw.clone();
    Imgproc.findContours(
            contourImage,
            contours,
            hierarchyOutputVector,
            Imgproc.RETR_EXTERNAL,
            Imgproc.CHAIN_APPROX_SIMPLE
    );

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

    // loop over all found contours
    for (MatOfPoint cnt : contours) {
        MatOfPoint2f curve = new MatOfPoint2f(cnt.toArray());

        // approximates a polygonal curve with the specified precision
        Imgproc.approxPolyDP(
                curve,
                approxCurve,
                0.02 * Imgproc.arcLength(curve, true),
                true
        );

        int numberVertices = (int) approxCurve.total();

When I use triangle as an input image , this one works and detect triangle[counters become 1 and numberVertices becomes 3]. But when i input a rectangle image , contours become 2 and numberVertices becomes 2. It must be 4 . Isn't it. Can anyone help me to find the bug.

edit retag flag offensive close merge delete