我在一个文件夹中有 5000 个多个文件夹,即测试,每个文件夹有 2-3 个图像,我需要裁剪图像,目前我的代码用于应用单个文件夹来裁剪图像,是否有任何替代选项可以让多个文件夹申请相同的代码。
这是我的代码
from PIL import Image
import os.path, sys
path = r"D:\test"
dirs = os.listdir(path)
def crop():
for item in dirs:
fullpath = os.path.join(path,item)
if os.path.isfile(fullpath):
im = Image.open(fullpath)
f, e = os.path.splitext(fullpath)
imCrop = im.crop((80, 270, 4000, 3000))
imCrop.save(f + 'Cropped.jpg', "JPEG")
crop()
您可以使用 os.walk 递归地遍历所有目录:
from PIL import Image
import os
root_dir = r"D:\test"
def crop_image(image_path):
try:
with Image.open(image_path) as im:
im_crop= im.crop((80,270,4000,3000))
file_name,ext =os.path.splitext(image_path)
cropped_image = file_name+'_Cropped.jpg'
im_crop.save(cropped_image,"JPEG")
except Exception as e:
print(f"Error {image_path}:{e}")
def crop_images_in_folders(root_folder):
for folder_name,subfolders,filenames in os.walk(root_folder):
for filename in filenames:
full_image_path = os.path.join(folder_name,filename)
if filename.lower().endswith(('.jpg','.jpeg', '.png')):
crop_image(full_image_path)
crop_images_in_folders(root_dir)