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.

Answer from Miriam Farber on Stack Overflow
🌐
PyTorch Forums
discuss.pytorch.org › vision
Pic should be PIL Image or ndarray. Got <class 'torch.Tensor'> - vision - PyTorch Forums
August 31, 2020 - import torch import torchvision from torch.utils.data import Dataset,DataLoader from sklearn import preprocessing class youtubeFacial(Dataset): def __init__(self,transform=None): raw_data = pd.read_csv('../input/fpoints/training.csv') raw_data.fillna(0,inplace = True) self.n_samples = raw_data.shape[0] raw_data['Image'] = raw_data['Image'].apply(lambda img: np.fromstring(img, sep = ' ')) X = np.vstack(raw_data['Image'].values) X = X.reshape(-1, 1, 96, 96) X...
Discussions

transforms.ToPILImage(): pic should be Tensor or ndarray
I am trying to convert a torch.FloatTensor, representing a 8-bit greyscale, to a PIL image (I am fairly new to pytorch). Whenever I do this, I get the following error: pic should be Tensor or ndarr... More on github.com
🌐 github.com
7
February 6, 2018
Pic should be Tensor or ndarray. Got <class 'dict'>
im facing the problem ‘pic should be tensor or ndarray’ . i check both img and to pil image on transforms. how to fix this problem ? Blockquote TypeError: Caught TypeError in DataLoader worker process 0. Original Traceback (most recent call last): File “/usr/local/lib/python3.6/dist-packages/torch... More on discuss.pytorch.org
🌐 discuss.pytorch.org
0
0
October 18, 2020
TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'>
TypeError: pic should be PIL Image or ndarray. Got #12 More on github.com
🌐 github.com
1
December 25, 2020
TypeError: pic should be Tensor or ndarray. Got <class 'PIL.Image.Image'>.
21K subscribers in the pytorch community. Pytorch is an open source machine learning framework with a focus on neural networks. More on reddit.com
🌐 r/pytorch
1
0
July 19, 2022
🌐
PyTorch Forums
discuss.pytorch.org › t › typeerror-pic-should-be-pil-image-or-ndarray-got-class-numpy-ndarray › 20134
TypeError: pic should be PIL Image or ndarray. Got <class 'numpy.ndarray'> - PyTorch Forums
June 23, 2018 - Could you print the shape and type or your input · I have the same issue, being that my data is of size torch.Size([32, 3, 64, 64]), and I’m using the transformations: · The ability to apply torchvision.transforms on tensors is relatively new and makes it easier now
🌐
GitHub
github.com › pytorch › vision › issues › 408
transforms.ToPILImage(): pic should be Tensor or ndarray · Issue #408 · pytorch/vision
February 6, 2018 - I am trying to convert a torch.FloatTensor, representing a 8-bit greyscale, to a PIL image (I am fairly new to pytorch). Whenever I do this, I get the following error: pic should be Tensor or ndarray. Got I do...
Author   pytorch
🌐
PyTorch Forums
discuss.pytorch.org › vision
Pic should be Tensor or ndarray. Got <class 'dict'> - vision - PyTorch Forums
October 18, 2020 - im facing the problem ‘pic should be tensor or ndarray’ . i check both img and to pil image on transforms. how to fix this problem ? Blockquote TypeError: Caught TypeError in DataLoader worker process 0. Original Tr…
🌐
Chsasank
chsasank.com › vision › _modules › torchvision › transforms.html
torchvision.transforms — Torchvision master documentation
from __future__ import division import torch import math import random from PIL import Image, ImageOps, ImageEnhance try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections import warnings def _is_pil_image(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3 def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) def to_tensor(pic): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(_is_pil_image(pic) or _is_numpy_image(pic)): raise TypeError('pic should be PIL Image or ndarray.
🌐
GitHub
github.com › fredzzhang › spatio-attentive-graphs › issues › 12
TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'> · Issue #12 · fredzzhang/spatially-conditioned-graphs
December 25, 2020 - Got {}'.format(type(pic))) TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'>
Author   fredzzhang
🌐
Reddit
reddit.com › r/pytorch › typeerror: pic should be tensor or ndarray. got .
TypeError: pic should be Tensor or ndarray. Got <class 'PIL.Image.Image'>. : r/pytorch
July 19, 2022 - 21K subscribers in the pytorch community. Pytorch is an open source machine learning framework with a focus on neural networks.
Find elsewhere
🌐
PyTorch
docs.pytorch.org › vision › 0.9 › _modules › torchvision › transforms › functional.html
torchvision.transforms.functional — Torchvision master documentation
See :class:`~torchvision.transforms.ToTensor` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(F_pil._is_pil_image(pic) or _is_numpy(pic)): raise TypeError('pic should be PIL Image or ndarray.
🌐
Catalyst-team
catalyst-team.github.io › catalyst › v21.03 › _modules › catalyst › data › transforms.html
catalyst.data.transforms — Catalyst 21.03 documentation
# based on https://github.com/pytorch/vision import numpy as np import torch _IMAGENET_STD = (0.229, 0.224, 0.225) _IMAGENET_MEAN = (0.485, 0.456, 0.406) def to_tensor(pic: np.ndarray) -> torch.Tensor: """Convert ``numpy.ndarray`` to tensor. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: torch.Tensor: Converted image. Raises: TypeError: if `pic` is not np.ndarray ValueError: if `pic` is not 2/3 dimensional.
🌐
Reddit
reddit.com › r/pytorch › resize transform on custom dataset
r/pytorch on Reddit: resize transform on custom dataset
June 29, 2022 -

I'm using a pretrained VGG19 on a custom image dataset that I would like to be resized to (150, 150, 3). I've used both ToTensor and Resize transforms with transform.Compose(), and I'm running into the following error (below). I have also pasted my code below this. Does anyone know how I can fix this?

in <module>

img, label = ds[sample_idx]

in __getitem__

image = self.transform(image)

in __call__

img = t(img)

in __call__

return F.to_tensor(pic)

in to_tensor

raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))

TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'>

MY CODE:

# create custom image dataset
class CustomImageDataset(torch.utils.data.Dataset):
def __init__(self, annotations_path, data_path, transform=None, target_transform=None):
self.labels = pd.read_csv(annotations_path)
self.data_path = data_path
self.transform = transform
self.target_transform = target_transform

def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
img_path = os.path.join(self.data_path, self.labels.iloc[idx,0])

image = torchvision.io.read_image(img_path)
label = self.labels.iloc[idx,1]
if self.transform:
image = self.transform(image)
if self.target_transform:
label = self.target_transform(label)
return image, label
# define transforms
transforms = torchvision.transforms.Compose([
torchvision.transforms.Resize((150,150)),
torchvision.transforms.ToTensor()
])
# initialize dataset
annotations_path = 'cats_dogs_dataset_torch/annotations/annotations.csv'
data_path = 'cats_dogs_dataset_torch/data'
ds = CustomImageDataset(
annotations_path=annotations_path,
data_path=data_path,
transform=transforms
)
# visualize dataset
labels_map = {
0: "Cat",
1: "Dog"
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
sample_idx = torch.randint(len(ds), size=(1,)).item()
img, label = ds[sample_idx]
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis("off")
plt.imshow(img.squeeze().permute(1,2,0))
plt.show()

# split data into train, validation, test
length = ds.__len__()
train_size = int(length * .8)
remaining_after_train = length - train_size
val_size = int(remaining_after_train * 0.5)
remaining_after_val = remaining_after_train - val_size
test_size = remaining_after_val
print(f'length: {length}')
print(f'train_size: {train_size}')
print(f'val_size: {val_size}')
print(f'test_size: {val_size}')
ds_train, ds_val, ds_test = torch.utils.data.random_split(
dataset=ds,
lengths=[train_size,val_size,test_size]
)
# wrap in dataloader
dl_train = torch.utils.data.DataLoader(ds_train, batch_size=64)
dl_val = torch.utils.data.DataLoader(ds_val, batch_size=64)
dl_test = torch.utils.data.DataLoader(ds_test, batch_size=64)
# build model
model = torchvision.models.vgg19(pretrained=True)
# freeze the feature extractor
for param in model.features.parameters():
param.requires_grad = False
# replace the classifier with appropriate layers
model.classifier = torch.nn.Sequential(
torch.nn.Linear(25088,8192),
torch.nn.ReLU(inplace=True),
torch.nn.Linear(8192,256),
torch.nn.ReLU(inplace=True),
torch.nn.Linear(256,1),
torch.nn.Sigmoid()
)
print(model)
'''HYPERPARAMETERS'''
lr = 1e-3
batch_size = 64
epochs = 5

# '''OPTIMIZATION LOOP'''
loss_fn = torch.nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(),lr=lr)
'''TRAINING'''
epochs = 25
for epoch in range(epochs):
# train loop
for batch_idx, (x, y) in enumerate(dl_train):
train_size = len(dl_train.dataset)
# forward pass
pred = model(x)
# compute loss
loss = loss_fn(pred, y)
# backward pass
optimizer.zero_grad()
loss.backward()
# update weights
optimizer.step()
# update accuracy / loss
if batch_idx % 100 == 0:
loss, current = loss.item(), batch_idx * len(x)
print(f'loss: {loss:>7f} [{current:>5d}/{train_size:>5d}]')

