Search code examples
pythonopencvlistdir

Cannot read a list of pictures cv2.imread()


I am new in programming, and I would like to make a picture resizer with gui. I have problems with making the gui. I grabbed the problematic part of the code:

from tkinter import *
from tkinter import filedialog
import os, backend, glob2, cv2

loaded_pics=[]
picture_read=[]
window = Tk()

browsed_dir = StringVar()

browsed_dir.set(filedialog.askdirectory(initialdir="/",title='Please select a directory'))
file_path = browsed_dir.get()#+"/"

for filename in os.listdir(file_path):
    if filename.endswith(('.jpg', '.jpeg', '.gif', '.png')):
        loaded_pics.append(filename)
print(loaded_pics)

try:
    for images in loaded_pics:
        imgs = cv2.imread(images, 1)
        print(imgs)
except:
    print("ERROR")


window.destroy()
window.mainloop()

So, I have got a list of .png/.jpg/.bmp files, I can print the list, but I cannot read them with cv2.imread(), when I print(imgs), I got "None"-s.

(I have not managed to make this with glob2. It is work well with current directory, but I could not make it with filedialog.)

I hope someone can help.

Thanks in advance!


Solution

  • You are building a list of filenames in loaded_pics. But this doesn't include the name of the directory, file_path. So when you call imread, your image is actually located at file_path/filename, but you are only passing filename. So cv2 cannot find your file, and returns None.