TensorFlow常用的数据增强主要分为3部分:裁剪、翻转、变色
另外还可以用过opencv实现图片的旋转 和 仿射变换
第一部分裁剪:
(1)如果目标图像尺寸小于原始图像尺寸,则在中心位置剪裁,反之则用黑色像素进行填充。
image = tf.image.resize_image_with_crop_or_pad(img, target_height, target_width)
(2)在图片随机裁剪一块
image = tf.random_crop(img, [target_height, target_width, img_channel])
(3)在图片规定位置处裁剪
image = tf.image.crop_to_bounding_box(image,offset_height,offset_width,target_height,target_width)
其中:返回图像的左上角位于image的offset_height, offset_width, 右下角处于offset_height + target_height, offset_width + target_width.
第二部分翻转:
(1)通过交换高度和宽度维度来转置图像
image = tf.image.transpose_image(img)
(2)左右翻转
image = tf.image.flip_left_right(img)
(3)上下翻转
image = tf.image.flip_up_down(img)
(4)随机左右翻转
image = tf.image.random_flip_left_right(img)
第三部分变色:
tf.image.adjust_contrast() 对比度
tf.image.adjust_gamma() gamma
tf.image.adjust_hue() 色相
tf.image.adjust_saturation() 饱和度
PS:
# 标准化 将图像的像素值转化成零均值和单位方差
standardization = tf.image.per_image_standardization(img_data)
import os
import cv2
import numpy as np
import tensorflow as tf
data_path = os.path.join('augment_test', 'ICVF')
all_dir = os.listdir(data_path) # 返回指定的文件夹包含的文件或文件夹的名字的列表
num = 0
with tf.Session() as sess:
for dir in all_dir:
dir_path = os.path.join(data_path, dir) # 这种写法适合多分类问题,有很多文件夹
img_list = os.listdir(dir_path) # 得到单个子文件夹里所有的图片名字
for img_name in img_list: # 开始对每个图片开始操作
img_name_split = img_name.split('.') # 只留下图片的名字,为后期重命名做准备
img_path = os.path.join(dir_path, img_name) # 把地址对准到单个图片的地址
img = cv2.imread(img_path)
num = num + 1
image1 = tf.image.flip_left_right(img)
image2 = tf.image.flip_up_down(img)
image3 = tf.image.resize_image_with_crop_or_pad(img, 80, 80)
image1 = np.asarray(image1.eval(), dtype='uint8')
image2 = np.asarray(image2.eval(), dtype='uint8')
image3 = np.asarray(image3.eval(), dtype='uint8')
save_path_image1 = os.path.join(dir_path, img_name_split[0] + '_image1' + '.bmp')
save_path_image2 = os.path.join(dir_path, img_name_split[0] + '_image2' + '.bmp')
save_path_image3 = os.path.join(dir_path, img_name_split[0] + '_image3' + '.bmp')
cv2.imwrite(save_path_image1, image1)
cv2.imwrite(save_path_image2, image2)
cv2.imwrite(save_path_image3, image3)