簡體   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