删除的轮廓并没有消失

Removed contours aren't gone

我正在尝试删除任何不是正方形的轮廓。我检查之前和之后的图像,看看是否删除了任何轮廓。我使用圆度公式,0.7 到 0.8 之间的值是方形的。我希望看到一些等高线被删除,但 none 是

这是我到目前为止所做的。

public static void main(String[] args) {


        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        Mat capturedFrame = Imgcodecs.imread("first.png");

        //Gray
        Mat gray = new Mat();
        Imgproc.cvtColor(capturedFrame, gray, Imgproc.COLOR_BGR2GRAY);

        //Blur
        Mat blur = new Mat();
        Imgproc.blur(gray, blur, new Size(3,3));
        //Canny image
        Mat canny = new Mat();
        Imgproc.Canny(blur, canny, 20, 40, 3, true);


        Imgcodecs.imwrite("test.png", canny);

        //Dilate image to increase size of lines
        Mat kernel = Imgproc.getStructuringElement(1, new Size(3,3));
        Mat dilated = new Mat();
        Imgproc.dilate(canny,dilated, kernel);


        List<MatOfPoint> contours = new ArrayList<>();
        //find contours
        Imgproc.findContours(dilated, contours, new Mat(), Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_NONE);

        //convert image 
        Imgproc.cvtColor(capturedFrame, capturedFrame, Imgproc.COLOR_BGR2RGB);


        //Draw contours on original image
        for(int n = 0; n < contours.size(); n++){
            Imgproc.drawContours(capturedFrame, contours, n, new Scalar(255, 0 , 0), 1);
        }

        Imgcodecs.imwrite("before.png", capturedFrame);

        //display image with all contours
        Imshow showImg = new Imshow("displayImage");
        showImg.show(capturedFrame);


        //Remove contours that aren't close to a square shape.
        for(int i = 0; i < contours.size(); i++){

            double area = Imgproc.contourArea( contours.get(i)); 
            MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(i).toArray());
            double perimeter = Imgproc.arcLength(contour2f, true);

            //Found squareness equation on wiki... 
            // https://en.wikipedia.org/wiki/Shape_factor_(image_analysis_and_microscopy)
            double squareness = 4 * Math.PI * area / Math.pow(perimeter, 2);

            System.out.println("Squareness: " + squareness);


            if(squareness <= 0.7 && squareness >=  0.8){
                contours.remove(i);
            }
        }


        for(int i = 0; i < contours.size(); i++){
            Imgproc.drawContours(capturedFrame, contours, i, new Scalar(0, 255, 0), 1);
        }

        showImg.show(capturedFrame);
        Imgcodecs.imwrite("remove.png", capturedFrame);

    }

这是原图:

这是删除任何轮廓之前的图像:

这是图像的最终图像,其中一些轮廓应该被移除:

squareness <= 0.7 && squareness >= 0.8 看起来情况不太可能 mean squareness <= 0.7 || squareness >= 0.8 ?