【问题标题】:Why does PIL fail to merge 2 images in my code?为什么 PIL 无法在我的代码中合并 2 个图像?
【发布时间】:2013-12-16 08:27:49
【问题描述】:

我正在尝试使用 Image.paste 功能将 2 个图像组合成一个更大的图像。我首先创建一个可以容纳两个图像的图像,然后粘贴 2 个图像:

wrapper = Image.new("I", (width, height+textHeight));

if placement=="bottom":
 wrapper.paste(img1); 
 wrapper.paste(textImage, (0, height, width, textHeight));
else:
 wrapper.paste(textImage);
 wrapper.paste(img1, (0,textHeight));

然后我每次都会收到这个错误:

 File "C:\Python27\lib\site-packages\PIL\Image.py", line 1127, in paste
    self.im.paste(im, box)
ValueError: images do not match

我非常确定图像的大小是正确的,并且包装图像可以容纳两个图像。避免此错误的唯一方法是使 3 个图像(包装器和 2 个组件)大小相同,并从 (0,0) 粘贴。

我无能为力,请帮忙!

【问题讨论】:

    标签: python image-processing python-imaging-library pillow


    【解决方案1】:

    有两个可能的问题。

    1. 你确定你的四元组(0, height, width, textHeight) 是正确的吗?它应该是(left, upper, right, lower) 像素坐标。在这种情况下,粘贴的图像必须与区域的大小匹配,我认为这就是您的错误所在。或者,您可以给出一个 2 元组,仅给出要粘贴图片的位置的左上角。见:http://effbot.org/imagingbook/image.htm

    2. 您确定 height、width、textHeight 是 ints 而不是 floats

    你可以试试这样的:

    x, y = img1.size
    wrapper.paste(textImage,(0,height,x,y))
    

    【讨论】:

    • 原来我设置图像大小的方式错误:我在textImage上绘制了一些文本,计算出文本使用的区域后,我需要裁剪掉额外的空白区域。我用 textImage.size=(w,h) 做到了这一点。正确的做法是使用crop方法。但是您的答案提供了导致此错误的 2 个最常见原因(我已经搜索了很多),因此我将其标记为已接受的答案。
    • 谢谢!很高兴知道你想通了。
    • 八年后,仍然有用:)
    猜你喜欢
    • 2021-07-10
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多