opencv C++ 求连通域直径的代码
时间: 2023-03-27 17:05:18 浏览: 144
opencv c++代码
以下是求连通域直径的代码:
```c
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat src = imread("test.jpg", IMREAD_GRAYSCALE);
if (src.empty())
{
cout << "Could not open or find the image!\n";
return -1;
}
// 二值化
Mat binary;
threshold(src, binary, , 255, THRESH_BINARY | THRESH_OTSU);
// 连通域分析
Mat labels, stats, centroids;
int num_labels = connectedComponentsWithStats(binary, labels, stats, centroids);
// 找到最大连通域
int max_label = 1, max_area = stats.at<int>(1, CC_STAT_AREA);
for (int i = 2; i < num_labels; i++)
{
int area = stats.at<int>(i, CC_STAT_AREA);
if (area > max_area)
{
max_label = i;
max_area = area;
}
}
// 找到最大连通域的最小外接圆
Point2f center;
float radius;
minEnclosingCircle(Mat(labels == max_label), center, radius);
// 输出直径
cout << "直径:" << 2 * radius << endl;
return ;
}
```
希望对你有帮助!
阅读全文