aryashah2k
aryashah2k

Reputation: 538

Unable to read images because of list index error

I am trying to read images from a directory on my local Jupyter Notebook using the following code:

While I try the same code on Colab, it works fine but in Jupyter Notebook I get the IndexError: list index out of range error

What is wrong when I implement this code in jupyter notebook?

images = []
image_names = []
image_dir = 'flickr-30k-final/*.jpg'
for img in glob.glob(image_dir):
    x = img.split("/")
    name = x[1].split("\\") # Change the index based on the number of subdirectories you have. Index Starts from 0.
    image_names.append(name[0])
    cv_img = cv2.imread(img)
    images.append(cv_img)

Detailed error output:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_29008\3390765231.py in <module>
      5 for img in glob.glob(image_dir):
      6     x = img.split("/")
----> 7     name = x[1].split("\\") # Change the index based on the number of subdirectories you have. Index Starts from 0.
      8     image_names.append(name[0])
      9     cv_img = cv2.imread(img)

Upvotes: -1

Views: 478

Answers (1)

user14772466
user14772466

Reputation:

Assuming that a sample image path After you split the directory by "/" looks like:

flickr-30k-final\\imagename.jpg

the index value for the below line should be 1 and not 0

image_names.append(name[0])

Thus, your final code should look something like:

images = []
image_names = []
image_dir = "flickr-30k-final/*.jpg"
for img in glob.glob(image_dir):
    x = img.split("/")
    name = x[0].split("\\") # Change the index based on the number of subdirectories you have. Index Starts from 0.
    image_names.append(name[1])
    cv_img = cv2.imread(img)
    images.append(cv_img)

Doing so, if it runs successfully, just print the image_names variable and see its output, a list of all your image names should be printed

Upvotes: 0

Related Questions