c++opencv找到轮廓后拟合圆
时间: 2023-08-11 18:03:20 浏览: 119
在C++ OpenCV中,可以使用以下步骤找到轮廓并拟合圆:
1. 读取图像并转换为灰度图像。
2. 对图像进行二值化处理,使轮廓更明显。
3. 使用findContours函数找到轮廓。
4. 使用minEnclosingCircle函数拟合轮廓的外接圆。
下面是一个示例代码:
```
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat srcImg = imread("circle.png");
if (srcImg.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
Mat grayImg;
cvtColor(srcImg, grayImg, COLOR_BGR2GRAY);
Mat binaryImg;
threshold(grayImg, binaryImg, 100, 255, THRESH_BINARY);
vector<vector<Point>> contours;
findContours(binaryImg, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
Mat resultImg = srcImg.clone();
for (size_t i = 0; i < contours.size(); i++)
{
Point2f center;
float radius;
minEnclosingCircle(contours[i], center, radius);
circle(resultImg, center, radius, Scalar(0, 0, 255), 2);
}
imshow("srcImg", srcImg);
imshow("resultImg", resultImg);
waitKey(0);
return 0;
}
```
其中,circle.png是一张包含圆形的图像,程序运行后会显示原图和拟合后的圆形,如下图所示:
![拟合圆形](https://img-blog.csdnimg.cn/20211019141858156.png)
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)