OpenCV4通过findContours找到指定轮廓后用drawContours填充制作掩膜
时间: 2023-10-14 09:28:01 浏览: 230
使用OpenCV4中的findContours函数可以找到指定轮廓,然后可以使用drawContours函数来填充制作掩膜。
以下是一个基本的示例代码:
```python
import cv2
# 读取图像
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 阈值化
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 创建掩膜
mask = np.zeros_like(img)
# 绘制轮廓
cv2.drawContours(mask, contours, 0, (255, 255, 255), -1)
# 显示结果
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先读取了一张测试图像,并将其转换为灰度图像。然后对灰度图像进行二值化处理,以便更好地查找轮廓。
接下来,我们使用findContours函数查找轮廓,并使用drawContours函数将轮廓绘制在掩膜上。最后,我们显示了生成的掩膜。
请注意,这只是一个简单的示例,你可能需要根据你的具体需求进行更改和调整。
相关问题
qt中用opencv获取轮廓之后怎么填充轮廓
在Qt中,可以使用OpenCV的代码来获取轮廓,并且将其填充。以下是一个简单的示例,描述如何在Qt中使用OpenCV来填充轮廓:
首先,需要包含OpenCV和Qt的头文件:
```
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <QImage>
```
然后,使用OpenCV中的函数来获取轮廓:
```
cv::Mat cvImage;
cvImage = cv::imread("yourImage.png");
cv::Mat grayImage;
cv::cvtColor(cvImage, grayImage, CV_BGR2GRAY);
cv::Mat binaryImage;
cv::threshold(grayImage, binaryImage, 100, 255, cv::THRESH_BINARY);
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(binaryImage, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // 获取轮廓
```
接下来,可以使用以下代码将轮廓填充:
```
QImage qim = QImage(cvImage.data, cvImage.cols, cvImage.rows, cvImage.step, QImage::Format_RGB888);
QPainter painter(&qim);
for(int i = 0; i< contours.size(); i++)
{
cv::drawContours(cvImage, contours, i, cv::Scalar(0, 255, 0), -1, 8, hierarchy); // 填充轮廓
}
painter.drawImage(0, 0, qim);
```
最后,将填充后的图像显示在Qt应用程序中:
```
QLabel* label = new QLabel();
QPixmap pixmap = QPixmap::fromImage(qim);
label->setPixmap(pixmap);
label->setFixedSize(pixmap.width(),pixmap.height());
label->show();
```
以上就是使用OpenCV和Qt填充轮廓的基本步骤。
opencv python 寻找轮廓 如何将轮廓边界填充成蓝色
可以使用cv2.drawContours()函数来绘制轮廓,并使用cv2.fillPoly()函数来填充轮廓。以下是示例代码:
```
import cv2
import numpy as np
# 读取图像
img = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 寻找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (255, 0, 0), 3)
# 填充轮廓
for contour in contours:
cv2.fillPoly(img, [contour], (255, 0, 0))
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上面的代码中,我们首先读取图像并将其转换为灰度图像。然后,使用cv2.threshold()函数将其二值化。接下来,使用cv2.findContours()函数寻找图像中的轮廓。然后,我们使用cv2.drawContours()函数绘制轮廓,并使用cv2.fillPoly()函数填充轮廓。最后,我们显示图像并等待按下任意键关闭窗口。
阅读全文
相关推荐













