python使用cv2库旋转图像,保持图像大小不变
时间: 2023-07-14 21:13:31 浏览: 55
可以使用cv2.warpAffine函数来实现图像旋转,同时保持图像大小不变。具体的实现步骤如下:
1. 计算图像中心点坐标
```python
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
```
2. 构造旋转矩阵
```python
M = cv2.getRotationMatrix2D(center, angle, scale=1.0)
```
其中,angle是旋转角度,scale是缩放比例(默认为1.0)。
3. 对图像进行旋转
```python
rotated = cv2.warpAffine(image, M, (w, h))
```
这里的输出rotated即为旋转后的图像,它的大小与原图像相同。
完整代码如下:
```python
import cv2
# 加载图像
image = cv2.imread("image.jpg")
# 计算中心点坐标
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
# 构造旋转矩阵
angle = 45
M = cv2.getRotationMatrix2D(center, angle, scale=1.0)
# 对图像进行旋转
rotated = cv2.warpAffine(image, M, (w, h))
# 显示旋转后的图像
cv2.imshow("Rotated Image", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
```