Python reads the pictures in the folder in numerical order (detailed notes, suitable for Xiaobai)

Python reads the pictures under the folder in numerical order

Don't talk nonsense and go directly to the code:

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)

The upper row in the figure below is the order when the image is read in without sorting, and the lower row is the effect after sorting:
insert image description here

Referenced article : https://blog.csdn.net/xiaobiyin9140/article/details/84638260

Guess you like

Origin blog.csdn.net/weixin_44517500/article/details/105531133