c++opencv轮廓填充
时间: 2023-07-19 20:41:12 浏览: 95
要使用OpenCV中的轮廓填充,可以按照以下步骤进行:
1. 读取图像并进行灰度化和二值化处理。
```c++
Mat image = imread("image.jpg");
cvtColor(image, image, CV_BGR2GRAY);
threshold(image, image, 128, 255, THRESH_BINARY);
```
2. 寻找轮廓并绘制轮廓。
```c++
vector<vector<Point>> contours;
findContours(image, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
Mat contourImage(image.size(), CV_8UC3, Scalar(0, 0, 0));
drawContours(contourImage, contours, -1, Scalar(255, 255, 255), FILLED);
```
3. 显示结果。
```c++
imshow("Contour Image", contourImage);
waitKey(0);
```
这样就可以得到填充后的轮廓图像。
相关问题
c++opencv 轮廓填充
使用OpenCV进行轮廓填充的基本步骤如下:
1. 读取图像并进行灰度化和二值化处理。
2. 使用 `findContours()` 函数查找轮廓。
3. 对每个轮廓,使用 `drawContours()` 函数进行绘制。
4. 对每个轮廓,使用 `fillPoly()` 函数进行填充。
下面是一个简单的示例代码:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读取图像并进行灰度化和二值化处理
Mat img = imread("test.png");
Mat gray, binary;
cvtColor(img, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 使用 findContours() 函数查找轮廓
vector<vector<Point>> contours;
findContours(binary, contours, RETR_LIST, CHAIN_APPROX_SIMPLE);
// 对每个轮廓,使用 drawContours() 函数绘制
Mat draw_img = Mat::zeros(img.size(), CV_8UC3);
for (size_t i = 0; i < contours.size(); i++)
{
drawContours(draw_img, contours, i, Scalar(255, 255, 255), 1, LINE_AA);
}
// 对每个轮廓,使用 fillPoly() 函数进行填充
Mat fill_img = Mat::zeros(img.size(), CV_8UC3);
for (size_t i = 0; i < contours.size(); i++)
{
fillPoly(fill_img, contours, i, Scalar(255, 255, 255), LINE_AA);
}
// 显示结果
imshow("Binary", binary);
imshow("Contours", draw_img);
imshow("Filled", fill_img);
waitKey(0);
return 0;
}
```
在上面的示例代码中,我们使用了 `findContours()` 函数查找轮廓,该函数返回一个 `vector` 类型的容器,其中每个元素都是一个 `vector` 类型的容器,表示一个轮廓。然后,我们可以使用 `drawContours()` 函数绘制轮廓,或者使用 `fillPoly()` 函数对轮廓进行填充。注意,在使用 `fillPoly()` 函数时,必须将轮廓转换为一个 `vector` 类型的容器,其中每个元素表示一个轮廓的顶点集合。
基于c++ opencv填充轮廓内部
要在C++ OpenCV中填充轮廓内部,可以使用cv::fillPoly函数。以下是一个示例代码:
```
// 创建一个黑色的图像
cv::Mat image = cv::Mat::zeros(500, 500, CV_8UC3);
// 定义一个包含多边形顶点的vector
std::vector<std::vector<cv::Point>> contours;
contours.push_back({cv::Point(100, 100), cv::Point(300, 100), cv::Point(200, 300)});
// 在图像上绘制多边形
cv::drawContours(image, contours, 0, cv::Scalar(255, 255, 255), -1);
// 填充多边形内部
cv::fillPoly(image, contours, cv::Scalar(255, 0, 0));
// 显示图像
cv::imshow("Filled Contour", image);
cv::waitKey(0);
```
在上面的代码中,我们首先创建了一个黑色的图像,然后定义了一个包含一个多边形顶点的vector。接着,我们使用`cv::drawContours`函数在图像上绘制了多边形,并使用`cv::fillPoly`函数填充了多边形内部。最后,我们显示了填充后的图像。
注意,在使用`cv::fillPoly`函数时,需要提供包含多边形顶点的vector和填充颜色。如果要填充多个轮廓,请将轮廓添加到vector中,并在调用`cv::fillPoly`函数时传递整个vector。
阅读全文
相关推荐
















