Tesk 2 数据扩增
在深度学习中数据扩增方法非常重要,数据扩增可以增加训练集的样本,同时也可以有效缓解模型过拟合的情况,也可以给模型带来的更强的泛化能力。
以torchvision为例,常见的数据扩增方法包括:
transforms.CenterCrop 对图片中心进行裁剪
transforms.ColorJitter 对图像颜色的对比度、饱和度和零度进行变换
transforms.Grayscale 对图像进行灰度变换
transforms.Pad 使用固定值进行像素填充
transforms.RandomAffine 随机仿射变换
transforms.RandomCrop 随机区域裁剪
transforms.RandomHorizontalFlip 随机水平翻转
transforms.RandomRotation 随机旋转
transforms.RandomVerticalFlip 随机垂直翻转
使用Image读取图像,图像的大小为(125,200, 3)
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
img = Image.open("./cat1.jpg")
img
1 对图片中心进行裁剪
torchvision.transforms.CenterCrop(size)
img_CenterCrop = transforms.CenterCrop((90, 120))(img)
img_CenterCrop
2 对图像颜色的对比度、饱和度和零度进行变换
torchvision.transforms.ColorJitter(brightness=0, contrast=0, saturation=0, hue=0)
brightnes(亮度):取值范围(0, 1)
contrast(对比度):取值范围(0, 1)
saturation(饱和度):取值范围(0, 1)
hue:取值范围(-0.5,0.5)
img_ColorJitter = transforms.ColorJitter(0.5, 0.5, 0.5)(img)
img_ColorJitter
3 将图像转化为灰度图
torchvision.transforms.Grayscale(num_output_channels = 1 )
输出通道数为1或3
img_Gray = transforms.Grayscale(1)(img)
img_Gray
使用matplotlib输出显示图像
plt.figure(figsize=(5, 5))
plt.subplot(221)
plt.imshow(img), plt.title("original"), plt.axis('off')
plt.subplot(222)
plt.imshow(img_CenterCrop), plt.title("centercrop"), plt.axis('off')
plt.subplot