可以使用 cv2.drawContours 函数将轮廓绘制到原始图像上
时间: 2023-06-16 07:06:31 浏览: 182
是的,可以使用cv2.drawContours函数将轮廓绘制到原始图像上。具体代码如下:
```python
import cv2
# 读取原始图像
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, (0, 255, 0), 2)
# 显示绘制后的图像
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,cv2.drawContours函数有以下参数:
- img:原始图像
- contours:轮廓
- contourIdx:绘制哪个轮廓,如果为-1,则绘制所有轮廓
- color:轮廓颜色(BGR格式)
- thickness:轮廓线条宽度
运行代码后,会将绘制好轮廓的图像显示出来。
相关问题
如何显示cv2.drawcontours()函数画的图像
要显示cv2.drawContours()函数画的图像,您需要使用cv2.imshow()函数将图像显示在屏幕上。这需要将图像转换为可显示的格式。以下是一个示例代码片段,它加载一个图像,使用cv2.drawContours()函数添加轮廓,并使用cv2.imshow()函数显示结果:
```python
import cv2
import numpy as np
# 加载图像
img = cv2.imread('image.png')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化图像
ret, thresh = cv2.threshold(gray, 127, 255, 0)
# 寻找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们使用cv2.imread()函数加载图像,然后将其转换为灰度图像和二值化图像。然后使用cv2.findContours()函数寻找图像中的轮廓,并使用cv2.drawContours()函数将轮廓绘制在原始图像上。最后,使用cv2.imshow()函数显示结果。请注意,cv2.waitKey()函数用于等待用户按下键盘上的任何键,而cv2.destroyAllWindows()函数用于关闭所有打开的窗口。
cv2.drawcontours()函数contours示例
下面是一个示例代码,利用`cv2.drawContours()`函数绘制图像中的轮廓:
```python
import cv2
import numpy as np
# 读取图像
img = cv2.imread('example.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, (0, 255, 0), 2)
# 显示图像
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先读取一张图像,并将其转换为灰度图像。然后使用阈值化处理将图像转换为二值图像。接着使用`cv2.findContours()`函数查找图像中的轮廓。最后使用`cv2.drawContours()`函数将轮廓绘制在原始图像上,并显示出来。
注意,在`cv2.drawContours()`函数的第二个参数中,我们传入了`contours`,即所有的轮廓。如果我们只想绘制其中一个轮廓,可以传入轮廓的索引,例如`contours[0]`表示第一个轮廓。在这个示例中,我们传入了`-1`,表示绘制所有的轮廓。函数的第三个参数是轮廓的颜色,这里使用绿色。函数的第四个参数是线宽,这里设置为2。
阅读全文
相关推荐














