Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

opencv

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?

like image 629
Ekci Avatar asked Jul 30 '16 15:07

Ekci


People also ask

How do you use Imread in Python?

imread() method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix. Parameters: path: A string representing the path of the image to be read.


1 Answers

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)

EDIT: Knowing a little more about python now than I did when I first answered this, you could actually simplify this a lot:

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

for img in images:
    print img

Should be much faster too. Yay list comprehensions!

like image 105
ClydeTheGhost Avatar answered Nov 03 '22 09:11

ClydeTheGhost