寻找二值化图中的矩形框
时间: 2023-07-30 20:06:20 浏览: 81
寻找二值化图像中的矩形框可以使用 `cv2.findContours()` 函数来查找轮廓,然后使用 `cv2.boundingRect()` 函数来获取轮廓的外接矩形。以下是示例代码:
```python
import cv2
# 加载图像并转换为灰度图像
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 阈值化操作,将图像转换为二值图像
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 查找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 获取轮廓的外接矩形
rectangles = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
rectangles.append((x, y, w, h))
# 在图像中绘制矩形框
for x, y, w, h in rectangles:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow('Rectangles', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个示例代码中,我们使用了红色的框来绘制矩形框,你可以根据实际情况进行调整。