如何计算 opencv (c++) 中标记组件(二值图像)之间的成对距离
How to calculate pair wise distances between labeled components (binary image) in opencv (c++)
我有二进制图像,我在这里显示:
我使用 opencv 函数成功计算了此图像中所有白点的质心和统计数据:connectedComponentsWithStats,信息 link 此处:
现在我必须计算所有白点(成对)距离之间的所有距离。我的问题是:
在 opencv (c++) 中计算白点成对距离的最简单方法是什么?我已经阅读了 Python 中的 k-Nearest Neighbor 但我不知道如何在 C++ 中实现它。计算完距离后,我必须将距离小于某个值的每两个点涂上颜色,例如,如果两个点距离小于 10 px,则应标记为红色(否则为绿色)
最简单的方法是使用两个循环和标准欧氏距离公式自己完成。着色可能用 setTo
完成,掩码集的值与当前循环索引
匹配
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);
}
}
}
我有二进制图像,我在这里显示:
我使用 opencv 函数成功计算了此图像中所有白点的质心和统计数据:connectedComponentsWithStats,信息 link 此处:
现在我必须计算所有白点(成对)距离之间的所有距离。我的问题是:
在 opencv (c++) 中计算白点成对距离的最简单方法是什么?我已经阅读了 Python 中的 k-Nearest Neighbor 但我不知道如何在 C++ 中实现它。计算完距离后,我必须将距离小于某个值的每两个点涂上颜色,例如,如果两个点距离小于 10 px,则应标记为红色(否则为绿色)
最简单的方法是使用两个循环和标准欧氏距离公式自己完成。着色可能用 setTo
完成,掩码集的值与当前循环索引
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);
}
}
}