65行python代码实现换脸

素颜马尾好姑娘i 2024-04-18 18:02 165阅读 0赞

下面来介绍一种对照片的简单换脸方法。

本文仅供学习,请勿用于侵权行为。

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

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

在这里插入图片描述

  1. import requests
  2. import simplejson
  3. import json
  4. import base64
  5. #Face++网址:[url]https://console.faceplusplus.com.cn/dashboard[/url]
  6. #第一步,获取人脸关键点
  7. def find_face(imgpath):
  8. print("正在查找……")
  9. http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
  10. data = {"api_key": '自己申请',
  11. "api_secret": '自己申请TLJC',
  12. "image_url": imgpath, "return_landmark": 1}
  13. files = {"image_file": open(imgpath, "rb")}
  14. response = requests.post(http_url, data=data, files=files)
  15. req_con = response.content.decode('utf-8')
  16. req_dict = json.JSONDecoder().decode(req_con)
  17. this_json = simplejson.dumps(req_dict)
  18. this_json2 = simplejson.loads(this_json)
  19. print(this_json2)
  20. faces = this_json2['faces']
  21. list0 = faces[0]
  22. rectangle = list0['face_rectangle']
  23. #print(rectangle)
  24. return rectangle
  25. #第二步,换脸,其中图片的大小应不超过2M
  26. # number表示换脸的相似度
  27. def merge_face(image_url1, image_url2, image_url, number):
  28. ff1 = find_face(image_url1)
  29. ff2 = find_face(image_url2)
  30. rectangle1 = str(str(ff1['top']) + "," + str(ff1['left']) + "," + str(ff1['width']) + "," + str(ff1['height']))
  31. rectangle2 = str(ff2['top']) + "," + str(ff2['left']) + "," + str(ff2['width']) + "," + str(ff2['height'])
  32. print(rectangle2)
  33. url_add = "https://api-cn.faceplusplus.com/imagepp/v1/mergeface"
  34. f1 = open(image_url1, 'rb')
  35. f1_64 = base64.b64encode(f1.read())
  36. f1.close()
  37. f2 = open(image_url2, 'rb')
  38. f2_64 = base64.b64encode(f2.read())
  39. f2.close()
  40. data = {"api_key": '自己申请',
  41. "api_secret": '自己申请TLJC',
  42. "template_base64": f1_64, "template_rectangle": rectangle1,
  43. "merge_base64": f2_64, "merge_rectangle": rectangle2, "merge_rate": number}
  44. response = requests.post(url_add, data=data)
  45. req_con1 = response.content.decode('utf-8')
  46. #print(req_con1)
  47. req_dict = json.JSONDecoder().decode(req_con1)
  48. result = req_dict['result']
  49. imgdata = base64.b64decode(result)
  50. file = open(image_url, 'wb')
  51. file.write(imgdata)
  52. file.close()
  53. image1 = r"E:\test\img01.jpg"
  54. image2 = r"E:\test\img02.jpg"
  55. image = r"E:\test\imgh.jpg"
  56. merge_face(image2, image1, image, 90)

参考:https://www.52pojie.cn/thread-1016974-1-2.html

发表评论

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

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

相关阅读