Ekci Ekci - 4 months ago 30
Python Question

Python/OpenCV - how to load all images from folder in alphabetical order

how to load all images from given folder in alphabetical order?

Code like this:

images = []
for img in glob.glob("images/*.jpg"):
n= cv2.imread(img)
images.append(n)
print (img)


...return:

...
images/IMG_9409.jpg
images/IMG_9425.jpg
images/IMG_9419.jpg
images/IMG_9376.jpg
images/IMG_9368.jpg
images/IMG_9417.jpg
...


Is there a way to get all images but in correct order?

Answer

Luckily, python lists have a built-in sort function that can sort strings using ASCII values. It is as simple as putting this before your loop:

filenames = [img for img in glob.glob("images/*.jpg")]

filenames.sort() # ADD THIS LINE

images = []
for img in filenames:
    n= cv2.imread(img)
    images.append(n)
    print (img)
Comments