一、tensorboard的使用
- 加载一张图片转化为tensor类型,并通过tenboard可视化
python
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
img_path = "dataset/train/ants_image/0013035.jpg"
img = Image.open(img_path)
#print(img)
writer = SummaryWriter('logs')
tensor_trans = transforms.ToTensor()
tensor_img = tensor_trans(img)
writer.add_image("Tesnor_img",tensor_img)
#print(tensor_img)
writer.close()
#在Terminal中输入 tensorboard --logdir=logs
二、transforms的常用函数
细心的小伙伴已发现了,上面已经使用了transforms了,我们在添加图片时,用到了ToTensor()这个函数。
ToTensor()函数:
将一个PIL类型转换成tensor类型;
python
#totensor
tensor_trans = transforms.ToTensor()
tensor_img = tensor_trans(img)
writer.add_image("to_Tesnor",tensor_img)
print(tensor_img)
Normalize() 函数:
用于归一化,使他的范数或者数值在一定的范围。
python
#normalize
trnas_norm = transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
img_norm = trnas_norm(tensor_img)
print(img_norm[0][0][0])
writer.add_image("normalize",img_norm)
Resize()函数:
用来调整数组大小。
python
#resize
print(img)
trans_resize = transforms.Resize((512,512))
img_resize = trans_resize(img)
img_resize = tensor_trans(img_resize)
writer.add_image("resize",img_resize,0)
print(img_resize)
Compose()函数:
简单来说就是将各种操作就行联合起来进行操作,注意操作顺序。
python
#compose
trans_resize_2 = transforms.Resize(512)
trans_compose = transforms.Compose([trans_resize_2,tensor_trans])
img_resize_2 = trans_compose(img)
writer.add_image("resize",img_resize_2,1)
RandomCrop()函数:
随机裁剪函数,看效果,这里只展示了一步。
python
#randomcrop
trans_random = transforms.RandomCrop(128)
trans_compose_2 = transforms.Compose([trans_random,tensor_trans])
for i in range(10):
img_crop = trans_compose_2(img)
writer.add_image("Randomcrop",img_crop,i)
writer.close()
tensorboard配合transforms就是pytorch学习中的两大利器