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

简介: PIL.Image.blend()的使用

将两幅图像合成一幅图像,是图像处理中常用的一种操作,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.csdn.net/AugustMe/article/details/112370003

参考

https://blog.csdn.net/guduruyu/article/details/71439733

https://blog.csdn.net/weixin_39190382/article/details/105863804

相关文章
|
算法 Unix Linux
【C/C++ 实用工具】性能分析工具一览
【C/C++ 实用工具】性能分析工具一览
1482 0
|
Unix Linux
Touch命令使用指南:创建、更新和修改文件时间戳
Touch命令使用指南:创建、更新和修改文件时间戳
2045 0
|
存储 SQL 运维
一篇文章彻底理解 HDFS 的安全模式
一篇文章彻底理解 HDFS 的安全模式
|
数据安全/隐私保护
邮件发送的原理,如何进行邮件发送
邮件发送的原理,如何进行邮件发送
|
数据可视化 定位技术 Python
【100天精通Python】Day68:Python可视化_Matplotlib 绘制热力图,示例+代码
【100天精通Python】Day68:Python可视化_Matplotlib 绘制热力图,示例+代码
4685 0
|
API Python Windows
python3应用windows api对后台程序窗口及桌面截图并保存的方法
python3应用windows api对后台程序窗口及桌面截图并保存的方法
1689 1
|
机器学习/深度学习 人工智能 自然语言处理
Baichuan-M1-14B:AI 助力医疗推理,为患者提供专业的建议!百川智能开源业内首个医疗增强大模型,普及医学的新渠道!
Baichuan-M1-14B 是百川智能推出的首个开源医疗增强大模型,专为医疗场景优化,支持多语言、快速推理,具备强大的医疗推理能力和通用能力。
1299 17
Baichuan-M1-14B:AI 助力医疗推理,为患者提供专业的建议!百川智能开源业内首个医疗增强大模型,普及医学的新渠道!
|
Linux Python
Linux 中某个目录中的文件数如何查看?这篇教程分分钟教会你!
在 Linux 系统中,了解目录下的文件数量是常见的需求。本文介绍了多种方法,包括使用 `ls` 和 `wc` 命令组合、`find` 命令、`tree` 命令以及编程方式(如 Python)。无论你是新手还是有经验的用户,都能找到适合自己的方法。掌握这些技巧将提高你在 Linux 系统中的操作效率。
853 4
|
Ubuntu
使用dpkg在ubuntu上安装软件包遇到依赖包的问题
使用dpkg在ubuntu上安装软件包遇到依赖包的问题
1330 1

热门文章

最新文章