简体   繁体   中英

How to calculate pair wise distances between labeled components (binary image) in opencv (c++)

I have binary image, that I show here:

在此处输入图片说明

I succesfully calculated centroids and stats of all white dots in this image by using opencv function: connectedComponentsWithStats, info link here:

connectedComponentsWithStats

Now I have to calculate all distances between all white dots (pair-wise) distances. My question is:

What is the easiest way to calculate pair-wise distances of white dots in opencv (c++)? I have read k-Nearest Neighbour in Python but I don't know how to implement that in c++. After distances calculated, I must color out every two dots that are closer than some value, for example, if two dots are closer than 10 px, they should be marked red (green otherwise)

Easiest would be to do it by yourself using two loops and standard euclidean distance formula. The coloring could probably done with setTo with mask set where values match current loop indices

cv::Mat centorids, connectedComponentsLabels;
connectedComponentsWithStats(image, connectedComponentsLabels, stats, centroids, 8, CV_32S);
cv::Mat resultsImage = cv::Mat::zeros(connectedComponentsLabels.size(), CV_8UC3);
resultsImage.setTo(cv::Scalar(0, 255, 0), connectedComponentsLabels != 0); //precolor all points green, so that red coloring can override it
for (int i = 1; i < centroids.rows - 1; ++i)
{
    for (int j = i + 1; j < centroids.rows; ++j)
    {
        auto vec = cv::Point2d(centroids.at<double>(i, 0), centroids.at<double>(i, 1)) - 
                   cv::Point2d(centroids.at<double>(j, 0), centroids.at<double>(j, 1));
        double distSquared = vec.x * vec.x + vec.y * vec.y;
        if (distSquared > 100) //compare with 10 squared to avoid slow sqrt for distance
        {   //do the coloring red here
            resultsImage.setTo(cv::Scalar(255, 0, 0), connectedComponentsLabels == i);
            resultsImage.setTo(cv::Scalar(255, 0, 0), connectedComponentsLabels == j);
        }
    }
}

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