How to show a image in jupyter notebook with pytorch easily?
like in itorch, I can use itorch.image to show a image in the notebook.
richardhahahaha
Yeah this frustrated me a lot too because it’s so easy with itorch… You have a few options with python but there’s not a stand-alone command that I’m aware of for displaying an image from a PyTorch Tensor.  If you convert to a PIL image then you can just execute the Image variable in a cell and it will display the image.  To load to PIL: <SCODE>img =  Image.open('path-to-image-file').convert('RGB')
<ECODE> Or to convert straight from a PyTorch Tensor: <SCODE>to_pil = torchvision.transforms.ToPILImage()
img = to_pil(your-tensor)

<ECODE>
amdegroot
this is how I display an image: <SCODE>import torch as t
from torchvision.transforms import ToPILImage
from IPython.display import Image
to_img = ToPILImage()

# display tensor
a = t.Tensor(3, 64, 64).normal_()
to_img(a)

# display imagefile
Image('/path/to/my.png')
<ECODE>
chenyuntc
you can look at my notebook here, but yea seems like no standard solution. Basically, I do: <SCODE>%matplotlib inline
def show(img):
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1,2,0)), interpolation='nearest')
<ECODE>
smth
Hi Soumith, I would like to know how I can use your solution, if I am using iterator like this <SCODE>dataiter = iter(trainloader)
images, labels = dataiter.next()
<ECODE> Thank you in advance.
oya163
I have same question…
farrokhi
<SCODE>    display(Image(image_path))
<ECODE>
Vimos
This is what I did, hope can be helpful for someone. <SCODE>from PIL import Image
`image = Image.open('img_path.jpg').convert('RGB')
 plt.imshow(np.transpose(np.asarray(content.squeeze()),(1,2,0)))`

<ECODE>
talha3111997
What I did: transfer the tensor to numpy array, reshape(if needed), and use plt.imshow(): <SCODE>import matplotlib.pyplot as plt
img_np_arr = img_tensor.numpy()   # transfer the pytorch tensor(img_tensor) to numpy array
img_np_arr.shape    # check shape before reshape if needed
img_np_arr_reshaped = img_np_arr.reshape(img_w, img_h)  # reshape to 2-dims image
plt.imshow(img_np_arr_reshaped, cmap='gray')   # when display the grayscale image
<ECODE>
xiaoyanzhuo
This worked flawlessly for displaying an image from CIFAR-100 dataset. Thank you!
ramapinnimty