opencv旋转图片python
时间: 2024-10-11 19:16:05 浏览: 67
在Python中使用OpenCV库旋转图片,你可以通过`cv2.getRotationMatrix2D()`和`cv2.warpAffine()`函数来实现。这两个函数分别用于计算旋转矩阵和应用旋转到图像上。以下是基本步骤:
1. 导入必要的库:
```python
import cv2
import numpy as np
```
2. 加载图片:
```python
image = cv2.imread('your_image_path.jpg')
```
3. 定义旋转中心、角度和缩放比例(如果需要)。例如,假设旋转角度为90度,并且想要保持原始尺寸:
```python
center = (image.shape[1] // 2, image.shape[0] // 2) # 图像中心点
angle = 90 # 角度,单位是度
scale = 1 # 缩放比例,通常设置为1保持原始大小
```
4. 计算旋转矩阵:
```python
rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)
```
5. 应用旋转并调整结果尺寸:
```python
rotated_image = cv2.warpAffine(image, rotation_matrix, image.shape[:2])
```
6. 可选地,保存旋转后的图片:
```python
cv2.imwrite('rotated_image_path.jpg', rotated_image)
```
相关问题
opencv旋转矩阵 python
### Python OpenCV 旋转矩阵实现方法
在Python中使用OpenCV实现旋转矩阵的操作主要依赖于`cv2.getRotationMatrix2D()`和`cv2.warpAffine()`两个函数。以下是详细的说明:
#### 函数介绍
1. **`cv2.getRotationMatrix2D(center, angle, scale)`**
- `center`: 图像旋转中心的坐标,通常设置为图像的几何中心 `(width/2, height/2)`。
- `angle`: 顺时针方向的角度值。如果要逆时针旋转,则输入负角度。
- `scale`: 缩放比例因子,控制旋转后的图像大小变化。
此函数返回一个 \(2 \times 3\) 的浮点型数组,表示旋转变换矩阵[^1]。
2. **`cv2.warpAffine(src, M, dsize)`**
- `src`: 输入图像。
- `M`: 变换矩阵(由`getRotationMatrix2D`生成)。
- `dsize`: 输出图像的尺寸,通常是原图像的宽度和高度 `(width, height)`。
这个函数应用仿射变换矩阵到输入图像上,完成旋转操作[^2]。
#### 示例代码
下面是一个完整的示例程序,展示如何使用上述函数实现图像旋转:
```python
import cv2
import numpy as np
# 加载原始图像
image = cv2.imread('example.jpg')
# 获取图像的高度和宽度
height, width = image.shape[:2]
# 定义旋转中心、角度和缩放比例
rotation_center = (width / 2, height / 2) # 中心点
rotation_angle = 45 # 旋转角度
scaling_factor = 1.0 # 缩放比例
# 计算旋转矩阵
rotation_matrix = cv2.getRotationMatrix2D(rotation_center, rotation_angle, scaling_factor)
# 应用仿射变换进行旋转
rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))
# 显示结果
cv2.imshow('Original Image', image)
cv2.imshow('Rotated Image', rotated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
此代码片段展示了如何加载一张图片并对其进行指定角度的旋转操作。
#### 数学原理
对于任意像素位置 \((x, y)\),其经过旋转后的目标位置可以通过如下公式计算得出:
\[ x' = (x - c_x) \cdot \cos(\theta) - (y - c_y) \cdot \sin(\theta) + c_x \]
\[ y' = (x - c_x) \cdot \sin(\theta) + (y - c_y) \cdot \cos(\theta) + c_y \]
其中,\((c_x, c_y)\) 是旋转中心,\(\theta\) 表示旋转角弧度制形式[^5]。
---
###
写出python opencv旋转图片代码
以下是 Python OpenCV 旋转图片的代码:
```python
import cv2
# 读取图片
img = cv2.imread('image.jpg')
# 获取图片的高度和宽度
(h, w) = img.shape[:2]
# 计算旋转中心点的坐标
center = (w // 2, h // 2)
# 定义旋转角度
angle = 45
# 定义缩放比例
scale = 1.0
# 获取旋转矩阵
M = cv2.getRotationMatrix2D(center, angle, scale)
# 执行旋转操作
rotated = cv2.warpAffine(img, M, (w, h))
# 显示旋转后的图片
cv2.imshow("Rotated Image", rotated)
cv2.waitKey(0)
```
希望这个代码能够帮到你!
阅读全文
相关推荐
















