一键换脸

import requests
import base64
import warnings;

warnings.simplefilter('ignore')

API_Key = ''  # 所获取的API Key
API_Secret = ''  # 所获取的API Secret


def find_face(imgpath):
    url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
    data = {
     'api_key': API_Key, 'api_secret': API_Secret, 'image_url': imgpath, 'return_landmark': 1}
    files = {
     'image_file': open(imgpath, 'rb')}
    response = requests.post(url, data=data, files=files)
    res_json = response.json()  # 转换为json
    faces = res_json['faces'][0]['face_rectangle']  # 获取面部大小的四个值,分别为长宽高低
    return faces  # 返回图片的面部参数


def change_face(image_1, image_2, number=99):
    url = "https://api-cn.faceplusplus.com/imagepp/v1/mergeface"  #
    find_p1 = find_face(image_1)
    find_p2 = find_face(image_2)
    rectangle1 = str(
        str(find_p1['top']) + ',' + str(find_p1['left']) + ',' + str(find_p1['width']) + ',' + str(find_p1['height']))
    rectangle2 = str(
        str(find_p2['top']) + ',' + str(find_p2['left']) + ',' + str(find_p2['width']) + ',' + str(find_p2['height']))

    page1 = open(image_1, 'rb')
    page1_64 = base64.b64encode(page1.read())
    page1.close()
    page2 = open(image_2, 'rb')
    page2_64 = base64.b64encode(page2.read())
    page2.close()
    data = {
     'api_key': API_Key, 'api_secret': API_Secret, 'template_base64': page1_64,
            'template_rectangle': rectangle1, 'merge_base64': page2_64, 'merge_rectangele': rectangle2,
            'merge_rate': number}
    response = requests.post(url, data=data).json()
    results = response['result']
    image = base64.b64decode(results)

    with open('所得到的图片.jpg', 'wb') as f:  # 将信息写入到图片
        f.write(image)
    print("转换完成")


if __name__ == '__main__':
    change_face('D:\\交换3.jpg',
                'D:\\交换4.jpg')

你可能感兴趣的:(python)