示例代码如下:
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
from PIL import Image
writer = SummaryWriter("logs")
img = Image.open(r"D:\pycharm_professional\PycharmProjects\learning_pytorch\images\baby.jpg")
# ToTensor
# 生成类对象
trans_totensor = transforms.ToTensor()
# 往类对象中传入参数并返回结果
img_tensor = trans_totensor(img)
# 将结果添加到事件当中
writer.add_image("ToTenser",img_tensor)
# Normalize
print(img_tensor[0][0][0])
# 为什么是传入[0.5,0.5,0.5],因为其有测试图片有三个通道
# 生成类对象
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 PIL -> resize -> img_resize PIL
img_resize = trans_resize(img)
print(img_resize) #
# resize之后的图像是PIL.Image的数据类型,想要把变化后的图片在tensorboard显示的话,还要将图像转换为tensor的数据类型
# img_resize PIL -> totensor -> img_resize tensor
img_resize = trans_totensor(img_resize)
writer.add_image("Resize",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()
tips
# 示例:
# 生成类对象
trans_totensor = transforms.ToTensor()
# 往类对象中传入参数并返回结果
img_tensor = trans_totensor(img)
# 将结果添加到事件当中
writer.add_image("ToTenser",img_tensor)
# 示例:
# Resize
print(img.size)
# 生成类对象
trans_resize = transforms.Resize((512,512))
# img PIL -> resize -> img_resize PIL
img_resize = trans_resize(img)
print(img_resize) #
# resize之后的图像是PIL.Image的数据类型,想要把变化后的图片在tensorboard显示的话,还要将图像转换为tensor的数据类型
# img_resize PIL -> totensor -> img_resize tensor
img_resize = trans_totensor(img_resize)
writer.add_image("Resize",img_resize)
像是Resize就是先将PIL进行尺寸变换,再对尺寸变换后的PIL图像进行ToTensor变换,再进行展示,而不能直接对tensor类型的图像数据进行Resize。
ctrl + alt
和ctrl + p
的使用,应为这两个快捷键可以减少很多的问题总结:
1.关注输入和输出类型
2.多看官方文档
3.不知道返回值的时候: