python如何裁剪文件夹中的所有图片并保存到另一个文件夹

v64noz0r  于 2023-01-14  发布在  Python
关注(0)|答案(1)|浏览(206)

我有一个文件夹的照片,并希望裁剪2个角落,然后旋转1个Angular 180度为2个类似的裁剪图像。我有一个问题,图像旋转和保存。这是我得到的代码,直到现在

from PIL import Image
import os.path, sys

path = r"D:\Machine_Learning\img"
dirs = os.listdir(path)

def crop():
    for item in dirs:
        fullpath = os.path.join(path,item)         #corrected
        if os.path.isfile(fullpath):
            im = Image.open(fullpath)
            f, e = os.path.splitext(fullpath)
            save_dir = r'D:\Machine_Learning\img\crop'
            imCropTop = im.crop((2125, 70, 2148, 310)) #corrected
            imCropTop.save(f+'TOP_Cropped.bmp', "BMP", quality=100)
            imCropBot = im.crop((2125, 684, 2148, 924))  # corrected
            imCropBot.save(f + 'BOT_Cropped.bmp', "BMP", quality=100)

crop()
mwngjboj

mwngjboj1#

这对我很有效。我已经修改了一些变量名以适应pep 8。清晰的变量名有助于避免混淆(特别是避免单字符名称-我最讨厌的)
当然,您必须使用自己的目录名。

from PIL import Image
import os.path

SOURCE_DIRECTORY = "../scratch/load_images/my_images"
TARGET_DIRECTORY = "../scratch/load_images/my_cropped_images/"
directory_list = os.listdir(SOURCE_DIRECTORY)

def crop():
    for source_file in directory_list:
        source_path = os.path.join(SOURCE_DIRECTORY, source_file) 
        if os.path.isfile(source_path):
            raw_image = Image.open(source_path)
            file_name = os.path.basename(source_path)
            file_name, extension = os.path.splitext(file_name)

            image_cropped_top = raw_image.crop((2125, 70, 2148, 310))
            image_cropped_top.save(TARGET_DIRECTORY + file_name+'TOP_Cropped.bmp', "BMP", quality=100)

if __name__ == '__main__':
    crop()

相关问题