在做深度学习工作时,有时数据集数量不够,势必要进行数据增强,一些框架如tensorflow、keras、pytorch也提供了相应的API用于数据增强。
keras中的tf.keras.preprocessing.image.ImageDataGenerator
使用实时数据增强生成批量张量图像数据。这里给出API整体:
tf.keras.preprocessing.image.ImageDataGenerator(
featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
zca_epsilon=1e-06,
rotation_range=0,
width_shift_range=0.0,
height_shift_range=0.0,
brightness_range=None,
shear_range=0.0,
zoom_range=0.0,
channel_shift_range=0.0,
fill_mode="nearest",
cval=0.0,
horizontal_flip=False,
vertical_flip=False,
rescale=None,
preprocessing_function=None,
data_format=None,
validation_split=0.0,
dtype=None,
)
具体使用方法,请参考Keras官网 图像数据预处理
除了使用上面API外,我们也可以使用OpenCV中的函数cv2.flip
进行处理。
语法结构:dst = cv2.flip(src, flipcode)
,其中src表示要处理的图像,flipCode表示旋转类型。
flipcode参数意义如下表:
参数值 | 说明 | 意义 |
---|---|---|
0 | 只能是0 | 绕x轴翻转 |
正数 | 1,2,3 等任意整数 | 绕y轴翻转 |
负数 | -1,-2,-3 等任意负数 | 绕x、y轴同时翻转 |
代码实现:
import cv2
import os
import numpy as np
def read_path(file_pathname):
for filename in os.listdir(file_pathname):
filename = filename
print(filename)
img = cv2.imread(file_pathname+'/'+filename)
imageR1p0 = cv2.flip(img, 0)
cv2.imwrite(r"C:\Users\Wxr\Desktop\2" + "/" + filename, imageR1p0)
read_path(r"C:\Users\Wxr\Desktop\1")
对flipcode参数更改后,得到的翻转图像如下图:
分别是:原图,绕x轴翻转,绕y轴翻转,绕x,y轴同时翻转。