【问题标题】:Python error while cropping images: tile cannot extend outside image裁剪图像时出现 Python 错误:图块无法扩展到图像之外
【发布时间】:2021-01-11 09:46:17
【问题描述】:

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

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

使用下面的代码,我收到错误 -tile 无法扩展到图像之外 **对于我提供的任何尺寸,例如 (500,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))

【问题讨论】:

  • 看来您不能指定比图像更大的裁剪区域。您还应该使用os.path 来操作路径,而不是手动操作(更容易出错的方式)。
  • 谢谢。在了解了这四个元组是如何工作的之后,我解决了这个问题。

标签: python image-processing computer-vision python-imaging-library crop


【解决方案1】:

"(2000,1500,2000,1500)" 是一个空框,这可以解释为什么即使“图块无法延伸到图像之外”错误不完全合适,裁剪也会失败。 crop 的 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, upper, right, lower))

【讨论】:

  • 我通过研究了解。非常感谢您的链接。现在问题解决了。图像尺寸为-2048x1536。我只想裁剪上下部分。我提供了参数 (0,30,2048,1450) 来获得我想要的输出。
猜你喜欢
  • 1970-01-01
  • 2016-08-28
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多