用C++调用opencv写一个提取轮廓的代码
时间: 2024-06-12 20:08:06 浏览: 15
以下是一个简单的用C调用opencv提取轮廓的代码:
```c
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("input.jpg", IMREAD_GRAYSCALE);
if (img.empty())
{
cout << "Could not open or find the image" << endl;
return -1;
}
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Canny(img, canny_output, 100, 200, 3);
findContours(canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
Scalar color = Scalar(255, 255, 255);
for (size_t i = 0; i< contours.size(); i++)
{
drawContours(drawing, contours, (int)i, color, 2, LINE_8, hierarchy, 0, Point());
}
namedWindow("Contours", WINDOW_AUTOSIZE);
imshow("Contours", drawing);
waitKey(0);
return 0;
}
```
这个代码首先用`imread`函数读取一张灰度图像,然后使用`Canny`函数进行边缘检测,接着使用`findContours`函数找到所有轮廓。最后,使用`drawContours`函数将轮廓画在一张黑色的图像上,并显示出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)