ToTensor
可以将PIL(Python Imaging Library是Python中最基础的图像处理库)格式图片转换为tensor格式。
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
image_path = "数据集/dataset/train/ants_image/0013035.jpg"
img = Image.open(image_path)
writer = SummaryWriter("log")
# ToTensor
trans_totensor = transforms.ToTensor()
img_tensor = trans_totensor(img)
writer.add_image("Tensor_img", img_tensor)
writer.close()
Normalize
归一化tensor格式图片。
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
image_path = "数据集/dataset/train/ants_image/0013035.jpg"
img = Image.open(image_path)
writer = SummaryWriter("log")
# ToTensor
trans_totensor = transforms.ToTensor()
img_tensor = trans_totensor(img)
writer.add_image("Tensor_img", 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)
writer.close()
Resize
改变图片的尺寸大小。
# 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
方法列表的组合,列表里放的都是方法,前一个的输出作为后一个的输入,可以减少代码量。
# Compose
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("Compose", img_resize_2, 0)
RandomCrop
随机裁剪。
# RandomCrop
trans_random = transforms.RandomCrop((200, 300))
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