c++opencv轮廓填充
时间: 2023-07-19 13:40:49 浏览: 64
要对轮廓进行填充,可以使用OpenCV中的 `cv::drawContours()` 函数。以下是一个简单的示例代码,演示如何使用该函数来填充轮廓:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 读取图像并将其转换为灰度图像
Mat image = imread("input.jpg");
Mat gray;
cvtColor(image, gray, COLOR_BGR2GRAY);
// 二值化图像并寻找轮廓
Mat binary;
threshold(gray, binary, 128, 255, THRESH_BINARY);
std::vector<std::vector<Point>> contours;
findContours(binary, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 创建一个与原始图像大小相同的掩码图像
Mat mask(image.size(), CV_8UC1, Scalar(0));
// 对每个轮廓进行填充
for (int i = 0; i < contours.size(); i++)
{
drawContours(mask, contours, i, Scalar(255), FILLED);
}
// 将掩码图像与原始图像进行按位与操作,以得到填充后的图像
Mat filled;
image.copyTo(filled, mask);
// 显示填充后的图像
imshow("Filled Image", filled);
waitKey(0);
return 0;
}
```
在这个示例中,我们首先读取图像并将其转换为灰度图像。然后,我们对图像进行二值化,并使用 `findContours()` 函数来寻找轮廓。接下来,我们创建一个与原始图像大小相同的掩码图像,并对每个轮廓进行填充。最后,我们将掩码图像与原始图像进行按位与操作,以得到填充后的图像。