基於TensorFlow的圖片數據增強代碼實現

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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章