How to convert from edges to contours in OpenCV

Question:

I have been getting images like this after edge detection:
edge detection

I’d like it to connect the edges together into straight-line polygons.

I thought this could be done using findCountours with chain approximation, but that doesn’t seem to be working well for me.

How can I convert an image like the one above into a simple straight-line polygons (that look like skewed triangles and trapezoids and squares)?

Asked By: Pro Q

||

Answers:

You need to first detect the lines and then construct the contours. You can do that using HoughLines(). There is a short tutorial here.

Answered By: fireant

Blur the image, then find the contours.

If the edges are that close together, a simple blurring with something like

def blur_image(image, amount=3):
    '''Blurs the image
    Does not affect the original image'''
    kernel = np.ones((amount, amount), np.float32) / (amount**2)
    return cv2.filter2D(image, -1, kernel)

should connect all the little gaps, and you can do contour detection with that.

If you then want to convert those contours into polygons, you can look to approximate those contours as polygons. A great tutorial with code for that is here.

The basic idea behind detecting polygons is running

cv2.findContours(image, cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)

Which tells OpenCV to approximate the contours with straight lines, creating polygons. (I’m not sure what the cv2.RETR_EXTERNAL parameter does at this time.)

Answered By: Pro Q