Search code examples
pythonimagereadfile

How do I read the pictures in the file in order?


I want to read the pictures in a file in the order they are in the file. But when I read it with python it reads mixed. I don't want it sorted. How can I fix this?

def read_img(path):
    
    st = os.path.join(path, "*.JPG")
    
    st_ = os.path.join(path, "*.jpg")
     
    for filename in glob.glob(st):
        print(st)
        #print("filename-------",filename)
        
        img_array_input.append(filename)
        print("image array append : ", filename)
        
    for filename in glob.glob(st_):
        
        img_array_input.append(filename)
        #print("filename-------",filename)
        global size
        size = len(img_array_input)
        
    for i in img_array_input:   

        print("detection ")     
        
        detection(i)
        print("detection out") 

enter image description here

original file

enter image description here

the order of reading

I want it to read in the order in the original file.


Solution

  • If you want the list populated in the order that os.listdir() reveals files then:

    from os import listdir
    from os.path import join, splitext
    
    BASE = '.' # directory to be parsed
    EXTS = {'jpg', 'JPG', 'jpeg', 'JPEG'} # file extensions of interest
    
    def ext(p):
        _, ext = splitext(p)
        if ext:
            return ext[1:]
    
    def getfiles(base, include_base=True):
        for entry in listdir(base):
            if ext(entry) in EXTS:
                yield join(base, entry) if include_base else entry
    
    detection = [file for file in getfiles(BASE, include_base=False)]
    
    print(detection)
    

    Note:

    os.listdir() returns a list of files in arbitrary order