Reputation: 269
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
Upvotes: 11
Views: 55051
Reputation: 53
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)
Upvotes: 0
Reputation: 2006
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)
Upvotes: 1
Reputation: 169
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
Upvotes: 14
Reputation: 83
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()
Upvotes: 0
Reputation: 982
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
).
Upvotes: 19