Pytorch 官方文档 - Transforms:https://pytorch.org/vision/stable/transforms.html
from torchvision import transforms
from PIL import Image
image_path = "./data/dataset/train/bees_image/476347960_52edd72b06.jpg"
img = Image.open(image_path)
print(img)
# Resize
print(img.size) # (500, 372)
trans_resize = transforms.Resize((512, 512))
img_resize = trans_resize(img)
print(img_resize) # <PIL.Image.Image image mode=RGB size=512x512 at 0x163F7ADB7C8>
# ToTensor
trans_tensor = transforms.ToTensor()
img_tensor = trans_tensor(img_resize)
# Normalize
print(img_tensor[0][0][0])
trans_norm = transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
img_norm = trans_norm(img_tensor)
print(img_norm[0][0][0])
writer = SummaryWriter("logs")
writer.add_image("Resize - ToTensor - Normalize", img_norm)
writer.close()
# Compose
trans_compose = transforms.Compose([trans_resize, trans_tensor, trans_norm])
img_output = trans_compose(img)
writer = SummaryWriter("logs")
writer.add_image("Compose", img_output)
writer.close()
# RandomCrop
trans_random = transforms.RandomCrop((50, 100))
trans_compose2 = transforms.Compose([trans_random, trans_tensor])
writer = SummaryWriter("logs")
for i in range(10):
img_crop = trans_compose2(img)
writer.add_image("RandomCrop2", img_crop, i)
writer.close()