Skip to content

Instantly share code, notes, and snippets.

@oostendo
Created July 11, 2013 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oostendo/5978514 to your computer and use it in GitHub Desktop.
Save oostendo/5978514 to your computer and use it in GitHub Desktop.
Polygon approximation for a contour segement with a given number of sides
def fixedPoly(contour, polysides = 8):
opencv_contour = contour.reshape(-1, 1, 2)
higherr = 50.0
lowerr = 1.0
tryerr = 25.0
poly = []
#binary search polygon approximations until we get a 4 point polygon
maxiterations = 100
while len(poly) != polysides and maxiterations:
poly = cv2.approxPolyDP(opencv_contour, tryerr, False)
maxiterations -= 1
if len(poly) < polysides:
higherr = tryerr
tryerr = (higherr + lowerr) / 2
if len(poly) > polysides:
lowerr = tryerr
tryerr = (higherr + lowerr) / 2
poly = poly.reshape(-1, 2) # get it out of opencv
return poly
@oostendo
Copy link
Author

this is probably backwards -- i imagine this can be much more efficiently done, but it works for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment