PyTorch教程【六】Transforms的使用

  from PIL import Image
  from torch.utils.tensorboard import SummaryWriter
  from torchvision import transforms

  # python的用法->tensor数据类型
  # 通过transforms.ToTensor去看两个问题

  # 绝对路径:D:leran_pytorchdatasettrainants013035.jpg
  # 相对路径:dataset/train/ants/0013035.jpg

  img_path = "dataset/train/ants/0013035.jpg"
  img = Image.open(img_path)

  writer = SummaryWriter("logs")
    
  # 1、transforms该如何使用(python)
  # 2、为什么我们需要Tensor数据类型
  tensor_trans = transforms.ToTensor()
  tensor_img = tensor_trans(img)

  writer.add_image("Tensor_img", tensor_img)

  writer.close()

2、常见的Transforms

PyTorch教程【六】Transforms的使用

  from PIL import Image
  from torch.utils.tensorboard import SummaryWriter
  from torchvision import transforms

  writer = SummaryWriter("logs")
  img = Image.open("images/6a00d8341c630a53ef00e553d0beb18834-800wi.jpg")
  print(img)

  # ToTensor
  trans_totensor = transforms.ToTensor()
  img_tensor = trans_totensor(img)
  writer.add_image("ToTensor", img_tensor)

  # 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.add_image("Normalize", img_norm, 2)

  # Resize
  print(img.size)
  trans_resize = transforms.Resize((512, 512))
  # img PIL -> resize -> img_resize PIL
  img_resize = trans_resize(img)
  # img_resize PIL->totensor ->img_resize tensor
  img_resize = trans_totensor(img_resize)
  writer.add_image("Resize", img_resize, 0)
  print(img_resize)

  # Compose - resize - 2
  trans_resize_2 = transforms.Resize(512)
  # PIL -> PIL ->tensor
  trans_compose = transforms.Compose([trans_resize_2, trans_totensor])
  img_resize_2 = trans_compose(img)
  writer.add_image("Resize", img_resize_2, 1)

  # RandomCrop
  trans_random = transforms.RandomCrop(512)
  trans_compose_2 = transforms.Compose([trans_random, [trans_totensor]])
  for i in range(10):
      img_crop = trans_compose_2(img)
      writer.add_image("RandomCrop", img_crop, i)

  writer.close()

PyTorch教程【六】Transforms的使用