Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

centroid of contour/object in opencv in c?

is there some good and better way to find centroid of contour in opencv, without using built in functions?

like image 592
Ayesha Khan Avatar asked Nov 15 '11 21:11

Ayesha Khan


1 Answers

While Sonaten's answer is perfectly correct, there is a simple way to do it: Use the dedicated opencv function for that: moments()

http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=moments#moments

It does not only returns the centroid, but some more statistics about your shape. And you can send it a contour or a raster shape (binary image), whatever best fits your need.

EDIT

example (modified) from "Learning OpenCV", by gary bradsky

CvMoments moments; 
double M00, M01, M10;

cvMoments(contour,&moments); 
M00 = cvGetSpatialMoment(&moments,0,0); 
M10 = cvGetSpatialMoment(&moments,1,0); 
M01 = cvGetSpatialMoment(&moments,0,1); 
centers[i].x = (int)(M10/M00); 
centers[i].y = (int)(M01/M00); 
like image 153
Sam Avatar answered Sep 20 '22 22:09

Sam