给照片换了脸。大家应该都看过了。在本文中,我们将介绍如何通过Python实现换脸。功能实现换脸功能的实现,我们大致分为两种:一种是所有功能都是自己编码实现的,另一种是借助于第三方API实现的。第一种方法可能需要我们做很多编码才能实现,而第二种方法只需要少量的编码就可以实现。在本文中,我们使用更简单的第二种方法来实现。我们使用的API接口提供者是Face++。首先,我们需要在网站上注册一个账号。注册地址为:https://console.faceplusplus.com。cn/register,打开后如下图:我们可以通过手机号和邮箱进行注册。注册好账号后,我们在登录地址https://console.faceplusplus.com.cn/login登录,登录之后,我们会发现网站已经为我们创建了一个应用,如下图:我们需要用到的就是上图中APIKey和APISecret的值,我们来看看具体的实现代码:#获取人脸key点deffind_face(imgpath):print("Lookingfor...")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']#打印(矩形)returnrectangle#对于换脸,图片大小不能超过2M,数字表示换脸的相似度defmerge_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":"Ownapi_key","api_secret":"Ownapi_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')req_dict=json.JSONDecoder().decode(req_con1)结果=req_dict['结果']imgdata=base64.b64decode(结果)file=open(image_url,'wb')file.write(imgdata)file.close()效果展示示例一首先我们用两位男明星的照片来展示效果。原图如下:换脸后的效果图如下:例2接下来,我们再用两位女明星的图片来展示效果。原图如下:换脸后效果图如下:源码可在公众号Python小二后台回复200427获取
