本文为学习笔记,感谢PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】
tensorboard是一种可视化工具,可以但不仅限于图片显示和函数显示。
一般是from torch.utils.tensorboard import SummaryWriter
,但是如果tensorboard有问题可以使用from tensorboardX import SummaryWriter
# from torch.utils.tensorboard import SummaryWriter
from tensorboardX import SummaryWriter #SummaryWriter相当于一个容器
from PIL import Image #操作PIL格式图片的库
import numpy as np
#规定创建logs文件夹路径,所有生成的事件文件都存在里面
writer = SummaryWriter('logs')
#图片路径
img_path = 'F:\python_project\deep_learning\\train\\ants_image\\0013035.jpg'
#打开图片
img = Image.open(img_path)
#将图片转换为numpy.arraynp格式
img_array = np.array(img)
#写入图片的方法add_image
#此处参数分别为(标题名,图片,step,通道顺序)
writer.add_image('ants',img_array,1,dataformats='HWC')
#写入标量的方法add_scalar
for i in range(50):
writer.add_scalar('y=2x',2*i,i)
#结束边界
writer.close()
总结:
1、writer = SummaryWriter('logs')
创建容器
2、add_image、add_scalar
加入数据
3、writer.close()
终止边界
4、运行后在logs目录下会有event事件文件,在终端用tensorboard --logdir=logs
命令运行,打开端口就可看到可视化
transform是用于改变图形工具,此处主要介绍transforms.ToTensor()
,transforms.Normalize()
,transforms.Resize()
,transforms.Compose()
,transforms.RandomCrop()
tips:tensorboard中SummaryWriter.add_image()函数只能接受tensor或numpy.nparray类型的图片,PIL不接受
from tensorboardX import SummaryWriter
from torchvision import transforms
from PIL import Image
writer = SummaryWriter('logs\\1')
img_path = 'F:\python_project\deep_learning\\0013035.jpg'
img = Image.open(img_path)
#Totensor将PIL转变为tensor
trans_totensor = transforms.ToTensor()
img_tensor = trans_totensor(img) #PIL -> tensor
writer.add_image('ToTensor',img_tensor,1)
#Normalize正规化
mean,std= [0.5,0.5,0.5],[0.5,0.5,0.5]
#参数是mean和std,RGB3通道就要传入3个mean和std
trans_norm = transforms.Normalize(mean,std)
img_norm = trans_norm(img_tensor)
writer.add_image('Normalize',img_norm,2)
#Resize重定义尺寸
trans_resize = transforms.Resize((512,512))
img_resize = trans_resize(img)
#PIL->tensor
img_resize = trans_totensor(img_resize)
writer.add_image('Resize512*512',img_resize,3)
#Compose转换合并
trans_resize2 = transforms.Resize((512,512))
trans_Compose = transforms.Compose([trans_resize2,trans_totensor])
img_Compose = trans_Compose(img)
writer.add_image('compose',img_Compose,4)
#RandomCrop随机裁剪
trans_randomcrop = transforms.RandomCrop((200,200))
trans_Compose2 = transforms.Compose([trans_randomcrop,trans_totensor])
for i in range(5,10):
img_crop = trans_Compose2(img)
writer.add_image('img_crop',img_crop,i)
writer.close()