常见的Transformers(二)
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
writer = SummaryWriter('logs')
img = Image.open(r'D:\Pytorch\hymenoptera_data\train\ants_image\6240329_72c01e663e.jpg')
# ToTensor
trans_totensor = transforms.ToTensor()
img_tensor = trans_totensor(img)
writer.add_image('ToTensor', img_tensor)
#Normalize
trans_norm = transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
img_norm = trans_norm(img_tensor)
writer.add_image('Normalize', img_norm)
print(img_tensor[0][0][0])
print(img_norm[0][0][0])
#Resize
print(img.size) # (500, 369)
trans_resized = transforms.Resize((512, 512))
img_resize = trans_resized(img)
img_resize = trans_totensor(img_resize)
writer.add_image('Resized', img_resize,0)
# Compose - resize - 2
trans_resized_2 = transforms.Resize(512) # 长度较小的边与512进行匹配,另一边等比变化
trans_compose = transforms.Compose([trans_resized_2, trans_totensor])
img_compose = trans_compose(img)
writer.add_image('Resized', img_compose,1)
#RandomCrop
trans_random = transforms.RandomCrop(300) # 或者使用HW形式 transforms.RandomCrop((300, 200))
trans_compose_2 = transforms.Compose([trans_random, trans_totensor])
for i in range(10):
img_crop = trans_compose_2(img)
writer.add_image('Random Crop', img_crop, i)
writer.close()