Python calls Baidu API to realize face fusion

1. About the author

Liu Shuaibo, male, School of Electronic Information, Xi'an Polytechnic University, 2021 graduate student, Zhang Hongwei Artificial Intelligence Research Group
Research direction: Machine Vision and Artificial Intelligence
Email: [email protected]

2. Introduction to face fusion

Simply put, it is to fuse the two faces, so that the generated face has the appearance features of the two faces at the same time. This is the online test page given by Baidu Smart Cloud official website platform. It supports four image formats, and the image size is required to be no more than 2M.
insert image description here

3. Call Baidu Smart Cloud API

The steps of how to create an application interface are as follows, click the arrow prompts in turn
. Step 1:

Step 2:
insert image description here
Step 3:
insert image description here

4. Code Analysis

4.1 Import the library

import requests         # 可以用来生成一个网络请求,抓取网络信息即用来调用百度云的接口
import base64           # 将图片信息采用Base64编码
import json             # 是一种轻量级的数据交换格式

4.2 Get token

# token获取
def get_token(client_id, client_secret):
    # client_id为官网获取的API Key,client_secret为官网获取的Secret Key.下行client_id=后的马赛克为你的API Key,client_secret=后的马赛克为你的Secret Key
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=********&client_secret=*********"
    response = requests.get(url)
    resultJson = response.json()
    return resultJson['access_token']

Here you need to use the API Key and Secret Key obtained by yourself in Baidu Smart Cloud. The token is equivalent to the "access license" issued to you by the server when you access the Baidu Cloud face fusion interface.

4.3 Read pictures, convert encoding

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

This is a fixed function model

4.4 Calling Baidu Smart Cloud Interface to Realize Image Fusion

# 调用百度的接口,实现融合图片
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'])

Here is the core part, calling Baidu API to realize face image fusion

4.5 Download Fusion Image

# 下载融合后图片
def down_photo(data):
    imagedata = base64.b64decode(data)
    file = open('D:\\研一任务\\课程作业\\人工智能高级语言程序设计\\result.jpg', "wb")
    # 融合图片保存路径,'wb':以二进制格式打开一个文件只用于写入,文件存在则覆盖,若不存在创建新文件
    file.write(imagedata)

Pay attention to the name of the save path here to avoid "\n", "\r" and other forms, which will cause the path to be unreadable.

4.6 Running the main program

# 主程序
if __name__ == '__main__':
    # 路径为自己的图片存储路径
    胡歌 = read_photo('D:\\研一任务\\课程作业\\人工智能高级语言程序设计\\1.jpg')                # 模板图片
    赵丽颖 = read_photo('D:\\研一任务\\课程作业\\人工智能高级语言程序设计\\2.jpg')              # 目标图片
    token = get_token('*********', '**********')  # 前者为API Key,后者改为Secret Key
    face_fusion(token, 胡歌, 赵丽颖)

Here you need to use the API Key and Secret Key obtained by Baidu Smart Cloud, and run the main program to get the result of the face fusion image (Note: You should choose a clear face photo with no occlusion on the front, otherwise there will be a prompt that no face can be detected. )

4.7 Display of fusion results

insert image description here

5. Complete code

'''
Author:LSB / 207
Date:2022年03月03日
'''

import requests         # 可以用来生成一个网络请求,抓取网络信息即用来调用百度云的接口
import base64           # 将图片信息采用Base64编码
import json             # 是一种轻量级的数据交换格式


# token获取
def get_token(client_id, client_secret):
    # client_id为官网获取的API Key,client_secret为官网获取的Secret Key.下行client_id=后的马赛克为你的API Key,client_secret=后的马赛克为你的Secret Key
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=***********&client_secret=************"  # 注意此处的&符号
    response = requests.get(url)
    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('D:\\研一任务\\课程作业\\人工智能高级语言程序设计\\result.jpg', "wb")
    # 融合图片保存路径,'wb':以二进制格式打开一个文件只用于写入,文件存在则覆盖,若不存在创建新文件
    file.write(imagedata)


# 主程序
if __name__ == '__main__':
    # 路径为自己的图片存储路径
    胡歌 = read_photo('D:\\研一任务\\课程作业\\人工智能高级语言程序设计\\1.jpg')                # 模板图片
    赵丽颖 = read_photo('D:\\研一任务\\课程作业\\人工智能高级语言程序设计\\2.jpg')              # 目标图片
    token = get_token('*********', '**********')  # 前者为API Key,后者改为Secret Key
    face_fusion(token, 胡歌, 赵丽颖)

Guess you like

Origin blog.csdn.net/m0_37758063/article/details/123643567