使用pillow實現tensorflow中的一些影象增強函式(crop,contrast,flip,per_image_standardization)
阿新 • • 發佈:2019-02-06
使用tensorflow自帶的tf.random_crop()、tf.image.random_flip_left_right()、以及random_contrast()等函式處理影象資料時,不僅需要使用session,而且處理速度非常慢。使用Pillow庫完成這些函式介面,在實際資料處理時就非常快速和方便。
#!/usr/bin/env python #-*- coding:utf-8 -*- ############################ #File Name: pic_process_PIL.py #Author: Wang #Mail: @hotmail.com #Created Time:2017-08-14 10:28:14 ############################ from PIL import Image import ImageEnhance import numpy as np from random import randint import random img = Image.open('1.jpg') #print img.format, img.size, img.mode #img.resize((1080,768)) #img.crop((14,14,79,79)).show() #print img.getpixel((1920,1080)) def random_crop(img, width, height): width1 = randint(0, img.size[0] - width ) height1 = randint(0, img.size[1] - height) width2 = width1 + width height2 = height1 + height img = img.crop((width1, height1, width2, height2)) return img def random_flip_left_right(img): prob = randint(0,1) if prob == 1: img = img.transpose(Image.FLIP_LEFT_RIGHT) return img def random_contrast(img, lower = 0.2, upper = 1.8): factor = random.uniform(lower, upper) img = ImageEnhance.Sharpness(img) img = img.enhance(factor) return img def random_brightness(img, lower = 0.6, upper = 1.4): factor = random.uniform(lower, upper) img = ImageEnhance.Brightness(img) img = img.enhance(factor) return img def random_color(img, lower = 0.6, upper = 1.5): factor = random.uniform(lower, upper) img = ImageEnhance.Color(img) img = img.enhance(factor) return img def per_image_standardization(img): '''stat = ImageStat.Stat(img) mean = stat.mean stddev = stat.stddev img = (np.array(img) - stat.mean)/stat.stddev''' if img.mode == 'RGB': channel = 3 num_compare = img.size[0] * img.size[1] * channel img_arr=np.array(img) #img_arr=np.flip(img_arr,2) img_t = (img_arr - np.mean(img_arr))/max(np.std(img_arr), 1/num_compare) return img_t #img = random_crop(img,1000,1000) #img = random_flip_left_right(img) '''img = ImageEnhance.Sharpness(img) img.enhance(5.0).show()''' #img = random_contrast(img, 4,6)
使用時只需匯入這個檔案即可。
關於使用PIL庫做影象增強,這裡有一篇部落格寫的很詳細: