使用Python快速实现人脸融合

你是否会好奇自己的孩子将来会长什么样子,或者纯粹想YY一下自己和某某人在一起的话,孩子会是什么样的,那就来试试吧。

前期准备

预测是通过人脸融合技术实现的,需要借助 Python 和百度现有的 API 。

(1)注册百度账号

1.首先登陆 百度智能云 ,没有账号的可以注册一下。
在这里插入图片描述

2.点击:产品服务 -> 人工智能 -> 人脸识别,进入人脸识别产品菜单。
在这里插入图片描述
3.点击创建应用创建自己的应用,创建成功后会生成自己的 API Key 和 Secret Key 一会会用到。
在这里插入图片描述

(2)准备Python环境

1.此接口可以使用多种方法调用,因为 Python 的便捷性,本文使用 Python 语言来演示。其他语言的操作可以参考官方API
在这里插入图片描述
2.Python 的安装十分简单和快捷,不明白的可以参考以下博文。

《Python基础:安装 Python》

(3)准备照片

1.测试需要准备男女的照片,经过测试,最好证明照片,证件照最优,合成效果最好。我试了一些非正面照片,那合成结果真是惨不忍睹。
2.调用接口时,需要男女各一张,可以分别命名为 boy 和 girl 。图片参数现支持PNG、JPG、JPEG、BMP,不支持GIF图片。

实现思路

(1)获取本地照片,并转换成base64

# 根据图片名读取图片,并转换成base64
def read_photo(name):
    with open('./%s' % name, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        s = base64_data.decode()
        return s

(2)获取token

# 获取token
# client_id 为官网获取的 API Key , client_secret 为官网获取的 Secret Key
def get_token(client_id, client_secret):
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"
    params = {"client_id": client_id, "client_secret": client_secret}
    response = requests.get(url, params=params)
    resultJson = response.json()
    return resultJson['access_token']

(3)调用人脸融合接口

# 调用百度的接口,实现融合图片
def face_fusion(token, template, target):
    url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge'
    request_url = url + '?access_token=' + token
    params = {
        "image_template": {
            "image": template,
            "image_type": "BASE64",
            "quality_control": "NORMAL"
        },
        "image_target": {
            "image": target,
            "image_type": "BASE64",
            "quality_control": "NORMAL"
        },
        "merge_degree": "HIGH"
    }
    params = json.dumps(params)
    headers = {'content-type': 'application/json'}
    result = requests.post(request_url, data=params, headers=headers).json()
    if result['error_code'] == 0:
        res = result["result"]["merge_image"]
        down_photo(res)
    else:
        print(str(result['error_code'])+result['error_msg'])

(4)保存融合结果

# 下载融合后图片,保存成名为 result.jpg 的文件
def down_photo(data):
    imagedata = base64.b64decode(data)
    file = open('./result.jpg', "wb")
    file.write(imagedata)

编码实现

完整的代码需要引入一些 Python 模块,如果没有的需要安装,比如:requests。安装也比较简单,直接使用 pip 安装。

# 安装requests
pip install requests

# 可能因为pip的问题安装失败,可以执行以下命令解决
python -m pip install --upgrade pip 

完整代码

 # encoding:utf-8
import requests 
import base64
import json

# 获取token
# client_id 为官网获取的AK, client_secret 为官网获取的SK
def get_token(client_id, client_secret):
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"
    params = {"client_id": client_id, "client_secret": client_secret}
    response = requests.get(url, params=params)
    resultJson = response.json()
    return resultJson['access_token']

# 根据图片名读取图片,并转换成base64
def read_photo(name):
    with open('./%s' % name, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        bd = base64_data.decode()
        return bd


# 调用百度的接口,实现融合图片
def face_fusion(token, template, target):
    url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge'
    request_url = url + '?access_token=' + token
    params = {
        "image_template": {
            "image": template,
            "image_type": "BASE64",
            "quality_control": "NORMAL"
        },
        "image_target": {
            "image": target,
            "image_type": "BASE64",
            "quality_control": "NORMAL"
        },
        "merge_degree": "HIGH"
    }
    params = json.dumps(params)
    headers = {'content-type': 'application/json'}
    result = requests.post(request_url, data=params, headers=headers).json()
    if result['error_code'] == 0:
        res = result["result"]["merge_image"]
        down_photo(res)
    else:
        print(str(result['error_code'])+result['error_msg'])

# 下载融合后图片
def down_photo(data):
    imagedata = base64.b64decode(data)
    file = open('./result.jpg', "wb")
    file.write(imagedata)

# 主程序
if __name__ == '__main__':
	boy = read_photo('boy.jpg')
	girl = read_photo('girl.jpg')
	token = get_token('API Key', 'Secret Key')
	face_fusion(token, boy, girl)

默认是以男为模板,可以修改为以女为模板

融合效果

1.融合前

在这里插入图片描述在这里插入图片描述

2.融合后

以男生为模板
在这里插入图片描述
以女生为模板,额~ 有点怪怪的。
在这里插入图片描述

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值