深度学习数据集中进行图像增强py
时间: 2023-10-14 20:06:31 浏览: 43
图像增强是深度学习中常用的一种技术,可以通过对原始图像进行一系列的变换操作,来增加数据集的多样性,提高模型的鲁棒性和泛化能力。下面是一个使用 Python 进行图像增强的示例:
```python
import cv2
import numpy as np
from matplotlib import pyplot as plt
# 读取原始图像
img = cv2.imread('image.jpg')
# 随机水平翻转
if np.random.random() > 0.5:
img = cv2.flip(img, 1)
# 随机垂直翻转
if np.random.random() > 0.5:
img = cv2.flip(img, 0)
# 随机旋转
rows, cols = img.shape[:2]
angle = np.random.randint(-10, 10)
M = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
img = cv2.warpAffine(img, M, (cols, rows))
# 随机裁剪
x1 = np.random.randint(0, cols-100)
x2 = x1 + np.random.randint(100, cols-x1)
y1 = np.random.randint(0, rows-100)
y2 = y1 + np.random.randint(100, rows-y1)
img = img[y1:y2, x1:x2]
# 随机亮度调整
brightness = np.random.randint(-50, 50)
img = cv2.add(img, np.array([brightness]))
# 随机噪声添加
noise = np.zeros(img.shape, np.int8)
cv2.randn(noise, 0, 10)
img = cv2.add(img, noise)
# 显示结果图像
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
```
上述代码实现了随机水平/垂直翻转、随机旋转、随机裁剪、随机亮度调整和随机噪声添加等图像增强操作。可以根据实际需要进行调整和扩展。