# How to calculate HuMoments for a contour/image in opencv using c++

hi,

i tried out the following tutorial.I used opencv 2.4.2 with visual studio 2010 and c++.(http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/moments/moments.html)

there i can calculate moments for each and every contour of the image, like this

vector<Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
{
mu[i] = moments( contours[i], false );
}


then i tried to calculate Hu-Moments in the same way. i tried with various combinations, but didn't got it work. My problems are,

1. is it possible to calculate Hu-Moments only for a one contour ?
2. should i calculate Hu-Moments for the whole image?

please can anyone explain this with some examples?

edit retag close merge delete

Sort by » oldest newest most voted

For Hu-Moments you need to compute the moments first. Moments you can compute of contours as in your example (i.e. a vector of points) or of images (or part of images) (cv::Mat of type CV_8UC1 oder CV_32FC1), see http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=moment#cv2.HuMoments

Example:

// From the example you posted, you already know how to compute the contours
// so let's take just the first one and compute the moments
cv::Moments mom = cv::moments(contours[0]);
double hu[7];
cv::HuMoments(mom, hu); // now in hu are your 7 Hu-Moments


For your second question: For what do you want to use the moments? Moments give you certain statistics about your image, like the sum of gray-values or center of gravity. Hu-Moments are also rotational invariant. So, they may be nice features depending on your application.

more

hi guanta ,

it worked thanks a lot. i involved with OCR application and trying to use these statistics as features, thats it. anyway thanks

( 2013-03-13 07:47:10 -0500 )edit

Cool! Maybe you want to accept/mark the answer as solved.

( 2013-03-13 08:50:48 -0500 )edit

hi guanta yes, it helped me lot. i want to accept this as anwser. how to do that

( 2013-03-18 05:57:38 -0500 )edit

ahh fine, i found the way, thanks a lot

( 2013-03-18 06:03:40 -0500 )edit

Official site

GitHub

Wiki

Documentation