import cv2 as cv

img = cv.imread("shapes.png", cv.IMREAD_GRAYSCALE)

_, threshold = cv.threshold(img, 240, 255, cv.THRESH_BINARY)
contours, _ = cv.findContours(threshold, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

def drawText(name, coords):
  # Pass the image, text, position, font, scale, color
  cv.putText(img, name, coords, cv.FONT_HERSHEY_DUPLEX, 1, (0))

for cnt in contours:
  # Calculates a contour perimeter or a curve length.
  peri = cv.arcLength(cnt, True) # True for closing the curve
  # Approximates a polygonal curve(s) with the specified precision
  approx = cv.approxPolyDP(cnt, 0.01 * peri, True) # True for closing the curve

  cv.drawContours(img, [approx], 0, (0), 5) # Last two are color and thickness

  # ravel returns a contiguous flattened array.
  pos = (approx.ravel()[0], approx.ravel()[1])

  if len(approx) == 3:
    drawText("Triangle", pos)
  elif len(approx) == 4:
    # compute the aspect ratio by using the bounding box of the contour
    (x, y, w, h) = cv.boundingRect(approx)
    ar = w / float(h)
    # a square has an aspect ratio that is almost equal to one
    shape = "square" if ar >= 0.95 and ar <= 1.05 else "rectangle"
    drawText(shape, pos)
  elif len(approx) == 5:
    drawText("Pentagon", pos)
  elif len(approx) == 6:
    drawText("Hexagon", pos)
  elif len(approx) > 10:
    drawText("Circle", pos)

cv.imwrite('shapes-detected.png', img)