Image reading showing error

suri_g: <p>Hi ,<br>
I am doing multilabel  image classification, I was prepared the data for CNN model then I am trying to show the images,  but  I was facing some errors. please help me out , how to fix it.</p>
<p>Note : my all images  arein single folder.<br>
Here my code</p>
<pre><code class="lang-auto">
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
from tqdm import tqdm_notebook as tqdm
from sklearn.preprocessing import LabelEncoder
from PIL import Image
import matplotlib.pyplot as plt
import torch
# Neural networks can be constructed using the torch.nn package.
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data import Dataset
import torchvision
import torchvision.transforms as transforms 

image_folder = "dance\dataset\train"
train=pd.read_csv("dance/dataset/train.csv")
train.head()

lb = LabelEncoder()
train['target_labels'] = lb.fit_transform(train['target'])
train.head()

|Image|target|target_labels|
|0|96.jpg|manipuri|4|
|1|163.jpg|bharatanatyam|0|
|2|450.jpg|odissi|6|
|3|219.jpg|kathakali|2|
|4|455.jpg|odissi|6|

batch_size = 128
validation_split = .3
shuffle_dataset = True
random_seed= 42
dataset_size = len(train)
indices = list(range(dataset_size))
split = int(np.floor(validation_split * dataset_size))
if shuffle_dataset :
    np.random.seed(random_seed)
    np.random.shuffle(indices)
train_indices, val_indices = indices[split:], indices[:split]

# Creating PT data samplers and loaders:
train_sampler = SubsetRandomSampler(train_indices)
valid_sampler = SubsetRandomSampler(val_indices)

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

class Dance_Dataset(Dataset):
    def __init__(self, img_data,img_path,transform=None):
        self.img_path = img_path
        self.transform = transform
        self.img_data = img_data
        
    def __len__(self):
        return len(self.img_data)
    
    def __getitem__(self, index):
        img_name = os.path.join(self.img_path,self.img_data.loc[index, 'target'],
                                self.img_data.loc[index, 'Image'])
        image = Image.open(img_name)
        #image = image.convert('RGB')
        image = image.resize((300,300))
        label = torch.tensor(self.img_data.loc[index, 'target_labels'])
        if self.transform is not None:
            image = self.transform(image)
        return image, label
dataset = Dance_Dataset(train,image_folder,transform)
train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, 
                                           sampler=train_sampler)
validation_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
                                                sampler=valid_sampler)

def img_display(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    npimg = np.transpose(npimg, (1, 2, 0))
    return npimg

dataiter = iter(train_loader)
images, labels = dataiter.next()
arthopod_types = {0: 'bharatanatyam', 1: 'kathak', 2: 'kathakali', 3: 'kuchipudi',4 :'manipuri', 5: 'mohiniyattam' ,6:'odissi', 7:'sattriya'}
# Viewing data examples used for training
fig, axis = plt.subplots(3, 5, figsize=(15, 10))
for i, ax in enumerate(axis.flat):
    with torch.no_grad():
        image, label = images[i], labels[i]
        ax.imshow(img_display(image)) # add image
        ax.set(title = f"{arthopod_types[label.item()]}") # add label
</code></pre>
<p>Error:</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
&lt;ipython-input-58-ad5957162f52&gt; in &lt;module&gt;
      1 # get some random training images
      2 dataiter = iter(train_loader)
----&gt; 3 images, labels = dataiter.next()
      4 arthopod_types = {0: 'bharatanatyam', 1: 'kathak', 2: 'kathakali', 3: 'kuchipudi',4 :'manipuri', 5: 'mohiniyattam' ,6:'odissi', 7:'sattriya'}
      5 # Viewing data examples used for training

~\anaconda3\envs\pytorch_b\lib\site-packages\torch\utils\data\dataloader.py in __next__(self)
    558         if self.num_workers == 0:  # same-process loading
    559             indices = next(self.sample_iter)  # may raise StopIteration
--&gt; 560             batch = self.collate_fn([self.dataset[i] for i in indices])
    561             if self.pin_memory:
    562                 batch = _utils.pin_memory.pin_memory_batch(batch)

~\anaconda3\envs\pytorch_b\lib\site-packages\torch\utils\data\dataloader.py in &lt;listcomp&gt;(.0)
    558         if self.num_workers == 0:  # same-process loading
    559             indices = next(self.sample_iter)  # may raise StopIteration
--&gt; 560             batch = self.collate_fn([self.dataset[i] for i in indices])
    561             if self.pin_memory:
    562                 batch = _utils.pin_memory.pin_memory_batch(batch)

&lt;ipython-input-49-4a698726eaaa&gt; in __getitem__(self, index)
     11         img_name = os.path.join(self.img_path,self.img_data.loc[index, 'target'],
     12                                 self.img_data.loc[index, 'Image'])
---&gt; 13         image = Image.open(img_name)
     14         #image = image.convert('RGB')
     15         image = image.resize((300,300))

~\anaconda3\envs\pytorch_b\lib\site-packages\PIL\Image.py in open(fp, mode)
   2841 
   2842     if filename:
-&gt; 2843         fp = builtins.open(filename, "rb")
   2844         exclusive_fp = True
   2845 

OSError: [Errno 22] Invalid argument: 'dance\\dataset\train\\kathakali\\190.jpg'
</code></pre>

ptrblck: <p>It seems that the passed image path isn’t a valid path. Could you check, if the root folder is missing?</p>

suri_g: <p>Hi ptrblck,<br>
Thanks for your replay<br>
I tried with one image, it was working<img src="https://discuss.pytorch.org/uploads/default/original/3X/e/9/e9eb969e7bfdd4bb9a5123fbb0f3e9b0f2265e67.png" alt="Capture6" data-base62-sha1="xnlZLVubx8uzkxZ0WJAokkk4hDh" width="445" height="330"></p>
<p>this is my folder path<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/b/d/bd18c3e729354b5e22049ed9034fd475a066103c.png" data-download-href="https://discuss.pytorch.org/uploads/default/bd18c3e729354b5e22049ed9034fd475a066103c" title="Capture7"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/b/d/bd18c3e729354b5e22049ed9034fd475a066103c_2_689x282.png" alt="Capture7" data-base62-sha1="qYPiFQHAtCFjHowlzbg2GyHqLKY" width="689" height="282" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/b/d/bd18c3e729354b5e22049ed9034fd475a066103c_2_689x282.png, https://discuss.pytorch.org/uploads/default/optimized/3X/b/d/bd18c3e729354b5e22049ed9034fd475a066103c_2_1033x423.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/b/d/bd18c3e729354b5e22049ed9034fd475a066103c.png 2x" data-dominant-color="FAFAFB"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">Capture7</span><span class="informations">1268×519 20.2 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

ptrblck: <p>Could you try to load the path, which seems to fail?</p>
<pre><code class="lang-python">'dance\\dataset\train\\kathakali\\190.jpg'
</code></pre>