利用人工智能合成换脸

前言

最近闲来无事逛逛博客,发现了一个特别好玩的东西,用AI 自动识别换脸!反正我感觉挺好玩的。

请看效果!

红红火火恍恍惚惚 :huaji:    帅不帅!美不美!

咳咳,跑题了,总的来说还不错。(图个好玩!)

使用方法

这个换脸的方法需要借助Face++,关于Face++的API,大家可自行查看说明文档,都比较简单。

文档地址:https://console.faceplusplus.com.cn/documents/20813963

首先你得下载一个python,不会下载的百度一下就行。

代码如下:

import requests
import simplejson
import json
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_secret": '自己申请TLJC',
"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_secret": '自己申请TLJC',
"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 = r"E:\test\img01.jpg"
image2 = r"E:\test\img02.jpg"
image = r"E:\test\imgh.jpg"

merge_face(image2, image1, image, 90)

另外说一下,我代码里标识的需要输入的api_key申请的TLJC是需要注册Face++登陆之后创建一个应用才能获取到的,一般都有自带一个应用,直接引用就行了。

可能存在的问题(针对新手刚安装的python)

如果你刚下载的python,运行结果出错,显示以下内容

原因:没有导入requests库

解决办法:

抱歉,只有登录并在本文发表评论才能阅读隐藏内容

可能出现的问题二(针对新手刚安装python)

上面的问题解决了,又有一种提示。

出现ImportError: No module named simplejson.scanner

如下图

原因:没有安装simplejson

解决方法:

抱歉,只有登录并在本文发表评论才能阅读隐藏内容

 

结尾

注意:文章仅用于技术参考,请勿用于非法用途,他人造成的任何任何法律责任与博主无关!

 

点赞
  1. 哈哈哈说道:
    WebView Android 9
    好好
  2. 君香君说道:
    Google Chrome Windows 10
    学习学习学习

君香君进行回复 取消回复

电子邮件地址不会被公开。必填项已用 * 标注