數據增強方法及代碼

參考鏈接

【技術綜述】一文道盡深度學習中的數據增強方法(上) - 簡書
https://www.jianshu.com/p/99450dbdadcf

【技術綜述】一文道盡深度學習中的數據增強方法(下) - 簡書
https://www.jianshu.com/p/661221525139

Image Data Processing - 江冬的博客 | JD Blog
http://www.jiangdongzml.com/2018/03/16/Image_Data_Processing/

圖像數據增強 - 代碼片段 - 碼雲 Gitee.com
https://gitee.com/hamjarl/codes/yl7q9g4bhv61ej2i8pnu319

tensorflow實現數據增強(隨機裁剪、翻轉、對比度設置、亮度設置) - 修煉之路 - CSDN博客
https://blog.csdn.net/sinat_29957455/article/details/80629098

Data Augmentation–數據增強解決你有限的數據集 - chang_rj的博客 - CSDN博客
https://blog.csdn.net/u010801994/article/details/81914716

摘要

本文主要針對tensorflow和PIL的數據增強方法做一個總結,所有代碼來源於互聯網。

部分方式的代碼,真的是各種沒有。

如果有大量數據增強方法需求的小夥伴,可以用這個【技術綜述】一文道盡深度學習中的數據增強方法(上) - 簡書博客提到的插件aleju/imgaug: Image augmentation for machine learning experiments來使用更多數據增強方法,這個插件功能非常強大,在此就不贅述了。

什麼是數據增強

Data Augmentation,基於有限的數據生成更多等價(同樣有效)的數據,豐富訓練數據的分佈,使通過訓練集得到的模型泛化能力更強。

舉個例子:

img

上面的左側大圖爲原圖,右側小圖是對左圖做了一些隨機的裁剪、縮放、旋轉操作得來的。

右邊的每張圖對於網絡來說都是不同的輸入,這樣就將數據擴充到10倍。

假如我們輸入網絡的圖片的分辨率大小是256×256,若採用隨機裁剪成224×224的方式,那麼一張圖最多可以產生32×32張圖,數據量擴充將近1000倍。

但因許多圖相似度太高,實際的效果並不等價。

如果再輔助其他的數據增強方法,將獲得更多的數據集,這就是數據增強的本質。

空間幾何變換類

import matplotlib.pyplot as plt
# tensorflow
import tensorflow as tf

image_raw_data=tf.gfile.FastGFile(img_path,'rb').read()
img_data=tf.image.decode_jpeg(image_raw_data)
# PIL
from PIL import Image,ImageChops,ImageEnhance

img_data = Image.open(img_path)

翻轉(Flip)

翻轉包括水平翻轉、垂直翻轉和對角線翻轉。

with tf.Session() as sess:
    # tensorflow
    flipped1=tf.image.flip_left_right(img_data)
    flipped2=tf.image.flip_up_down(img_data)
    transpose_img=tf.image.transpose_image(img_data)
    # PIL
    flipped1=Image.FLIP_LEFT_RIGHT(img_data)
    flipped2=Image.FLIP_UP_DOWN(img_data)
    transpose_img=Image.TRANSPOSE(img_data)    
    
    for i,img in enumerate([img_data,flipped1,flipped2,transpose_img]):
        plt.subplot(1,4,i+1)
        plt.tight_layout()
        plt.imshow(img.eval())
    plt.show()

[外鏈圖片轉存失敗(img-GG6HRltC-1562401382764)(數據增強.assets/1562328431016.png)]

裁剪(crop)

裁剪圖片的感興趣區域(ROI),通常在訓練的時候,會採用隨機裁剪的方法。

    # tensorflow
    img = tf.image.random_crop(img_data, [400, 600, 3])
    # tf.image.central_crop(image,0.5) 按比例裁剪
    
    with tf.Session() as sess:
        img = sess.run(img)
        plt.subplot(1,2,1)
        plt.imshow(img)
        plt.title("tensorflow")
    
    # PIL
    img = img_data.crop((200, 100, 800, 500))  # 參數爲座標左上右下
    plt.subplot(1, 2, 2)
    plt.imshow(img)
    plt.title("PIL")
    plt.show()

