我一直在 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%:
我明白了:
如果那是您想要的,您需要将图像调整为常见大小并更改此行:
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)
然后您可以这样做 - 请注意,您可以在每个点看到不同数量的两个图像:
因此,作为将透明图像叠加到不透明背景上的具体示例,并从帕丁顿熊 (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('/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/