Python calls image fusion API

Python calls image fusion API

This article records the use of Python to call the image fusion API of Tencent AI Open Platform. The demo given on the official website uses PHP. As a fan of Python, bloggers naturally want to use it to compete with the "best" language, and by the way, deepen their understanding of service calls.

Official website PHP implementation

Tencent's official documentation should be very detailed. The PHP code that can be directly run is as follows:

<?php

// getReqSign :根据 接口请求参数 和 应用密钥 计算 请求签名
// 参数说明
//   - $params:接口请求参数(特别注意:不同的接口,参数对一般不一样,请以具体接口要求为准)
//   - $appkey:应用密钥
// 返回数据
//   - 签名结果
function getReqSign($params /* 关联数组 */, $appkey /* 字符串*/)
{
    // 1. 字典升序排序
    ksort($params);

    // 2. 拼按URL键值对
    $str = '';
    foreach ($params as $key => $value)
    {
        if ($value !== '')
        {
            $str .= $key . '=' . urlencode($value) . '&';
        }
    }

    // 3. 拼接app_key
    $str .= 'app_key=' . $appkey;

    // 4. MD5运算+转换大写,得到请求签名
    $sign = strtoupper(md5($str));
    return $sign;
}


// doHttpPost :执行POST请求,并取回响应结果
// 参数说明
//   - $url   :接口请求地址
//   - $params:完整接口请求参数(特别注意:不同的接口,参数对一般不一样,请以具体接口要求为准)
// 返回数据
//   - 返回false表示失败,否则表示API成功返回的HTTP BODY部分
function doHttpPost($url, $params)
{
    $curl = curl_init();

    $response = false;
    do
    {
        // 1. 设置HTTP URL (API地址)
        curl_setopt($curl, CURLOPT_URL, $url);

        // 2. 设置HTTP HEADER (表单POST)
        $head = array(
            'Content-Type: application/x-www-form-urlencoded'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $head);

        // 3. 设置HTTP BODY (URL键值对)
        $body = http_build_query($params);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);

        // 4. 调用API,获取响应结果
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_NOBODY, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($curl);
        if ($response === false)
        {
            $response = false;
            break;
        }

        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($code != 200)
        {
            $response = false;
            break;
        }
    } while (0);

    curl_close($curl);
    return $response;
}



// 图片base64编码
$path   = 'test.jpg';
$data   = file_get_contents($path);
$base64 = base64_encode($data);

// 设置请求数据
$appkey = 'your_appkey';
$params = array(
    'app_id'     => 'your_app_id',
    'image'      => $base64,
    'model'      => '1',
    'time_stamp' => strval(time()),
    'nonce_str'  => strval(rand()),
    'sign'       => '',
);
$params['sign'] = getReqSign($params, $appkey);

// 执行API调用
$url = 'https://api.ai.qq.com/fcgi-bin/ptu/ptu_facemerge';
$response = doHttpPost($url, $params);
echo $response;

According to this program, the base64 encoding of the fused picture can be returned, and then the picture can be obtained by decoding

Python version implementation

The following code is rewritten by bloggers with reference to php. It is worth noting that urlencode is a specific data format, especially the picture information must be encoded according to this, otherwise an error message will be returned

# coding=utf-8
import requests
import time
import random
import hashlib
import base64
from urllib import urlencode


def get_sign(para, app_key):
    # 签名的key有严格要求,按照key升序排列
    data = sorted(para.items(), key=lambda item: item[0])
    s = urlencode(data)
    # app_key最后加
    s += '&app_key=' + app_key
    # 计算md5报文信息
    md5 = hashlib.md5()
    md5.update(s)
    digest = md5.hexdigest()
    return digest.upper()


url = 'https://api.ai.qq.com/fcgi-bin/ptu/ptu_facemerge'
app_key = 'your_app_key'
# 读取图片数据
raw_data = open('test.jpg').read()
image_data = base64.b64encode(raw_data)

# 定义发送的post数据
data = {
    'app_id': 'your_app_id',
    'image': image_data,
    'model': '1',  # 选定想要融合的模板
    'time_stamp': str(int(time.time())),
    'nonce_str': str(random.random()),
}

data['sign'] = get_sign(data, app_key)

# 发送post请求
r = requests.post(url, data=data)
# 将得到的数据解码,然后保存到jpg
res_image = base64.b64decode(r.json()['data']['image'])
img = open('out.jpg', 'w')
img.write(res_image)
img.close()

Effect

Input picture (face picture on the Internet, invade and delete)

test.jpg

Fusion template given by Tencent 1

output

out.jpg

summary

The logic of this experiment is not very complicated. The knowledge points are mainly the signature algorithm and POST request . You can see that the code of Python is much shorter than that of PHP, mainly because some packaged libraries are used.

With the face fusion service, I feel like I can do a lot of interesting things~

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325277618&siteId=291194637