Search code examples
pythonopencvobject-detectioncontourshapes

Shape Openness detection in OpenCV


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.

enter image description here

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?


Solution

  • 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
    

    and this is the result: enter image description here