图像数据增强python代码
时间: 2023-10-12 16:16:23 浏览: 39
以下是一个基本的图像数据增强的Python代码示例:
```python
import cv2
import numpy as np
import random
# 加载图像
img = cv2.imread('image.jpg')
# 随机旋转
rows, cols = img.shape[:2]
angle = random.randint(-30, 30)
M = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
img = cv2.warpAffine(img, M, (cols, rows))
# 随机缩放
scale = random.uniform(0.7, 1.3)
rows, cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols/2, rows/2), 0, scale)
img = cv2.warpAffine(img, M, (cols, rows))
# 随机平移
tx = random.randint(-50, 50)
ty = random.randint(-50, 50)
M = np.float32([[1, 0, tx], [0, 1, ty]])
img = cv2.warpAffine(img, M, (cols, rows))
# 随机反转
flip = random.randint(0, 1)
if flip == 1:
img = cv2.flip(img, 1)
# 随机添加噪声
noise = np.zeros(img.shape, np.uint8)
cv2.randn(noise, 0, 50)
img = cv2.add(img, noise)
# 显示结果
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
该代码实现了以下数据增强操作:
- 随机旋转
- 随机缩放
- 随机平移
- 随机反转
- 随机添加噪声
使用该代码可以对图像进行数据增强,增加模型的训练数据,提高模型的泛化能力。