44 lines
1.5 KiB
Python
44 lines
1.5 KiB
Python
|
from PIL import Image
|
||
|
from torch.utils.tensorboard import SummaryWriter
|
||
|
from torchvision import transforms
|
||
|
|
||
|
writer = SummaryWriter("logs")
|
||
|
img = Image.open(r"images/7759525_1363d24e88.jpg")
|
||
|
|
||
|
# TeTensor的使用
|
||
|
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([1, 3, 5], [3, 2, 1])
|
||
|
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) # 返回的是PIL
|
||
|
# img_resize PIL -> ToTensor -> img_resize Tensor
|
||
|
img_resize = trans_totensor(img_resize) # PIL转换为Tensor
|
||
|
writer.add_image("Resize", img_resize, 0)
|
||
|
|
||
|
# Compose的使用 compose = ToTensor + Normalize
|
||
|
trans_resize_2 = transforms.Resize(512)
|
||
|
# transforms.Compose([trans_resize_2, trans_totensor])是一个类,可以直接调用
|
||
|
# 用于将多个transforms组合起来使用 达到 ToTensor + Normalize 的效果
|
||
|
trans_compose = transforms.Compose([trans_resize_2, trans_totensor])
|
||
|
img_resize_2 = trans_compose(img)
|
||
|
writer.add_image("Raszie", img_resize_2, 1)
|
||
|
|
||
|
# RandomCrop的使用
|
||
|
trans_random = transforms.RandomCrop(256, 128)
|
||
|
trans_compose2 = transforms.Compose([trans_random, trans_totensor])
|
||
|
for i in range(10):
|
||
|
img_crop = trans_compose2(img)
|
||
|
writer.add_image("RandomCrop", img_crop, i)
|
||
|
|
||
|
writer.close()
|