# test loop
num_batches = len(dl_val)
size = len(dl_val.dataset)
test_loss, correct = 0,0
with torch.no_grad():
for x, y in dl_val:
# foward pass
pred = model(x)
# compute loss
test_loss += loss_fn(pred, y)
correct += (pred.argmax(1) == y).type(torch.float).sum().item()

test_loss /= num_batches
correct /= size
print(f'Test Error: \n Accuracy: {(100 * correct):>0.1f}%, Avg loss: {test_loss:>8f} \n')

print('Done!')

🌐
Lightrun
lightrun.com › answers › pytorch-vision-transformstopilimage-pic-should-be-tensor-or-ndarray
transforms.ToPILImage(): pic should be Tensor or ndarray
import torch import torchvision.transforms.functional as F a = torch.FloatTensor(1, height, width) a = F.to_pil_image(a) (i.e. yours needs to be a [1, Height, Width] shaped tensor). Although this error message sucks, I will open a ticket to improve that ... TypeError: pic should be Tensor or ndarray. Got <class ‘numpy.ndarray’>. Read more comments on GitHub >
🌐
PyTorch
docs.pytorch.org › vision › 0.14 › _modules › torchvision › transforms › functional.html
torchvision.transforms.functional — Torchvision 0.14 documentation
Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not torch.jit.is_scripting() and not torch.jit.is_tracing(): _log_api_usage_once(to_tensor) if not (F_pil._is_pil_image(pic) or _is_numpy(pic)): raise TypeError(f"pic should be PIL Image or ndarray.
🌐
PyTorch
docs.pytorch.org › vision › 0.8 › _modules › torchvision › transforms › functional.html
torchvision.transforms.functional — Torchvision 0.8.1 documentation
Raises: RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range of the integer ``dtype``. """ if not isinstance(image, torch.Tensor): raise TypeError('Input img should be Tensor Image') return F_t.convert_image_dtype(image, dtype) [docs]def to_pil_image(pic, mode=None): """Convert a tensor or an ndarray to PIL Image.
🌐
PyTorch Forums
discuss.pytorch.org › vision
Having TypeError: pic should be PIL Image or ndarray. Got <class 'NoneType'> For custom dataset - vision - PyTorch Forums
March 2, 2023 - I’m trying to use a custom unlabeled dataset for self-supervised training and I got “TypeError: pic should be PIL Image or ndarray. Got <class ‘NoneType’>”. I have double checked the image files in the directory and it i…