Error using transforms

shubz_308: <p>Hi while using transforms for an image dataset like this</p>
<pre><code class="lang-auto"> train_transform = transforms.Compose([
                                          transforms.Resize((205, 205)), 
                                          transforms.RandomVerticalFlip(p=0.5), 
                                          transforms.RandomCrop((200, 200)),
                                          transforms.ToTensor()])
</code></pre>
<p>I got this entire error</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-12-7a9e35561311&gt; in &lt;module&gt;
     47    # print(PCP(sample1.unsqueeze(0), sample2.unsqueeze(0)))
     48 
---&gt; 49     plotSamples(LSP_dataset)
     50 
     51     plt.tight_layout()

&lt;ipython-input-3-2b3f96239780&gt; in plotSamples(dataset)
      3     for i in range(25):
      4         ax = axes[i // 5, i % 5]
----&gt; 5         sample = dataset[i]
      6         image = sample['image']
      7         joints = sample['joints']

&lt;ipython-input-1-ae4f8f0687a1&gt; in __getitem__(self, idx)
     68         sample = {'image': image, 'joints': joints}
     69         if self.transform:
---&gt; 70             sample = self.transform(sample)
     71 
     72         return sample

~\anaconda3\lib\site-packages\torchvision\transforms\transforms.py in __call__(self, img)
     58     def __call__(self, img):
     59         for t in self.transforms:
---&gt; 60             img = t(img)
     61         return img
     62 

~\anaconda3\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)
    887             result = self._slow_forward(*input, **kwargs)
    888         else:
--&gt; 889             result = self.forward(*input, **kwargs)
    890         for hook in itertools.chain(
    891                 _global_forward_hooks.values(),

~\anaconda3\lib\site-packages\torchvision\transforms\transforms.py in forward(self, img)
    271             PIL Image or Tensor: Rescaled image.
    272         """
--&gt; 273         return F.resize(img, self.size, self.interpolation)
    274 
    275     def __repr__(self):

~\anaconda3\lib\site-packages\torchvision\transforms\functional.py in resize(img, size, interpolation)
    373     if not isinstance(img, torch.Tensor):
    374         pil_interpolation = pil_modes_mapping[interpolation]
--&gt; 375         return F_pil.resize(img, size=size, interpolation=pil_interpolation)
    376 
    377     return F_t.resize(img, size=size, interpolation=interpolation.value)

~\anaconda3\lib\site-packages\torchvision\transforms\functional_pil.py in resize(img, size, interpolation)
    207 def resize(img, size, interpolation=Image.BILINEAR):
    208     if not _is_pil_image(img):
--&gt; 209         raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
    210     if not (isinstance(size, int) or (isinstance(size, Sequence) and len(size) in (1, 2))):
    211         raise TypeError('Got inappropriate size arg: {}'.format(size))
------------------------------------------------------------------------------------------------
TypeError: img should be PIL Image. Got &lt;class 'dict'&gt;
</code></pre>
<p>not sure how to fix it.Any suggestions welcome</p>

InnovArul: <aside class="quote no-group" data-username="shubz_308" data-post="1" data-topic="136883">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/8edcca/48.png" class="avatar"> shubz_308:</div>
<blockquote>
<p><code>TypeError: img should be PIL Image. Got &lt;class 'dict'&gt;</code></p>
</blockquote>
</aside>
<p>This error message is thrown from <code>transforms</code>. It is clear enough. No?<br>
It seems you are passing a python dict to the transform instead of the PIL image.</p>

shubz_308: <p>train_transform = transforms.Compose([    transforms.ToPILImage(),<br>
transforms.Resize((205, 205)),<br>
transforms.RandomVerticalFlip(p=0.5),<br>
transforms.RandomCrop((200, 200)),<br>
transforms.ToTensor()<br>
])<br>
I tried to make it PIL using transforms but it still doesnt work<br>
I posted log</p>
<hr>
<p>TypeError                                 Traceback (most recent call last)<br>
 in <br>
6     ])<br>
7 LSP_dataset = LSPLoader(train_transform)<br>
----&gt; 8 plotSamples(LSP_dataset)<br>
9 plt.show()</p>
<p> in plotSamples(dataset)<br>
3     for i in range(25):<br>
4         ax = axes[i // 5, i % 5]<br>
----&gt; 5         sample = dataset[i]<br>
6         image = sample[‘image’]<br>
7         joints = sample[‘joints’]</p>
<p> in <strong>getitem</strong>(self, idx)<br>
68         sample = {‘image’: image, ‘joints’: joints}<br>
69         if self.transform:<br>
—&gt; 70             sample = self.transform(sample)<br>
71             img = sample[‘image’]<br>
72             label = sample[‘landmarks’]</p>
<p>~\anaconda3\lib\site-packages\torchvision\transforms\transforms.py in <strong>call</strong>(self, img)<br>
58     def <strong>call</strong>(self, img):<br>
59         for t in self.transforms:<br>
—&gt; 60             img = t(img)<br>
61         return img<br>
62</p>
<p>~\anaconda3\lib\site-packages\torchvision\transforms\transforms.py in <strong>call</strong>(self, pic)<br>
177<br>
178         “”"<br>
 → 179         return F.to_pil_image(pic, self.mode)<br>
180<br>
181     def <strong>repr</strong>(self):</p>
<p>~\anaconda3\lib\site-packages\torchvision\transforms\functional.py in to_pil_image(pic, mode)<br>
217     “”"<br>
218     if not(isinstance(pic, torch.Tensor) or isinstance(pic, np.ndarray)):<br>
 → 219         raise TypeError(‘pic should be Tensor or ndarray. Got {}.’.format(type(pic)))<br>
220<br>
221     elif isinstance(pic, torch.Tensor):</p>
<p>TypeError: pic should be Tensor or ndarray. Got &lt;class ‘dict’&gt;.</p>

InnovArul: <aside class="quote no-group" data-username="shubz_308" data-post="3" data-topic="136883">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/8edcca/48.png" class="avatar"> shubz_308:</div>
<blockquote>
<p>68 sample = {‘image’: image, ‘joints’: joints}<br>
69 if self.transform:<br>
—&gt; 70 sample = self.transform(sample)</p>
</blockquote>
</aside>
<p>you are passing a dictionary to <code>self.transform</code> which the error points out.<br>
try <code>self.transform(image)</code>.</p>

shubz_308: <h2>
<a name="ok-the-error-now-changed-to-1" class="anchor" href="#ok-the-error-now-changed-to-1"></a>ok the error now changed to</h2>
<p>IndexError                                Traceback (most recent call last)<br>
 in <br>
6     ])<br>
7 LSP_dataset = LSPLoader(train_transform)<br>
----&gt; 8 plotSamples(LSP_dataset)<br>
9 plt.show()</p>
<p> in plotSamples(dataset)<br>
3     for i in range(25):<br>
4         ax = axes[i // 5, i % 5]<br>
----&gt; 5         sample = dataset[i]<br>
6         image = sample[‘image’]<br>
7         joints = sample[‘joints’]</p>
<p> in <strong>getitem</strong>(self, idx)<br>
69         if self.transform:<br>
70             sample = self.transform(image)<br>
—&gt; 71             img = sample[‘image’]<br>
72             label = sample[‘landmarks’]<br>
73</p>
<p>IndexError: too many indices for tensor of dimension 3</p>

InnovArul: <p>you can print the <code>type()</code> of variables that you have and understand which variable holds the input PIL and then pass it to transform. Also, please read up more on python programming and different data types. That might help.</p>

shubz_308: <p>I understand what you are saying about self.transform(image)<br>
I have a dict defined in my dataloader here</p>
<pre><code class="lang-auto">def __getitem__(self, idx):

        image_name = os.path.join(self.__image_path, self.__image_names[idx])
        image = io.imread(image_name)
        joints = self.__mat_data[:-1, :, idx]
        sample = {'image': image, 'joints': joints}
        if self.transform:
            sample = self.transform(sample)
            img = sample['image']
            label = sample['landmarks']

        return sample

</code></pre>
<p>So when applying</p>
<pre><code class="lang-auto">train_transform = transforms.Compose([ transforms.ToPILImage(),
transforms.Resize((205, 205)),
transforms.RandomVerticalFlip(p=0.5),
transforms.RandomCrop((200, 200)),
transforms.ToTensor()
])
</code></pre>
<p>is there an option to apply self image transform in this command itself?</p>

InnovArul: <aside class="quote no-group" data-username="shubz_308" data-post="7" data-topic="136883">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/8edcca/48.png" class="avatar"> shubz_308:</div>
<blockquote>
<pre><code class="lang-auto">def __getitem__(self, idx):

        image_name = os.path.join(self.__image_path, self.__image_names[idx])
        image = io.imread(image_name)
        joints = self.__mat_data[:-1, :, idx]
        sample = {'image': image, 'joints': joints}
        if self.transform:
            sample = self.transform(sample)
            img = sample['image']
            label = sample['landmarks']

        return sample
</code></pre>
</blockquote>
</aside>
<p>you can apply <code>self.transform(img)</code> given that <code>img</code> contains the image.</p>

shubz_308: <p>so for a random vertical flip transform for img,we write something like self.transform(img,randomverticalflip)?or should we make a function for this ?</p>

InnovArul: <p>You can refer to the page: <a href="https://pytorch.org/vision/stable/transforms.html" class="inline-onebox">torchvision.transforms — Torchvision 0.11.0 documentation</a> to know the available transforms.<br>
vertical flip: <a href="https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.RandomVerticalFlip">torchvision.transforms.RandomVerticalFlip</a></p>