【问题标题】:How can I process images from nested directories and save them into their respective directories in python?如何处理嵌套目录中的图像并将它们保存到 python 中各自的目录中?
【发布时间】:2020-06-03 10:39:05
【问题描述】:

我一直在尝试调整嵌套目录中包含的所有图像的大小,并将生成的图像保存到与原始图像结构相同的目录中。我不断收到目录或文件不存在的错误(尽管它确实存在)。

root_path= 'D:/Users/mbeng/OneDrive/Desktop/mass_buildings'
def locate(pattern, root_path):
    for path, dirs, files in os.walk(os.path.abspath(root_path)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)

path = [f for f in locate('*.tiff', root_path)]

for file in path:
    i = Image.open(file)

    #fname = file[file.find('mass_buildings\\'):]
    fname = file.replace('D:\\Users\\mbeng\\OneDrive\\Desktop\\mass_buildings', 'D:\\Users\\mbeng\\OneDrive\\Desktop\\resized2')
    #fname = fname.replace('\\', '_')

    fn, fext = os.path.splitext(fname)
    #print(file)
    img = i.resize((300, 300))
    #print(img)
    img.save('{}.tiff'.format(fn), 'TIFF')

当我运行上面的代码时,我得到了错误:

D:\Users\mbeng\Python\PyTorch\python.exe D:/Users/mbeng/Python/FeatureExtract/fils_list.py
Traceback (most recent call last):
  File "D:/Users/mbeng/Python/FeatureExtract/fils_list.py", line 68, in <module>
    img.save('{}.tiff'.format(fn), 'TIFF')
  File "D:\Users\mbeng\Python\PyTorch\lib\site-packages\PIL\Image.py", line 2085, in save
    fp = builtins.open(filename, "w+b")
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\Users\\mbeng\\OneDrive\\Desktop\\resized2\\test\\map\\22828930_15.tiff'

Process finished with exit code 1

reized2 是我为保存已处理文件而创建的目录。它包含以下目录:traintestvalid,每个目录都包含两个子目录:satmap。原(mass_buildings)文件所在目录结构与resized2相同。 我怎样才能让它发挥作用?

【问题讨论】:

    标签: python-3.x image-processing python-imaging-library


    【解决方案1】:

    我发现了一些导致代码无法工作的原因。

    1. replace() 方法不起作用,因此我将路径更改为原始字符串并将// 替换为\

    2. 我必须删除预先创建的目录以保存已处理的文件,以便在运行时使用 Pathlib.Path().mkdir() 创建它们。

    root_path= 'D:/Users/mbeng/OneDrive/Desktop/mass_buildings'
    def locate(pattern, root_path):
        for path, dirs, files in os.walk(os.path.abspath(root_path)):
            for filename in fnmatch.filter(files, pattern):
                yield os.path.join(path, filename)
    
    path = [f for f in locate('*.tiff', root_path)]
    
    for file in path:
        fname = file.replace(r'D:\Users\mbeng\OneDrive\Desktop\mass_buildings', r'D:\\Users\\mbeng\\OneDrive\\Desktop\\resized')
        fp = os.path.split(fname)[:-1][0]
        base = os.path.basename(fname)
        Path(fp).mkdir(parents=True, exist_ok=True)
        fn, fext = os.path.splitext(base)
    
        i = Image.open(file)
        img = i.resize((700, 700), PIL.Image.NEAREST)
        img.save(os.path.join(fp, '{}.tiff'.format(fn)))
    

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多