裁剪图像时发生Python错误:图块无法扩展到图像外部

问题描述

我有一个2048x1536大小的JPG图像文件夹。在每个图像日期,时间和温度中,在顶部给出,在末尾给出相机型号名称。我只想裁剪这些图像的上部下部

图片样本:https://drive.google.com/file/d/1TefkFws5l2RBnI2iH22EI5vkje8JbeBk/view?usp=sharing

使用以下代码,我遇到错误-瓷砖不能延伸到外部图像 **对于我提供的任何尺寸,例如(500,500,500)**。我的目标是(1500,2000,1500,2000)

从PIL导入图像 导入操作系统

#Create an Image Object from an Image
dir=r"C:\\Users\\Desktop\\crop1"
output_dir = r"C:\\Users\\Desktop\\crop2"
file_names = os.listdir(dir)

for file_name in file_names:
    file_path = dir +"\{}".format(file_name)
    im = Image.open(r"{}".format(file_path))
    cropped = im.crop((2000,1500,2000,1500))
    output_file= output_dir+"\{}".format(file_name)
    cropped.save(r"{}".format(output_file))

解决方法

“(2000,1500,2000,1500)”是一个空框,它可以解释为什么即使“平铺无法延伸到外部图像”错误也无法完全消除农作物失败的原因。作物的4元组参数的含义为“((左,上,右,下))”。 Image.crop() documentation中的示例:

from PIL import Image

im = Image.open("hopper.jpg")

# The crop method from the Image module takes four coordinates as input.
# The right can also be represented as (left+width)
# and lower can be represented as (upper+height).
(left,upper,right,lower) = (20,20,100,100)

# Here the image "im" is cropped and assigned to new variable im_crop
im_crop = im.crop((left,lower))