Search code examples
c++opencvpointcontourimaging

Find distance from contour to a Point opencv C++


I would create a Matrix that has in the coloumn[i] the distances from a fixed Point (mass center(mc(i)) of a contour) to the Points of the contour[i].

This is the code where I find contours and mass centers:

findContours(binMat, contours, cv::RETR_EXTERNAL, CHAIN_APPROX_SIMPLE,Point(0,0));

/// Get the moments
vector<Moments> mu(contours.size());
for (int i = 0; i < contours.size(); i++)
{
    mu[i] = moments(contours[i], false);
}

///  Get the mass centers
vector<Point2f> mc(contours.size());
for (int i = 0; i < contours.size(); i++)
{
    mc[i] = Point2d(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
}

This code is working well.

Next, I tried many way to find the distance, but having many problems because I'm new programming with C++ and using OpenCV.


Solution

  • for (int i = 0; i < contours.size(); i++)
    {
        mc[i] = Point2d(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
    
        KeyPoint k;
        k.pt = mc[i];
    
        float d = (k.pt.x,k.pt.y, centerX,centerY);
    }
    

    A function to calculate distance between 2 points

    float distance(int x1, int y1, int x2, int y2)
    {
    
        float d = sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2));
    
        return d;
    }