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

前端 未结 1 1046
青春惊慌失措
青春惊慌失措 2021-01-04 18:20

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         


        
相关标签:
1条回答
  • 2021-01-04 18:37

    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!

    0 讨论(0)
提交回复
热议问题