[外鏈圖片轉存失敗(img-qQmlk2ks-1562401382764)(數據增強.assets/1562333687678.png)]

旋轉(rotate)

對圖像做一定角度的旋轉操作

    # tensorflow
    img = tf.image.rot90(img_data, 1)

    with tf.Session() as sess:
        img = sess.run(img)
        plt.subplot(1,2,1)
        plt.title("tensorflow")
        plt.imshow(img)

    # PIL
    img = img_data.rotate(90)  # 逆時針旋轉
    plt.subplot(1, 2, 2)
    plt.title("PIL")
    plt.imshow(img)
    plt.show()

[外鏈圖片轉存失敗(img-jU0xgyst-1562401382764)(數據增強.assets/1562334574494.png)]

縮放變形(scale)

隨機選取圖像的一部分,然後將其縮放到原圖像尺度。

    # PIL
    plt.subplot(1,2,1)
    plt.title("original")
    plt.imshow(img_data)

    img = img_data.crop((200, 100, 800, 500))
    img = img.resize((1000,600),resample=Image.LANCZOS)
    plt.subplot(1,2,2)
    plt.title("scale")
    plt.imshow(img)
    plt.show()

[外鏈圖片轉存失敗(img-ji2cA96A-1562401382765)(數據增強.assets/1562335238968.png)]

平移變換(shift)

圖像整體平移一段距離

	# PIL
    plt.subplot(1,2,1)
    plt.title("original")
    plt.imshow(img)

    img = ImageChops.offset(img_data,200,100)
    plt.subplot(1,2,2)
    plt.title("scale")
    plt.imshow(img)
    plt.show()

在這裏插入圖片描述

顏色變換類

    # tensorflow
    #隨機設置圖片的亮度
    random_brightness = tf.image.random_brightness(img_data,max_delta=30)
    #隨機設置圖片的對比度
    random_contrast = tf.image.random_contrast(img_data,lower=0.2,upper=1.8)
    #隨機設置圖片的色度
    random_hue = tf.image.random_hue(img_data,max_delta=0.3)
    #隨機設置圖片的飽和度
    random_satu = tf.image.random_saturation(img_data,lower=0.2,upper=1.8)

[外鏈圖片轉存失敗(img-En0K5zT7-1562401382765)(數據增強.assets/1562396202140.png)]

	# PIL
    # 調整圖像的飽和度
    random_factor1 = np.random.randint(5, 20) / 10.  # 隨機因子
    color_image = ImageEnhance.Color(img_data).enhance(random_factor1)  
    # 調整圖像的亮度
    random_factor2 = np.random.randint(5, 21) / 10.
    brightness_image = ImageEnhance.Brightness(img_data).enhance(random_factor2)  
    # 調整圖像對比度
    random_factor3 = np.random.randint(5, 20) / 10.
    contrast_image = ImageEnhance.Contrast(img_data).enhance(random_factor3)
    # 調整圖像的銳度
    random_factor4 = np.random.randint(5, 20) / 10.
    sharp_image = ImageEnhance.Sharpness(img_data).enhance(random_factor4)   

[外鏈圖片轉存失敗(img-mHOcLAkq-1562401382765)(數據增強.assets/1562396486182.png)]

噪聲變換類

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import math
import random
import cv2
import scipy.misc
import scipy.signal
import scipy.ndimage

def medium_filter(im, x, y, step):
    sum_s=[]
    for k in range(-int(step/2),int(step/2)+1):
        for m in range(-int(step/2),int(step/2)+1):
            sum_s.append(im[x+k][y+m])
    sum_s.sort()
    return sum_s[(int(step*step/2)+1)]

def mean_filter(im, x, y, step):
    sum_s = 0
    for k in range(-int(step/2),int(step/2)+1):
        for m in range(-int(step/2),int(step/2)+1):
            sum_s += im[x+k][y+m] / (step*step)
    return sum_s

