Pytorch 官方文档 - Transforms:https://pytorch.org/vision/stable/transforms.html

    1. from torchvision import transforms
    2. from PIL import Image
    3. image_path = "./data/dataset/train/bees_image/476347960_52edd72b06.jpg"
    4. img = Image.open(image_path)
    5. print(img)
    1. # Resize
    2. print(img.size) # (500, 372)
    3. trans_resize = transforms.Resize((512, 512))
    4. img_resize = trans_resize(img)
    5. print(img_resize) # <PIL.Image.Image image mode=RGB size=512x512 at 0x163F7ADB7C8>
    1. # ToTensor
    2. trans_tensor = transforms.ToTensor()
    3. img_tensor = trans_tensor(img_resize)
    1. # Normalize
    2. print(img_tensor[0][0][0])
    3. trans_norm = transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
    4. img_norm = trans_norm(img_tensor)
    5. print(img_norm[0][0][0])
    1. writer = SummaryWriter("logs")
    2. writer.add_image("Resize - ToTensor - Normalize", img_norm)
    3. writer.close()
    1. # Compose
    2. trans_compose = transforms.Compose([trans_resize, trans_tensor, trans_norm])
    3. img_output = trans_compose(img)
    4. writer = SummaryWriter("logs")
    5. writer.add_image("Compose", img_output)
    6. writer.close()
    1. # RandomCrop
    2. trans_random = transforms.RandomCrop((50, 100))
    3. trans_compose2 = transforms.Compose([trans_random, trans_tensor])
    4. writer = SummaryWriter("logs")
    5. for i in range(10):
    6. img_crop = trans_compose2(img)
    7. writer.add_image("RandomCrop2", img_crop, i)
    8. writer.close()

    image.pngimage.png