Search code examples
pythonpython-2.7opencvshape-recognition

how to compute interior angles of hexagon shape in python openCV


I have detected the shape of hexagon in Python using OpenCV. I just want to compute its interior angle -- shape is detected by using contour technique and approximation ..

hexagon


Solution

  • cv2.CHAIN_APPROX_SIMPLE as suggested by parthagar is indeed very useful but it works by removing all the "unnecessary" points in straight lines. If the lines are not entirely straight, as they don't seem to be in this picture, it won't work. So while you'll end up with less points which is nice it almost certainly won't be exactly 6 points as you want.

    To get an approximation of exactly 6 points you need to do some more custom work. OpenCV offers cv2.approxPolyDP (Tutorial py contour features - 4. Contour Approximation) which can be used for this. It does require finding the right epsilon value to get the right amount of points but this can be found by brute forcing:

    #cnt = Your contour to be approximated
    points_wanted = 6
    precision = 10000
    for x in range(precision):
        epsilon = (x/precision)*cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, epsilon, True)
        if approx.shape[0] == points_wanted:
            break
    

    The result can be seen below. Note that it won't be completly perfect, it's an approximation, but hopefully it will be close enough. Methods for finding angles between two points can be found in parthagars link. Good luck!

    enter image description here