[英]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 机器中,您可以执行以下操作:
pip install Pillow
安装 Pillow 库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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.