How to remove unclosed curves in a binary image?
opencv
Solution
As @John Zwinck mentions this can be done using `floodfill`, but I figure your problem is you want to return to the original black background, and retain the contours of the closed shapes. While you could use `contours` to figure this out, here is a fairly simple approach that will remove all non-closed and unenclosed line segments from an image, even if they are attached to a closed shape, But retain the edges of the closed curves.
- floodfill image with white - this removes your problem non-closed lines, but also the borders of your wanted objects.
- erode the image, then invert it
- AND the image with the original image - thus restoring the borders.
Output:
The code is in python, but should easily translate to the usual C++ cv2 usage.
import cv2
import numpy as np
im = cv2.imread('I7qZP.png',cv2.CV_LOAD_IMAGE_GRAYSCALE)
im2 = im.copy()
mask = np.zeros((np.array(im.shape)+2), np.uint8)
cv2.floodFill(im, mask, (0,0), (255))
im = cv2.erode(im, np.ones((3,3)))
im = cv2.bitwise_not(im)
im = cv2.bitwise_and(im,im2)
cv2.imshow('show', im)
cv2.imwrite('fin.png',im)
cv2.waitKey()
Problem
After some processing, I have this binary image: I want to remove the unclosed curves i.e. the top left and the bottom right curves. Can you suggest me the algorithm for doing this? Thanks.