AI换脸

AI换脸

技术

调用到百度的AI接口,layui的图片上传,栅格化布局

核心代码

纯py文件运行

 # 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(name, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        base64_code = base64_data.decode()
    return base64_code


# 调用百度的接口,实现融合图片
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": "NONE"
        },
        "image_target": {
            "image": target,
            "image_type": "BASE64",
            "quality_control": "NONE"
        },
        "merge_degree": "NORMAL"
    }
    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__':
    template = read_photo('img/jjy.jpg')
    target = read_photo('img/mzc.jpeg')
    token = get_token('你的ID', '你的key')
    face_fusion(token, template, target)

实战开发-换脸大法

操作步骤

1.准备页面:两个图片上传,一个为模板图,一个为目标图,还有一个结果图

2.上传照片后,当点击“开始换脸”就会将两张图片的地址发送到后端,通过上面的纯py代码,下载换脸后的照片到本地,将地址返还给前端

3.前端将src进行更换即可

展示

将知否中的盛明兰与张一凡进行换脸

原文地址:https://www.cnblogs.com/xiaofengzai/p/14490348.html