移除的轮廓没有消失

时间:2017-08-11 00:09:26

标签: opencv contour

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

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

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);

    }

这是原始图片:

enter image description here

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

enter image description here

这是图像最终图像,其中应删除轮廓的某些轮廓:

enter image description here

1 个答案:

答案 0 :(得分:1)

squareness <= 0.7 && squareness >= 0.8您看起来像mean squareness <= 0.7 || squareness >= 0.8

相关问题