cv2.moments documentation code example
Example: cv2.moment()
# convert image to grayscale image
2
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
3
4
# convert the grayscale image to binary image
5
ret,thresh = cv2.threshold(gray_image,127,255,0)
6
7
# calculate moments of binary image
8
M = cv2.moments(thresh)
9
10
# calculate x,y coordinate of center
11
cX = int(M["m10"] / M["m00"])
12
cY = int(M["m01"] / M["m00"])
13
14
# put text and highlight the center
15
cv2.circle(img, (cX, cY), 5, (255, 255, 255), -1)
16
cv2.putText(img, "centroid", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
17
18
# display the image
19
cv2.imshow("Image", img)
20
cv2.waitKey(0)