I am trying to remove any contours that aren't in a square like shape. I check the image before and after to see if any contours have been removed. I use the circularity formula and values between 0.7 and 0.8 are square shaped. I expect to see that some contour lines are removed but none are
Here is what I have done so far.
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);
}
Here is the original image:
Here is the image before any contours are removed:
Here is the image final image where contours some contours should be removed: