Firstly, some useful function that we need
def getContours(img):
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
#print(area)
if area > 500:
cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
peri = cv2.arcLength(cnt, True)
#print(peri)
approx = cv2.approxPolyDP(cnt, 0.02*peri, True)
print(len(approx))
objCorners = len(approx)
x, y, w, h = cv2.boundingRect(approx)
if objCorners == 3:
objectType = "Tri"
elif objCorners == 4:
aspectRatio = w/float(h)
if aspectRatio > 0.95 and aspectRatio < 1.05: objectType = "Square"
else: objectType = "Rectangle"
elif objCorners > 4: objectType = "Circle"
else:
objectType = "None"
cv2.rectangle(imgContour, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.putText(imgContour, objectType, (x+(w//2)-10, y+(h//2)-10), cv2.FONT_ITALIC, 0.6, (0,0,0), 2)