python opencv draw numpy contours
时间: 2023-11-12 13:06:13 浏览: 125
要在 OpenCV 中使用 Numpy 数组绘制轮廓,可以按照以下步骤进行:
1. 读取图像并将其转换为灰度图像。
2. 对灰度图像进行二值化处理。
3. 使用 `cv2.findContours()` 函数查找轮廓。
4. 通过 `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)
# 绘制所有轮廓的外接矩形
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示图像
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例中,我们首先将图像转换为灰度图像,然后使用 `cv2.threshold()` 函数进行二值化处理。接下来,我们使用 `cv2.findContours()` 函数查找轮廓,返回轮廓的数组和它们的层次结构。最后,我们遍历轮廓数组,使用 `cv2.boundingRect()` 函数获取每个轮廓的外接矩形,并使用 `cv2.rectangle()` 函数绘制矩形。最终,使用 `cv2.imshow()` 函数显示图像。
阅读全文
相关推荐


















