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



我有一个照片文件夹,想裁剪它的两个角,然后旋转一个角度180度,得到两个相似的裁剪图像。我有一个问题,图像旋转和保存。这是我现在得到的代码

from PIL import Image
import os.path, sys
path = r"D:Machine_Learningimg"
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_Learningimgcrop'
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()

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

最新更新