当前位置:首页 > 行业动态 > 正文

Python腾讯云接口对接攻略:实现人脸识别功能

准备工作

1、注册腾讯云账号并登录

Python腾讯云接口对接攻略:实现人脸识别功能  第1张

2、开通人脸识别服务

3、获取API密钥(包括SecretId和SecretKey)

安装SDK

1、安装腾讯云Python SDK

pip install tencentcloudsdkpython

实现人脸识别功能

1、导入所需库

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.ai.v20180321 import ai_client, models
from tencentcloud.ai.v20180321 import AIErrorCode
import base64

2、设置认证信息

cred = credential.Credential("SecretId", "SecretKey")
http_profile = HttpProfile()
http_profile.endpoint = "ai.tencentcloudapi.com"
client_profile = ClientProfile()
client_profile.httpProfile = http_profile
client = ai_client.AiClient(cred, "apguangzhou", client_profile)

3、定义人脸识别函数

def face_recognition(image_path):
    with open(image_path, 'rb') as f:
        img_base64 = base64.b64encode(f.read())
    req = models.DetectFaceRequest()
    params = models.DetectFaceRequest.Params()
    params.ImageBase64 = img_base64
    req.Params = params
    try:
        resp = client.DetectFace(req)
        print(resp.to_json_string(indent=2))
    except AIErrorCode.AIErrorException as e:
        print(e.error_code)
        print(e.message)

4、调用人脸识别函数

if __name__ == '__main__':
    image_path = "test.jpg"  # 替换为实际图片路径
    face_recognition(image_path)

运行上述代码,即可实现人脸识别功能。

0