opencv画出最小外接矩形
时间: 2023-10-20 07:07:10 浏览: 267
可以使用OpenCV中的函数`minAreaRect()`来画出最小外接矩形。具体步骤如下:
1. 读入图像并进行灰度化和二值化处理。
2. 使用`findContours()`函数找到图像中的轮廓。
3. 对每个轮廓,使用`minAreaRect()`函数计算其最小外接矩形。
4. 使用`drawContours()`函数画出轮廓,并使用`rectangle()`函数画出最小外接矩形。
下面是一个示例代码:
```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)
# 画出轮廓和最小外接矩形
for cnt in contours:
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)
cv2.drawContours(img,[cnt],0,(255,0,0),2)
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文
相关推荐


















