【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

相关文章
|
4月前
|
存储 计算机视觉 Python
|
计算机视觉 Python Windows
技巧 | Python 图片转换GIF/视频
技巧 | Python 图片转换GIF/视频
|
存储 Python
【Python标准库】pillow中Image模块学习
【Python标准库】pillow中Image模块学习
|
计算机视觉 Python Windows
Python如何安装cv2模块
Python如何安装cv2模块
273 0
|
计算机视觉 Python
用Python的PIL库(Pillow)处理图像
用Python的PIL库(Pillow)处理图像
150 0
【python】使用python中的pillow生成gif动态图
在之前的文章中,介绍了使用imageio生成gif动态图片,十分方便,简单,容易上手。 我发现pillow这个库也可以生成gif动态图片。
【python】使用python中的pillow生成gif动态图
|
计算机视觉 Python
|
计算机视觉 Python
【python】python中PIL.Image和OpenCV图像格式相互转换
python中PIL.Image和OpenCV图像格式相互转换