Calculate the center of a contour/Area
16,303
You can get the center of mass in the y direction by first calculating the Moments. Then the center of mass is given by yc = M01 / M00
, where M01 and M00 are fields in the structure returned by the Moments call.
If you just want the center of the bounding rectangle, that is also easy to do with BoundingRect. This returns you a CvRect and you can just take half of the height.
Let me know if this isn't precise enough, I have sample code somewhere I can dig up for you.
Author by
SHRISH M
Updated on June 07, 2022Comments
-
SHRISH M almost 2 years
I'm working on a Image-processing chain that seperates a single object by color and contour and then calculates the y-position of this object.
How do I calculate the center of a contour or area with OpenCV?
Opencv links:
-
Kiv almost 15 yearsNo point doing it yourself when there's multiple builtin ways to do it.
-
rwong almost 14 yearsThirdly, you can compute the Convex Hull and its moment (which is in fact the first internal step in BoundingRect). Fourthly, you can calculate the center of mass of just the contour pixels (i.e. the pixels that lie exactly on the contour). All these methods will give different values, and their usefulness will depend on your application's specific needs.
-
Martin Beckett over 11 yearsThe center of the points of a contour isn't the center of gravity. 99% of the contour points could be concentrated in a small area with high variation and only 3 cover the rest of a larger regular shape.
-
buzjwa over 9 yearsThe moments for a contour are not computed by summing over the contour points but by using Green's theorem. The results are not exactly as computing the center of mass for the filled contour in the image but are similar, and in any way are not skewed by irregularity in the contour point spread as you suggest.