|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +@author: 闲欢 |
| 5 | +""" |
| 6 | +import json |
| 7 | +import requests |
| 8 | +import base64 |
| 9 | + |
| 10 | + |
| 11 | +API_KEY = '你的API_KEY' |
| 12 | +SECRET_KEY = '你的SECRET_KEY' |
| 13 | + |
| 14 | + |
| 15 | +# 获取token |
| 16 | +def get_token(client_id, client_secret): |
| 17 | + url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials" |
| 18 | + params = {"client_id": client_id, "client_secret": client_secret} |
| 19 | + res = requests.get(url, params=params) |
| 20 | + result = res.json() |
| 21 | + return result['access_token'] |
| 22 | + |
| 23 | + |
| 24 | +# 读取图片,转换成base64 |
| 25 | +def read_pic(name): |
| 26 | + with open('./%s' % name, 'rb') as f: |
| 27 | + base64_data = base64.b64encode(f.read()) |
| 28 | + s = base64_data.decode() |
| 29 | + return s |
| 30 | + |
| 31 | + |
| 32 | +# 下载图片 |
| 33 | +def down_pic(data): |
| 34 | + imagedata = base64.b64decode(data) |
| 35 | + file = open('./result.jpg', "wb") |
| 36 | + file.write(imagedata) |
| 37 | + |
| 38 | + |
| 39 | +# 融合图片 |
| 40 | +def merge(token, template, target): |
| 41 | + url = 'https://aip.baidubce.com/rest/2.0/face/v1/merge' |
| 42 | + request_url = url + '?access_token=' + token |
| 43 | + params = { |
| 44 | + "image_template": { |
| 45 | + "image": template, |
| 46 | + "image_type": "BASE64", |
| 47 | + "quality_control": "NORMAL" |
| 48 | + }, |
| 49 | + "image_target": { |
| 50 | + "image": target, |
| 51 | + "image_type": "BASE64", |
| 52 | + "quality_control": "NORMAL" |
| 53 | + }, |
| 54 | + "merge_degree": "HIGH" |
| 55 | + } |
| 56 | + params = json.dumps(params) |
| 57 | + headers = {'content-type': 'application/json'} |
| 58 | + result = requests.post(request_url, data=params, headers=headers).json() |
| 59 | + if result['error_code'] == 0: |
| 60 | + res = result["result"]["merge_image"] |
| 61 | + down_pic(res) |
| 62 | + else: |
| 63 | + print(str(result['error_code'])+result['error_msg']) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + girl = read_pic('girl.jpg') |
| 68 | + boy = read_pic('boy.jpg') |
| 69 | + token = get_token(API_KEY, SECRET_KEY) |
| 70 | + merge(token, girl, boy) |
| 71 | + |
| 72 | + |
| 73 | + |
0 commit comments