換臉!
這段時間,deepfakes搞得火熱,比方說把《射雕英雄傳》里的朱茵換成了楊冪,看下面的圖!毫無違和感!
其實早在之前,基于ai換臉的技術就得到了應用,比方說《速度與激情7》里面的演員保羅.沃克,由于發生意外,
后期的視頻都是由他的兄弟完成拍攝,然后再對其換臉,最終也就是我們影院看到的效果。
當然,也有人把這項技術應用在其他的領域,例如把某種電影的女主換成了蓋爾.加朵(《神奇女俠》的扮演者),,,
這真的是對“技術是一把又刃劍”闡述的十分到位。。。
關于deepfakes這里不再詳細說明,好吧,小編承認是來蹭熱度的。。。
下面來介紹一種對照片的簡單換臉方法。
本篇介紹的換臉方法需要借助face++,關于face++的api,大家可自行查看說明文檔,都比較簡單,小編在這里就不做具體
說明了:
文檔地址:https://console.faceplusplus.com.cn/documents/20813963
1.配置工具:
1
2
|
pip install requests pip install simplejson |
2.獲取face++ api_key和secret
face++網址:https://console.faceplusplus.com.cn/dashboard
3.換臉步驟
調用的庫
1
2
3
4
|
import requests import simplejson import json import base64 |
第一步,獲取人臉關鍵點,代碼如下說述:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
def find_face(imgpath): print ( "finding" ) http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect' data = { "api_key" : '自己申請' , "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) faces = this_json2[ 'faces' ] list0 = faces[ 0 ] rectangle = list0[ 'face_rectangle' ] # print(rectangle) return rectangle |
第二步,換臉,其中圖片的大小應不超過2m,代碼如下所述:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#number表示換臉的相似度 def merge_face(image_url_1,image_url_2,image_url,number): ff1 = find_face(image_url_1) ff2 = find_face(image_url_2) 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' ]) url_add = "https://api-cn.faceplusplus.com/imagepp/v1/mergeface" f1 = open (image_url_1, 'rb' ) f1_64 = base64.b64encode(f1.read()) f1.close() f2 = open (image_url_2, 'rb' ) f2_64 = base64.b64encode(f2.read()) f2.close() data = { "api_key" : '自己申請' , "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_con = response.content.decode( 'utf-8' ) req_dict = json.jsondecoder().decode(req_con) result = req_dict[ 'result' ] imgdata = base64.b64decode(result) file = open (image_url, 'wb' ) file .write(imgdata) file .close() |
測試
1
2
3
4
5
6
7
8
9
|
def test(): image1 = r "f:\gxt.bmp" image2 = r "f:\msc.bmp" image = r "f:\meg.bmp" merge_face(image2,image1,image, 90 ) |
測試結果:
左圖:關某某
右圖:馬某某
中圖:merge
以上所述是小編給大家介紹的python換臉實例詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/feengg/article/details/88539685