关注官方文档给的输入与输出格式--容易出错
from PIL import Image from torch.utils.tensorboard import SummaryWriter from torchvision import transforms writer = SummaryWriter("logs") img = Image.open("images/1600DOG007-2.jpg") # PIL类型 print(img) #totensor 把PIL.Image或ndarray从 (H x W x C)形状转换为 (C x H x W) 的tensor trans_totensor = transforms.ToTensor() # tensor对象 print(trans_totensor) img_tensor = trans_totensor(img) #tensor类型 # print(img_tensor) writer.add_image("ToTensor",img_tensor) #Normalize 对图像进行标准化 print(img_tensor[0][0][0]) trans_norm=transforms.Normalize([0.1,0.2,0.3],[0.3,0.2,0.1]) img_norm=trans_norm(img_tensor) print(img_norm[0][0][0]) writer.add_image("Normalize",img_norm,3) #Resize 调整PILImage对象的尺寸,注意不能是用io.imread或者cv2.imread读取的图片,这两种方法得到的是ndarray print(img.size) # img_PIL->resize->img_resize PIL trans_resize=transforms.Resize((512,512)) img_resize=trans_resize(img) print(img_resize) # 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) trans_compose=transforms.Compose([trans_resize_2,trans_totensor]) print(trans_compose) 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()
运行后在控制台输入tensorboard --logdir=logs即可在浏览器可视化