opencv将图片旋转一定角度
时间: 2024-11-28 11:13:32 浏览: 32
在OpenCV中,如果你想把一张图片旋转一定角度,可以使用`getRotationMatrix2D`和`warpAffine`这两个函数配合。以下是一个基本步骤:
1. 导入必要的库:
```python
import cv2
from math import degrees
```
2. 加载图片:
```python
img = cv2.imread('your_image.jpg')
```
3. 计算旋转矩阵(`M`),需要知道中心点(通常是图片的中心)和旋转的角度(以弧度为单位):
```python
center = (img.shape[1] // 2, img.shape[0] // 2) # 图片中心
angle_in_degrees = degrees(90) # 要旋转的角度,这里是顺时针90度,你可以替换为你想要的值
angle_in_radians = math.radians(angle_in_degrees)
M = cv2.getRotationMatrix2D(center, angle_in_radians, 1.0) # 缩放因子设为1保持原始大小
```
4. 应用旋转并创建新图像(`rotated_img`):
```python
rotated_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
```
5. 显示或保存旋转后的图片:
```python
cv2.imshow('Rotated Image', rotated_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上就是使用OpenCV进行图像旋转的基本过程。如果你有特定的旋转中心或其他需求,可以根据`getRotationMatrix2D`函数文档做相应调整。
阅读全文
相关推荐

















