完美解决 TypeError: Invalid shape (3, 224, 224) for image data

简介: 完美解决 TypeError: Invalid shape (3, 224, 224) for image data

问题描述

使用matplotlib显示彩色图像出现问题

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-edd857df93f0> in <module>
     20 # import numpy as np
     21 # # np_img = np.array(pil_img)
---> 22 plt.imshow(np.array(img))
     23 # plt.imshow(img.permute(1,2,0))
     24 plt.show()
TypeError: Invalid shape (3, 224, 224) for image data

原因分析:

使用matplotlib显示彩色图像需要数据的维度为 【width, height, channel】,就是224 * 224 * 3

报错原因是我这里的tensor的维度为 3 * 224 * 224

x_train_tensor = torch.from_numpy(x_train)
y_train_tensor = torch.from_numpy(y_train)

解决方案:

将tensor或者数组的维度交换即可

可以使用permute函数,这个函数的参数就是我们交换之后新维度的排序,下面为1,2,0就是我们需要将原来1和2维度的内容排在前面,而通道维度放在最后

img.permute(1,2,0)

或者还可以使用transpose函数直接交换维度

img.transpose(0,2)


目录
相关文章
RuntimeError: Given groups=1, weight of size 64 128 1 7, expected input[16,
RuntimeError: Given groups=1, weight of size 64 128 1 7, expected input[16,
2936 0
|
6月前
|
计算机视觉 Python
error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
168 0
|
计算机视觉
cv2.error: OpenCV(4.5.2) : -1 : error: (-5:Bad argument) in function ‘rectangle‘
cv2.error: OpenCV(4.5.2) : -1 : error: (-5:Bad argument) in function ‘rectangle‘
445 0
|
Python
AttributeError: type object ‘Image‘ has no attribute ‘open‘
原因分析:Image调用顺序出错,因为第一行的from PIL import Image与第二行tkinter import *冲突,tkinter中也含有Image类,所以你使用的是tkinter.Image
249 0
CVI2012报错:Function imaqMorphology: (errorCode == -1074396154 [0xbff60406]). The image is not large e
CVI2012报错:Function imaqMorphology: (errorCode == -1074396154 [0xbff60406]). The image is not large e
|
机器学习/深度学习 PyTorch 算法框架/工具
解决Pytorch中RuntimeError: expected scalar type Double but found Float
解决Pytorch中RuntimeError: expected scalar type Double but found Float
2691 0
|
TensorFlow 算法框架/工具
解决TypeError: tf__update_state() got an unexpected keyword argument ‘sample_weight‘
解决TypeError: tf__update_state() got an unexpected keyword argument ‘sample_weight‘
275 0
解决TypeError: tf__update_state() got an unexpected keyword argument ‘sample_weight‘
报错:pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 7, saw 2
报错:pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 7, saw 2
报错:pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 7, saw 2
|
计算机视觉
【opencv】cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘imshow‘
【opencv】cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘imshow‘
813 0
【opencv】cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘imshow‘