TypeError: Invalid dimensions for image data

902003b7648b9e4c4217: <p>Hi there.  I have a problem.<br>
I want to show my images for the purpose of knowing precision and recall.<br>
However, my images can’t be loaded by imshow.<br>
I think images and imshow are mismatch.<br>
so,I want to fix my problem.</p>
<blockquote>
<p>dataiter = iter(testloader)<br>
for data in dataiter:<br>
images, labels = data<br>
print (images.shape)<br>
imshow(torchvision.utils.make_grid(images, nrow=5))<br>
images, labels = images.to(device), labels.to(device)</p>
</blockquote>
<pre><code>outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
print(predicted)

print('Correct : ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
print('Predcit  : ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
print(predicted==labels)
</code></pre>
<blockquote>
<p>torch.Size([4, 3, 255, 255])</p>
</blockquote>
<hr>
<blockquote>
<p>TypeError                                 Traceback (most recent call last)<br>
 in ()<br>
3     images, labels = data<br>
4     print (images.shape)<br>
----&gt; 5     imshow(torchvision.utils.make_grid(images, nrow=5))<br>
6<br>
7 #     images, labels = images.to(device), labels.to(device)<br>
/opt/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, hold, data, **kwargs)<br>
3203                         filternorm=filternorm, filterrad=filterrad,<br>
3204                         imlim=imlim, resample=resample, url=url, data=data,<br>
 → 3205                         **kwargs)<br>
3206     finally:<br>
3207         ax._hold = washold<br>
/opt/anaconda3/lib/python3.6/site-packages/matplotlib/<strong>init</strong>.py in inner(ax, *args, **kwargs)<br>
1853                         “the Matplotlib list!)” % (label_namer, func.<strong>name</strong>),<br>
1854                         RuntimeWarning, stacklevel=2)<br>
 → 1855             return func(ax, *args, **kwargs)<br>
1856<br>
1857         inner.<strong>doc</strong> = _add_data_doc(inner.<strong>doc</strong>,<br>
/opt/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)<br>
5485                               resample=resample, **kwargs)<br>
5486<br>
 → 5487         im.set_data(X)<br>
5488         im.set_alpha(alpha)<br>
5489         if im.get_clip_path() is None:<br>
/opt/anaconda3/lib/python3.6/site-packages/matplotlib/image.py in set_data(self, A)<br>
651         if not (self._A.ndim == 2<br>
652                 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):<br>
 → 653             raise TypeError(“Invalid dimensions for image data”)<br>
654<br>
655         if self._A.ndim == 3:<br>
TypeError: Invalid dimensions for image data</p>
</blockquote>

ptrblck: <p>You could try to permute the image tensor so that the channels are stored in dim2:</p>
<pre><code class="lang-python">images = torch.randn(4, 3, 255, 255)
plt.imshow(torchvision.utils.make_grid(images, nrow=5).permute(1, 2, 0))
</code></pre>

902003b7648b9e4c4217: <aside class="quote no-group" data-username="ptrblck" data-post="2" data-topic="35888">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>permute</p>
</blockquote>
</aside>
<p>Thank you ,your advice. my code is working. but… I have a new problem.<br>
When I used for your advice, the code outputs</p>
<blockquote>
<p>Clipping input data to the valid range for imshow with RGB data ([0…1] for floats or [0…255] for integers).</p>
</blockquote>
<p>and…images are noise like snow noise.<br>
in addition, this is my channels.</p>
<blockquote>
<p>class Net(nn.Module):<br>
def <strong>init</strong>(self):<br>
super(Net, self).<strong>init</strong>()<br>
self.conv1 = nn.Conv2d(3, 6, 5)<br>
self.pool = nn.MaxPool2d(2, 2)<br>
self.conv2 = nn.Conv2d(6, 16, 5)<br>
self.fc1 = nn.Linear(16<em>60</em>60, 120)<br>
self.fc2 = nn.Linear(120, 84)<br>
self.fc3 = nn.Linear(84, 10)</p>
</blockquote>
<pre><code>def forward(self, x):
    x = self.pool(F.relu(self.conv1(x)))
    x = self.pool(F.relu(self.conv2(x))) 
  
    x = x.view(x.size(0), 16 * 60 * 60)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)


    return x
</code></pre>

ptrblck: <p>You could avoid the clipping by normalizing the images first:</p>
<pre><code class="lang-python">images -= images.min()
images /= images.max()
</code></pre>
<p>I just created the images using gaussian noise (<code>torch.randn</code>).<br>
You should use your <code>images</code> tensor instead or do you see random noise there too?</p>

saba: <aside class="quote no-group" data-username="ptrblck" data-post="2" data-topic="35888">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p><code>.permute(1, 2, 0)</code></p>
</blockquote>
</aside>
<p>Hi,</p>
<p>sorry, the data3 is the torch size of (64,21,21,11), I want to see the middle slice in grid. I am using the current code it give me error. Would you please tell me what is wrong? the fake33 has a (64,21,21) size.<br>
Error is :  (TypeError(“Invalid dimensions for image data”)<br>
TypeError: Invalid dimensions for image data)</p>
<pre><code class="lang-auto">            fake33=data3[:,:,:,6]
            plt.close("all")
            plt.figure()
            plt.figure(figsize=(8,8))
            plt.axis("off")
            plt.title("Fake Images")
            plt.imshow(np.transpose(vutils.make_grid(fake33.detach().to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))
            plt.savefig(os.path.join(root_dirDurringTraining13+'Eoch-'+str(epoch)+'Seed='+str(manualSeed))+'fakes.jpg')</code></pre>

ptrblck: <p>I assume that you would like to visualize each of the 64 slices as a grayscale image?<br>
If that’s the case, this code should work:</p>
<pre><code class="lang-python">imgs = torch.randn(64, 21, 21)
imgs = torchvision.utils.make_grid(imgs.unsqueeze(1))
print(imgs.shape)
&gt; torch.Size([3, 186, 186])

imgs = imgs.permute(1, 2, 0).numpy()
plt.imshow(imgs)
</code></pre>