繁体   English   中英

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

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

我有二进制图像,在这里显示:

在此处输入图片说明

我通过使用opencv函数成功计算了此图像中所有白点的质心和统计信息:connectedComponentsWithStats,信息链接位于此处:

connectedComponentsWithStats

现在,我必须计算所有白点之间的所有距离(成对)。 我的问题是:

在opencv(c ++)中计算白点的成对距离的最简单方法是什么? 我已经在Python中阅读了k-Nearest Neighbor,但是我不知道如何在c ++中实现。 计算出距离后,我必须为每两个比某个值更近的点上色,例如,如果两个点比10 px更近,则应将它们标记为红色(否则为绿色)

最简单的方法是自己使用两个循环和标准的欧几里得距离公式来完成。 着色可能使用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