Problem CNN picture

randino: <p>how to display a picture with deep learning</p>
<pre><code class="lang-auto">print('Validation accuracy test: {:.4f}%'.format(float(accuracy_score(val_y, predictions)) * 100))
conf_matrix  = confusion_matrix(val_y, predictions)
print(conf_matrix)
plt.imshow(torchvision.utils.make_grid(predictions))  
</code></pre>
<p>Error :</p>
<pre><code class="lang-auto">TypeError                                 Traceback (most recent call last)
&lt;ipython-input-8-767abd2c3c6d&gt; in &lt;module&gt;()
    402 
    403 print(conf_matrix)
--&gt; 404 plt.imshow(torchvision.utils.make_grid(predictions))

1 frames
/usr/local/lib/python3.7/dist-packages/torchvision/utils.py in make_grid(tensor, nrow, padding, normalize, value_range, scale_each, pad_value, **kwargs)
     44     if not (torch.is_tensor(tensor) or
     45             (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
---&gt; 46         raise TypeError(f'tensor or list of tensors expected, got {type(tensor)}')
     47 
     48     if "range" in kwargs.keys():

TypeError: tensor or list of tensors expected, got &lt;class 'numpy.ndarray'&gt;
</code></pre>
<p>Help me plzzz</p>

ptrblck: <p><code>make_grid</code> expects a 4D tensor or a list of of images as described in the <a href="https://pytorch.org/vision/stable/utils.html#torchvision.utils.make_grid">docs</a>:</p>
<blockquote>
<p><strong>tensor</strong> (<em>Tensor</em> <em>or</em> <a href="https://docs.python.org/3/library/stdtypes.html#list"><em>list</em></a>) – 4D mini-batch Tensor of shape (B x C x H x W) or a list of images all of the same size.</p>
</blockquote>
<p>while you are trying to pass a numpy array to it.</p>

randino: <p>thank you for your reply <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>But when I tested this :</p>
<pre><code class="lang-auto">conf_matrix  = confusion_matrix(val_y, predictions)

        

print(conf_matrix)

plt.imshow(torchvision.utils.make_grid((predictions, nrow: int = 8, padding: int = 2, normalize: bool = False, value_range: Optional[Tuple[int, int]] = None, scale_each: bool = False, pad_value: int = 0, **kwargs))
</code></pre>
<p>Error :</p>
<p>File “”, line 403<br>
plt.imshow(torchvision.utils.make_grid((predictions, nrow: int = 8, padding: int = 2, normalize: bool = False, value_range: Optional[Tuple[int, int]] = None, scale_each: bool = False, pad_value: int = 0, **kwargs))<br>
^<br>
SyntaxError: invalid syntax</p>

ptrblck: <p>It seems you might have just copied the arguments from the docs without defining them.<br>
This would work:</p>
<pre><code class="lang-python">predictions = torch.randn(4, 3, 224, 224)
plt.imshow(torchvision.utils.make_grid(predictions).permute(1, 2, 0))  
</code></pre>

randino: <p>Thank you <a class="mention" href="/u/ptrblck">@ptrblck</a>  but how to save the image in  extension .mat? plzz</p>

ptrblck: <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.savemat.html"><code>scipy.io.savemat</code></a> should work.</p>

randino: <p>Plzz <a class="mention" href="/u/ptrblck">@ptrblck</a>  when I affiched the image with this code , always , it displays under this form</p>
<pre><code class="lang-auto">mat = pjoin('./sample_data/', 'img.mat')
    #print('Mat loading ...')
mat = sio.loadmat(mat)
mat = torch.randn(1, 1, 100, 100)
plt.imshow(torchvision.utils.make_grid(mat).permute(1, 2, 0)) 
</code></pre>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/a/4/a4cad30245d404065cec66ff7cc7ed8dbec86a7f.png" data-download-href="https://discuss.pytorch.org/uploads/default/a4cad30245d404065cec66ff7cc7ed8dbec86a7f" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/a/4/a4cad30245d404065cec66ff7cc7ed8dbec86a7f_2_690x249.png" alt="image" data-base62-sha1="nvOQXcVgWSbga6klI0DQp9eZRHF" width="690" height="249" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/a/4/a4cad30245d404065cec66ff7cc7ed8dbec86a7f_2_690x249.png, https://discuss.pytorch.org/uploads/default/original/3X/a/4/a4cad30245d404065cec66ff7cc7ed8dbec86a7f.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/a/4/a4cad30245d404065cec66ff7cc7ed8dbec86a7f.png 2x" data-dominant-color="DADADA"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">903×326 99.8 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>yet it is not this image</p>
<p>help me plzz <a class="mention" href="/u/ptrblck">@ptrblck</a></p>

Sayed_Nadim: <p>Hey <a class="mention" href="/u/randino">@randino</a> ,<br>
Your code is wrong.<br>
You are using <code>mat</code> to load your image and again assigning <code>mat</code> to a tensor with random value. So, no matter how many times you change the image path, you will get a random image. Let me explain.<br>
This two lines will read the <code>mat</code> file.</p>
<pre><code class="lang-auto">mat = pjoin('./sample_data/', 'img.mat')
    #print('Mat loading ...')
mat = sio.loadmat(mat) # image values are loaded into 'mat' variable 
</code></pre>
<p>So, <code>mat</code> is now a numpy array image. But, this line will assign a tensor with random values, overwriting previous <code>mat</code> value.</p>
<pre><code class="lang-auto">mat = torch.randn(1, 1, 100, 100) # you are assigning a random tensor to 'mat' variable 
</code></pre>
<p>So, when you try to show or save the image, you get a random image.</p>
<pre><code class="lang-auto">plt.imshow(torchvision.utils.make_grid(mat).permute(1, 2, 0) # this mat is a random tensor
</code></pre>
<p>You can try the following.</p>
<pre><code class="lang-auto">mat = pjoin('./sample_data/', 'img.mat')
    #print('Mat loading ...')
mat = sio.loadmat(mat)
## extract image from mat
## .....
## .....
mat = torchvision.transforms.ToTensor()(mat)
#save image
torchvision.utils.save_image(mat, "image.png")
#show image 
plt.imshow(torchvision.transforms.ToPILImage()(mat))
plt.show()
</code></pre>

randino: <p><a class="mention" href="/u/sayed_nadim">@Sayed_Nadim</a>  thank you for your reply</p>
<p>but this error</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/3X/7/5/7524af478d1d6b7abb8a7af3044dd1af9bf52646.png" alt="image" data-base62-sha1="gIisyCmna52V0kZw8MaFTfqS3EW" width="690" height="213"></p>

Sayed_Nadim: <p>Hi <a class="mention" href="/u/randino">@randino</a> ,<br>
My bad! I have edited the code. Please check.</p>

randino: <p>HI <a class="mention" href="/u/sayed_nadim">@Sayed_Nadim</a><br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/0/3/03d13b3b60572490344a51469002dfc62e6c312a.png" data-download-href="https://discuss.pytorch.org/uploads/default/03d13b3b60572490344a51469002dfc62e6c312a" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/0/3/03d13b3b60572490344a51469002dfc62e6c312a.png" alt="image" data-base62-sha1="xLHVIIPYJUbH2NigeVV6bOSFD4" width="690" height="300" data-dominant-color="F5F5F9"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">829×361 14.7 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>in this line the problem</p>
<pre><code class="lang-auto">mat = torchvision.transforms.ToTensor()(mat)
</code></pre>

Sayed_Nadim: <p>Hi <a class="mention" href="/u/randino">@randino</a>,<br>
This is expected as <code>mat</code> files are <code>dict</code> files with <code>keys</code> being the <code>MATLAB</code> variables and <code>values</code> being the objects assigned to those variables.<br>
Please refer to this <a href="https://www.askpython.com/python/examples/mat-files-in-python" rel="noopener nofollow ugc">answer</a>.</p>

randino: <p>Thank you <a class="mention" href="/u/sayed_nadim">@Sayed_Nadim</a></p>
<p>But when I saved in my computer size (256,256) and  whenI read with matlab I find the size change (252, 262)!</p>

Sayed_Nadim: <p>Please check if you have any resize operation anywhere in code. Also, check your saving code.</p>

randino: <p>No i just did right button save image</p>

randino: <p>Hi <a class="mention" href="/u/sayed_nadim">@Sayed_Nadim</a> <a class="mention" href="/u/ptrblck">@ptrblck</a>  how I save the image in my computer plzz</p>

Sayed_Nadim: <p>Hi <a class="mention" href="/u/randino">@randino</a> ,<br>
Please check the following minimal example on how to read, save and load image from <code>mat</code> file.</p>
<pre><code class="lang-auto">import scipy.io as sio
import matplotlib.pyplot as plt
import numpy as np

# taking the cifar-10 mat version for testing
mat = './cifar-10-batches-mat/data_batch_1.mat'
# loading mat file
mat = sio.loadmat(mat)
# finding the key values
print(mat.keys())
# output:  dict_keys(['__header__', '__version__', '__globals__', 'data', 'labels', 'batch_label'])

# we will take the "data" key from the dict as it contains images
data = np.asarray(mat.get('data'))
# reshaping the raw data into image format (channel first approach)
data = data.reshape((-1, 3, 32, 32))
data = data.swapaxes(3, 2).swapaxes(1, 3)  # swapping axes for image correction
data_image = data[0]  # taking the first image of the dataset
print(data_image.shape)
# output: (32,32,3)
plt.imsave('./data_image.jpg', np.asarray(data_image))  # saving the image

# reading back
image = plt.imread('/home/la-belva/code_ground/data_image.jpg')  # reading the saved image
print(image.shape)
# output: (32,32,3)
</code></pre>
<p>Let me know if you face any problems.<br>
<img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=10" title=":slight_smile:" class="emoji only-emoji" alt=":slight_smile:"></p>

randino: <p><a class="mention" href="/u/sayed_nadim">@Sayed_Nadim</a> <a class="mention" href="/u/ptrblck">@ptrblck</a>  it did not work</p>

Sayed_Nadim: <p>What seems to be the problem?</p>

randino: <p><a class="mention" href="/u/sayed_nadim">@Sayed_Nadim</a>  I want to display the results of the classification (prediction of the code) in image, how?</p>
<p>I tested by this code which gave by <a class="mention" href="/u/ptrblck">@ptrblck</a>  but still displays this image</p>
<pre><code class="lang-auto">print('Validation accuracy test: {:.4f}%'.format(float(accuracy_score(val_y, predictions)) * 100))
conf_matrix  = confusion_matrix(val_y, predictions)
print(conf_matrix)
predictions = torch.randn(1, 1, 224, 224)
plt.imshow(torchvision.utils.make_grid(predictions).permute(1, 2, 0))  
</code></pre>
<p><img src="https://discuss.pytorch.org/uploads/default/original/3X/6/9/69ebf2487426aa7bb7fcbe83db4f31b2b5d720d0.png" alt="image" data-base62-sha1="f71E85Ikfd0T7T2sy4dpISA7KGA" width="248" height="252"></p>