### Python 实现图像缩放、平移和翻转的代码示例
以下是使用 Python 和 OpenCV 实现图像缩放、平移和翻转的完整代码示例:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取图片
img = cv2.imread('test.jpg')
src = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 图像缩放
rows, cols = src.shape[:2]
result_resize = cv2.resize(src, (int(cols * 0.6), int(rows * 1.2))) # 缩放比例为宽度0.6,高度1.2
# 图像平移
M_translation = np.float32([[1, 0, 50], [0, 1, 30]]) # 平移矩阵:向右移动50像素,向下移动30像素
result_translation = cv2.warpAffine(src, M_translation, (cols, rows))
# 图像翻转
result_flip_x = cv2.flip(src, 0) # X轴翻转
result_flip_y = cv2.flip(src, 1) # Y轴翻转
result_flip_xy = cv2.flip(src, -1) # X轴和Y轴同时翻转
# 显示结果
titles = ['Source', 'Resize', 'Translation', 'Flip_X', 'Flip_Y', 'Flip_XY']
images = [src, result_resize, result_translation, result_flip_x, result_flip_y, result_flip_xy]
for i in range(6):
plt.subplot(2, 3, i + 1), plt.imshow(images[i])
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
```
#### 代码说明
- **图像缩放**:通过 `cv2.resize` 函数调整图像大小,参数 `(int(cols * 0.6), int(rows * 1.2))` 表示将图像宽度缩小为原来的 60%,高度放大为原来的 120%[^3]。
- **图像平移**:使用 `cv2.warpAffine` 函数结合平移矩阵实现图像平移。平移矩阵 `[[1, 0, 50], [0, 1, 30]]` 表示图像向右移动 50 像素,向下移动 30 像素[^4]。
- **图像翻转**:通过 `cv2.flip` 函数实现图像翻转。参数 `0` 表示以 X 轴为对称轴翻转,`1` 表示以 Y 轴为对称轴翻转,`-1` 表示同时以 X 轴和 Y 轴为对称轴翻转[^2]。
### 注意事项
- 确保安装了 OpenCV 库,可以通过命令 `pip install opencv-python` 安装[^1]。
- 示例中的 `test.jpg` 文件需要替换为实际存在的图像文件路径。