一、查找add_image( )函数的定义和使用方法
def add_image(
self, tag, img_tensor, global_step=None, walltime=None, dataformats="CHW"
):
"""Add image data to summary.
Note that this requires the ``pillow`` package.
Args:
tag (string): Data identifier
img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data
global_step (int): Global step value to record
walltime (float): Optional override default walltime (time.time())
seconds after epoch of event
dataformats (string): Image data format specification of the form
CHW, HWC, HW, WH, etc.
Shape:
img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to
convert a batch of tensor into 3xHxW format or call ``add_images`` and let us do the job.
Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitable as long as
corresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``.
再使用opencv对numpy型数据进行读取
小土堆使用的是numpy.array( )对PIL图片转换。
从PIL到numpy, 需要在add_image( )中指定shape中每一个数字/维的含义。
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image
# 创建一个实例
writer = SummaryWriter("logs")
img_path = "lianshou_dataset/train/ants_image/0013035.jpg"
img_PIL = Image.open(img_path)
img_array = np.array(img_PIL)
print(type(img_array))
print(img_array.shape)
# 再使用两个类方法,其中函数参数默认值修改看上面的函数定义。
writer.add_image("test", img_array, 1, dataformats='HWC')
for i in range(100):
writer.add_scalar("y=2x", 2*i, i)
writer.close()
结果如下:
再对代码进行改动,改变step的步数,改成2,代码如下:
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image
# 创建一个实例
writer = SummaryWriter("logs")
img_path = "lianshou_dataset/train/bees_image/16838648_415acd9e3f.jpg"
img_PIL = Image.open(img_path)
img_array = np.array(img_PIL)
print(type(img_array))
print(img_array.shape)
# 再使用两个类方法
writer.add_image("test", img_array, 2, dataformats='HWC')
for i in range(100):
writer.add_scalar("y=2x", 2*i, i)
writer.close()
结果如下:
结果与小土堆的视频吻合。