close

[Solved] PyTorch – Getting the ‘TypeError: pic should be PIL Image or ndarray. Got ‘ error

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error PyTorch – Getting the ‘TypeError: pic should be PIL Image or ndarray. Got <class ‘numpy.ndarray’>’ in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How PyTorch – Getting the ‘TypeError: pic should be PIL Image or ndarray. Got <class ‘numpy.ndarray’> ‘ Error Occurs?

Today I get the following error PyTorch – Getting the ‘TypeError: pic should be PIL Image or ndarray. Got <class ‘numpy.ndarray’>’ in python.

How To Solve PyTorch – Getting the ‘TypeError: pic should be PIL Image or ndarray. Got <class ‘numpy.ndarray’>’ Error ?

  1. How To Solve PyTorch – Getting the 'TypeError: pic should be PIL Image or ndarray. Got ' Error ?

    To Solve PyTorch – Getting the 'TypeError: pic should be PIL Image or ndarray. Got <class 'numpy.ndarray'>' Error you cannot use transforms.ToTensor() on numpy.ndarray objects. You can convert numpy arrays to torch tensors using torch.from_numpy() and then cast your tensor to the required datatype.

  2. PyTorch – Getting the 'TypeError: pic should be PIL Image or ndarray. Got ' error

    To Solve PyTorch – Getting the 'TypeError: pic should be PIL Image or ndarray. Got <class 'numpy.ndarray'>' Error you cannot use transforms.ToTensor() on numpy.ndarray objects. You can convert numpy arrays to torch tensors using torch.from_numpy() and then cast your tensor to the required datatype.

Solution 1

you cannot use transforms.ToTensor() on numpy.ndarray objects. You can convert numpy arrays to torch tensors using torch.from_numpy() and then cast your tensor to the required datatype.


Eg:

>>> import numpy as np
>>> import torch
>>> np_arr = np.ones((5289, 38))
>>> torch_tensor = torch.from_numpy(np_arr).long()
>>> type(np_arr)
<class 'numpy.ndarray'>
>>> type(torch_tensor)
<class 'torch.Tensor'>

Solution 2

This happens because of the transformation you use:

self.transform = transforms.Compose([transforms.ToTensor()])

As you can see in the documentation, torchvision.transforms.ToTensor converts a PIL Image or numpy.ndarray to tensor. So if you want to use this transformation, your data has to be of one of the above types.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read