简体   繁体   English

如何在OpenCV(C ++)中计算标记组件之间的成对距离(二进制图像)

[英]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: 我通过使用opencv函数成功计算了此图像中所有白点的质心和统计信息:connectedComponentsWithStats,信息链接位于此处:

connectedComponentsWithStats 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++)? 在opencv(c ++)中计算白点的成对距离的最简单方法是什么? I have read k-Nearest Neighbour in Python but I don't know how to implement that in c++. 我已经在Python中阅读了k-Nearest Neighbor,但是我不知道如何在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) 计算出距离后,我必须为每两个比某个值更近的点上色,例如,如果两个点比10 px更近,则应将它们标记为红色(否则为绿色)

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 着色可能使用setTo和mask设置完成,其中值与当前循环索引匹配

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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