【PyTorch学习笔记2】transforms

1 简介

transforms一个torchvision下的一个工具箱,包含常用的图像预处理方法。主要用于用于图像格式转化,视觉处理工具,不用于文本。
【PyTorch学习笔记2】transforms_第1张图片
包含多个工具类:
【PyTorch学习笔记2】transforms_第2张图片

【PyTorch学习笔记2】transforms_第3张图片

2 常见的transforms

【PyTorch学习笔记2】transforms_第4张图片

代码实战:

# -*- coding=utf-8 -*-
# name: nan chen
# date: 2022/7/22 14:56

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

writer = SummaryWriter("logs")
img = Image.open("hymenoptera_data/train/ants/0013035.jpg")

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

img_toPILImage = transforms.ToPILImage()
img_img = img_toPILImage(img_tensor)
img_img.show()

# 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)

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

# Compose
trans_resize_2 = transforms.Resize(512)
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):
    trans_crop = trans_compose_2(img)
    writer.add_image("RandomCrop", trans_crop, i)

writer.close()

结果:

原图:
【PyTorch学习笔记2】transforms_第5张图片
【PyTorch学习笔记2】transforms_第6张图片
【PyTorch学习笔记2】transforms_第7张图片
【PyTorch学习笔记2】transforms_第8张图片
参考:
bilibili小土堆教程
https://blog.csdn.net/u011995719/article/details/85107009

你可能感兴趣的:(PyTorch,pytorch,学习,深度学习)