C++opencv,如何只保留图片(灰度图)轮廓内(轮廓不规则)的部分?
时间: 2023-07-28 10:10:37 浏览: 69
你可以使用OpenCV中的轮廓提取函数 `findContours` 来获取图像中的轮廓,然后创建一个与原始图像相同大小的掩模图像 `mask`,并使用 `drawContours` 函数在 `mask` 上绘制轮廓。最后,使用 `bitwise_and` 函数将原始图像与 `mask` 进行按位与操作,以获取只包含轮廓内部像素的图像。
下面是一个示例代码:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 读取灰度图像
Mat image = imread("input.png", IMREAD_GRAYSCALE);
// 二值化处理
Mat binary;
threshold(image, binary, 128, 255, THRESH_BINARY);
// 提取轮廓
std::vector<std::vector<Point>> contours;
findContours(binary, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
// 创建掩模图像
Mat mask = Mat::zeros(image.size(), CV_8UC1);
// 在掩模图像上绘制轮廓
drawContours(mask, contours, 0, Scalar(255), FILLED);
// 将原始图像与掩模图像进行按位与操作
Mat result;
bitwise_and(image, mask, result);
// 显示结果
imshow("Result", result);
waitKey();
return 0;
}
```
在这个示例中,我们首先读取了一张灰度图像,并对其进行了二值化处理。然后,使用 `findContours` 函数提取了图像中的轮廓,并创建了一个与原始图像相同大小的掩模图像。接着,在掩模图像上使用 `drawContours` 函数绘制了轮廓,并使用 `bitwise_and` 函数将原始图像与掩模图像进行按位与操作。最后,将结果显示出来。