当前位置:   article > 正文

python调用API轻松实现AI 换脸_换脸api

换脸api
  1. # AI换脸
  2. # AndyChe
  3. import requests
  4. import json
  5. import simplejson
  6. import base64
  7. # 第一步:获取人脸关键点
  8. def find_face(imgpath):
  9. """
  10. :param imgpath: 图片的地址
  11. :return: 一个字典类型的人脸关键点 如:{'top': 156, 'left': 108, 'width': 184, 'height': 184}
  12. """
  13. http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect' # 获取人脸信息的接口
  14. data = {
  15. "api_key": "x2NyKaa6vYuArYwat4x0-NpIbM9CrwGU", # 访问url所需要的参数
  16. "api_secret": "OuHx-Xaey1QrORwdG7QetGG5JhOIC8g7", # 访问url所需要的参数
  17. "image_url": imgpath, # 图片地址
  18. "return_landmark": 1
  19. }
  20. files = {'image_file': open(imgpath, 'rb')} # 定义一个字典存放图片的地址
  21. response = requests.post(http_url, data=data, files=files)
  22. res_con1 = response.content.decode('utf-8')
  23. res_json = simplejson.loads(res_con1)
  24. faces = res_json['faces']
  25. list = faces[0]
  26. rectangle = list['face_rectangle']
  27. return rectangle
  28. # 第二步:实现换脸
  29. def merge_face(image_url1, image_url2, image_url, number):
  30. """
  31. :param image_url1: 被换脸的图片路径
  32. :param image_url2: 换脸的图片路径
  33. :param image_url: 换脸后生成图片所保存的路径
  34. :param number: 换脸的相似度
  35. """
  36. # 首先获取两张图片的人脸关键点
  37. face1 = find_face(image_url1)
  38. face2 = find_face(image_url2)
  39. # 将人脸转换为字符串的格式
  40. rectangle1 = str(
  41. str(face1['top']) + "," + str(face1['left']) + "," + str(face1['width']) + "," + str(face1['height']))
  42. rectangle2 = str(
  43. str(face2['top']) + "," + str(face2['left']) + "," + str(face2['width']) + "," + str(face2['height']))
  44. # 读取两张图片
  45. f1 = open(image_url1, 'rb')
  46. f1_64 = base64.b64encode(f1.read())
  47. f1.close()
  48. f2 = open(image_url2, 'rb')
  49. f2_64 = base64.b64encode(f2.read())
  50. f2.close()
  51. url_add = 'https://api-cn.faceplusplus.com/imagepp/v1/mergeface' # 实现换脸的接口
  52. data = {
  53. "api_key": "x2NyKaa6vYuArYwat4x0-NpIbM9CrwGU",
  54. "api_secret": "OuHx-Xaey1QrORwdG7QetGG5JhOIC8g7",
  55. "template_base64": f1_64,
  56. "template_rectangle": rectangle1,
  57. "merge_base64": f2_64,
  58. "merge_rectangle": rectangle2,
  59. "merge_rate": number
  60. }
  61. response1 = requests.post(url_add, data=data)
  62. res_con1 = response1.content.decode('utf-8')
  63. res_dict = json.JSONDecoder().decode(res_con1)
  64. result = res_dict['result']
  65. imgdata = base64.b64decode(result)
  66. file = open(image_url, 'wb')
  67. file.write(imgdata)
  68. file.close()
  69. if __name__ == '__main__':
  70. # 别人的图
  71. image1 = r"E:\test\12.jpg"
  72. # 自己的图
  73. image2 = r"E:\test\2.jpg"
  74. # 结果图
  75. image3 = r"E:\test\result.jpg"
  76. merge_face(image1, image2, image3, 100)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/123627
推荐阅读
相关标签
  

闽ICP备14008679号