如何用cv2将封闭图像框出来并将直角框的角的坐标和框的大小排名打印出来
时间: 2024-03-23 15:42:01 浏览: 96
可以使用cv2.findContours和cv2.minAreaRect方法来框出封闭图像并获取直角框的角的坐标和框的大小,具体的步骤如下:
1. 读取图像并将其转换为灰度图像
```python
import cv2
img = cv2.imread('image_path')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
2. 对灰度图像进行二值化
```python
threshold_value = 127
max_value = 255
ret, binary = cv2.threshold(gray, threshold_value, max_value, cv2.THRESH_BINARY)
```
3. 查找图像中的轮廓
```python
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
```
4. 遍历轮廓并绘制矩形框
```python
rects = []
for contour in contours:
rect = cv2.minAreaRect(contour)
rects.append(rect)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
```
5. 计算矩形框的大小和角的坐标并按照大小排名打印输出
```python
for i, rect in enumerate(sorted(rects, key=lambda x: x[1][0] * x[1][1], reverse=True)):
print(f'Rank {i+1}: Size={rect[1][0]*rect[1][1]:.2f}, TopLeft={rect[0]}, Width={rect[1][0]:.2f}, Height={rect[1][1]:.2f}, Angle={rect[2]:.2f}')
```
完整代码如下:
```python
import cv2
import numpy as np
img = cv2.imread('image_path')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshold_value = 127
max_value = 255
ret, binary = cv2.threshold(gray, threshold_value, max_value, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rects = []
for contour in contours:
rect = cv2.minAreaRect(contour)
rects.append(rect)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
for i, rect in enumerate(sorted(rects, key=lambda x: x[1][0] * x[1][1], reverse=True)):
print(f'Rank {i+1}: Size={rect[1][0]*rect[1][1]:.2f}, TopLeft={rect[0]}, Width={rect[1][0]:.2f}, Height={rect[1][1]:.2f}, Angle={rect[2]:.2f}')
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文