2017-08-11 105 views
1

我正在嘗試刪除不像正方形的任何輪廓。我檢查前後的圖像,看看是否有任何輪廓已被刪除。我使用圓形公式,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

+0

我在看到輪廓時首先看到它,你需要減少計數器i。 –

+0

我還有什麼要做的嗎? @AndreySmorodov – ProgrammingCuber

回答

1

squareness <= 0.7 && squareness >= 0.8看起來像impossibe條件你是mean squareness <= 0.7 || squareness >= 0.8

+0

我的意思是方塊度大於0.7且小於0.8 – ProgrammingCuber

+0

它如何可能同時小於約束且大於上限?嘗試在紙上繪製間隔並在那裏放點。可能是正方形> = 0.7 &&正方形<= 0.8? –

+0

我只是想刪除不在0.7和0.8之間的值。 – ProgrammingCuber