繁体   English   中英

如何遍历包含图像的目录和子目录并将它们保存为 Python 中的 jpeg

[英]How to iterate over directories and subdirectories that contain images and save them as jpegs in Python

我正在尝试编写一些 Python 代码,它将遍历目录中多个文件夹中的图像文件,如果它们具有 .tif 扩展名,我需要打开文件,将其转换为大小为 2500 x 2500 的 RGB,然后保存作为一个jpeg。 以下代码不起作用。 在 Python 中执行此操作的最佳方法是什么? 当我在文件夹中看到文件时,这一直给我一个文件不存在的错误:

import os
from PIL import Image
for (dirname, dirs, files) in os.walk('S:/DAM/Test/Approved/'):
    for filename in files:
        if filename.endswith('.tif'):
           img = Image.open(filename).convert('RGB')
           imageResize = img.resize((2500, 2500))
           imageResize.save(filename.jpg)

您应该提供使用 PIL 库打开和保存图像的完整路径。

假设您的目录结构类似于:

.
└── scriptfolder
       -- your-script.py
       -- picture.tif
       imagefolder
           -- picture2.tif
           -- picture3.jpg
           imagefolder2
               --example.jpg
               --example2.tif
               --whatever.png 

如果您使用的是 Linux 机器并且该脚本位于相对于图像的顶级目录中,则以下脚本应该可以工作:

# !/usr/bin/python3

from PIL import Image
import os

for root, dirs, files in os.walk(".", topdown = False):
   for name in files:
      if name.endswith('.tif'):
         filename = os.path.join(root, name)
         img = Image.open(filename).convert('RGB')
         imageResize = img.resize((2500,2500))
         imageResize.save(filename[:-4]+'.jpg','JPEG')

编辑

在 Windows 机器中,您可以执行以下操作:

  1. Install a clean version of Python 3 for Windows (eg https://www.python.org/downloads/release/python-376/ )
  2. 以管理员身份运行安装程序,并在安装提示符下确保标记将 Python 环境变量添加到路径并安装 pip。
  3. 以管理员身份打开 CMD 并使用pip install Pillow安装 Pillow 库
  4. 打开 IDLE 并创建以下脚本:将“path_to_images”变量更改为存储图像的正确路径。
from PIL import Image
import os

path_to_images = "D:\Images\Path-to-images"

for root, dirs, files in os.walk(path_to_images, topdown = False):
   for name in files:
      if name.endswith('.tif'):
         filename = os.path.join(root, name)
         print(filename)
         img = Image.open(filename).convert('RGB')
         imageResize = img.resize((2500,2500))
         imageResize.save(filename[:-4]+"toJPEG.jpg",'JPEG')

  1. 使用 F5 在 IDLE 中运行模块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM