数据增强是在数据量比较少的情况下,通过对原有的数据进行灰度、裁切、旋转、镜像、明度、色调、饱和度变化的一系列过程,用来增加数据量。
import os
from PIL import Image
import torchvision.transforms as transforms
# 数据增强
def DataEnhance(sourth_path,aim_dir,size):
name=0
#得到源文件的文件夹
file_list=os.listdir(sourth_path)
#创建目标文件的文件夹
if not os.path.exists(aim_dir):
os.mkdir(aim_dir)
for i in file_list:
img=Image.open('%s\%s'%(sourth_path,i))
print(img.size)
name+=1
transform1=transforms.Compose([
transforms.ToTensor(),
transforms.ToPILImage(),
transforms.Resize(size),
])
img1=transform1(img)
img1.save('%s/%s'%(aim_dir,name))
name+=1
transform2=transforms.Compose([
transforms.ToTensor(),
transforms.ToPILImage(),
transforms.ColorJitter(brightness=0.5,contrast=0.5,hue=0.5)
])
img2 = transform1(img)
img2.save('%s/%s' % (aim_dir, name))
name+=1
transform3=transforms.Compose([
transforms.ToTensor(),
transforms.ToPILImage(),
transforms.RandomCrop(227,pad_if_needed=True),
transforms.Resize(size)
])
img3 = transform1(img)
img3.save('%s/%s' % (aim_dir, name))
name+=1
transform4=transforms.Compose([
transforms.Compose(),
transforms.ToPILImage(),
transforms.RandomRotation(60),
transforms.Resize(size),
])
img4 = transform1(img)
img4.save('%s/%s' % (aim_dir, name))
作用:Crops the given PIL Image at the center
from PIL import Image
import torchvision.transforms as transforms
img=Image.open('./Set14/baboon.png')
transform1=transforms.Compose([
transforms.ToTensor(),
transforms.ToPILImage(),
transforms.CenterCrop((224,224)),
])
img=transform1(img)
img.show()
原始图片
裁剪后图片
from PIL import Image
import torchvision.transforms as transforms
img=Image.open('./Set14/baboon.png')
transform1=transforms.Compose([
transforms.ToTensor(),
transforms.ToPILImage(),
transforms.RandomCrop((224,224)),
])
img=transform1(img)
img.show()
依概率p水平翻转transforms.RandomHorizontalFlip
from PIL import Image
import torchvision.transforms as transforms
img=Image.open('./Set14/baboon.png')
transform1=transforms.Compose([
transforms.ToTensor(),
transforms.ToPILImage(),
# transforms.RandomCrop((224,224)),
transforms.RandomHorizontalFlip(p=0.999999)
])
img=transform1(img)
img.show()
依概率p垂直翻转transforms.RandomVerticalFlip
以给定的概率随机垂直翻转给定的PIL图像
torchvision.transforms.RandomVerticalFlip(p=0.5)
随机旋转:transforms.RandomRotation
torchvision.transforms.RandomRotation(degrees)
Resize the input PIL Image to the given size.注意这些函数的输入都是PIL格式
from PIL import Image
import torchvision.transforms as transforms
img=Image.open('./Set14/baboon.png')
transform1=transforms.Compose([
transforms.ToTensor(),
transforms.ToPILImage(),
transforms.Resize((224,224),interpolation=2)
])
img=transform1(img)
print(img.size)
img.show()
torchvision.transforms.Normalize(mean, std)
将PIL Image或者 ndarray 转换为tensor,并且归一化至[0-1]
将tensor 或者 ndarray的数据转换为 PIL Image 类型数据 参数: mode- 为None时,为1通道, mode=3通道默认转换为RGB,4通道默认转换为RGBA。
从给定的一系列transforms中选一个进行操作
pytorch实现AlexNet(含完整代码)_不会水的鱼o的博客-CSDN博客_alexnet pytorch