【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

相关文章
|
9月前
|
计算机视觉 Python
PIL pillow
PIL pillow
61 1
|
8月前
|
计算机视觉 Python
|
前端开发 算法 Linux
Python:wordcloud.wordcloud()函数的参数解析及其说明
Python:wordcloud.wordcloud()函数的参数解析及其说明
|
7月前
|
UED Python
tqdm进度条函数使用 python
tqdm进度条函数使用 python
|
计算机视觉 开发者 Python
【PyCharm中PIL/Pillow的安装】
【PyCharm中PIL/Pillow的安装】
383 0
|
6月前
|
Python
Python 进度条 tqdm模块
Python 进度条 tqdm模块
45 0
|
Web App开发 Python
|
Unix Windows Python
python中os.path常用属性和部分使用方法
python中os.path常用属性和部分使用方法
189 0
|
9月前
|
关系型数据库 Python
Python小姿势 - Python Tips: How to Use Context Managers
Python小姿势 - Python Tips: How to Use Context Managers
|
存储 索引 Python
python中 itertools模块的使用方法
itertools模块的使用方法
100 0
python中 itertools模块的使用方法

热门文章

最新文章