NO.56——Face Swapping with Face++ API(換臉)

在上篇博客中,介紹了應用dlib和openCV進行人臉融合的方法,這裏介紹一個更簡單、效果更好的方法,就是調用曠世科技的人臉融合接口:https://api-cn.faceplusplus.com/imagepp/v1/mergeface。

在實際運用過程中,還調用了人臉檢測接口:https://api-cn.faceplusplus.com/facepp/v3/detect。

效果如圖,可見,比前一種方法效果好很多:

 

具體代碼如下:

import requests
import simplejson
import json
#接口的報文是通過base64加密傳輸的,這種加密方式是可逆的。所以在進行接口自動化時,需要對所傳的參數進行base64編碼
import base64

#Face++網址:[url]https://console.faceplusplus.com.cn/dashboard[/url]
#第一步,獲取人臉關鍵點
def find_face(imgpath):
    print("正在查找……")
    http_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(http_url, data=data, files=files)
    req_con = response.content.decode('utf-8')
    req_dict = json.JSONDecoder().decode(req_con)
    this_json = simplejson.dumps(req_dict)
    this_json2 = simplejson.loads(this_json)
    print(this_json2)
    faces = this_json2['faces']
    list0 = faces[0]
    rectangle = list0['face_rectangle']
    #print(rectangle)
    return rectangle

#第二步,換臉,其中圖片的大小應不超過2M
# number表示換臉的相似度
def merge_face(image_url1, image_url2, image_url, number):
    
    ff1 = find_face(image_url1)
    ff2 = find_face(image_url2)
    
    rectangle1 = str(str(ff1['top']) + "," + str(ff1['left']) + "," + str(ff1['width']) + "," + str(ff1['height']))
    rectangle2 = str(ff2['top']) + "," + str(ff2['left']) + "," + str(ff2['width']) + "," + str(ff2['height'])
    print(rectangle2)
    url_add = "https://api-cn.faceplusplus.com/imagepp/v1/mergeface"
    f1 = open(image_url1, 'rb')
    f1_64 = base64.b64encode(f1.read())
    f1.close()
    f2 = open(image_url2, 'rb')
    f2_64 = base64.b64encode(f2.read())
    f2.close()
    
    data = {"api_key": 'api_key',
            "api_secret": 'api_secret',
            "template_base64": f1_64, "template_rectangle": rectangle1,
            "merge_base64": f2_64, "merge_rectangle": rectangle2, "merge_rate": number}
    
    response = requests.post(url_add, data=data)
    req_con1 = response.content.decode('utf-8')
    #print(req_con1)
    req_dict = json.JSONDecoder().decode(req_con1)
    result = req_dict['result']
    imgdata = base64.b64decode(result)
    file = open(image_url, 'wb')
    file.write(imgdata)
    file.close()

image1 = '/Users/chenyan/Desktop/AI/googleAI/faceswap_Face++/11.jpg'
image2 = '/Users/chenyan/Desktop/AI/googleAI/faceswap_Face++/bb.jpg'
image = '/Users/chenyan/Desktop/AI/googleAI/faceswap_Face++/testbb.jpg'

merge_face(image2, image1, image, 80)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章