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

yipeiwu_com6年前Python基础

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

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

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

1、使用Image.blend()接口

代码如下:

# -*- 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 进行。

合成结果如下:

2、使用Image.composite()接口

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

代码如下:

# -*- 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数学运算技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

Python中Collections模块的Counter容器类使用教程

Python中Collections模块的Counter容器类使用教程

1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict、set、list、tuple以外的一些特殊的容器类型,分别是: Order...

Django 使用logging打印日志的实例

Django使用python自带的logging 作为日志打印工具。简单介绍下logging。 logging 是线程安全的,其主要由4部分组成: Logger 用户使用的直接接口,将...

Python实现对字符串的加密解密方法示例

本文实例讲述了Python实现对字符串的加密解密方法。分享给大家供大家参考,具体如下: 需求是是要将密码存在数据库里,所以要加密解密是可逆的,在数据库里不要有特殊字符,防止数据库备份和恢...

Python实现求两个csv文件交集的方法

本文实例讲述了Python实现求两个csv文件交集的方法。分享给大家供大家参考,具体如下: #!/usr/bin/env python rd3 = open('data_17_17_...

linux下安装easy_install的方法

如果想使用easy_install工具,可能需要先安装setuptools,不过更酷的方法是使用ez_setup.py脚本:复制代码 代码如下:wget -q http://peak.t...