Using OpenCV C ++ cv :: Moments

I am trying to find a centroid using OpenCV C ++ cv :: Moments. Whatever arguments I obey, all I get is zeros. It’s clear that I am doing something very simple. Code output:

23 of 500 elements in unit 3
point values 2.976444 18.248287
matrix size 23
moments 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
moments 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000

And the code:

printf("%d of %d elements in unit %d\n",k,number_of_features,i);
cv::Mat x(k, 1, cv::DataType<cv::Point2f>::type);
k=0;
for(int j=0;j <number_of_features;j++) {
    if(i  == labels.at<int>(j)) {
        x.at<cv::Point2f>(k++) = samples.at<cv::Point2f>(i); 
    }
}
printf("point values %f %f\n", x.at<cv::Point2f>(0).x,x.at<cv::Point2f>(0).y);
cv::Size s=x.size();
printf("matrix size %d\n",s.height);
cv::Moments m=cv::moments(x);
printf("moments %f %f %f %f %f %f %f %f\n",m.m00,m.m01,m.m20,m.m11,m.m02,m.m30,m.m21,m.m03);
double h[7];
cv::HuMoments(m,h);
printf("moments %f %f %f %f %f %f %f\n",h[0],h[1],h[2],h[3],h[4],h[5],h[6]);

Strange, I cannot find an identical code sample from Google. All I see are C style approaches.

+5
source share
2 answers

Using moments to search for a centroid is a little trick of imho. You can use the following algorithm:

sumX = 0; sumY = 0;
size = array_points.size;
if(size > 0){

    foreach(point in array_points){
        sumX += point.x;
        sumY += point.y;
    }

 centroid.x = sumX/size;
 centroid.y = sumY/size;
}

Or using Opencv boundingRect:

//pseudo-code:

Rect bRect = Imgproc.boundingRect(array_points);

centroid.x = bRect.x + (bRect.width / 2);
centroid.y = bRect.y + (bRect.height / 2);
+10
source

I would recommend you visit the official tutorial for the moment. Study and run this code first.

http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/moments/moments.html#moments

, , .

+3

All Articles