首页 > 解决方案 > ValueError:在 PIL 中混合图片时图像不匹配

问题描述

我一直在用 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

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

标签: pythonpython-imaging-library

解决方案


这里有几件事:

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

例如,如果我选择帕丁顿和白金汉宫,各取 50%:

在此处输入图像描述

在此处输入图像描述

我明白了:

在此处输入图像描述

如果这是您想要的,您需要将图像调整为通用大小并更改此行:

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

bg = Image.blend(im1, im2, 0.5)          # blend half and half
  • 如果要粘贴具有透明度的内容,使其仅显示在某些位置,则需要从具有透明度的 GIF 或 PNG 加载叠加层并使用:

    background.paste(覆盖,框=无,掩码=覆盖)

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

在此处输入图像描述

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

在此处输入图像描述

在此处输入图像描述

#!/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')

在此处输入图像描述

如果您想从网站上抓取图像,请使用以下命令:

from PIL import Image 
import requests 
from io import BytesIO                                                                      

# Grab the star image from this answer
response = requests.get('https://i.stack.imgur.com/wKQCT.png')                              

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

推荐阅读