PIL进行数据增强

利用PIL对图像进行随机数据增强。左右翻转,上下翻转,随机旋转

from PIL import Image
import random
import numpy as np


def augment(img,hflip=True,rot=True):
    hflip = hflip and random.random() < 0.5
    vflip = rot and random.random() < 0.5
    rot90 = rot and random.random() < 0.5
    if hflip:img=img.transpose(Image.FLIP_LEFT_RIGHT)
    if vflip:img=img.transpose(Image.FLIP_TOP_BOTTOM)
    if rot90:img=img.rotate(random.choice([90,180,270]),expand=True)
    # if rot90: img = img.rotate(random.randint(0,360), expand=True)  ###这种情况下会产生大量的黑边
    return img

if __name__=='__main__':
    import matplotlib.pyplot as plt
    img = Image.open('./test/Set5/bird.png')
    hh=img.transpose(Image.FLIP_TOP_BOTTOM)
    hhh=img.rotate(360,expand=True)
    print(np.array(hh)==np.array(hhh))
    plt.subplot(1, 3, 1)
    plt.xticks([])  # 去掉x轴的刻度
    plt.yticks([])  # 去掉y轴的

猜你喜欢

转载自blog.csdn.net/qq_40107571/article/details/127377797
今日推荐