温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么实现一个换脸功能

发布时间:2021-07-05 15:24:20 来源:亿速云 阅读:174 作者:Leah 栏目:大数据

这篇文章给大家介绍Python中怎么实现一个换脸功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。


功能实现

实现换脸功能,我们大致可以分为两种:一种是所有功能都通过自己编码来实现,另一种是借助于第三方 API 来实现,第一种方式可能需要我们进行大量的编码才能实现,而第二种方式我们只需进行少量的编码即可实现。

本文我们使用更简单的第二种方式来实现,我们用到的 API 接口提供方是 Face++,首先我们需要到该网站注册一个自己的账号,注册地址为:https://console.faceplusplus.com.cn/register,打开后如下所示:

Python中怎么实现一个换脸功能

我们可以通过手机号和邮箱两种方式来注册,注册好账号之后,我们再到登录地址 https://console.faceplusplus.com.cn/login 进行登录,登录之后,我们会发现网站已经为我们创建好了应用,如下图所示:

Python中怎么实现一个换脸功能

我们需要用到的是上图中的 API KeyAPI Secret 的值,下面来看一下具体实现代码:

# 获取人脸关键点
def find_face(imgpath):
    print("正在查找……")
    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']
    # 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_key",
            "api_secret": "自己的 api_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)
    result = req_dict['result']
    imgdata = base64.b64decode(result)
    file = open(image_url, 'wb')
    file.write(imgdata)
    file.close()


关于Python中怎么实现一个换脸功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI