更新时间:2024-10-17 GMT+08:00
分享

Python SDK

本章节介绍人脸识别服务Python SDK,您可以参考本章节进行快速集成开发。

准备工作

  • 注册华为账号并开通华为云,并完成实名认证,账号不能处于欠费或冻结状态。
  • 已开通人脸识别服务。如未开通,请登录人脸识别管理控制台人脸识别管理控制台开通所需服务。
  • 已具备开发环境,支持Python3及以上版本。
  • 登录“我的凭证 > 访问秘钥”页面,获取Access Key(AK)和Secret Access Key(SK)。
    图1 获取AK、SK
  • 登录“我的凭证”页面,获取“IAM用户名”“账号名”以及待使用区域的“项目ID”。调用服务时会用到这些信息,请提前保存。

    本样例以“华北-北京四”区域为例,获取对应的项目ID(project_id)。

    图2 我的凭证

安装SDK

支持Python3及以上版本,执行python --version检查当前Python的版本信息。

使用SDK前,需要安装“huaweicloudsdkcore”和“huaweicloudsdkfrs”。

# 安装核心库
pip install huaweicloudsdkcore
# 安装FRS服务库
pip install huaweicloudsdkfrs

开始使用

在开始使用之前,请确保您安装的是最新版本的SDK。使用过时的版本可能会导致兼容性问题或无法使用最新功能。您可以通过运行以下命令来检查并更新SDK至最新版本。

pip show huaweicloudsdkcore
pip show huaweicloudsdkfrs
pip install --upgrade huaweicloudsdkcore
pip install --upgrade huaweicloudsdkfrs

