Python/OpenCV-如何按字母顺序从文件夹中加载所有图像 [英] Python/OpenCV - how to load all images from folder in alphabetical order

查看:180
本文介绍了Python/OpenCV-如何按字母顺序从文件夹中加载所有图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按字母顺序从给定文件夹中加载所有图像?

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

这样的代码:

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

...返回:

...
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?

推荐答案

幸运的是,python列表具有内置的sort函数,该函数可以使用ASCII值对字符串进行排序.只需将其放在循环之前就很简单:

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)

编辑:与我第一次回答这个问题相比,现在我对python有了更多的了解,您实际上可以简化很多事情:

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!

这篇关于Python/OpenCV-如何按字母顺序从文件夹中加载所有图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