Home > front end >  cv2.imread works with one file but not when iterating os.listdir()
cv2.imread works with one file but not when iterating os.listdir()

Time:10-19

I try to import several images to opencv with cv.imread() function. I think there is a problem with the way I give the path to imread().

With one file it's ok with:

cv.imread('data/img.png')

But within a for loop:

imgs = os.listdir('./data')
targets = []
for img in imgs:
    target = cv.imread(img)
    targets.append(target)

I keep getting an array full of None values, which means opencv didn't load the file.

print(img) give me an output like ['btn1.png','btn2.png','btn3.png'] which seems fine to me: it's a list of string.

What I am doing wrong here and why did this string is not passed as it is printed to me?

CodePudding user response:

The problem is imgs contains the filename of images but they aren't full file path, so your program cannot find the your image file.

Try to fix your program to be something like

root_dir = './data'
imgs = [os.path.join(root_dir, f) for f in os.listdir(root_dir)]
targets = []
for img in imgs:
    target = cv2.imread(img)
    targets.append(target)

CodePudding user response:

os.listdir gives the file name, not its path. You need to add the path back in or use a different API that includes the path. glob.glob(os.path.join("path", "*.png")) would do it. But you can also use pathlib

from pathlib import Path
targets = [cv.imread(path) for path in Path("data").glob("*.png")]
  • Related