使用pillow实现tensorflow中的一些图像增强函数(crop,contrast,flip,per_image_standardization)

来源:互联网 发布:移动adhoc网络的特点 编辑:程序博客网 时间:2024/06/14 06:42

使用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 Imageimport ImageEnhanceimport numpy as npfrom random import randintimport randomimg = 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 imgdef random_flip_left_right(img):    prob = randint(0,1)    if prob == 1:        img = img.transpose(Image.FLIP_LEFT_RIGHT)    return imgdef random_contrast(img, lower = 0.2, upper = 1.8):    factor = random.uniform(lower, upper)    img = ImageEnhance.Sharpness(img)    img = img.enhance(factor)    return imgdef random_brightness(img, lower = 0.6, upper = 1.4):    factor = random.uniform(lower, upper)    img = ImageEnhance.Brightness(img)    img = img.enhance(factor)    return imgdef random_color(img, lower = 0.6, upper = 1.5):    factor = random.uniform(lower, upper)    img = ImageEnhance.Color(img)    img = img.enhance(factor)    return imgdef 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库做图像增强,这里有一篇博客写的很详细:

http://www.cnblogs.com/txw1958/archive/2012/02/21/python3-PIL.html


原创粉丝点击