title: PyTorch - How to use "toPILImage" correctly
body: <p>I would like to know, whether I used <a href="http://pytorch.org/docs/master/torchvision/transforms.html#torchvision.transforms.ToPILImage" rel="nofollow noreferrer">toPILImage</a> from torchvision correctly. I want to use it, to see how the images look after initial image transformations are applied to the dataset.</p>
  
  <p>When I use it like in the code below, the image that comes up has weird colors like <a href="https://i.stack.imgur.com/G9IMe.png" rel="nofollow noreferrer">this one</a>. The original image is a regular RGB image.</p>
  
  <p>This is my code:</p>
  
  <pre><code>import os
  import torch
  from PIL import Image, ImageFont, ImageDraw
  import torch.utils.data as data
  import torchvision
  from torchvision import transforms    
  import matplotlib.pyplot as plt
  
  # Image transformations
  normalize = transforms.Normalize(
      mean=[0.485, 0.456, 0.406],
      std=[0.229, 0.224, 0.225]
      )
  transform_img = transforms.Compose([
      transforms.Resize(256),
      transforms.CenterCrop(256),
      transforms.ToTensor(),
      normalize ])
  
  train_data = torchvision.datasets.ImageFolder(
      root='./train_cl/',
      transform=transform_img
      )
  test_data = torchvision.datasets.ImageFolder(
      root='./test_named_cl/',
      transform=transform_img                                             
      )
  
  train_data_loader = data.DataLoader(train_data,
      batch_size=4,
      shuffle=True,
      num_workers=4) #num_workers=args.nThreads)
  
  test_data_loader = data.DataLoader(test_data,
      batch_size=32,
      shuffle=False,
      num_workers=4)        
  
  # Open Image from dataset:
  to_pil_image = transforms.ToPILImage()
  my_img, _ = train_data[248]
  results = to_pil_image(my_img)
  results.show()
  </code></pre>
  
  <p>Edit:</p>
  
  <p>I had to use .data on the Torch Variable to get the tensor. 
  Also I needed to rescale the numpy array before transposing. I found a working solution <a href="https://stackoverflow.com/questions/47318871/valueerror-floating-point-image-rgb-values-must-be-in-the-0-1-range-while-usi">here</a>, but it doesn't always work well. How can I do this better?</p>
  
  <pre><code>for i, data in enumerate(train_data_loader, 0):
      img, labels = data
      img = Variable(img)
      break
  
  image = img.data.cpu().numpy()[0]
  
  # This worked for rescaling:
  image = (1/(2*2.25)) * image + 0.5
  
  # Both of these didn't work:
  # image /= (image.max()/255.0)
  # image *= (255.0/image.max())
  
  image = np.transpose(image, (1,2,0))
  plt.imshow(image)
  plt.show() 
  </code></pre>