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