Retrieving error while accessing files from the folders

Tags: ,



I have the following code I need to files from the folder to be read by opencv.

 filename = 'C:/Users/test_image'
 files = filename
 for file in files:
    orig = cv2.imread(file)
    image = image_utils.load_img(file, target_size=(224,224))
    image = image_utils.img_to_array(image)
     

I am retrieving the below error.

test_imagenet.py:26: in <module>
 image = image_utils.load_img(file, target_size=(224, 224))
 ....miniconda3envstensorflowlibsite-packageskeras_preprocessingimageutils.py:110: in 
 load_img
 img = pil_image.open(path)
 ....miniconda3envstensorflowlibsite-packagesPILImage.py:2809: in open
 fp = builtins.open(filename, "rb")
 E   FileNotFoundError: [Errno 2] No such file or directory: 'C'
 collected 0 items / 1 error

Help is highly appreciated. Thanks

Answer

You’re iterating over a string, so it will only get the first character. You need to list the contents of the directory. Use os.listdir like this.

import os
filename = 'C:/Users/test_image'
files = os.listdir(filename)
for file in files:
    orig = cv2.imread(file)
    image = image_utils.load_img(file, target_size=(224,224))
    image = image_utils.img_to_array(image)


Source: stackoverflow