python opencv实现旋转矩形框裁减功能
时间: 2024-11-18 21:26:58 浏览: 26
python opencv实现旋转矩形框裁减功能.pdf
在Python的OpenCV库中,实现旋转矩形框裁减功能通常涉及到图像几何变换,特别是仿射变换。这里是一个简单的步骤描述:
1. 导入必要的库:
```python
import cv2
import numpy as np
```
2. 加载原始图片并读取矩形框信息:
```python
img = cv2.imread('image.jpg')
x, y, w, h = (rotated_rectangle_center_x, rotated_rectangle_center_y, width, height) # 矩形中心坐标和尺寸
angle = rotated_rectangle_angle # 旋转角度,单位通常是度
```
3. 创建旋转矩阵 `M`:
```python
center = (x, y)
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0) # 使用旋转中心、角度和缩放比例(这里是1保持大小不变)
```
4. 计算新矩形的边界:
```python
new_w, new_h = int(w * abs(np.cos(angle)) + h * abs(np.sin(angle))), int(h * abs(np.cos(angle)) + w * abs(np.sin(angle)))
rotated_box = (
int(center[0] - new_w / 2), # 新的左上角X
int(center[1] - new_h / 2) # 新的左上角Y
)
```
5. 应用旋转变换:
```python
rotated_img = cv2.warpAffine(img, rotation_matrix, (new_w, new_h))
```
6. 裁剪出旋转后的矩形:
```python
cropped_rect = img[rotated_box[1]:rotated_box[1]+new_h, rotated_box[0]:rotated_box[0]+new_w]
```
7. 显示结果或保存图片:
```python
cv2.imshow("Rotated rectangle", cropped_rect)
cv2.waitKey(0) # 等待用户按键
cv2.destroyAllWindows()
```
阅读全文