opencv轮廓检测c++形态学
时间: 2023-12-04 21:41:37 浏览: 113
opencv 轮廓检测
3星 · 编辑精心推荐
以下是使用OpenCV进行轮廓检测和形态学运算的C++代码示例:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读取图像
Mat src = imread("image.jpg");
// 灰度化
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);
// 二值化
Mat binary;
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 形态学操作
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
Mat morph;
morphologyEx(binary, morph, MORPH_OPEN, kernel);
// 轮廓检测
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(morph, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 绘制轮廓
Mat result(src.size(), CV_8U, Scalar(255));
drawContours(result, contours, -1, Scalar(0), 2);
// 显示结果
imshow("src", src);
imshow("result", result);
waitKey(0);
return 0;
}
```
阅读全文