Pic should be Tensor or ndarray. Got <class 'dict'>

username: akcaymert
cooked: <p>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 ?</p>
<blockquote>
<p>Blockquote<br>
TypeError: Caught TypeError in DataLoader worker process 0.<br>
Original Traceback (most recent call last):<br>
File “/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/worker.py”, line 185, in _worker_loop<br>
data = fetcher.fetch(index)<br>
File “/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py”, line 44, in fetch<br>
data = [self.dataset[idx] for idx in possibly_batched_index]<br>
File “/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py”, line 44, in <br>
data = [self.dataset[idx] for idx in possibly_batched_index]<br>
File “”, line 40, in <strong>getitem</strong><br>
self.sample = self.transform(self.sample)<br>
File “/usr/local/lib/python3.6/dist-packages/torchvision/transforms/transforms.py”, line 61, in <strong>call</strong><br>
img = t(img)<br>
File “/usr/local/lib/python3.6/dist-packages/torchvision/transforms/transforms.py”, line 172, in <strong>call</strong><br>
return F.to_pil_image(pic, self.mode)<br>
File “/usr/local/lib/python3.6/dist-packages/torchvision/transforms/functional.py”, line 190, in to_pil_image<br>
raise TypeError(‘pic should be Tensor or ndarray. Got {}.’.format(type(pic)))<br>
TypeError: pic should be Tensor or ndarray. Got &lt;class ‘dict’&gt;.</p>
</blockquote>
<pre><code class="lang-auto">train_transform = transforms.Compose([transforms.ToPILImage(),                                  
  transforms.Resize(226),
  transforms.RandomVerticalFlip(p=0.5),
transforms.ToTensor(), 
  
])


class DatasetLoader_Custom(Dataset):
    def __init__(self,root_dir, transform=None):
        """
        Args:
            root_dir (string): Directory with all the images.
            transform (callable, optional): Optional transform to be applied
                on a sample.
        """
        self.images = []
        self.label = []
        for filename in os.listdir(root_dir):
          for folder in os.listdir(os.path.join(root_dir,filename)):
            img = Image.open(os.path.join(os.path.join(root_dir,filename),folder))
            text = filename
            if img is not None:
              #zeros = np.zeros(3,960,720)
              img = np.array(img)
              img = img.transpose(2,1,0)
              if text.find("_") &gt; 0:
                self.images.append(img)
              else:
                self.label.append(img)
            else:
              print('Errorrr')

        self.transform = transform
        
        print("Images: ",self.images[1])
        print(self.images[1].shape)
        print("************************")
        print("Label: ",self.label[1])
        print(self.label[1].shape)
    def __len__(self):
        return len(self.images)

    def __getitem__(self, x):
        self.sample = {'image': self.images, 'landmarks': self.label}

        if self.transform:
            self.sample = self.transform(self.sample)
        self.images = self.sample['image']
        self.labels = self.sample['landmarks']

        return self.images[x],self.labels[x]
</code></pre>

username: planet_pluto
cooked: <p>Why do you want to perform the <code>self.transform()</code> operation on all images every time when the <code>__getitem__()</code> of the dataloader is called? You’re required to do the transform operation only on <code>self.images[x]</code> and <code>self.labels[x]</code>. It’s not wrong, but it’s not a good programming practice as you’re doing a redundant operation. Try to change your <code>__getitem__()</code> to the following definition:</p>
<pre><code class="lang-auto">def __getitem__(self, x):
        img, label = self.images[x], self.labels[x]
        sample = {'image': img, 'landmarks': label}

        if self.transform:
            sample = self.transform(sample)
        img = sample['image']
        label = sample['landmarks']

        return img, label
</code></pre>

username: akcaymert
cooked: <p>Actually, i only  tried this operation because its would cause a problem. the problem still continues</p>
<blockquote>
<p>Blockquote<br>
Caught TypeError in DataLoader worker process 0.<br>
Original Traceback (most recent call last):<br>
File “/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/worker.py”, line 185, in _worker_loop<br>
data = fetcher.fetch(index)<br>
File “/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py”, line 44, in fetch<br>
data = [self.dataset[idx] for idx in possibly_batched_index]<br>
File “/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py”, line 44, in <br>
data = [self.dataset[idx] for idx in possibly_batched_index]<br>
File “”, line 41, in <strong>getitem</strong><br>
sample = self.transform(sample)<br>
File “/usr/local/lib/python3.6/dist-packages/torchvision/transforms/transforms.py”, line 61, in <strong>call</strong><br>
img = t(img)<br>
File “/usr/local/lib/python3.6/dist-packages/torchvision/transforms/transforms.py”, line 172, in <strong>call</strong><br>
return F.to_pil_image(pic, self.mode)<br>
File “/usr/local/lib/python3.6/dist-packages/torchvision/transforms/functional.py”, line 190, in to_pil_image<br>
raise TypeError(‘pic should be Tensor or ndarray. Got {}.’.format(type(pic)))<br>
TypeError: pic should be Tensor or ndarray. Got &lt;class ‘dict’&gt;.</p>
</blockquote>

username: ptrblck
cooked: <p>Assuming you are passing <code>train_transform</code> to the <code>transform</code> argument in <code>DatasetLoader_Custom</code>, you would have to apply this transformation for each image separately as noted by <a class="mention" href="/u/planet_pluto">@planet_pluto</a>.</p>
<p>Currently you are passing the <code>sample</code> <code>dict</code>  to <code>self.transform</code> so use <code>self.transform(sample['image'])</code> instead.</p>

username: akcaymert
cooked: <p>I think we solved the problem, but now I encounter an error in the iterator. Can you explain what is the source of these problems?</p>
<pre><code class="lang-auto"> len(valid_data_loader)
 iterator = iter(valid_data_loader)
 x,y = next(iterator)
</code></pre>
<blockquote>
<p>TypeError                                 Traceback (most recent call last)<br>
 in ()<br>
1 len(valid_data_loader)<br>
2 iterator = iter(valid_data_loader)<br>
----&gt; 3 x,y = next(iterator)</p>
<p>7 frames<br>
/usr/local/lib/python3.6/dist-packages/torchvision/transforms/functional.py in resize(img, size, interpolation)<br>
317     “”"<br>
318     if not _is_pil_image(img):<br>
 → 319         raise TypeError(‘img should be PIL Image. Got {}’.format(type(img)))<br>
320     if not (isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2)):<br>
321         raise TypeError(‘Got inappropriate size arg: {}’.format(size))</p>
<p>TypeError: img should be PIL Image. Got &lt;class ‘torch.Tensor’&gt;</p>
</blockquote>

username: ptrblck
cooked: <p><code>Resize</code> expects a <code>PIL.Image</code>, while you are passing a tensor.<br>
The most recent <code>torchvision</code> version added transformations, which also accept tensors so you could install the nightly or build from source.<br>
If you don’t want to update <code>torchvision</code>, pass a <code>PIL.Image</code> to the transformation.</p>

username: akcaymert
cooked: <p>i dont understand where to use this information because i feed to the dataloader by opening PIL.Image.Open and converting numpy array for operation .Morever, i used ToPILImage by pytorch.Frankly, im really confusing</p>