Converting RGB into Grayscale

username: brunoj
cooked: <p>Hello. I have 3 folders with images subfolders as train, test and validate. I have used T.Grayscale(1) to convert into grayscale but when I show the image , its like this. I dont understand why? Here is the image which Im getting<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/9/1/91a141ad145d35d4e11249d5db15f29ea6594480.png" data-download-href="https://discuss.pytorch.org/uploads/default/91a141ad145d35d4e11249d5db15f29ea6594480" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/9/1/91a141ad145d35d4e11249d5db15f29ea6594480_2_690x388.png" alt="image" data-base62-sha1="kMiISbEqjRC5oCG3gRLuNd97iOA" width="690" height="388" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/9/1/91a141ad145d35d4e11249d5db15f29ea6594480_2_690x388.png, https://discuss.pytorch.org/uploads/default/optimized/3X/9/1/91a141ad145d35d4e11249d5db15f29ea6594480_2_1035x582.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/9/1/91a141ad145d35d4e11249d5db15f29ea6594480_2_1380x776.png 2x" data-dominant-color="EFEEE3"><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">1920×1080 226 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>my code is here:<br>
import matplotlib.pyplot as plt<br>
import torch.nn.functional as F<br>
import torch<br>
import numpy as np</p>
<p>def show_image(image,label):</p>
<pre><code>image = image.permute(1,2,0)
plt.imshow(image)
plt.title(label)
</code></pre>
<p>def show_grid(image,title = None):</p>
<pre><code>image = image.permute(1,2,0)


plt.figure(figsize=[15, 15])
plt.imshow(image)
if title != None:
    plt.title(title)
</code></pre>
<p>def accuracy(y_pred,y_true):<br>
y_pred = F.softmax(y_pred,dim = 1)<br>
top_p,top_class = y_pred.topk(1,dim = 1)<br>
equals = top_class == y_true.view(*top_class.shape)<br>
return torch.mean(equals.type(torch.FloatTensor))</p>
<p>def view_classify(image,ps,label):</p>
<pre><code>class_name = ['F', 'M' ,'N', 'S', 'Q','V']
classes = np.array(class_name)

ps = ps.cpu().data.numpy().squeeze()

image = image.permute(1,2,0)

fig, (ax1, ax2) = plt.subplots(figsize=(8,12), ncols=2)
ax1.imshow(img)
ax1.set_title('Ground Truth : {}'.format(class_name[label]))
ax1.axis('off')
ax2.barh(classes, ps)
ax2.set_aspect(0.1)
ax2.set_yticks(classes)
ax2.set_yticklabels(classes)
ax2.set_title('Predicted Class')
ax2.set_xlim(0, 1.1)

plt.tight_layout()

return None
</code></pre>
<p>train_transform = T.Compose([</p>
<pre><code>                         T.Resize(size=(CFG.img_size,CFG.img_size)), 
                         T.ToTensor(), 
                         T.Grayscale(num_output_channels=1)
</code></pre>
<p>])</p>
<p>validate_transform = T.Compose([</p>
<pre><code>                         T.Resize(size=(CFG.img_size,CFG.img_size)), 
                        
                         T.ToTensor(),
                         T.Grayscale(num_output_channels=1)
</code></pre>
<p>])</p>
<p>test_transform = T.Compose([</p>
<pre><code>                         T.Resize(size=(CFG.img_size,CFG.img_size)), # Resizing the image to be 32 by 22
                         
                         T.ToTensor(), 
                         T.Grayscale(num_output_channels=1)
</code></pre>
<p>])</p>

username: brunoj
cooked: <p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/9/4/945b70fbac8dcfebce8aacb5e1f8afa5be54cfb9.png" data-download-href="https://discuss.pytorch.org/uploads/default/945b70fbac8dcfebce8aacb5e1f8afa5be54cfb9" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/9/4/945b70fbac8dcfebce8aacb5e1f8afa5be54cfb9_2_690x388.png" alt="image" data-base62-sha1="laqzP2A1ZRy8B1m4kupt8epVY5b" width="690" height="388" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/9/4/945b70fbac8dcfebce8aacb5e1f8afa5be54cfb9_2_690x388.png, https://discuss.pytorch.org/uploads/default/optimized/3X/9/4/945b70fbac8dcfebce8aacb5e1f8afa5be54cfb9_2_1035x582.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/9/4/945b70fbac8dcfebce8aacb5e1f8afa5be54cfb9_2_1380x776.png 2x" data-dominant-color="343333"><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">1920×1080 74.1 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><br>
The original images are like thid. But above output imge gets blurry as well. I understand i changed the size like 32x32 from original size 438x288 so maybe thats the reason it is blurry.</p>

