Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove unclosed curves in a binary image?

Tags:

opencv

After some processing, I have this binary image:

enter image description here

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.

like image 728
flowfree Avatar asked Feb 18 '13 13:02

flowfree


2 Answers

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.

  1. floodfill image with white - this removes your problem non-closed lines, but also the borders of your wanted objects.
  2. erode the image, then invert it
  3. AND the image with the original image - thus restoring the borders.

Output:

enter image description here

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()
like image 179
fraxel Avatar answered Nov 12 '22 07:11

fraxel


You're looking for Flood Fill: http://en.wikipedia.org/wiki/Flood_fill

like image 5
John Zwinck Avatar answered Nov 12 '22 07:11

John Zwinck