python学习笔记之图像常用增强变换

在进行图像处理的时候,难免会涉及到很多常见的操作,包括图像改变大小、旋转、翻转、平移、对比度变换、添加噪音、颜色扰动、锐化等等。这些操作也常常作为图像扩增的方式。

为了在每次使用时便于快速的进行编码应用,将常用的一些方法总结在此。

#-*- coding:UTF-8 -*-
"""
image enhance : resize \ rotate \ flip \ translation \ add nosise [Gaussian] \ contrast \ sharpness
"""
import skimage.io
import os
import matplotlib.pyplot as plt
from PIL import Image,ImageEnhance,ImageChops
import random
import numpy as np 

def ImgResize(root_path,img_name,ScaleFactor,result_dir):
    """
    按比例(保持长宽比)进行尺寸调整
    """
    Img = Image.open(os.path.join(root_path, img_name))
    ImgSize = Img.size
    NewSize = [int(ImgSize[0]*ScaleFactor),int(ImgSize[1]*ScaleFactor)]
    Img = Img.resize(NewSize)   
    Img.save(os.path.join(result_dir,img_name.split('.')[0] + '_resize_ratio.jpg'))
    return Img       

def ImgResizeTo(root_path,img_name,NewSize,result_dir):
    """
    按指定大小进行尺寸调整
    """
    Img = Image.open(os.path.join(root_path, img_name))
    Img = Img.resize(NewSize)    
    Img.save(os.path.join(result_dir,img_name.split('.')[0] + '_resize.jpg'))
    return Img     

def ImgRotate(root_path,img_name,result_dir,Degree=25):
    """
    旋转
    """
    Img = Image.open(os.path.join(root_path, img_name))
    Img = Img.rotate(Degree)
    Img.save(os.path.join(result_dir,img_name.split('.')[0] + '_rotate.jpg'))
    return Img

def ImgLRMirror(root_path,img_name,result_dir):
    """
    水平镜像
    """
    Img = Image.open(os.path.join(root_path, img_name))
    Img = Img.transpose(Image.FLIP_LEFT_RIGHT)
    Img.save(os.path.join(result_dir,img_name.split('.')[0] + '_flip_lr.jpg'))
    return Img

def ImgTBMirror(root_path,img_name,result_dir):
    """
    垂直镜像
    """
    Img = Image.open(os.path.join(root_path, img_name))
    Img = Img.transpose(Image.FLIP_TOP_BOTTOM)
    Img.save(os.path.join(result_dir,img_name.split('.')[0] + '_flip_tb.jpg'))
    return Img

def ImgOfffSet(root_path,img_name,result_dir,xoff=20,yoff=20,):
    """
    平移
    xoff:水平平移距离
    yoff:垂直平移距离
    """
    Img = Image.open(os.path.join(root_path, img_name))
    width, height = Img.size
    c = ImageChops.offset(Img,xoff,yoff)
    c.paste((0,0,0),(0,0,xoff,height))
    c.paste((0,0,0),(0,0,width,yoff))
    c.save(os.path.join(result_dir,img_name.split('.')[0] + '_offset.jpg'))
    return c

def aj_contrast(root_path,img_name,result_dir): 
    """
    调整对比度 两种方式 gamma/log
    """
    image = skimage.io.imread(os.path.join(root_path, img_name))
    gam= skimage.exposure.adjust_gamma(image, 0.5)
    # skimage.io.imsave(os.path.join(result_dir,img_name.split('.')[0] + '_gam.jpg'),gam)
    log= skimage.exposure.adjust_log(image)
    skimage.io.imsave(os.path.join(result_dir,img_name.split('.')[0] + '_log.jpg'),log)
    return gam,log

def randomGaussian(root_path, img_name,result_dir, mean=0, sigma=25,):  
    """
    高斯噪声
    """
    image = Image.open(os.path.join(root_path, img_name))
    im = np.array(image)
    #r通道
    r = im[:,:,0].flatten()
    g = im[:,:,1].flatten()
    b = im[:,:,2].flatten()

    #计算新的像素值
    for i in range(im.shape[0]*im.shape[1]):

        pr = int(r[i]) + random.gauss(0,sigma)

        pg = int(g[i]) + random.gauss(0,sigma)

        pb = int(b[i]) + random.gauss(0,sigma)

        if(pr < 0):
            pr = 0
        if(pr > 255):
            pr = 255
        if(pg < 0):
            pg = 0
        if(pg > 255):
            pg = 255
        if(pb < 0):
            pb = 0
        if(pb > 255):
            pb = 255
        r[i] = pr
        g[i] = pg
        b[i] = pb
    im[:,:,0] = r.reshape([im.shape[0],im.shape[1]])

    im[:,:,1] = g.reshape([im.shape[0],im.shape[1]])

    im[:,:,2] = b.reshape([im.shape[0],im.shape[1]])
    gaussian_image = Image.fromarray(np.uint8(im))
    gaussian_image.save(os.path.join(result_dir,img_name.split('.')[0] + '_gaussian.jpg'))
    return gaussian_image

def randomColor(root_path, img_name,result_dir): #随机颜色
    """
    对图像进行颜色抖动
    :param image: PIL的图像image
    :return: 有颜色色差的图像image
    """
    image = Image.open(os.path.join(root_path, img_name))
    random_factor = np.random.randint(0, 31) / 10.  # 随机因子
    color_image = ImageEnhance.Color(image).enhance(random_factor)  # 调整图像的饱和度
    random_factor = np.random.randint(10, 21) / 10.  # 随机因子
    brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor)  # 调整图像的亮度
    random_factor = np.random.randint(10, 21) / 10.  # 随机因子
    contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor)  # 调整图像对比度
    random_factor = np.random.randint(0, 31) / 10.  # 随机因子
    sharp_image = ImageEnhance.Sharpness(contrast_image).enhance(random_factor) # 调整图像锐度
    # color_image.save(os.path.join(result_dir,img_name.split('.')[0] + '_color.jpg'))
    # brightness_image.save(os.path.join(result_dir,img_name.split('.')[0] + '_bright.jpg'))
    # contrast_image.save(os.path.join(result_dir,img_name.split('.')[0] + '_contrast.jpg'))
    sharp_image.save(os.path.join(result_dir,img_name.split('.')[0] + '_sharp.jpg'))
    return  color_image,brightness_image,contrast_image,sharp_image

if __name__ == "__main__":
    image_dir = '/home/study/data/query'  # image source dir path
    result_dir = '/home/study/data/image' # result dir path 
    for img in os.listdir(image_dir):
        ImgRotate(image_dir,img,result_dir,20)
        ImgLRMirror(image_dir,img,result_dir) 
        ImgTBMirror(image_dir,img,result_dir)
        x = random.randrange(20,100)
        y = random.randrange(20,100)
        ImgOfffSet(image_dir,img,result_dir,x,y)
        aj_contrast(image_dir,img,result_dir)
        randomGaussian(image_dir,img,result_dir)
        randomColor(image_dir,img,result_dir)

代码在撰写时借鉴了一些网上的资料,侵删,谢谢。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章