我一直在用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
我什至不确定我是否使用正确的功能将两个图像“混合”在一起,所以,如果我不知道,请告诉我。
这里发生了几件事:
例如,如果我带帕丁顿宫和白金汉宫,各取50%:
我得到这个:
如果这是您想要的,则需要将图像调整为通用大小并更改此行:
bg = Image.blend(im1, im2, 0)
至
bg = Image.blend(im1, im2, 0.5) # blend half and half
如果要粘贴具有透明性的东西,使其仅在某些地方显示,则需要从具有透明性的GIF或PNG加载叠加层并使用:
background.paste(覆盖,框=无,遮罩=覆盖)
然后,您可以执行此操作-注意,您可以在每个点看到不同数量的两个图像:
因此,作为将透明图像叠加到不透明背景上并从Paddington(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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句