Python實(shí)現(xiàn)AI換臉功能
需要用到的接口:
獲取人臉信息的接口:https://api-cn.faceplusplus.com/facepp/v3/detect
實(shí)現(xiàn)換臉的接口 :https://api-cn.faceplusplus.com/imagepp/v1/mergeface
代碼分為三步
代碼:
import requestsimport jsonimport simplejsonimport base64#第一步:獲取人臉關(guān)鍵點(diǎn)def find_face(imgpath): ''' :param imgpath: 圖片的地址 :return: 一個(gè)字典類型的人臉關(guān)鍵點(diǎn) 如:{’top’: 156, ’left’: 108, ’width’: 184, ’height’: 184} ''' http_url = ’https://api-cn.faceplusplus.com/facepp/v3/detect’ #獲取人臉信息的接口 data = { 'api_key':'x2NyKaa6vYuArYwat4x0-NpIbM9CrwGU',#訪問url所需要的參數(shù) 'api_secret':'OuHx-Xaey1QrORwdG7QetGG5JhOIC8g7',#訪問url所需要的參數(shù) 'image_url':imgpath, #圖片地址 'return_landmark':1 } files = {’image_file’:open(imgpath,’rb’)} #定義一個(gè)字典存放圖片的地址 response = requests.post(http_url,data=data,files=files) res_con1 = response.content.decode(’utf-8’) res_json = simplejson.loads(res_con1) faces = res_json[’faces’] list = faces[0] rectangle = list[’face_rectangle’] return rectangle#第二步:實(shí)現(xiàn)換臉def merge_face(image_url1,image_url2,image_url,number): ''' :param image_url1: 被換臉的圖片路徑 :param image_url2: 換臉的圖片路徑 :param image_url: 換臉后生成圖片所保存的路徑 :param number: 換臉的相似度 ''' #首先獲取兩張圖片的人臉關(guān)鍵點(diǎn) face1 = find_face(image_url1) face2 = find_face(image_url2) #將人臉轉(zhuǎn)換為字符串的格式 rectangle1 = str(str(face1[’top’]) + ',' + str(face1[’left’]) + ',' + str(face1[’width’]) + ',' + str(face1[’height’])) rectangle2 = str(str(face2[’top’]) + ',' + str(face2[’left’]) + ',' + str(face2[’width’]) + ',' + str(face2[’height’])) #讀取兩張圖片 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() url_add = ’https://api-cn.faceplusplus.com/imagepp/v1/mergeface’ #實(shí)現(xiàn)換臉的接口 data={ 'api_key': 'x2NyKaa6vYuArYwat4x0-NpIbM9CrwGU', 'api_secret': 'OuHx-Xaey1QrORwdG7QetGG5JhOIC8g7', 'template_base64':f1_64, 'template_rectangle':rectangle1, 'merge_base64':f2_64, 'merge_rectangle':rectangle2, 'merge_rate':number } response1 = requests.post(url_add,data=data) res_con1 = response1.content.decode(’utf-8’) res_dict = json.JSONDecoder().decode(res_con1) result = res_dict[’result’] imgdata = base64.b64decode(result) file=open(image_url,’wb’) file.write(imgdata) file.close()if __name__ == ’__main__’: image1 = r'meizi1.jpg' image2 = r'meizi.jpg' image3 = r'face1.jpg' merge_face(image1,image2,image3,100)
效果:
換臉前
要換的臉:
換臉后:
總結(jié)
到此這篇關(guān)于Python實(shí)現(xiàn)AI換臉的代碼的文章就介紹到這了,更多相關(guān)Python實(shí)現(xiàn)AI換臉內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP基礎(chǔ)知識(shí)VBScript基本元素講解2. ajax請(qǐng)求添加自定義header參數(shù)代碼3. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟4. Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫5. Python requests庫參數(shù)提交的注意事項(xiàng)總結(jié)6. 基于javascript處理二進(jìn)制圖片流過程詳解7. 解決android studio引用遠(yuǎn)程倉庫下載慢(JCenter下載慢)8. asp知識(shí)整理筆記4(問答模式)9. axios和ajax的區(qū)別點(diǎn)總結(jié)10. 詳談ajax返回?cái)?shù)據(jù)成功 卻進(jìn)入error的方法
