pythonopencvscipyscipy.ndimage

How to find coordinate of polygon shape from binary image?


The image is below, where dark area is 0, bright area is 255. I want to find 4 coordinates [(x1, y1),(x2, y2),(x3, y3),(x4, y4)] of bright area from this image. This bright area would be polygon shape (pentagon, hexagon, triangle etc.).

I have tried with cv2.findContours() function like following code:

# Find contour(s)
cnts, _ = cv2.findContours(bin_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)    
print(cnts)

I also have tried with np.where() function like following code:

idx_points = np.where(bin_img == 255)
print(idx_points)

I can't find out expected result like [(x1, y1),(x2, y2),(x3, y3),(x4, y4),(x5,y5), ...]. What can I do this for expected result?

enter image description here


Solution

  • Based on their tutorial, https://docs.opencv.org/3.4/d4/d73/tutorial_py_contours_begin.html, this is exactly what cv2.CHAIN_APPROX_SIMPLE would do for you:

    The left part image shows cv2.CHAIN_APPROX_NONE, keeping all contour points, without trying anything. The right part shows cv2.CHAIN_APPROX_SIMPLE attempting to recognize and store corners only. (Image comes from the same tutorial page)