| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | import cv2
 
img = cv2.imread('d:/tmp/formes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
ret,thresh = cv2.threshold(gray,120,255,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)
print("Nombre de contours détectés : ", len(contours))
nbsquares = 0
for cnt in contours:
    x1,y1 = cnt[0][0]
    approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
    if len(approx) == 4:
        x, y, w, h = cv2.boundingRect(cnt)
        ratio = float(w)/h
        if ratio >= 0.9 and ratio <= 1.1:
            img = cv2.drawContours(img, [cnt], -1, (255,255,0), 1)
            cv2.putText(img, 'Square', (x1, y1 -10 ), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
            nbsquares += 1
        else:
            cv2.putText(img, 'Rectangle', (x1, y1 -10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
            img = cv2.drawContours(img, [cnt], -1, (0,255,0), 1)
print ("Nombre de carrés détectés : " + str(nbsquares))
cv2.imshow("Formes", img)
cv2.waitKey(0)
cv2.destroyAllWindows() |