图像数据增强python代码
时间: 2023-10-12 19:19:01 浏览: 84
以下是一个基于Python和OpenCV库的图像数据增强代码示例:
```python
import cv2
import numpy as np
# 图像旋转
def rotate(image, angle):
# 获取图像尺寸
(h, w) = image.shape[:2]
# 计算旋转中心点
center = (w // 2, h // 2)
# 获取旋转矩阵
M = cv2.getRotationMatrix2D(center, angle, 1.0)
# 执行旋转
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
# 水平翻转
def flip(image, axis):
flipped = cv2.flip(image, axis)
return flipped
# 随机裁剪
def random_crop(image, size):
# 获取图像尺寸
(h, w) = image.shape[:2]
# 计算裁剪范围
x = np.random.randint(0, w - size[1])
y = np.random.randint(0, h - size[0])
# 执行裁剪
cropped = image[y:y + size[0], x:x + size[1]]
return cropped
# 随机亮度调整
def random_brightness(image, alpha=1.0, beta=0.0):
# 执行亮度调整
adjusted = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
return adjusted
```
这些函数可以进行图像旋转、水平翻转、随机裁剪和随机亮度调整等数据增强操作,具体使用方法可以参考以下示例代码:
```python
# 加载图像
image = cv2.imread('test.jpg')
# 旋转图像
rotated = rotate(image, 30)
# 水平翻转
flipped = flip(image, 1)
# 随机裁剪
cropped = random_crop(image, (200, 200))
# 随机亮度调整
adjusted = random_brightness(image, alpha=1.5, beta=0)
# 显示图像
cv2.imshow('Original', image)
cv2.imshow('Rotated', rotated)
cv2.imshow('Flipped', flipped)
cv2.imshow('Cropped', cropped)
cv2.imshow('Adjusted', adjusted)
cv2.waitKey()
cv2.destroyAllWindows()
```
阅读全文