SVHN data grayscale and resize

torlarse: <p>Hi, sorry for yet another SVHN grayscale and resize problem permutation. After following lots of advice here on the forum I have a solution that renders some output. However when plotting a sample image it just shows a distorted color image, instead of the expected grayscale house number.</p>
<p>EDIT: I want a SVHN dataset with images in grayscale and size 28 x 28 in order to train the dataset on my MNIST CNN routine.  Is this a correct method for fetching the dataset?</p>
<pre><code class="lang-auto">import torch
import torchvision
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import matplotlib.pyplot as plt

class GetDataset(datasets.SVHN):
    def __init__(self, root, split='train',
                 transform=None, target_transform=None, download=True):
        super(GetDataset, self).__init__(
            root, split, transform, target_transform, download)

    def __getitem__(self, index):
        """
        Args:
            index (int): Index
        Returns:
            tuple: (image, target) where target is index of the target class.
        """
        img, target = self.data[index], int(self.labels[index])

        if self.transform is not None:
            img = self.transform(img)

        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target


svhn_transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.Resize((28, 28)),
    transforms.Grayscale(num_output_channels=1),
    transforms.ToTensor(),
    # transforms.Normalize((0.5, 0.5), (0.5, 0.5))
    transforms.Normalize([0.5], [0.5])
])


def main():
    svhn_training_dataset = GetDataset(
        root='./data',
        transform=svhn_transform
    )
    svhn_training_set_loader = torch.utils.data.DataLoader(svhn_training_dataset,
                                                           batch_size=128,
                                                           shuffle=True,
                                                           num_workers=1)
    test_img, test_lb = next(iter(svhn_training_set_loader))
    plt.imshow(test_img[0, 0], cmap='gray')
    plt.show()


if __name__ == '__main__':
    main()
</code></pre>
<details>
<summary>
Summary</summary>
<p>This text will be hidden</p>
</details>

torlarse: <p>After a bit of fiddling I find that setting <code>transforms.Resize(28)</code> returns an image of shape <code>(28, 298)</code>. Could my use of the <code>Grayscale()</code> function be wrong?</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/3X/a/d/ad1a3b1b08e9445110735bba4705b187a4a00968.png" alt="weird_svhn" data-base62-sha1="oHkNI5oiRHztfyPEQs2VMnbSmec" width="640" height="480"></p>

ptrblck: <p>You are missing the permutation inside your <code>__getitem__</code>:</p>
<pre><code class="lang-python">img, target = self.data[index], int(self.labels[index])
img = np.transpose(img, (1, 2, 0))
if self.transform is not None:
    ...
</code></pre>
<p>Since you are loading each sample as a numpy array, you would have to permute it manually.</p>

torlarse: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> thanks so much for reaching out! Your answer certainly solved the dimensional weirdness.</p>
<p>Unfortunately there is still an issue with the grayscale. A sample image <code>test_img[0]</code> has the shape <code>(1, 28, 28)</code>. If i try <code>plt.imshow(test_img[0].permute(1, 2, 0)</code> that is one dimension too many for <code>imshow()</code>. If I try <code>plt.imshow(test_img[0].squeeze()</code> I get the following picture. That sample image seem neither grayscaled nor appropriately resized. Any ideas?</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/3X/8/4/84c61a1cb5f9b512b87ccd7a124c33c9879840fa.png" alt="squeeze" data-base62-sha1="iWzsnjvciWBpduEFaFIrK64mCn0" width="640" height="480"></p>

ptrblck: <p><code>matplotlib</code> uses the <code>viridis</code> colormap by default.<br>
In your first code snippet you were setting the color map to <code>gray</code> via:</p>
<pre><code class="lang-python">plt.imshow(test_img[0, 0], cmap='gray')
</code></pre>

torlarse: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> sorry for that, of course you are right. I also realize that I was fooled by the high resolution of my screen. Thank you so much for helping, solution accepted.</p>

ptrblck: <p>Haha, there is no reason to be sorry. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=9" title=":wink:" class="emoji" alt=":wink:"><br>
I’m glad it’s working now.</p>