title: How to convert RGB images to grayscale in PyTorch dataloader?
body: <p>I've downloaded some sample images from the MNIST dataset in <code>.jpg</code> format. Now I'm loading those images for testing my pre-trained model.</p>
  
  <pre><code># transforms to apply to the data
  trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
  
  # MNIST dataset
  test_dataset = dataset.ImageFolder(root=DATA_PATH, transform=trans)
  
  # Data loader
  test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
  </code></pre>
  
  <p>Here <code>DATA_PATH</code> contains a subfolder with the sample image.</p>
  
  <p>Here's my network definition</p>
  
  <pre><code># Convolutional neural network (two convolutional layers)
  class ConvNet(nn.Module):
      def __init__(self):
          super(ConvNet, self).__init__()
          self.network2D = nn.Sequential(
             nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2),
             nn.ReLU(),
             nn.MaxPool2d(kernel_size=2, stride=2),
             nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),
             nn.ReLU(),
             nn.MaxPool2d(kernel_size=2, stride=2))
          self.network1D = nn.Sequential(
             nn.Dropout(),
             nn.Linear(7 * 7 * 64, 1000),
             nn.Linear(1000, 10))
  
      def forward(self, x):
          out = self.network2D(x)
          out = out.reshape(out.size(0), -1)
          out = self.network1D(out)
          return out
  </code></pre>
  
  <p>And this is my inference part</p>
  
  <pre><code># Test the model
  model = torch.load("mnist_weights_5.pth.tar")
  model.eval()
  
  for images, labels in test_loader:
     outputs = model(images.cuda())
  </code></pre>
  
  <p>When I run this code, I get the following error:</p>
  
  <pre><code>RuntimeError: Given groups=1, weight of size [32, 1, 5, 5], expected input[1, 3, 28, 28] to have 1 channels, but got 3 channels instead
  </code></pre>
  
  <p>I understand that the images are getting loaded as 3 channels (RGB). So how do I convert them to single channel in the <code>dataloader</code>?</p>
  
  <p>Update:
  I changed <code>transforms</code> to include <code>Grayscale</code> option</p>
  
  <pre><code>trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), transforms.Grayscale(num_output_channels=1)])
  </code></pre>
  
  <p>But now I get this error</p>
  
  <pre><code>TypeError: img should be PIL Image. Got &lt;class 'torch.Tensor'&gt;
  </code></pre>