如何解决Pytorch错误:ValueError:图片应为2/3维有4个尺寸
尝试遵循本教程here。虽然当我尝试使用imshow()函数时选择内容图像和样式图像时,却出现此错误:
ValueError: pic should be 2/3 dimensional. Got 4 dimensions.
使用google,我还无法真正找到解决该问题的方法。
这是我的代码:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
import numpy as np
# This detects if cuda is available for GPU training otherwise will use CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
# Desired size of the output image
imsize = 512 if torch.cuda.is_available() else 256
print(imsize)
# Helper function
def image_loader(image_name,imsize):
# Scale the imported image and transform it into a torch tensor
loader = transforms.Compose([transforms.Resize(imsize),transforms.ToTensor()])
image = Image.open(image_name)
# Fake batch dimension required to fit network's input dimension
image = loader(image).unsqueeze(0)
return image.to(device,torch.float)
# Helper function to show the tensor as a PIL image
def imshow(tensor,title=None):
unloader = transforms.ToPILImage()
image = tensor.cpu().clone()
image = unloader(image)
plt.imshow(image)
if title is not None:
plt.title(title)
plt.pause(0.001) # Pause so that the plots are updated
# Loading of images
image_directory = './images/'
style_img = image_loader(image_directory + "pb.jpg",imsize)
content_img = image_loader(image_directory + "content.jpg",imsize)
assert style_img.size() == content_img.size(),"we need to import style and content images of the same size"
plt.figure()
imshow(style_img,title='style image')
任何建议都会很有帮助。
以下是样式和内容图片供参考:
解决方法
matplotlib.pyplot
期望2D(灰度,尺寸=(W,H))或3D(彩色,尺寸=(W,H,颜色通道))在imshow
函数中。
您可能仍将batchsize作为第一个维度在张量中,因为在代码中您可以这样做:
# Fake batch dimension required to fit network's input dimension
image = loader(image).unsqueeze(0)
添加第一个尺寸。如果是这样,请尝试使用以下一种方法:
plt.imshow(np.squeeze(image))
或
plt.imshow(image[0])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。