How to Compute Image Moments in OpenCV Python?
In computer vision, image moments is a measure of image features such as area, centroid, and orientation. Image segmentation, object recognition, and tracking depend on image moments. This article explains how to compute image moments in OpenCV Python using cv2.moments()
.
Pre-requisites
Before computing the image moments, you need to import the OpenCV library into your Python code. You can import it like this:
import cv2
Also, you need to read an image before you can compute the moments. You can read an image like this:
image = cv2.imread('your-image.jpg')
Computing Image Moments
Now that you have imported the OpenCV library and read an image, you can compute the image moments using cv2.moments()
. Here’s how you can do it:
# Compute image moments
moments = cv2.moments(image)
# Get the area
area = moments['m00']
# Get the centroid x, y coordinates
centroid_x = moments['m10'] / area
centroid_y = moments['m01'] / area
The cv2.moments()
function returns a dictionary containing all the image moments. The m00
moment represents the area of the binary blob (the white pixels), while the m10
and m01
moments represent the centroid of the blob.
You can also compute higher-order moments such as mu20
, mu02
, and mu11
as follows:
# Compute higher-order moments
mu20 = moments['mu20'] / area
mu02 = moments['mu02'] / area
mu11 = moments['mu11'] / area
These moments can be used to compute the orientation and elongation of the blob.
Example
Let’s take an example to illustrate how to compute image moments in OpenCV Python.
Here’s the Python code to compute the moments:
import cv2
# Read the image
image = cv2.imread('rectangle.png', cv2.IMREAD_GRAYSCALE)
# Threshold the image
thresh = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY)[1]
# Compute image moments
moments = cv2.moments(thresh)
# Get the area
area = moments['m00']
# Get the centroid x, y coordinates
centroid_x = moments['m10'] / area
centroid_y = moments['m01'] / area
# Print the area and centroid coordinates
print('Area:', area)
print('Centroid x:', centroid_x)
print('Centroid y:', centroid_y)
Running this code produces the following output:
Area: 120050.0
Centroid x: 398.8587746667472
Centroid y: 234.95629537002933
Here, we first read the image and convert it to grayscale. Then, we apply thresholding to convert the image to binary, where the white pixels represent the rectangle. Finally, we compute the moments and print the area and centroid coordinates.
The area of the rectangle is 120,050 pixels, and the centroid is located at x=398, y=234.
Conclusion
In this article, we learned how to compute image moments in OpenCV Python using cv2.moments()
. We covered how to read an image, threshold it, and compute its moments. Image moments are essential features in computer vision, and we can use them for image segmentation, object recognition, and tracking.