from torch.utils.tensorboard import SummaryWriter import torch import numpy as np # create a summary writer writer = SummaryWriter() # create a sample image image = torch.rand(3, 256, 256) # convert the image to numpy format image_np = image.numpy() # add the image to TensorBoard summary writer writer.add_image('image', image_np, 0) # close the summary writer writer.close()
from torch.utils.tensorboard import SummaryWriter import torch import numpy as np # create a summary writer writer = SummaryWriter() # create a list of sample images images = [] for i in range(5): img = torch.rand(3, 256, 256) images.append(img) # convert each image to numpy format images_np = [im.numpy() for im in images] # add all the images to TensorBoard summary writer for step, img_np in enumerate(images_np): writer.add_image(f'image_{step}', img_np, step) # close the summary writer writer.close()This code creates a list of 5 sample images with random pixel values and adds each of them to the `SummaryWriter` object with a different name. The `add_image` function is then used with an additional argument to specify the step at which each image was added. In summary, the `torch.utils.tensorboard` package library offers a convenient way to visualize PyTorch models and data using the TensorBoard web application. The `SummaryWriter` object allows adding a wide range of data types, including images, to the TensorBoard.