脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python图像处理实现两幅图像合成一幅图像的方法【测试可用】

Python图像处理实现两幅图像合成一幅图像的方法【测试可用】

2021-05-12 00:05PHILOS_THU Python

这篇文章主要介绍了Python图像处理实现两幅图像合成一幅图像的方法,结合实例形式分析了Python使用Image.blend()接口与Image.composite()接口进行图像合成的相关操作技巧,需要的朋友可以参考下

本文实例讲述了python图像处理实现两幅图像合成一幅图像的方法。分享给大家供大家参考,具体如下:

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

下面我们通过不同的方式,将两图合并成一幅图像。

Python图像处理实现两幅图像合成一幅图像的方法【测试可用】

Python图像处理实现两幅图像合成一幅图像的方法【测试可用】

1、使用image.blend()接口

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding:utf-8 -*-
from pil import image
def blend_two_images():
  img1 = image.open( "bridge.png ")
  img1 = img1.convert('rgba')
  img2 = image.open( "birds.png ")
  img2 = img2.convert('rgba')
  img = image.blend(img1, img2, 0.3)
  img.show()
  img.save( "blend.png")
  return
blend_two_images()

两幅图像进行合并时,按公式:blended_img = img1 * (1 – alpha) + img2* alpha 进行。

合成结果如下:

Python图像处理实现两幅图像合成一幅图像的方法【测试可用】

2、使用image.composite()接口

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

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding:utf-8 -*-
from pil import image
def blend_two_images2():
  img1 = image.open( "bridge.png ")
  img1 = img1.convert('rgba')
  img2 = image.open( "birds.png ")
  img2 = img2.convert('rgba')
  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( "blend2.png")
  return
blend_two_images2()

代码第9行中指定的204起到的效果和使用blend()接口时的0.3类似。

合并后的效果如下:

Python图像处理实现两幅图像合成一幅图像的方法【测试可用】

希望本文所述对大家python程序设计有所帮助。

原文链接:https://blog.csdn.net/guduruyu/article/details/71439733

延伸 · 阅读

精彩推荐