首页 > 解决方案 > 如何裁剪文件夹中的所有图片并通过python将其保存到另一个文件夹

问题描述

我有一个照片文件夹,想裁剪它的 2 个角,然后将 1 个角度旋转 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()

标签: pythonpython-3.xpython-requestspython-imaging-library

解决方案


这对我有用。我已经更改了一些变量名称以适应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)

crop()

推荐阅读