图像增广

In [2]:
%matplotlib inline
import torch
import torchvision
from torch import nn
from d2l import torch as d2l

d2l.set_figsize()
img = d2l.Image.open('../img/cat1.jpg')
d2l.plt.imshow(img);
2021-07-09T05:23:49.668601 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/
In [3]:
def apply(img, aug, num_rows=2, num_cols=4, scale=1.5):
    Y = [aug(img) for _ in range(num_rows * num_cols)]
    d2l.show_images(Y, num_rows, num_cols, scale=scale)

左右翻转图像

In [4]:
apply(img, torchvision.transforms.RandomHorizontalFlip())
2021-07-09T05:23:50.208447 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/

上下翻转图像

In [5]:
apply(img, torchvision.transforms.RandomVerticalFlip())
2021-07-09T05:23:50.813218 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/

随机裁剪

In [6]:
shape_aug = torchvision.transforms.RandomResizedCrop(
    (200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)
2021-07-09T05:23:51.293504 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/

随机更改图像的亮度

In [7]:
apply(
    img,
    torchvision.transforms.ColorJitter(brightness=0.5, contrast=0,
                                       saturation=0, hue=0))
2021-07-09T05:23:51.721826 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/

随机更改图像的色调

In [8]:
apply(
    img,
    torchvision.transforms.ColorJitter(brightness=0, contrast=0, saturation=0,
                                       hue=0.5))
2021-07-09T05:23:52.294212 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/

随机更改图像的亮度(brightness)、对比度(contrast)、饱和度(saturation)和色调(hue

In [9]:
color_aug = torchvision.transforms.ColorJitter(brightness=0.5, contrast=0.5,
                                               saturation=0.5, hue=0.5)
apply(img, color_aug)
2021-07-09T05:23:52.926084 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/

结合多种图像增广方法

In [10]:
augs = torchvision.transforms.Compose([
    torchvision.transforms.RandomHorizontalFlip(), color_aug, shape_aug])
apply(img, augs)
2021-07-09T05:23:53.562902 image/svg+xml Matplotlib v3.3.4