cv2.drawContours()函数怎么用
时间: 2023-11-02 13:37:54 浏览: 67
cv2.drawContours()函数用于在图像上绘制轮廓。它的语法为:
cv2.drawContours(image, contours, contourIdx, color, thickness)
其中,image为要绘制的图像,contours为轮廓,contourIdx为要绘制的轮廓索引,color为轮廓颜色,thickness为轮廓线条的粗细。
例如,如果要在一张名为“img”的图像上绘制所有轮廓,可以这样做:
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
这里使用cv2.findContours()函数找到所有轮廓,然后使用cv2.drawContours()函数在原图像上绘制这些轮廓,颜色为绿色,线条粗细为3。
相关问题
cv2.drawContours函数怎么使用
cv2.drawContours函数用于在图像上绘制轮廓。函数的输入参数包括图像、轮廓、轮廓索引、绘制颜色和线宽等。具体使用方法如下:
result = cv2.drawContours(image, contours, contourIdx, color, thickness)
- image:输入的图像,可以是彩色图像或灰度图像。
- contours:轮廓,是一个表示轮廓的列表。
- contourIdx:要绘制的轮廓的索引,-1表示绘制所有的轮廓。
- color:绘制的颜色,可以是RGB元组或灰度值。
- thickness:线的宽度,为正数表示实心线,为负数或0表示绘制轮廓边界。
以下是使用cv2.drawContours函数绘制轮廓的示例代码:
result = cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
可以使用 cv2.drawContours 函数将轮廓绘制到原始图像上
是的,可以使用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:轮廓线条宽度
运行代码后,会将绘制好轮廓的图像显示出来。