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


使用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库做图像增强,这里有一篇博客写的很详细:

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