python实现一键换脸+源码+教程

水深无声 2023-10-07 13:49 43阅读 0赞

开篇,先看一下效果图,如果觉得效果不够,那就看本文末尾的效果图:在这里插入图片描述

源代码

  1. ## author:VX公众号[python小二]
  2. import requests, simplejson, json, base64
  3. # 获取人脸关键点
  4. def find_face(imgpath):
  5. print("正在查找……")
  6. http_url = "https://api-cn.faceplusplus.com/facepp/v3/detect"
  7. data = {
  8. "api_key": "你的api_key", ##替换掉‘你的api_key’,不要删除双引号,下面同理
  9. "api_secret": "你的api_secret",##替换掉‘你的api_secret
  10. "image_url": imgpath, "return_landmark":1}
  11. files = {
  12. "image_file": open(imgpath, "rb")}
  13. response = requests.post(http_url, data=data, files=files)
  14. req_con = response.content.decode('utf-8')
  15. req_dict = json.JSONDecoder().decode(req_con)
  16. this_json = simplejson.dumps(req_dict)
  17. this_json2 = simplejson.loads(this_json)
  18. #print(this_json2)
  19. faces = this_json2['faces']
  20. list0 = faces[0]
  21. rectangle = list0['face_rectangle']
  22. # print(rectangle)
  23. return rectangle
  24. # 换脸,图片的大小应不超过 2M,number 表示换脸的相似度
  25. def merge_face(image_url1, image_url2, image_url, number):
  26. ff1 = find_face(image_url1)
  27. ff2 = find_face(image_url2)
  28. rectangle1 = str(str(ff1['top']) + "," + str(ff1['left']) + "," + str(ff1['width']) + "," + str(ff1['height']))
  29. rectangle2 = str(ff2['top']) + "," + str(ff2['left']) + "," + str(ff2['width']) + "," + str(ff2['height'])
  30. print(rectangle2)
  31. url_add = "https://api-cn.faceplusplus.com/imagepp/v1/mergeface"
  32. f1 = open(image_url1, 'rb')
  33. f1_64 = base64.b64encode(f1.read())
  34. f1.close()
  35. f2 = open(image_url2, 'rb')
  36. f2_64 = base64.b64encode(f2.read())
  37. f2.close()
  38. data = {
  39. "api_key": "你的api_key", ##替换掉‘你的api_key’
  40. "api_secret": "你的api_secret",##替换掉‘你的api_secret
  41. "template_base64": f1_64, "template_rectangle": rectangle1,
  42. "merge_base64": f2_64, "merge_rectangle": rectangle2, "merge_rate": number}
  43. response = requests.post(url_add, data=data)
  44. req_con1 = response.content.decode('utf-8')
  45. req_dict = json.JSONDecoder().decode(req_con1)
  46. result = req_dict['result']
  47. imgdata = base64.b64decode(result)
  48. file = open(image_url, 'wb')
  49. file.write(imgdata)
  50. file.close()
  51. image1 = r"原始图片1.jpg" ##原始照片1的路径,若为/.png格式则将‘jpg’改为‘png’,下面同理
  52. image2 = r"原始图片2.jpg" ##原始照片2的路径;→将照片1 的五官加在照片2上;
  53. image = r"新生成图片3.jpg" ##生成的新照片
  54. merge_face(image2, image1, image, 90)

教程
在源代码中,需要添加自己的api_keyapi_secret信息;
1.访问网址-注册信息-获取api_keyapi_secret信息;
2.将api_keyapi_secret信息复制,添加到源代码中;
3.自行寻找两张人物图片后,更改源代码中图片名,运行代码即可!

首先访问网址并注册个人信息:https://console.faceplusplus.com.cn/register
在这里插入图片描述
注册个人信息后登陆进入网站,在菜单栏中选择“API_Key”再在页面中选择“查看”:
在这里插入图片描述
复制api_keyapi_secret信息:
在这里插入图片描述
将复制的信息,在源代码中进行替换:
在这里插入图片描述
下载两张人物图片,并在源代码中添加图片名称:
在这里插入图片描述
最后,运行:
在这里插入图片描述
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,43人围观)

还没有评论,来说两句吧...

相关阅读