username: ptrblck
cooked: <p><code>matplotlib.pyplot.plot</code> uses the <code>viridis</code> colormap by default so you would need to use <code>cmap="gray"</code> to show the image in grayscale:</p>
<pre><code class="lang-python">img = np.random.randint(0, 256, (32, 32)).astype(np.uint8)
plt.imshow(img)

plt.imshow(img, cmap="gray")
</code></pre>
<p>Yes, resizing the image to 32x32 pixels will create these artifacts.</p>

username: brunoj
cooked: <p>Thankyou so much. This worked for me. I have trained my model, saved the weights and tested now Im trying to use view_classify from a tutorial but it is giving me errors like invalid shape for image data. What can I do? I searched it here people said copy the helper.py and add i dont know where is helper.py as I just used the tutorial but nothing is mentioned there.  Someone on the forum pasted this code:<br>
import matplotlib.pyplot as plt<br>
import numpy as np</p>
<p>def view_classify(img, ps, version=“MNIST”):<br>
‘’’ Function for viewing an image and it’s predicted classes.<br>
‘’’<br>
ps = ps.data.numpy().squeeze()</p>
<pre><code>fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)
ax1.imshow(img.resize_(1, 28, 28).numpy().squeeze())
ax1.axis('off')
ax2.barh(np.arange(10), ps)
ax2.set_aspect(0.1)
ax2.set_yticks(np.arange(10))
if version == "MNIST":
    ax2.set_yticklabels(np.arange(10))
elif version == "Fashion":
    ax2.set_yticklabels(['T-shirt/top',
                        'Trouser',
                        'Pullover',
                        'Dress',
                        'Coat',
                        'Sandal',
                        'Shirt',
                        'Sneaker',
                        'Bag',
                        'Ankle Boot'], size='small');
ax2.set_title('Class Probability')
ax2.set_xlim(0, 1.1)
</code></pre>
<p>plt.tight_layout()</p>
<p>I saved it as view_classify.ipynb and uploaded to colab. like this:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/8/0/8061cfade77c16b0f03c3e04b61b6527f34e18f8.png" data-download-href="https://discuss.pytorch.org/uploads/default/8061cfade77c16b0f03c3e04b61b6527f34e18f8" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/8/0/8061cfade77c16b0f03c3e04b61b6527f34e18f8_2_690x388.png" alt="image" data-base62-sha1="ijIFTXAJxp8JmkbbXFOXWRXmqda" width="690" height="388" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/8/0/8061cfade77c16b0f03c3e04b61b6527f34e18f8_2_690x388.png, https://discuss.pytorch.org/uploads/default/optimized/3X/8/0/8061cfade77c16b0f03c3e04b61b6527f34e18f8_2_1035x582.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/8/0/8061cfade77c16b0f03c3e04b61b6527f34e18f8_2_1380x776.png 2x" data-dominant-color="EDEDEE"><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">1920×1080 277 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>And I got error in the image above. Plz tell how to fix asap. My dataset is from kaggle ecg data images and 32x32x1 CHANNEL.</p>

username: brunoj
cooked: <p><a href="https://medium.com/geekculture/train-a-pytorch-efficientnet-model-for-medical-diagnosis-1d000c540bd" class="inline-onebox" rel="noopener nofollow ugc">Train an EfficientNet Model in PyTorch for Medical Diagnosis | by Yaokun Lin @ MachineLearningQuickNotes | Geek Culture | Medium</a>   This is the tutorial that Im following.</p>

username: ptrblck
cooked: <p>I would guess channels-last data layout is expected so <code>permute</code> your tensor into <code>[height, width, channels]</code> and it should work.</p>