Skip to content

Instantly share code, notes, and snippets.

@rezamarzban
Created August 20, 2022 05:16
Show Gist options
  • Save rezamarzban/add4034c96ca4d3ad765d8a86829a0a6 to your computer and use it in GitHub Desktop.
Save rezamarzban/add4034c96ca4d3ad765d8a86829a0a6 to your computer and use it in GitHub Desktop.
Image moments help you to calculate some features like center of mass of the object, area of the object etc. The function cv2.moments() gives a dictionary of all moment values calculated. See the code:
import cv2
import numpy as np
img = cv2.imread('star.jpg',0)
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)
cnt = contours[0]
M = cv2.moments(cnt)
print(M)
@rezamarzban
Copy link
Author

From this moments, you can extract useful data like area, centroid etc.

cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])

Contour area is given by the function cv2.contourArea() or from moments, M[‘m00’]:

area = cv2.contourArea(cnt)

Also contour perimeter:

perimeter = cv2.arcLength(cnt,True)

More info: https://opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment