from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image
writer = SummaryWriter('logs')
# 用writer.add_scalar()绘制函数图像
for i in range(100):
writer.add_scalar('y=2x', 2 * i, i) # 'y=2x'为图表标题,第一个i为y轴,第二个i为x轴
# 用writer.add_image()显示图片,该函数可以读取torch.Tensor,numpy.array, 和 string/blobname类型
image_path = 'hymenoptera_data/train/ants/0013035.jpg'
image_PIL = Image.open(image_path)
print(type(image_PIL)) # 为PIL类型
image_array = np.array(image_PIL) # 将PIL类型转换为add_image()可以识别的numpy.array类型
print(image_array.shape) # 打印image_array的形状(H, W, C)
writer.add_image('test', img_tensor=image_array, global_step=1, dataformats='HWC') # 由于是HWC顺序,因此要指定dataformats
writer.close()
# 查看结果在Terminal中输入tensorboard --logdir=logs --port=6007
# 其中--logdir=用于指定结果保存的文件夹,而--port=用于指定保存的网页端口号码
需要注意的点:
在应用numpy.array()将PIL格式的图像转换为numpy数组时,形状为HWC,而默认的writer.add_image()为CHW,因此在调用时需要用到dataformats=‘HWC’进行转换。