Pic should be PIL Image or ndarray. Got <class 'torch.Tensor'>`

username: aleemsidra
cooked: <p>I am creating a custom DataLoader for my Dataset.</p>
<pre><code class="lang-auto">import numpy as np
import pandas as pd
from __future__ import print_function, division
import os
import cv2
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import  Dataset, DataLoader
from torchvision import transforms, utils
</code></pre>
<p>Here is my custom  class</p>
<pre><code class="lang-auto">class DFU_Dataset(Dataset):
    def __init__(self, root_dir, csv, transform):
        
        self.root_dir = root_dir
        self.landmarks_frame = pd.read_csv(csv)
        self.transform = transform
    
    def __len__(self):
        
        return len(self.landmarks_frame)
    
    def __getitem__(self, idx):
        
        img_name = os.path.join(self.root_dir , self.landmarks_frame.iloc[idx,0])
        image = io.imread(img_name)
        label = np.argmax(self.landmarks_frame.loc[idx, 'none':'both'].values)
        
#          # Transform
        if self.transform is not None: 
            image = self.transform(torch.from_numpy(image))
            label = self.transform(torch.from_numpy(label))
            sample = {'image': image, 'label': label}   
        return sample
</code></pre>
<pre><code class="lang-auto"> transform = transforms.Compose([transforms.ToTensor()])
</code></pre>
<pre><code class="lang-auto">DFU_Dataset = DFU_Dataset(root_dir = '/Users/sidraaleem/Documents/code/DFU/Labelled_test_images',
                          csv = '/Users/sidraaleem/Documents/code/DFU/Labelled_data_ground_truth.csv',
                          transform = transform
                          )
</code></pre>
<p>*Here I am trying to check whether the image, and label have been converted to tensor: *</p>
<pre><code class="lang-auto">for i in range(len(DFU_Dataset)):
    sample = DFU_Dataset[i]
    print(sample)
</code></pre>
<p><strong>However, I am having the below error:</strong></p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-232-2d085f7b0abc&gt; in &lt;module&gt;
      1 for i in range(len(DFU_Dataset)):
----&gt; 2     sample = DFU_Dataset[i]
      3     print(sample)

&lt;ipython-input-229-31f45f491e1e&gt; in __getitem__(self, idx)
     18 #          # Transform
     19         if self.transform is not None:
---&gt; 20             image = self.transform(torch.from_numpy(image))
     21             label = self.transform(torch.from_numpy(label))
     22             sample = {'image': image, 'label': label}

~/opt/anaconda3/lib/python3.8/site-packages/torchvision/transforms/transforms.py in __call__(self, img)
     65     def __call__(self, img):
     66         for t in self.transforms:
---&gt; 67             img = t(img)
     68         return img
     69 

~/opt/anaconda3/lib/python3.8/site-packages/torchvision/transforms/transforms.py in __call__(self, pic)
    102             Tensor: Converted image.
    103         """
--&gt; 104         return F.to_tensor(pic)
    105 
    106     def __repr__(self):

~/opt/anaconda3/lib/python3.8/site-packages/torchvision/transforms/functional.py in to_tensor(pic)
     62     """
     63     if not(F_pil._is_pil_image(pic) or _is_numpy(pic)):
---&gt; 64         raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))
     65 
     66     if _is_numpy(pic) and not _is_numpy_image(pic):

TypeError: pic should be PIL Image or ndarray. Got &lt;class 'torch.Tensor'&gt;```</code></pre>

username: eqy
cooked: <p>Some transforms expect to be passed PIL Images and some expect tensors. There are utility methods to convert between the two in case you have one format and need the other: e.g.,<br>
<a href="https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.ToPILImage" rel="noopener nofollow ugc">ToPILImage</a><br>
<a href="https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.ToTensor" rel="noopener nofollow ugc">ToTensor</a></p>