Finding the centroid of a blob in Python

asked 2014-06-13 11:14:58 -0500

luketheduke gravatar image

updated 2014-06-15 12:35:14 -0500

I am a newbie to Python and OpenCV and I am trying to find the centroid of a blob. I have succesfully been able to find the blob using this code:

import cv2 import numpy as np

cap = cv2.VideoCapture(0)


# Take each frame
_, frame =

# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

# define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])

# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)

# Bitwise-AND mask and original image
res = cv2.bitwise_and(frame,frame, mask= mask)

k = cv2.waitKey(5) & 0xFF
if k == 27:

but I can't figure out how to find the centroid of the blob. I have looked at the Moments() command but I don't know how and where to implement it into my program.I am using Python 2.7 with the latest OpenCV package and Ubuntu 14.04 LTS. All help is appreciated and I will gladly provide detials if needed. Thanks, L

Thanks for the help so far. But is it possible that someone could provide me with some code that implements the moments() function in python. All the code I have tried so far will not run because of various errors... Thanks, L

edit retag flag offensive close merge delete


if you get exactly 1 blob after inRange, you can apply moments() directly on the mask, if there's more, you need to call findContours() and apply moments() on each of them.

berak gravatar imageberak ( 2014-06-13 13:16:37 -0500 )edit