【问题标题】:Iterate over images with pattern用模式迭代图像
【发布时间】:2018-08-18 09:28:45
【问题描述】:

我有成千上万张标记为IMG_####_0 的图像,其中第一个图像是IMG_0001_0.png,第22 个是IMG_0022_0.png,第100 个是IMG_0100_0.png 等等。我想通过迭代它们来执行一些任务。 我用这个fnames = ['IMG_{}_0.png'.format(i) for i in range(150)] 来迭代第一个150 图像,但我得到这个错误FileNotFoundError: [Errno 2] No such file or directory: '/Users/me/images/IMG_0_0.png',这表明它不是正确的方法。关于如何在能够迭代指定数量的图像的同时捕获此模式的任何想法,即在我的情况下,从 IMG_0001_0.pngIMG_0150_0.png

【问题讨论】:

    标签: python-3.x iteration


    【解决方案1】:
    fnames = ['IMG_{0:04d}_0.png'.format(i) for i in range(1,151)]
    print(fnames)
    
    for fn in fnames:
        try:
            with open(fn, "r") as reader:
                # do smth here            
                pass
        except ( FileNotFoundError,OSError) as err:
            print(err)
    

    输出:

      ['IMG_0000_0.png', 'IMG_0001_0.png', ...,  'IMG_0148_0.png', 'IMG_0149_0.png']
    

    文档:string-format()format mini specification

    '{:04d}' # format the given parameter with 0 filled to 4 digits as decimal integer
    

    另一种方法是创建一个普通字符串并用 0 填充它:

    print(str(22).zfill(10))
    

    输出:

    0000000022
    

    但对于您的情况,格式语言更有意义。

    【讨论】:

    • 诀窍是我的图像从IMG_0001_0.png 开始,所以如果我应用你的代码,我仍然会得到FileNotFoundError: [Errno 2] No such file or directory: '/Users/me/images/IMG_0000_0.png。有什么办法吗?
    • @WasswaSamuel 1st:使用 range(1,80) 生成 1-79。第二:使用错误处理。修改后的代码。
    【解决方案2】:

    生成可能的名称列表并尝试是否存在是迭代文件的缓慢而可怕的方式。

    试试看https://docs.python.org/3/library/glob.html

    类似:

    from glob import iglob
    
    filenames = iglob("/path/to/folder/IMG_*_0.png")
    

    【讨论】:

      【解决方案3】:

      您需要使用format pattern 来获取您要查找的格式。您不仅希望将整数转换为字符串,还特别希望它始终是具有四位数字的字符串,使用前导 0 填充任何空白空间。最好的方法是:

      'IMG_{:04d}_0.png'.format(i)
      

      而不是您当前的格式字符串。结果如下所示:

      In [2]: 'IMG_{:04d}_0.png'.format(3)
      Out[2]: 'IMG_0003_0.png'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-27
        • 2013-01-12
        • 1970-01-01
        • 1970-01-01
        • 2011-07-03
        • 2011-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多