def getContours(img):
contours, hierarchy = cv.findContours(img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv.contourArea(cnt)
if area >500:
cv.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
peri = cv.arcLength(cnt,True)
approx = cv.approxPolyDP(cnt,0.02*peri,True)
objCor = len(approx)
x, y, w, h = cv.boundingRect(approx)
if objCor==3:objectType = "Tri"
elif objCor==4:
aspRatio = w/float(h)
if aspRatio >0.95 and aspRatio<1.05:
objectType="Square"
else:
objectType="Rectangle"
elif objCor>4 :objectType="Circle"
cv.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)
cv.putText(imgContour,objectType,(x-10,y+10),cv.FONT_HERSHEY_COMPLEX,0.5,
(0,0,0),1)
path = "image/shape.png"
img = cv.imread(path)
imgContour = img.copy()
imgGray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
imgBlur = cv.GaussianBlur(imgGray,(7,7),1)
imgCanny = cv.Canny(imgBlur,50,50)
getContours(imgCanny)
imgBlank = np.zeros_like(img)
imgstack = stackImages(1,([imgContour]))
cv.imshow("imgStack",imgstack)
cv.waitKey(0)