How to compute Hu-Moments of an image in OpenCV Python?

The Hu-Moments can be computed using the cv2.HuMoments() function in OpenCV. It returns seven moments invariant to translation, rotation, and scale, with the seventh moment being skew-invariant.

To compute Hu-Moments, we first need to find the contours of objects in the image. Image moments are calculated for objects using their contours, so we detect contours and apply cv2.moments() to compute the moments.

Syntax

The following syntax is used for this function ?

M = cv2.moments(cnt)
hu_moments = cv2.HuMoments(M)

Parameters

  • cnt ? A numpy array of the contour points of an object in the image.

  • M ? The image moments computed from the contour.

Steps to Compute Hu-Moments

You can use the following steps to compute Hu-Moments in an image ?

Step 1: Import the required library. Make sure OpenCV is installed.

import cv2
import numpy as np

Step 2: Read the input image and convert it to grayscale.

img = cv2.imread('shape.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Step 3: Apply thresholding to create a binary image.

ret, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)

Step 4: Find contours in the binary image.

contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

Step 5: Compute moments and Hu-Moments for each contour.

cnt = contours[0]
M = cv2.moments(cnt)
hu_moments = cv2.HuMoments(M)

Example 1: Computing Hu-Moments for First Contour

This example demonstrates how to compute Hu-Moments for the first detected contour and visualize it ?

import cv2
import numpy as np

# Create a simple test image with shapes
img = np.zeros((300, 400, 3), dtype=np.uint8)
img.fill(255)  # White background

# Draw some shapes
cv2.rectangle(img, (50, 50), (150, 100), (0, 0, 0), -1)
cv2.circle(img, (250, 80), 40, (0, 0, 0), -1)
cv2.ellipse(img, (120, 200), (60, 30), 0, 0, 360, (0, 0, 0), -1)

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply thresholding
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)

# Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("Number of Contours detected:", len(contours))

# Compute Hu-Moments for first contour
cnt = contours[0]
M = cv2.moments(cnt)
hu_moments = cv2.HuMoments(M)

# Draw the first contour
cv2.drawContours(img, [cnt], -1, (0, 255, 255), 3)

print("Hu-Moments of first contour:")
for i, moment in enumerate(hu_moments):
    print(f"Moment {i+1}: {moment[0]:.2e}")
Number of Contours detected: 3
Hu-Moments of first contour:
Moment 1: 1.59e-01
Moment 2: 4.70e-05
Moment 3: 1.90e-10
Moment 4: 8.95e-14
Moment 5: 2.03e-25
Moment 6: 4.24e-16
Moment 7: -3.08e-25

Example 2: Computing Hu-Moments for All Contours

This example computes Hu-Moments for all detected contours and compares them ?

import cv2
import numpy as np

# Create test image with multiple shapes
img = np.zeros((300, 400, 3), dtype=np.uint8)
img.fill(255)

# Draw different shapes
cv2.rectangle(img, (50, 50), (150, 100), (0, 0, 0), -1)
cv2.circle(img, (250, 80), 40, (0, 0, 0), -1)
cv2.ellipse(img, (120, 200), (60, 30), 0, 0, 360, (0, 0, 0), -1)

# Convert and threshold
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)

# Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("Number of contours detected:", len(contours))

# Compute Hu-Moments for all contours
for i, cnt in enumerate(contours):
    M = cv2.moments(cnt)
    hu_moments = cv2.HuMoments(M)
    
    # Draw contour
    cv2.drawContours(img, [cnt], -1, (0, 255, 255), 2)
    
    print(f"\nHu-Moments for Contour {i+1}:")
    print(f"First moment: {hu_moments[0][0]:.2e}")
    print(f"Second moment: {hu_moments[1][0]:.2e}")
    print(f"Seventh moment: {hu_moments[6][0]:.2e}")
Number of contours detected: 3

Hu-Moments for Contour 1:
First moment: 1.59e-01
Second moment: 4.70e-05
Seventh moment: -3.08e-25

Hu-Moments for Contour 2:
First moment: 1.68e-01
Second moment: 3.04e-04
Seventh moment: 2.48e-22

Hu-Moments for Contour 3:
First moment: 2.30e-01
Second moment: 1.58e-02
Seventh moment: 6.83e-07

Key Properties of Hu-Moments

Moment Invariant Properties Use Case
Moments 1-6 Translation, rotation, scale Shape matching and recognition
Moment 7 Translation, rotation, scale, skew Distinguishing mirror images

Conclusion

Hu-Moments provide a powerful way to describe shape characteristics that remain consistent under geometric transformations. Use cv2.HuMoments() after computing contour moments with cv2.moments() for robust shape analysis and object recognition tasks.

Updated on: 2026-03-26T22:06:02+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements