如何使用 ImageDataGenerator 对读取的文件进行排序

How to sort read files by using ImageDataGenerator

enter image description here

enter image description here

我在使用 DataGenerator 加载图像时遇到问题。正如您从图像中看到的那样,它不像我的真实路径。它应该像 img(1), img(2), ... 但是 img(1), img(10), img(100), ...

我该如何解决这个问题?提前谢谢你。

顺序与您期望的不同的原因是生成器按字母数字顺序处理图像。例如,如果您的图像被标记为 1.jpg、2.jpg、...9.jpg、10.jpg、11.jpg ...等 它们将按顺序处理 1.jpg,10,jpg,11.jpg,等,2.jpg,20.jpg等 保留顺序的一种方法是使用“零”填充来命名文件。例如,如果您有 20 个文件,则将它们标记为 01.jpg、02.jpg 等 09.jpg、10.jpg 等。请注意,如果您使用 flow_from_directory,也会处理 class 目录按字母数字顺序。下面包含的是一个函数的代码,该函数将从整数值 (snum) 开始以数字方式重命名目录 (source_dir) 中的所有文件,并使用适当的 'zeros' 填充。

def rename (source_dir, snum, ):
    import os    
    import shutil         
    flist=os.listdir(source_dir)       
    temp_dir=os.path.join(source_dir, 'temp')    
    if os.path.isdir(temp_dir):
        shutil.rmtree(temp_dir)
    os.mkdir(temp_dir)
    for f in flist:
        fpath=os.path.join(source_dir,f)
        dpath=os.path.join(temp_dir,f)
        shutil.copy(fpath, dpath)
    tlist=os.listdir(temp_dir)
    for f in tlist:
        fpath=os.path.join(source_dir,f)
        os.remove(fpath)
    tlist=os.listdir(temp_dir)    
    fc=len(tlist)  # determine number of d files to process which determines amout of zeros padding needed     
    pad=0
    mod = 10     
    for i in range(1, fc + 1): # skip i=0 because 0 modulo anything is 0 and we don't want to increment pad
        if i % mod == 0:
            pad=pad+1                    
            mod =mod * 10     
    for i,f in enumerate(tlist):                 
        fpath=os.path.join(temp_dir,f) #full path to the file       
        index=fpath.rfind('.') # find location of last . in file name          
        new_path=os.path.join(source_dir, str(i + snum).zfill(pad+1) + fpath[index :] )          
        shutil.copy(fpath, new_path)        
    shutil.rmtree(temp_dir)