opencv绘制多个轮廓矩形
时间: 2023-07-07 10:34:40 浏览: 363
要绘制多个轮廓矩形,可以使用 OpenCV 中的 `cv2.rectangle()` 函数。该函数可以接受多组坐标参数,分别绘制多个矩形。具体的步骤如下:
1. 读入图像并进行预处理,找到轮廓。
```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)
```
2. 循环绘制矩形。
```python
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.rectangle()` 函数绘制矩形。函数的参数分别是图像、左上角坐标、右下角坐标、颜色、线宽。
最后,可以使用 `cv2.imshow()` 函数显示绘制好的图像。
```python
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文
相关推荐















