Search code examples
pythonopencvcontouredge-detection

How to convert from edges to contours in OpenCV


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)?


Solution

  • 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.)