以下是一个遍历目录中的每张图片的解决方法的示例代码,使用Python的os和PIL库:
import os
from PIL import Image
def traverse_directory(directory):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg"):
image_path = os.path.join(root, file)
# 使用PIL库打开图片
image = Image.open(image_path)
# 在这里可以对图片进行进一步的处理,如调整大小、修改格式等
# ...
# 输出图片路径和尺寸
print("Image path:", image_path)
print("Image size:", image.size)
# ...
# 调用函数并指定目录路径
traverse_directory("/path/to/directory")
上述代码通过使用os.walk()
函数遍历给定目录及其子目录中的所有文件。然后,对于每个文件,检查其扩展名是否为常见的图片文件类型(如.jpg、.png、.jpeg),如果是,则使用PIL库的Image.open()
函数打开文件,然后可以进行进一步的处理。在示例代码中,只打印了图片的路径和尺寸,你可以根据自己的需求对图片进行其他操作。