FileNotFoundError: [Errno 2] No such file or directory for Image Dataset one-hot encoded

Question:

I tried to one-hot encoded using to_categorical() in my image dataset but I failed because of FileNotFoundError: [Errno 2] No such file or directory error and the code is given below,

import os
import numpy as np
from PIL import Image
from keras.utils import to_categorical

# Define the classes in the dataset
classes = ['BL_Healthy']

# Initialize the arrays to store the image data and labels
X = []
y = []

# Loop through the dataset and load each image
for class_id, class_name in enumerate(classes):
    for image_file in os.listdir('/content/imdadulhaque/' + class_name):
        image_path = os.path.join(class_name, image_file)
        image = Image.open(image_path)
        X.append(np.array(image))
        y.append(class_id)

# Convert the labels to one-hot encoded labels
num_classes = len(classes)
y = to_categorical(y, num_classes)

Although, there are images but unfortunately, it showed an error the file is not found.

Error is:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-34-9d42022783bc> in <module>
     14     for image_file in os.listdir('/content/imdadulhaque/' + class_name):
     15         image_path = os.path.join(class_name, image_file)
---> 16         image = Image.open(image_path)
     17         X.append(np.array(image))
     18         y.append(class_id)

/usr/local/lib/python3.8/dist-packages/PIL/Image.py in open(fp, mode)
   2841 
   2842     if filename:
-> 2843         fp = builtins.open(filename, "rb")
   2844         exclusive_fp = True
   2845 

FileNotFoundError: [Errno 2] No such file or directory: 'BL_Healthy/BL_Healthy_0_451.jpg'

The desired error screenshot is mentioned in the attached file. Please help who have ideas.

enter image description here

Asked By: Imdadul Haque

||

Answers:

You forgot to join /content/imdadulhaque/ with class_name and image_file for your variable image_path Do something like:

image_path = os.path.join('/content/imdadulhaque/', class_name, image_file)

Answered By: mimocha