Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Calculating image moments after connected component labeling function

I need to calculate the Hu moments from an input image. The input image input consists of several objects so I need to pre-process it using the connected components labeling function:

# input image is thresholded
(T, thresh) = cv2.threshold(input, 90, 255, cv2.THRESH_BINARY)

# getting the labels of the connected components
output = cv2.connectedComponentsWithStats(thresh, 4, cv2.CV_32S)
num_labels = output[0]
labels = output[1]
stats = output[2]
centroids = output[3]

# for every component in the output image
for c in centroids[1:num_labels]:
img_moments = cv2.moments(c)
hu = cv2.HuMoments(img_moments)

However this is not giving me the correct Hu moments values of the components. Originally I used the thresholded image for getting the moments cv2.moments(thresh), but this is not useful when they’re multiple components within the image. I’m using Python 2 with OpenCV 3.

Just for the record, I already obtained the correct number of labels of the image, in this case input image has 10 components + 1 label for the background, that's 11 labels, I know the first label is for the background, therefore the array values are all zeros. I want the get the values of the rest of the labels (from 1 to n-labels) and parse those values to a Numpy array for computing the moments individually.