【问题标题】:How to sort read files by using ImageDataGenerator如何使用 ImageDataGenerator 对读取的文件进行排序
【发布时间】:2021-10-04 07:52:41
【问题描述】:

enter image description here

enter image description here

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

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

【问题讨论】:

    标签: tensorflow keras tf.keras


    【解决方案1】:

    顺序不是您所期望的原因是生成器按字母数字顺序处理图像。例如,如果您的图像标记为 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,则类目录也按字母数字顺序处理。下面包括一个函数的代码,该函数将从一个整数值 (snum) 开始以数字方式重命名目录 (source_dir) 中的所有文件,并带有适当的“零”填充。

    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)
                         
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 2017-12-28
      • 2015-12-27
      • 2019-04-06
      相关资源
      最近更新 更多