TypeError: tensor should be a torch tensor. Got <class 'dict'>

For the following code:

transformed_dataset = MothLandmarksDataset(csv_file='moth_gt.csv',
                                           root_dir='.',
                                           transform=transforms.Compose([
                                               Rescale(256),
                                               RandomCrop(224),
                                               
                                               ToTensor(),
                                               transforms.Normalize(mean = [ 0.485, 0.456, 0.406 ],
                                                        std = [ 0.229, 0.224, 0.225 ])
                                           ]))

for i in range(len(transformed_dataset)):
    sample = transformed_dataset[i]

    print(i, sample['image'].size(), sample['landmarks'].size())

    if i == 3:
        break

I get the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-82-e22271bc36d7> in <module>
     11 
     12 for i in range(len(transformed_dataset)):
---> 13     sample = transformed_dataset[i]
     14 
     15     print(i, sample['image'].size(), sample['landmarks'].size())

<ipython-input-48-9d04158922fb> in __getitem__(self, idx)
     30 
     31         if self.transform:
---> 32             sample = self.transform(sample)
     33 
     34         return sample

~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/transforms.py in __call__(self, img)
     59     def __call__(self, img):
     60         for t in self.transforms:
---> 61             img = t(img)
     62         return img
     63 

~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/transforms.py in __call__(self, tensor)
    210             Tensor: Normalized Tensor image.
    211         """
--> 212         return F.normalize(tensor, self.mean, self.std, self.inplace)
    213 
    214     def __repr__(self):

~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/functional.py in normalize(tensor, mean, std, inplace)
    278     """
    279     if not torch.is_tensor(tensor):
--> 280         raise TypeError('tensor should be a torch tensor. Got {}.'.format(type(tensor)))
    281 
    282     if tensor.ndimension() != 3:

TypeError: tensor should be a torch tensor. Got <class 'dict'>.

Also, using this other code, I got another error:

'''transformed_dataset = MothLandmarksDataset(csv_file='moth_gt.csv',
                                           root_dir='.',
                                           transform=transforms.Compose(
                                               [
                                               Rescale(256),
                                               RandomCrop(224),
                                               
                                               ToTensor(),
                                               transforms.Normalize(mean = [ 0.485, 0.456, 0.406 ],
                                                        std = [ 0.229, 0.224, 0.225 ])
                                               ]
                                                                        )
                                           )'''

transformed_dataset = MothLandmarksDataset(csv_file='moth_gt.csv',
                                           root_dir='.',
                                             transform=transforms.Compose([transforms.Resize(255), 
                                       transforms.CenterCrop(224),  
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ToTensor(), 
                                       transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]))
                                           





for i in range(len(transformed_dataset)):
    sample = transformed_dataset[i]

    print(i, sample['image'].size(), sample['landmarks'].size())

    if i == 3:
        break

Error is:


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-86-56c15f3aa1fa> in <module>
     27 
     28 for i in range(len(transformed_dataset)):
---> 29     sample = transformed_dataset[i]
     30 
     31     print(i, sample['image'].size(), sample['landmarks'].size())

<ipython-input-48-9d04158922fb> in __getitem__(self, idx)
     30 
     31         if self.transform:
---> 32             sample = self.transform(sample)
     33 
     34         return sample

~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/transforms.py in __call__(self, img)
     59     def __call__(self, img):
     60         for t in self.transforms:
---> 61             img = t(img)
     62         return img
     63 

~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/transforms.py in __call__(self, img)
    242             PIL Image: Rescaled image.
    243         """
--> 244         return F.resize(img, self.size, self.interpolation)
    245 
    246     def __repr__(self):

~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/functional.py in resize(img, size, interpolation)
    317     """
    318     if not _is_pil_image(img):
--> 319         raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
    320     if not (isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2)):
    321         raise TypeError('Got inappropriate size arg: {}'.format(size))

TypeError: img should be PIL Image. Got <class 'dict'>

you can try print(type(img)) before img = t(img) , it is obvious that the img is not a tensor , you can convert it to a torch.tensor

sorry I think the error is from transforms.Normalize, and the ToTensor() function doesn’t convert the img to tensor. you can break up the transforms.Compose into step-by-step, and use print(type(img)) to see what type is it.