一、数据增强方法:
1. 对图片进行比例缩放
2. 对图片进行随机位置的截取
3. 对图片进行随机水平和竖直翻转
4. 对图片进行随机角度的旋转
5. 对图片进行亮度、对比度和颜色随机变化
二、Torch中已经把这些方法内置在了torchvision中,可以直接调用
from PIL import Image
from torchvision import transforms as tfs
- 1
- 2
im = Image.open('../input/cat.jpg')
im
- 1
- 2
1. 随机比例缩放
使用:torchvision.transforms.Resize(),参数1表示缩放图片大小,可以为tuple,参数2表示缩放方法,默认为双线性插值
print('before scale, shape: {}'.format(im.size))
new_im = tfs.Resize((100,200))(im)
print('after scale, shape: {}'.format(new_im.size))
new_im
- 1
- 2
- 3
- 4
before scale, shape: (121, 121)
after scale, shape: (200, 100)
- 1
- 2
2.随机位置截取
使用:
(1)torchvision.transforms.RandomCrop(),参数为截取图片的大小
(2)torchvision.transforms.CenterCrop(),参数为截取图片的大小,但以原始图片的中心为中心
# 随机裁剪
random_im = tfs.RandomCrop((60, 60))(im)
random_im
- 1
- 2
- 3
# 中心裁剪
center_im = tfs.CenterCrop((60, 60))(im)
center_im
- 1
- 2
- 3
3.随机水平和竖直翻转
使用torchvision.transforms.RandomHorizontalFlip() 和torchvision.transforms.RandomVerticalFlip()
无参数
horizontal_im = tfs.RandomHorizontalFlip()(im)
horizontal_im
- 1
- 2
vertical_im = tfs.RandomVerticalFlip()(im)
vertical_im
- 1
- 2
4.随机角度旋转
使用:torchvision.transforms.RandomRotation()。参数为旋转的角度。比如20,则会随机在-20~20之间进行旋转
rotation_im = tfs.RandomRotation(45)(im)
rotation_im
- 1
- 2
5. 亮度、对比度和颜色
torchvision.transforms.ColorJitter()。参数1为亮度,参数2为对比度,参数3为饱和度
bright_im = tfs.ColorJitter(brightness=1)(im) #随机在0~2之间变化,1
bright_im
- 1
- 2
contrast_im = tfs.ColorJitter(contrast=1)(im) #随机在0~2之间变化,
contrast_im
- 1
- 2
color_im = tfs.ColorJitter(hue=0.5)(im) # 随机从 -0.5 ~ 0.5 之间变化
color_im
- 1
- 2
三、联合使用数据增强方法
使用 torchvision.transforms.Compose()。利用List进行组装,然后传递给Compose
im_aug = tfs.Compose([
tfs.Resize(120),
tfs.RandomHorizontalFlip(),
tfs.RandomCrop(96),
tfs.ColorJitter(brightness=0.5, contrast=0.5, hue=0.5)
])
- 1
- 2
- 3
- 4
- 5
- 6
import matplotlib.pyplot as plt
%matplotlib inline
- 1
- 2
nrows = 3
ncols = 3
figsize = (8, 8)
fig, figs = plt.subplots(nrows, ncols, figsize=figsize)
for i in range(nrows):
for j in range(ncols):
figs[i][j].imshow(im_aug(im))
figs[i][j].axes.get_xaxis().set_visible(False)
figs[i][j].axes.get_yaxis().set_visible(False)
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
四、使用数据增强
(1)训练集采用数据增强
def train_tf(x):
im_aug = tfs.Compose([
tfs.Resize(120),
tfs.RandomHorizontalFlip(),
tfs.RandomCrop(96),
tfs.ColorJitter(brightness=0.5, contrast=0.5, hue=0.5),tfs.ToTensor(),
tfs.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
x = im_aug(x)
return x
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
(2)测试集不采用数据增强
def test_tf(x):
im_aug = tfs.Compose([
tfs.Resize(96),
tfs.ToTensor(),
tfs.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
x = im_aug(x)
return x
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
训练过程省略。。。。。。