python - 值错误 : images do not match when blending pictures in PIL

标签 python python-imaging-library

我一直在 python 中乱搞,看是否可以将两张图片“混合”在一起。我的意思是图像是透明的,你可以同时看到两张图片。如果这仍然没有意义,请查看此链接:(只有我会混合图片和图片而不是 gif)

https://cdn.discordapp.com/attachments/652564556211683363/662770085844221963/communism.gif

这是我的代码:

from PIL import Image

im1 = Image.open('oip.jpg')
im2 = Image.open('star.jpg')

bg = Image.blend(im1, im2, 0)
bg.save('star_oip_paste.jpg', quality=95)

我得到了错误:

line 6, in <module> bg = Image.blend(im1, im2, 0) ValueError: images do not match

我什至不确定我是否使用了正确的函数将两个图像“混合”在一起——所以如果我不正确,请告诉我。

最佳答案

这里有几件事:

  • 您的输入图像都是不支持透明度的 JPEG,因此您只能在整个图像中进行固定混合。我的意思是你不能在一个点看到一个图像而在另一个点看到另一个图像。您只会在每个点看到每个图像的相同比例。这是你想要的吗?

比如我拿帕丁顿熊和白金汉宫各拿50%:

enter image description here

enter image description here

我明白了:

enter image description here

如果那是您想要的,您需要将图像调整为常见大小并更改此行:

bg = Image.blend(im1, im2, 0)

bg = Image.blend(im1, im2, 0.5)          # blend half and half
  • 如果你想粘贴一些透明的东西,让它只出现在某些地方,你需要从 GIF 或 PNG 加载透明的叠加层并使用:

    background.paste(overlay, box=None, mask=overlay)

然后您可以这样做 - 请注意,您可以在每个点看到不同数量的两个图像:

enter image description here

因此,作为将透明图像叠加到不透明背景上的具体示例,并从帕丁顿熊 (400x400) 和这颗星星 (500x500) 开始:

enter image description here

enter image description here

#!/usr/bin/env python3

from PIL import Image

# Open background and foreground and ensure they are RGB (not palette)
bg = Image.open('paddington.png').convert('RGB')
fg = Image.open('star.png').convert('RGBA')

# Resize foreground down from 500x500 to 100x100
fg_resized = fg.resize((100,100))

# Overlay foreground onto background at top right corner, using transparency of foreground as mask
bg.paste(fg_resized,box=(300,0),mask=fg_resized)

# Save result
bg.save('result.png')

enter image description here

如果你想从网站抓取图片,使用这个:

from PIL import Image 
import requests 
from io import BytesIO                                                                      

# Grab the star image from this answer
response = requests.get('/image/wKQCT.png')                              

# Make it into a PIL image
img = Image.open(BytesIO(response.content))  

关于python - 值错误 : images do not match when blending pictures in PIL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59585605/

相关文章:

android - "adb screencap/sdcard/screenshot.raw"产生什么格式? (没有 "-p"标志)

python - 为 ARM 与 x86 编写代码时有何区别?

python - 从 shell 前面添加 sys.path?

python - Image.fromarray(pixels) 和 np.array(img) 是否应该保持数据不变?

python - 使用 Python 图像库 (PIL) 绘制抗锯齿线

python - Pyinstaller 不能很好地与 ImageTk 和 Tkinter 配合使用

python - 如何使用 Pillow 的 Image.load() 函数生成蒙版

python - Unresolved 导入 : HTMLTestRunner

python - 我怎样才能更好地编写这些函数以使其有意义

python - Ansible 过滤器 stdout_lines 剪切或分割