def convert_2d(r):
    n = 3
    # 3*3 濾波器, 每個係數都是 1/9
    window = np.ones((n, n)) / n ** 2
    # 使用濾波器卷積圖像
    # mode = same 表示輸出尺寸等於輸入尺寸
    # boundary 表示採用對稱邊界條件處理圖像邊緣
    s = scipy.signal.convolve2d(r, window, mode='same', boundary='symm')
    return s.astype(np.uint8)

# def convert_3d(r):
#     s_dsplit = []
#     for d in range(r.shape[2]):
#         rr = r[:, :, d]
#         ss = convert_2d(rr)
#         s_dsplit.append(ss)
#     s = np.dstack(s_dsplit)
#     return s


def add_salt_noise(img):
    rows, cols, dims = img.shape 
    R = np.mat(img[:, :, 0])
    G = np.mat(img[:, :, 1])
    B = np.mat(img[:, :, 2])

    Grey_sp = R * 0.299 + G * 0.587 + B * 0.114
    Grey_gs = R * 0.299 + G * 0.587 + B * 0.114

    snr = 0.9
    mu = 0
    sigma = 0.12
    
    noise_num = int((1 - snr) * rows * cols)

    for i in range(noise_num):
        rand_x = random.randint(0, rows - 1)
        rand_y = random.randint(0, cols - 1)
        if random.randint(0, 1) == 0:
            Grey_sp[rand_x, rand_y] = 0
        else:
            Grey_sp[rand_x, rand_y] = 255
    
    Grey_gs = Grey_gs + np.random.normal(0, 48, Grey_gs.shape)
    Grey_gs = Grey_gs - np.full(Grey_gs.shape, np.min(Grey_gs))
    Grey_gs = Grey_gs * 255 / np.max(Grey_gs)
    Grey_gs = Grey_gs.astype(np.uint8)

    # 中值濾波
    Grey_sp_mf = scipy.ndimage.median_filter(Grey_sp, (8, 8))
    Grey_gs_mf = scipy.ndimage.median_filter(Grey_gs, (8, 8))

    # 均值濾波
    n = 3
    window = np.ones((n, n)) / n ** 2
    Grey_sp_me = convert_2d(Grey_sp)
    Grey_gs_me = convert_2d(Grey_gs)

    plt.subplot(321)
    plt.title('Grey salt and pepper noise')
    plt.imshow(Grey_sp, cmap='gray')
    plt.subplot(322)
    plt.title('Grey gauss noise')
    plt.imshow(Grey_gs, cmap='gray')

    plt.subplot(323)
    plt.title('Grey salt and pepper noise (medium)')
    plt.imshow(Grey_sp_mf, cmap='gray')
    plt.subplot(324)
    plt.title('Grey gauss noise (medium)')
    plt.imshow(Grey_gs_mf, cmap='gray')

    plt.subplot(325)
    plt.title('Grey salt and pepper noise (mean)')
    plt.imshow(Grey_sp_me, cmap='gray')
    plt.subplot(326)
    plt.title('Grey gauss noise (mean)')
    plt.imshow(Grey_gs_me, cmap='gray')
    plt.show()

    


def main():
    img = np.array(Image.open('LenaRGB.bmp'))
    add_salt_noise(img)



if __name__ == '__main__':
    main()

img

其他

圖像標準化

    # tensorflow
    # 將圖像均值變爲0,方差變爲1
    tf.image.per_image_standardization(img_data)

[外鏈圖片轉存失敗(img-H4cJBytB-1562401382766)(數據增強.assets/1562397416908.png)]

遮擋

    # PIL
    img_data.paste(paste_data,(200,300,200+paste_data.size[0],300+paste_data.size[1]))

[外鏈圖片轉存失敗(img-vQaFWXbk-1562401382766)(數據增強.assets/1562400269664.png)]

實例

AlexNet

數據增強的第一種形式由生成圖像轉化和水平反射組成。

數據增強的第二種形式包含改變訓練圖像中RGB通道的強度。

YOLO

隨機裁剪、旋轉

變換顏色、變換飽和度(saturation)、變換曝光度(exposure shifts)

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