Shape Openness detection in OpenCV
Question:
I’m building a shape analysis algorithm and one of the attributes we would like to add is whether the shape is open or closed. For example, the left circle is closed, the middle circle is open and the right circle is more open.
I tried to do it via the contours but I search for a more robust (and hopefully easy) way to achieve it. I know it can be solved with ANN but I don’t want to go in that direction.
(I’m working with Python/OpenCV 4)
Any ideas?
Answers:
If the object is the only thing in the array you are analyzing you could flood fill from any of the corners. If the area occupied by your flood fill value is less than the image area with the drawing’s area subtracted it would be a closed object.
There is a great way to do it using ImageDraw.floodfill function.
Attached is a working code:
from PIL import Image, ImageDraw
def openOrClose(img2):
isCLosed = False
img = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)
target_pixel = (0,0) #Corner of the image
target_color = (255,255,0) #Yellow
im_pil = Image.fromarray(img)
ImageDraw.floodfill(im_pil,target_pixel,target_color)
im = np.asarray(im_pil)
count =0
for i in range(im.shape[0]):
for j in range(im.shape[1]):
if ((im[i][j] == [255,255,255]).all() == True):
count+=1
if count != 0:
isCLosed = True
return isCLosed
I’m building a shape analysis algorithm and one of the attributes we would like to add is whether the shape is open or closed. For example, the left circle is closed, the middle circle is open and the right circle is more open.
I tried to do it via the contours but I search for a more robust (and hopefully easy) way to achieve it. I know it can be solved with ANN but I don’t want to go in that direction.
(I’m working with Python/OpenCV 4)
Any ideas?
If the object is the only thing in the array you are analyzing you could flood fill from any of the corners. If the area occupied by your flood fill value is less than the image area with the drawing’s area subtracted it would be a closed object.
There is a great way to do it using ImageDraw.floodfill function.
Attached is a working code:
from PIL import Image, ImageDraw
def openOrClose(img2):
isCLosed = False
img = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)
target_pixel = (0,0) #Corner of the image
target_color = (255,255,0) #Yellow
im_pil = Image.fromarray(img)
ImageDraw.floodfill(im_pil,target_pixel,target_color)
im = np.asarray(im_pil)
count =0
for i in range(im.shape[0]):
for j in range(im.shape[1]):
if ((im[i][j] == [255,255,255]).all() == True):
count+=1
if count != 0:
isCLosed = True
return isCLosed