简体   繁体   中英

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.

There is a function in openCV for this; pointPolygonTest .

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM