Calculating image moments
Image moments are statistical values computed from an image. They allow us to analyze the image as a whole. Note that it's often useful to extract contours first, and only then compute and work with each component moment, independently. In this recipe, you will learn how to compute moments for binary/grayscale images.
Getting ready
You need to have OpenCV 3.x installed, with Python API support.
How to do it...
- Import the modules:
import cv2 import numpy as np import matplotlib.pyplot as plt
- Draw a test image—a white ellipse with the center at point (
320
,240
), on a black background:
image = np.zeros((480, 640), np.uint8) cv2.ellipse(image, (320, 240), (200, 100), 0, 0, 360, 255, -1)
- Compute the moments and print their values:
m = cv2.moments(image) for name, val in m.items(): print(name, '\t', val)
- Perform a simple test to check whether the computed moments make sense, compute the center of the mass of the image using its first moments. It must be close to the center...