python - 如何裁剪文件夹中的所有图片并通过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()
解决方案
这对我有用。我已经更改了一些变量名称以适应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()
推荐阅读
- node.js - 无法使用 node.js 在 mongodb 集合中删除
- python - 熊猫向前填充具有特定值的时间戳列(1秒)
- java - Java:如何创建具有“类”对象的实例?
- jenkins - Jenkins 管道:NPE,因为我在 Jenkinsfile 中输入了参数字段名称
- ios - Firebase crashlytics 报告了许多
我的生产版本中的第 0 行崩溃,这些崩溃是真的吗? - encoding - 如何在 elixir 中将二进制转换为 base10(十进制)整数
- django - 根据相关模型中的字段顺序删除重复项
- java - 在同一个路由器上使用多个通道
- microservices - 网关中的用户管理是个好主意吗?
- android-studio - Android Studio 可以在调用中显示方法参数吗?