【python】PIL.Image.blend()的使用

本文介绍了Python图像处理库PIL中两种融合图像的方法:Image.blend()和Image.composite()。通过示例代码详细展示了如何将两张图片按不同方式融合,并保存结果。其中,Image.blend()基于特定比例混合图片,而Image.composite()则利用掩码进行合成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将两幅图像合成一幅图像,是图像处理中常用的一种操作,python图像处理库PIL中提供了多种将两幅图像合成一幅图像的接口。

1. 方法1:PIL.Image.blend()

在这里插入图片描述
现在要将图片1和图片2进行融合:

from PIL import Image

def blend_two_images():
    img1 = Image.open("/home/ubuntu/Z/Temp/mergepic/1.jpg")
    # img1 = img1.convert('RGBA') # 根据需求是否转换颜色空间
    print(img1.size)
    img1 = img1.resize((400,400)) # 注意,是2个括号
    print(img1.size)

    img2 = Image.open("/home/ubuntu/Z/Temp/mergepic/2.jpg")
    # # img2 = img2.convert('RGBA')
    print(img2.size)
    img2 = img2.resize((400,400)) # 注意,是2个括号
    print(img2.size)

    img = Image.blend(img1, img2, 0.4) # blend_img = img1 * (1 – 0.3) + img2* alpha
    img.show()
    img.save("blend13.png") # 注意jpg和png,否则 OSError: cannot write mode RGBA as JPEG

    return

if __name__ == "__main__":
    blend_two_images()

上述方法,根据公式 blend_img = img1 * (1 – alpha) + img2 * alpha进行融合。

得到结果:
在这里插入图片描述

2. 方法2:PIL.Image.composite()

该接口使用掩码(mask)的形式对两幅图像进行合并。

from PIL import Image

def blend_two_images():
    img1 = Image.open("/home/ubuntu/Z/Temp/mergepic/1.jpg")
    # img1 = img1.convert('RGBA') # 根据需求是否转换颜色空间
    print(img1.size)
    img1 = img1.resize((400,400)) # 注意,是2个括号
    print(img1.size)

    img2 = Image.open("/home/ubuntu/Z/Temp/mergepic/2.jpg")
    # # img2 = img2.convert('RGBA')
    print(img2.size)
    img2 = img2.resize((400,400)) # 注意,是2个括号
    print(img2.size)

    r, g, b, alpha = img2.split()
    alpha = alpha.point(lambda i: i > 0 and 204)

    img = Image.composite(img2, img1, alpha)

    img.show()
    img.save("blend1122.png") # 注意jpg和png,否则 OSError: cannot write mode RGBA as JPEG

    return

if __name__ == "__main__":
    blend_two_images()

代码中

alpha = alpha.point(lambda i: i > 0 and 204)

指定的204起到的效果和使用blend()接口时的alpha类似。

运行结果:
在这里插入图片描述

参考

https://blog.youkuaiyun.com/guduruyu/article/details/71439733

https://blog.youkuaiyun.com/weixin_39190382/article/details/105863804

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

机器不学习我学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值