图像数据增强函数 - Python 实现
图像数据增强函数
import numpy as np
from scipy import ndimage
import cv2
def data_augmentation(image):
# 随机旋转
angle = np.random.randint(-10, 10)
image = ndimage.rotate(image, angle, reshape=False)
# 随机平移
t_x, t_y = np.random.randint(-10, 10, size=(2,))
rows, cols = image.shape
M = np.float32([[1, 0, t_x], [0, 1, t_y]])
image = cv2.warpAffine(image, M, (cols, rows))
# 随机裁剪
x1, y1 = np.random.randint(0, 10, size=(2,))
x2, y2 = np.random.randint(20, 30, size=(2,))
image = image[x1:x2, y1:y2]
# 随机翻转
flip = np.random.randint(0, 2)
if flip == 1:
image = np.fliplr(image)
# 随机色彩变化
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hue_shift = np.random.randint(0, 50)
hsv[:, :, 0] = (hsv[:, :, 0] + hue_shift) % 180
sat_shift = np.random.randint(0, 50)
hsv[:, :, 1] = np.clip(hsv[:, :, 1] + sat_shift, 0, 255)
val_shift = np.random.randint(0, 50)
hsv[:, :, 2] = np.clip(hsv[:, :, 2] + val_shift, 0, 255)
image = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return image
使用方法:
# 加载图像
image = cv2.imread('image.jpg')
# 进行数据增强
augmented_image = data_augmentation(image)
# 显示增强后的图像
cv2.imshow('Augmented Image', augmented_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
注意:
cv2.COLOR_BGR2HSV和cv2.COLOR_HSV2BGR用于在 BGR 和 HSV 颜色空间之间转换。np.clip用于将饱和度和亮度值限制在 0 到 255 之间。- 可以根据需要调整数据增强参数,例如旋转角度、平移量、裁剪区域等。
示例:
以下是使用该函数进行数据增强后的示例图像:
[示例图像]
更多信息:
原文地址: https://www.cveoy.top/t/topic/mQav 著作权归作者所有。请勿转载和采集!