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)

代碼在撰寫時借鑑了一些網上的資料,侵刪,謝謝。

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