基于OpenCV的connectedComponentsWithStats查找图像连通域,使用C++并进行从左上角到右下角的质心坐标排序
时间: 2024-05-15 18:15:04 浏览: 10
以下是基于OpenCV的C代码实现:
```c
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// 读取图像
Mat image = imread("test.jpg", IMREAD_GRAYSCALE);
if (image.empty())
{
cout << "Could not open or find the image" << endl;
return -1;
}
// 提取连通域
Mat labels, stats, centroids;
int num_labels = connectedComponentsWithStats(image, labels, stats, centroids);
// 构造排序索引
vector<int> idx(num_labels - 1);
for (int i = 1; i < num_labels; i++)
idx[i - 1] = i;
// 对索引进行排序
sort(idx.begin(), idx.end(), [&](int a, int b)
{
return centroids.at<Point2d>(a)[0] < centroids.at<Point2d>(b)[0] ||
(centroids.at<Point2d>(a)[0] == centroids.at<Point2d>(b)[0] &&
centroids.at<Point2d>(a)[1] < centroids.at<Point2d>(b)[1]);
});
// 输出排序结果
for (int i = 0; i < num_labels - 1; i++)
{
int label = idx[i];
cout << "Label " << label << " center: (" << centroids.at<Point2d>(label) << ")" << endl;
}
return 0;
}
```
首先读取图像,然后使用connectedComponentsWithStats函数提取连通域,得到每个连通域的标签、状态和质心坐标。接着,构造排序索引,对索引进行排序,排序规则为从左到右、从上到下。最后输出排序结果。