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

username: Mona_Jalal
cooked: <p>For the following code:</p>
<pre><code class="lang-auto">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
</code></pre>
<p>I get the following error:</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-82-e22271bc36d7&gt; in &lt;module&gt;
     11 
     12 for i in range(len(transformed_dataset)):
---&gt; 13     sample = transformed_dataset[i]
     14 
     15     print(i, sample['image'].size(), sample['landmarks'].size())

&lt;ipython-input-48-9d04158922fb&gt; in __getitem__(self, idx)
     30 
     31         if self.transform:
---&gt; 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:
---&gt; 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         """
--&gt; 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):
--&gt; 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 &lt;class 'dict'&gt;.
</code></pre>

username: Mona_Jalal
cooked: <p>Also, using this other code, I got another error:</p>
<pre><code class="lang-auto">'''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
</code></pre>
<p>Error is:</p>
<pre><code class="lang-auto">
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-86-56c15f3aa1fa&gt; in &lt;module&gt;
     27 
     28 for i in range(len(transformed_dataset)):
---&gt; 29     sample = transformed_dataset[i]
     30 
     31     print(i, sample['image'].size(), sample['landmarks'].size())

&lt;ipython-input-48-9d04158922fb&gt; in __getitem__(self, idx)
     30 
     31         if self.transform:
---&gt; 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:
---&gt; 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         """
--&gt; 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):
--&gt; 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 &lt;class 'dict'&gt;
</code></pre>

username: wxystudio
cooked: <aside class="quote no-group" data-username="Mona_Jalal" data-post="1" data-topic="99264">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mona_jalal/48/25715_2.png" class="avatar"> Mona_Jalal:</div>
<blockquote>
<p><code>MothLandmarksDataset</code></p>
</blockquote>
</aside>
<p>you can try <code>print(type(img))</code> before <code>img = t(img)</code> , it is obvious that the img is not a tensor , you can convert it to a torch.tensor</p>

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