在opencv中使用c++对二值图筛选大面积的轮廓并提取较大轮廓
时间: 2023-06-01 10:04:41 浏览: 71
可以使用以下步骤来实现:
1. 读取二值图像并转换为灰度图像
```
Mat binaryImage = imread("binaryImage.png", IMREAD_GRAYSCALE);
```
2. 对图像进行膨胀操作,以填充轮廓内部的空白区域
```
Mat dilatedImage;
Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(5, 5));
dilate(binaryImage, dilatedImage, kernel);
```
3. 查找轮廓并筛选出较大的轮廓
```
vector<vector<Point>> contours;
findContours(dilatedImage, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<vector<Point>> largeContours;
for (int i = 0; i < contours.size(); i++) {
double area = contourArea(contours[i]);
if (area > 1000) { // 根据面积大小筛选轮廓
largeContours.push_back(contours[i]);
}
}
```
4. 绘制筛选出的轮廓
```
Mat contourImage = Mat::zeros(dilatedImage.size(), CV_8UC3);
Scalar color(0, 255, 0);
drawContours(contourImage, largeContours, -1, color, 2);
```
完整代码示例:
```
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
Mat binaryImage = imread("binaryImage.png", IMREAD_GRAYSCALE);
Mat dilatedImage;
Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(5, 5));
dilate(binaryImage, dilatedImage, kernel);
vector<vector<Point>> contours;
findContours(dilatedImage, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<vector<Point>> largeContours;
for (int i = 0; i < contours.size(); i++) {
double area = contourArea(contours[i]);
if (area > 1000) {
largeContours.push_back(contours[i]);
}
}
Mat contourImage = Mat::zeros(dilatedImage.size(), CV_8UC3);
Scalar color(0, 255, 0);
drawContours(contourImage, largeContours, -1, color, 2);
imshow("Contour Image", contourImage);
waitKey(0);
return 0;
}
```