1. 程式人生 > >基於TensorFlow批量的隨機處理圖片,實現影象增強

基於TensorFlow批量的隨機處理圖片,實現影象增強

最近在做機器學習相關的專案。由於資料量不夠,需要進行資料增強。TensorFlow它當中自帶影象處理的介面。使我們能夠很輕鬆的完成這些任務。你也可以在我的程式碼基礎上。加上一些其他的影象處理的功能。比其他的影象處理的庫要稍微簡單一點。

"""author:youngkun data:20180618 function:image enhancement"""
import tensorflow as tf
import os
import random

source_file="./0/"       #原始檔案地址
target_file="./test2/"  #修改後的檔案地址
num=50                  #產生圖片次數

if not os.path.exists(target_file):  #如果不存在target_file,則創造一個
    os.makedirs(target_file)

file_list=os.listdir(source_file)   #讀取原始檔案的路徑

with tf.Session() as sess:
    for i in range(num):

        max_random=len(file_list)-1
        a = random.randint(1, max_random)          #隨機數字區間
        image_raw_data=tf.gfile.FastGFile(source_file+file_list[a],"rb").read()#讀取圖片
        print("正在處理:",file_list[a])
        image_data=tf.image.decode_jpeg(image_raw_data)

        filpped_le_re=tf.image.random_flip_left_right(image_data)   #隨機左右翻轉

        filpped_up_down=tf.image.random_flip_up_down(image_data)    #隨機上下翻轉

        adjust=tf.image.random_brightness(filpped_up_down,0.4)      #隨機調整亮度

        image_data=tf.image.convert_image_dtype(adjust,dtype=tf.uint8)

        encode_data=tf.image.encode_jpeg(image_data)

        with tf.gfile.GFile(target_file+str(i)+"_enhance"+".jpeg","wb") as f:
            f.write(encode_data.eval())
print("影象增強完畢")