详细的SDK介绍,使用异步客户端,配置日志等操作请参见SDK中心Python SDK使用指导Python SDK使用视频

  1. 导入依赖模块
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkcore.exceptions import exceptions
    
    # 导入v2版本sdk
    from huaweicloudsdkfrs.v2.region.frs_region import FrsRegion
    from huaweicloudsdkfrs.v2 import *
    
    import os
  2. 配置认证信息
    配置AK、SK信息。华为云通过AK识别用户的身份,通过SK对请求数据进行签名验证,用于确保请求的机密性、完整性和请求者身份的正确性。AK、SK获取方法请参见准备工作
    def GetCredential(ak, sk):
        return BasicCredentials(ak, sk)

    初始化认证信息:

    ak = os.environ.get("HUAWEICLOUD_SDK_AK")
    sk = os.environ.get("HUAWEICLOUD_SDK_SK")
    credentials = GetCredential(ak, sk)
    • 认证用的 ak 和sk 硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全。
    • 本示例以 ak 和 sk 保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。
    图3 Windows环境新建环境变量
  3. 初始化客户端
    指定region方式
    # 初始化人脸识别服务的客户端,并选择服务部署区域
    def GetClient():
        client =  FrsClient.new_builder(FrsClient) \
             .with_credentials(credentials) \
             .with_region(FrsRegion.value_of("cn-north-4")) \
             .build()
        return client

    服务部署区域请参见终端节点

  4. 发送请求并查看响应
    # 以调用人脸检测 DetectFaceByBase64 接口为例
    request = DetectFaceByBase64Request()
    request.body = FaceDetectBase64Req(
        image_base64="/9j/4AAQSkZJRgABAQAAAQABAAD..."
    )
    response = client.detect_face_by_base64(request)
    print(response)

    使用人脸比对SDK时,image1、image2参数需为相同类型,即同为url、base64或file。

  5. 异常处理
    表1 异常处理

    一级分类

    一级分类说明

    二级分类

    二级分类说明

    ConnectionException

    连接类异常

    HostUnreachableException

    网络不可达、被拒绝。

    SslHandShakeException

    SSL认证异常。

    RequestTimeoutException

    响应超时异常

    CallTimeoutException

    单次请求,服务器处理超时未返回。

    RetryOutageException

    在重试策略消耗完成后,仍无有效的响应。

    ServiceResponseException

    服务器响应异常

    ServerResponseException

    服务端内部错误,Http响应码:[500,]。

    ClientRequestException

    请求参数不合法,Http响应码:[400, 500)

    // 捕获和处理不同类型的异常
    try:
        request = DetectFaceByBase64Request()
        request.body = FaceDetectBase64Req(
            image_base64="/9j/4AAQSkZJRgABAQAAAQABAAD..."
        )
        response = client.detect_face_by_base64(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

SDK代码解析

  • 人脸检测
    # detect face by base64
    def detectFaceByBase64():
        try:
            request = DetectFaceByBase64Request()
            request.body = FaceDetectBase64Req(
                image_base64="/9j/4AAQSkZJRgABAQAAAQABAAD...",
                attributes="2,4"
            )
            response = client.detect_face_by_base64(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
    # detect face by file
    def detectFaceByFile():
        try:
            request = DetectFaceByFileRequest()
            with open("/root/picture.jpg", "rb") as f:
                request.body = DetectFaceByFileRequestBody(image_file=FormFile(f))
                response = client.detect_face_by_file(request)
                print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 人脸比对
    # compare face by base64
    def compareFaceByBase64():
        try:
            request = CompareFaceByBase64Request()
            request.body = FaceCompareBase64Req(
                image1_base64="/9j/4AAQSkZJRgABAQAAAQABAAD...",
                image2_base64="/9j/4AAQSkZJRgABAQAAAQABAAD..."
            )
            response = client.compare_face_by_base64(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
    # compare face by file
    def compareFaceByFile():
        try:
            request = CompareFaceByFileRequest()
            with open("/root/picture1.jpg", "rb") as f1:
                with open("/root/picture2.jpg", "rb") as f2:
                    request.body = CompareFaceByFileRequestBody(image1_file=FormFile(f1),
                                                                image2_file=FormFile(f2))
                    response = client.compare_face_by_file(request)
                    print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • 人脸搜索
    # search face by base64
    def searchFaceByBase64():
        try:
            request = SearchFaceByBase64Request()
            request.face_set_name = "face_set_name"
            listFaceSearchBase64ReqReturnFieldsbody = [
                "timestamp"
            ]
            request.body = FaceSearchBase64Req(
                return_fields=listFaceSearchBase64ReqReturnFieldsbody,
                image_base64="/9j/4AAQSkZJRgABAQAAAQABAAD..."
            )
            response = client.search_face_by_base64(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
    # search face by file
    def searchFaceByFile():
        try:
            request = SearchFaceByFileRequest()
            request.face_set_name = "face_set_name"
            with open("/root/picture.jpg", "rb") as f:
                    request.body = SearchFaceByFileRequestBody(
                    return_fields="[\"timestamp\"]",
                    filter="timestamp:10",
                    top_n=10,
                    image_file=FormFile(f)
                )
                response = client.search_face_by_file(request)
                print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • 创建人脸库
    def createFaceSet():
        try:
            request = CreateFaceSetRequest()
            request.body = CreateFaceSetReq(
                face_set_name="face_set_name",
                external_fields={"timestamp": {"type": "long"}}
            )
            response = client.create_face_set(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 查询人脸库
    def showFaceSet():
        try:
            request = ShowFaceSetRequest()
            request.face_set_name = "face_set_name"
            response = client.show_face_set(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 查询所有人脸库
    def showAllFaceSet():
        try:
            request = ShowAllFaceSetsRequest()
            response = client.show_all_face_sets(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 删除人脸库
    def deleteFaceSet():
        try:
            request = DeleteFaceSetRequest()
            request.face_set_name = "face_set_name"
            response = client.delete_face_set(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 添加人脸
    # add face by base64
    def addFacesByBase64():
        try:
            request = AddFacesByBase64Request()
            request.face_set_name = "face_set_name"
            request.body = AddFacesBase64Req(
                external_fields="{\"timestamp\":12}",
                image_base64="/9j/4AAQSkZJRgABAQAAAQABAAD..."
            )
            response = client.add_faces_by_base64(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
    # add face by file
    def addFacesByFile():
        try:
            request = AddFacesByFileRequest()
            request.face_set_name = "face_set_name"
            with open("/root/picture.jpg", "rb") as f:
                request.body = AddFacesByFileRequestBody(
                    external_fields="{\"timestamp\":12}",
                    image_file=FormFile(f)
                )
                response = client.add_faces_by_file(request)
                print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 删除人脸
    def deleteFace():
        # Delete Face By FaceId
        try:
            request = DeleteFaceByFaceIdRequest()
            request.face_set_name = "face_set_name"
            request.face_id = "LkPJblq6"
            response = client.delete_face_by_face_id(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
        # Delete Face By ExternalImageId
        try:
            request = DeleteFaceByExternalImageIdRequest()
            request.face_set_name = "face_set_name"
            request.external_image_id = "external_image_id"
            response = client.delete_face_by_external_image_id(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 批量删除人脸
    def batchDeleteFaces():
        try:
            request = BatchDeleteFacesRequest()
            request.face_set_name = "face_set_name"
            request.body = DeleteFacesBatchReq(
                filter="age:[20 TO 30]"
            )
            response = client.batch_delete_faces(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 更新人脸
    def updateFace():
        try:
            request = UpdateFaceRequest()
            request.face_set_name = "face_set_name"
            request.body = UpdateFaceReq(face_id="LkPJblq6")
            response = client.update_face(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 查询人脸
    def showFaces():
        # Show Faces By FaceId
        try:
            request = ShowFacesByFaceIdRequest()
            request.face_set_name = "face_set_name"
            request.face_id = "LkPJblq6"
            response = client.show_faces_by_face_id(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
        # Show Faces By Limit
        try:
            request = ShowFacesByLimitRequest()
            request.face_set_name = "face_set_name"
            request.offset = 0
            request.limit = 10
            response = client.show_faces_by_limit(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 动作活体检测
    # detect live by base64
    def detectLiveByBase64():
        try:
            request = DetectLiveByBase64Request()
            request.body = LiveDetectBase64Req(
                actions="1,2,3,4",
                video_base64="/9j/4AAQSkZJRgABAQAAAQABAAD..."
            )
            response = client.detect_live_by_base64(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
    # detect live by file
    def detectLiveByFile():
        try:
            request = DetectLiveByFileRequest()
            with open("/root/video.mp4", "rb") as f:
                request.body = DetectLiveByFileRequestBody(
                    video_file=FormFile(f),
                    actions="1,2,3,4"
                )
                response = client.detect_live_by_file(request)
                print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
  • 静默活体检测
    # detect live face by base64
    def detectLiveFaceByBase64():
        try:
            request = DetectLiveFaceByBase64Request()
            request.body = LiveDetectFaceBase64Req(
                image_base64="/9j/4AAQSkZJRgABAQAAAQABAAD..."
            )
            response = client.detect_live_face_by_base64(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
    # detect live face by file
    def detectLiveFaceByFile():
        try:
            request = DetectLiveFaceByFileRequest()
            with open("/root/picture.jpg", "rb") as f:
                request.body = DetectLiveFaceByFileRequestBody(
                    image_file=FormFile(f)
                )
                response = client.detect_live_face_by_file(request)
                print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)

SDK代码自动生成

API Explorer提供API检索及平台调试,支持全量快速检索、可视化调试、帮助文档查看和在线咨询。

您只需要在API Explorer中修改接口参数,即可自动生成对应的代码示例。同时,可在集成开发环境CloudIDE中完成代码的构建、调试和运行等操作。

图4 API Explorer

相关文档