c++opencvcentroid

openCV C++ reduce objects/blobs to centroids


Task:

I try to write a method, that reduces the objects in a binary image to their centroids (meaning center of mass).


Solution

  • Parameters:

    Mat *pMA_Out, Mat *pMA_In, int mode, int method, unsigned int thickness
    

    Body:

    //Allocate contours
    vector<vector<Point>> vvp_countours;
    
    //Find countours
    findContours(
                *pMA_In,
                vvp_countours,
                mode,
                method,
                Point(0, 0));
    
    //Get the moments
    vector<Moments> v_moments(vvp_countours.size());
    for(int c = 0; c < vvp_countours.size(); c++)
        v_moments[c] = moments(vvp_countours[c], false);
    
    //Get the mass centers
    vector<Point2f> v_centroid(vvp_countours.size());
    for(int c = 0; c < vvp_countours.size(); c++)
        v_centroid[c] = Point2f(
                    v_moments[c].m10 / v_moments[c].m00,
                    v_moments[c].m01 / v_moments[c].m00);
    
    //Create output image
    Mat MA_tmp = Mat(pMA_In->size(), CV_8UC1, Scalar(0));
    
    //Draw centroids
    for(int c = 0; c < v_centroid.size(); c++)
        line(
                    MA_tmp,
                    v_centroid[c],
                    v_centroid[c],
                    Scalar(255),
                    thickness,
                    8);
    *pMA_Out = MA_tmp.clone();