【问题标题】:How to loop over images in a directory? [duplicate]如何遍历目录中的图像? [复制]
【发布时间】:2020-12-14 11:55:59
【问题描述】:

我的目录中有猫的图像。我想手动对这些图像应用数据增强。

我的目录是Downloads/Images/Cats/
此目录包含具有两种标签/名称的图像:

  1. cat1_001.png, cat1_002.png, ...
  2. cat2_001.png, cat2_002.png, ...

指定两种类型的猫图像。

那么我怎样才能只从 python 的目录中遍历标签为 1 的图像呢?

【问题讨论】:

  • for f in glob.glob('Downloads/Images/Cats/*001.png'): ...
  • 或者cat1_*.png,具体取决于“标签 1”的确切含义。当描述可能模棱两可时,在问题中举例通常会很有帮助。

标签: python computer-vision


【解决方案1】:

你可以这样做:

import os
directory_in_str = 'Downloads/Images/Cats/'
directory = os.fsencode(directory_in_str)
    
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if(filename.startswith('cat1_') and filename.endswith('.png')):
        print(filename)
        # do your staff here

【讨论】:

  • 我不会测试 cat1_ 是否在文件名中,而是测试文件名是否以 cat1_ 开头。我们不知道名称约定,这应该更准确。
  • 好点 :) 我编辑了 anwser
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多