To find an object’s centroid in an image with OpenCV, threshold the image into a mask, compute its image moments with cv2.moments, and divide: cx = m10 / m00 and cy = m01 / m00. The centroid is the average pixel position of the object, and the difference between cx and the image centre is the error a robot can steer on.
Key takeaways
- The centroid of a binary mask is the mean of the x and y positions of all its white pixels.
- In OpenCV, m00 is the area (pixel count), m10 is the sum of x positions and m01 is the sum of y positions.
- Always check that m00 is not zero before dividing, because an empty mask has no centroid.
- Horizontal pixel error from the image centre converts to a steering or pan command through a gain, which you must tune on your robot.
Blobs and Masks
A mask is a black and white image where white pixels mark the object you care about and black marks everything else. A blob is a connected group of white pixels in that mask.
You usually get a mask by converting the frame to a colour space such as HSV and keeping pixels in a range, or by thresholding a greyscale image. A coloured ball is a typical target. Small specks of noise also appear white, so clean the mask with a morphological open or close and keep only the largest blob. Otherwise a few stray pixels pull the centroid away from the real object. For the setup of OpenCV and the camera, see OpenCV on a Raspberry Pi for robot vision.
Image Moments
An image moment is a weighted sum over the image pixels. For a binary mask, the raw moments are simple counts and sums.
m00is the sum of all pixel values, which for a 0 or 1 mask is the area in pixels.m10is the sum of x for every white pixel, where x is the column number.m01is the sum of y for every white pixel, where y is the row number.
OpenCV returns these and many others as a dictionary from cv2.moments(mask). For an 8-bit mask with values 0 and 255, m00 will be 255 times the pixel count unless you pass binaryImage=True, but the centroid ratio is the same either way because the scale cancels.
Centroid Formula
The centroid is the area-weighted average position. The formulas are cx = m10 / m00 and cy = m01 / m00. Both come out as decimal values, so a centroid can fall between pixel positions, which is useful for smooth control.
# Untested sample. Check on your own frames.
import cv2
# mask: uint8 image, 255 for the object, 0 elsewhere
m = cv2.moments(mask, binaryImage=True)
if m["m00"] > 0: # avoid dividing by zero on an empty mask
cx = m["m10"] / m["m00"]
cy = m["m01"] / m["m00"]
else:
cx = cy = None # nothing found in this frameImage coordinates start at the top left, with x increasing to the right and y increasing downward. Keep that in mind when you map cy to a tilt servo, because the sign may need flipping.
Worked Example on a Mask
Take a tiny mask with white pixels at these (x, y) positions. Row 1 has x = 2, 3, 4. Row 2 has x = 2, 3, 4, 5. Row 3 has x = 3, 4.
- Area m00 = 3 + 4 + 2 = 9 pixels.
- m10 = sum of x. Row 1: 2 + 3 + 4 = 9. Row 2: 2 + 3 + 4 + 5 = 14. Row 3: 3 + 4 = 7. Total = 9 + 14 + 7 = 30.
- m01 = sum of y. Row 1 has 3 pixels at y = 1, giving 3. Row 2 has 4 pixels at y = 2, giving 8. Row 3 has 2 pixels at y = 3, giving 6. Total = 3 + 8 + 6 = 17.
- cx = 30 / 9 = 3.333 and cy = 17 / 9 = 1.889.
Check by eye: the x values range from 2 to 5 with most weight in the middle, so 3.33 is reasonable, and the shape sits mostly on rows 1 and 2, so 1.89 is reasonable. The pixel list can be re-added a second way: x values 2, 2, 3, 3, 3, 4, 4, 4, 5 sum to 30 as well.
Turning Pixel Error into Steering
Pixel error is the horizontal distance of the centroid from the middle of the image. It tells the robot which way to turn and by how much.
Assume a 640 pixel wide frame, so the centre is at x = 320. If cx = 400, then error = 400 minus 320 = 80 pixels to the right. A simple proportional rule is correction = Kp x error. With an assumed Kp of 0.05 degrees per pixel, the correction is 80 x 0.05 = 4.0 degrees. That Kp is only an example. You find the real one by trying small values and watching for overshoot.
If you know the camera’s horizontal field of view, you can estimate the true angle instead. For an assumed 60 degree FOV across 640 pixels, 80 pixels is about 80 / 640 x 60 = 7.5 degrees using a linear approximation. This is rougher at wide angles, so use the arctangent relationship between pixel offset and focal length in pixels for the exact angle, and see camera calibration with OpenCV in Python for correcting distortion. The colour tracking pan-tilt project applies this loop to servos. If you want a small microcontroller to drive the servos from the Pi’s error value over serial or Wi-Fi, a board like the Raspberry Pi Pico W is one option to consider.
How to check this yourself
- Draw a filled white rectangle on a black image with a known position, for example from x = 100 to 199 and y = 50 to 99.
- Calculate the expected centroid by hand: the middle of the rectangle, which is x = 149.5 and y = 74.5.
- Run
cv2.momentson the image and compute cx and cy. They should match your hand calculation. - Add a few stray white pixels far away and see how far the centroid moves, then remove them with a morphological open and compare.
- Run the same code on live frames of a coloured object and print cx. Move the object left and right and confirm cx follows.
Common mistakes
- Dividing by m00 without checking for zero, which crashes the script when the object leaves the frame.
- Computing the centroid of a noisy mask without cleaning it first.
- Mixing up x and y or forgetting that y increases downward.
- Using the centroid of every blob together when only the largest one is the target.
- Applying a large gain so the camera hunts left and right around the target.
Quick checklist
- Build a clean mask and keep the largest blob.
- Use
cv2.momentswithbinaryImage=True. - Guard against m00 equal to zero.
- Compute error relative to the image centre.
- Start with a small gain and increase slowly.
Frequently asked questions
How do I find the centre of an object in OpenCV?
Make a binary mask of the object, call cv2.moments on it, then compute cx = m10 / m00 and cy = m01 / m00. These are the average x and y positions of the white pixels. Check that m00 is above zero first, because an empty mask has no centre.
What is m00 in OpenCV moments?
The moment m00 is the sum of all pixel values in the image. For a binary mask it equals the object’s area in pixels, or 255 times the pixel count if the mask uses 255 and binaryImage is not set. It is the denominator when you compute the centroid.
How do I make a robot follow an object using its centroid?
Compute the horizontal error between the centroid and the image centre, then multiply by a small gain to get a steering or pan correction. Update each frame, and tune the gain on your robot so it follows smoothly without oscillating. Handle frames where the object is lost.
Related reading
- Robot vision with YOLO object detection for when colour masks are not enough and you want a learned detector.
- ESP32-CAM robot car for a low-cost camera robot build.
- Learn hub for more vision topics.
About the author and how this is kept accurate
Written, checked and maintained by Jignesh Panchal of Jaadu Digital. Figures in worked examples come from the stated assumptions, not from a bench test of our own. Read the editorial standard, follow the author on LinkedIn, or send a correction. Last reviewed: November 2026.



