Python 封装图像增强,想用什么增强方式直接指定

# -*- coding:utf-8 -*-
from PIL import Image,ImageEnhance
import os
import shutil

# 亮度增强
def Enhance_Brightness(image,options):
    brightness = float(options)
    image_bri = ImageEnhance.Brightness(image).enhance(brightness)
    return image_bri

# 颜色均衡
def Enhance_Color(image,options):
    color = float(options)
    image_color = ImageEnhance.Color(image).enhance(color)
    return image_color

# 对比度增强
def Enhance_Contrast(image,options):
    enh_con = ImageEnhance.Contrast(image)
    contrast = float(options)
    image_contrasted = enh_con.enhance(contrast)
    return image_contrasted

# 锐度增强
def Enhance_Sharpness(image,options):
    enh_sha = ImageEnhance.Sharpness(image)
    sharpness = float(options)
    image_sharped = enh_sha.enhance(sharpness)
    return image_sharped

# train_data_path参数是需要增强的图片路径
# enhance_options参数是需要增强的方式,我做的项目环境在网络通信上,所以会有这种写法,完全可以改成本地的。格式例如:[{'code':'contrast','num':1.2},{{'code':'sharpness','num':1.2}}],指定了两种增强方式。
def img_enhance_and_save_train_path(train_data_path, enhance_options):
    try:
        # 我的目录在/home/xxx/train_data_path/img下所以这么写了。
        # image_path = os.path.join(train_data_path, 'img')
        image_path = train_data_path
        all_images = [os.path.join(image_path, fileName) for fileName in os.listdir(image_path)]
        enhance_list = {'contrast': Enhance_Contrast,
                        'sharpness': Enhance_Sharpness,
                        'brightness': Enhance_Brightness,
                        'color': Enhance_Color}
        for i, image in enumerate(all_images):
            image_bri = Image.open(image)
            #可以一次配合多种增强方式。
       #mg_option['code']当时我的坏境是个json,例如{'code':'contrast'}
            #img_option['num'] 也是个json,例如{'num':1.2}
            for img_option in enhance_options:
                method_due, option_num = img_option['code'], img_option['num']
                image_bri = enhance_list[method_due](image_bri, option_num)
                # print('img enhance method is {}'.format(img_option['code']))
            image_name = os.path.basename(image).split('.')[0] + '_enhance.jpg'
            image_bri.save(os.path.join(image_path, image_name))
            box_name = os.path.basename(image).split('.')[0] + '.box'
            enhance_box_name = os.path.basename(image).split('.')[0] + '_enhance.box'
            shutil.copyfile(os.path.join(train_data_path, 'box', box_name),
                            os.path.join(train_data_path, 'box', enhance_box_name))
            print('Begin {}/{},Current Image is {}.'.format(i+1,len(all_images),image_name))
    except:
        print('Enhance images Error,Please Input Correct Enhance Option Value,must be float ')

你可能感兴趣的:(图像增强)