I was recently going through some OpenCV code that finds the center of mass in a contour and realized there is potential room for optimisation.
What I noticed looking back through my code is when I calculate the mass I'm using contours.size() which makes me believe that I'm calculating the moments and center of mass for all of my contours.
In my cases this is not needed as I have a function that returns the largest contour that I have found getMaxAreaContourId(contours, imageSize);
which returns an int that I can use like contours[largestContour]
and largestContour
would be set from the result of getMaxAreaContourId
So if I'm not mistaken would I be able to just find the moment and mass from a single contour and completely remove two for loops?
Because Ultimately I end up doing this:
int CenterOfContourX = mc[largestContour].x;
int CenterOfContourY = mc[largestContour].y;
Really the end goal is to end up with two integers that represent the center of mass of my contour.
Code to optimise:
// Get the moments
mu.reserve(contours.size());
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }
// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }