使用torch.utils.tensorboard中的SummaryWriter类显示图像时报错size of input tensor and input format are different

问题描述

环境:Windows+Python+Pytorch

学习使用Pytorch中torch.utils.tensorboard中的SummaryWriter类显示处理图像的数据时,报错提示:
assert(len(tensor.shape) == len(input_format)), "size of input tensor and input format are different.
AssertionError: size of input tensor and input format are different. tensor shape: (64, 3, 32, 32), input_format: CHW

此类size of input tensor and input format are different报错原因主要在于add_image或add_images函数上:
①首先查看时是输入的单张图片还是多张图片,单张图片应使用add_image,多张图片使用add_images
②看输入图像的formats是否相同,一般函数默认为CHW,使用tensor.shape()可以看看是否符合该要求
③看看通道数是否符合要求

import torch
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

dataset = torchvision.datasets.CIFAR10("../data", train=False, transform=torchvision.transforms.ToTensor(),
                                       download=True)
dataloader = DataLoader(dataset, 64)
writer = SummaryWriter("nn_conv2d")
step = 0
for data in dataloader:
    imgs, targets = data
    writer.add_image("Old Image", imgs, step)//add_image出错
    step = step + 1
writer.close()

//报错:assert(len(tensor.shape) == len(input_format)), "size of input tensor and input format are different. \ AssertionError: size of input tensor and input format are different.         tensor shape: (64, 3, 32, 32), input_format: CHW

原因分析:

此处imgs不止一张图片,类型为[64, 3, H, W],add_image只用于一张图片


解决方案:

将add_image换成add_images

你可能感兴趣的:(深度学习,python,pytorch,深度学习)