I am attempting to detect convex pentagons in an image using OpenCV. I am using the following image:
I first find the contours in the image and then do this:
approx = cv2.approxPolyDP(c, 0.04 * perimeter, True)
isPentagon = len(approx) == 5
When I ran this on the image, I got this result:
This white part in the image is being detected. I thought that checking the concavity would solve it. Here is what I attempted:
isPentagon = len(approx) == 5 and cv2.isContourConvex(c)
However, for all the pentagons I tried, isContourConvex
returned False
. I am not sure why. I tried other images as well and the same happened. Variable c
is the contour.
Is there a way to fix this? Maybe a better way to check if a polygon is regular?
The issues was that I was passing in the original contour found by cv2.findContours
into the cv2.isContourConvex
. That original contour has a ton of points, some of which give the shape a concave characteristic.
To fix this, I had to call cv2.isContourConvex(approx)
. This would evaluate the approximation of the pentagon that has exactly five sides and five vertices. Although I would later draw the initial contour, evaluating the contourConvex function on the approximation yielded the correct result.