python按数字顺序读取文件夹下的图片
废话不多说直接上代码:
import cv2
import os
array_of_img = [] # 用来存放图片的列表,不需要的可以删除
def read_template(directory_name):
#读取工程文件夹下存放图片的文件夹的图片名
imgList = os.listdir(r"./"+directory_name)
imgList.sort(key=lambda x: int(x.split('.')[0])) # 按照数字顺序排列图片名
print(imgList)#打印出来看看效果,不想看也可以删掉这句
#这个for循环是用来读入图片放入array_of_img这个列表中,因为前面的操作都只是图片名而已,图片是其实未读入的
for count in range(0, len(imgList)):
filename = imgList[count]
img = cv2.imread(directory_name + "/" + filename) #根据图片名读入图片
array_of_img.append(img) #这一步是将图片放入array_of_img中,如果不需要的可以和这个列表的定义一起删掉
cv2.imshow("test",array_of_img[3]) #显示第四张图片,严重是否正确,可以更改中括号里的数字多验证几张图片
#***************************************************************
#我这里的template2是我工程文件夹下存放图片的文件夹名,用的时候根据自己的需求该文件夹名就行了
read_template("template2")
cv2.waitKey(0)
下图中上一行是未排序读入图片时的顺序,下行为经过排序后的效果:
参考的文章:https://blog.csdn.net/xiaobiyin9140/article/details/84638260