How can I view Tensor as an image?

Question:

I learned some data with tensorflow.

For the test, I saw the shape of the final result.

It was tensor of (1, 80, 80, 1).

I use matplotlib or PIL to do this,

I wanted to see the image after changing to a pie array.

But I could not change the tensor to numpy.

I could not do anything because of the session even if I used eval ().

There is no way to convert tensor to numpy.

Can I see the tensor as an image?

(mytensor1) # mytensor

arr = np.ndarray(mytensor1)
arr_ = np.squeeze(arr)
plt.imshow(arr_)
plt.show()

but there is error message:
TypeError: expected sequence object with len >= 0 or a single integer

Asked By: ONION

||

Answers:

You can use squeeze function from numpy.
For example

arr = np.ndarray((1,80,80,1))#This is your tensor
arr_ = np.squeeze(arr) # you can give axis attribute if you wanna squeeze in specific dimension
plt.imshow(arr_)
plt.show()

Now, you can easily display this image (e.g. above code, assuming you are using matplotlib.pyplot as plt).

Answered By: talos1904

If your image has only one channel (ie: black and white), you can also useplt.matshow:

image = np.random.uniform(0,1, (1,80,80,1))
image = image.reshape(80,80)
plt.matshow(image)
plt.show() 
Answered By: Mounsif Mehdi

For people using PyTorch, the simplest way that I know is this:

import matplotlib.pyplot as plt

plt.imshow(my_tensor.numpy()[0], cmap='gray')

That should do it

Answered By: J. Krajewski

Torch is in shape of channel,height,width need to convert it into height,width, channel so permute.

plt.imshow(white_torch.permute(1, 2, 0))

Or directly if you want

import torch
import torchvision
from torchvision.io import read_image
import torchvision.transforms as T

!wget 'https://images.unsplash.com/photo-1553284965-83fd3e82fa5a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8NHx8fGVufDB8fHx8&w=1000&q=80'  -O white_horse.jpg

white_torch = torchvision.io.read_image('white_horse.jpg')

T.ToPILImage()(white_torch)

enter image description here

Answered By: TheExorcist

Convert the tensor to np.array and reshape it as shown below and change it to 3 channel Image

def tensorToImageConversion(Tensor):
    # if it doesn't work remove *255 and try it 
    Tensor = Tensor*255
    Tensor = np.array(Tensor, dtype=np.uint8)
    if np.ndim(Tensor)>3:
        assert Tensor.shape[0] == 1
        Tensor = Tensor[0]
    return PIL.Image.fromarray(Tensor)
Answered By: Vishvajit Jambuti