跳转到主要内容

Microsoft Azure Ai Vision Face Python客户端库

项目描述

Azure AI Face Python客户端库

Azure AI Face服务提供AI算法,用于检测、识别和分析图像中的人脸。它包括以下主要功能

  • 人脸检测和分析
  • 活体检测
  • 人脸识别
    • 人脸验证("一对一"匹配)
  • 查找相似人脸
  • 分组人脸

源代码 | 包(PyPI) | API参考文档 | 产品文档 | 示例

入门指南

先决条件

  • 使用此包需要Python 3.8或更高版本。
  • 您需要Azure订阅才能使用此包。
  • 您的Azure账户必须分配有Cognitive Services Contributor角色,以便您同意负责任AI条款并创建资源。要将此角色分配给您的账户,请遵循分配角色文档中的步骤,或联系您的管理员。
  • 一旦您有足够的权限控制您的Azure订阅,您需要

创建人脸或Azure AI服务多服务账户

Azure AI 人脸服务支持多服务和单服务访问。如果您计划在单个端点/密钥下访问多个Azure AI服务,请创建Azure AI服务多服务账户。仅为了人脸访问,请创建人脸资源。

安装包

python -m pip install azure-ai-vision-face

客户端认证

为了与Face服务交互,您需要创建客户端实例。创建客户端对象需要endpointcredential

客户端认证支持密钥凭证和Microsoft Entra ID凭证。出于安全考虑,我们强烈建议在生产环境中使用Microsoft Entra ID凭证进行认证,而AzureKeyCredential应仅用于测试环境。

获取端点

您可以使用Azure门户或Azure CLI找到Face资源的端点。

# Get the endpoint for the Face resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"

认证可以使用区域端点或自定义子域。它们的格式如下:

Regional endpoint: https://<region>.api.cognitive.microsoft.com/
Custom subdomain: https://<resource-name>.cognitiveservices.azure.com/

区域端点在每个区域内的资源中是相同的。支持的完整区域端点列表可以在此处查阅。请注意,区域端点不支持Microsoft Entra ID认证。如果您想将资源迁移到使用自定义子域,请遵循此处的说明。

另一方面,自定义子域是唯一的资源名称。一旦创建并关联到资源,就不能再修改。

使用Microsoft Entra ID凭证创建客户端

本入门指南中的示例使用AzureKeyCredential进行认证,但您也可以使用azure-identity库使用Microsoft Entra ID进行认证。请注意,区域端点不支持Microsoft Entra ID认证。为了使用此类型的认证,您需要在资源中创建一个自定义子域名称。

要使用下面所示的DefaultAzureCredential类型或Azure SDK提供的其他凭证类型,请安装azure-identity包。

pip install azure-identity

您还需要注册一个新的Microsoft Entra ID应用程序并授予Face访问权限,通过将"Cognitive Services User"角色分配给您的服务主体来实现。

完成操作后,将Microsoft Entra ID应用程序的客户端ID、租户ID和客户端密钥的值设置为环境变量:AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_CLIENT_SECRET

"""DefaultAzureCredential will use the values from these environment
variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
"""
from azure.ai.vision.face import FaceClient
from azure.identity import DefaultAzureCredential

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = DefaultAzureCredential()

face_client = FaceClient(endpoint, credential)

使用AzureKeyCredential创建客户端

要将API密钥作为credential参数,请将密钥作为字符串传递到AzureKeyCredential实例中。您可以使用Azure门户或Azure CLI获取Face资源的API密钥。

# Get the API keys for the Face resource
az cognitiveservices account keys list --name "<resource-name>" --resource-group "<resource-group-name>"
from azure.core.credentials import AzureKeyCredential
from azure.ai.vision.face import FaceClient

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")
face_client = FaceClient(endpoint, credential)

关键概念

FaceClient

FaceClient提供以下操作:

  • 人脸检测与分析:在图像中检测人类人脸并返回其位置的长方形坐标,可选地标和与人脸相关的属性。此操作是所有其他人脸识别场景的第一步。
  • 人脸识别:根据用户的脸数据与目标脸的匹配程度,确认用户声称的身份。它包括人脸验证(“一对一”匹配)。
  • 从看起来与目标人脸相似的小集合中找到相似的人脸。
  • 根据相似度将人脸分组到几个较小的组中。

FaceSessionClient

FaceSessionClient提供用于与用于活体检测的会话交互的功能。

  • 创建、查询和删除会话。
  • 查询活体检测和验证结果。
  • 查询审计结果。

示例

以下部分提供了几个代码片段,涵盖了最常见的面部任务,包括

人脸检测

从二进制数据中检测和分析人脸。最新模型是最准确且推荐的。有关不同版本的检测和识别模型之间的详细差异,请参阅以下链接。

from azure.core.credentials import AzureKeyCredential
from azure.ai.vision.face import FaceClient
from azure.ai.vision.face.models import (
    FaceDetectionModel,
    FaceRecognitionModel,
    FaceAttributeTypeDetection03,
    FaceAttributeTypeRecognition04,
)

endpoint = "<your endpoint>"
key = "<your api key>"

with FaceClient(endpoint=endpoint, credential=AzureKeyCredential(key)) as face_client:
    sample_file_path = "<your image file>"
    with open(sample_file_path, "rb") as fd:
        file_content = fd.read()

    result = face_client.detect(
        file_content,
        detection_model=FaceDetectionModel.DETECTION_03,  # The latest detection model.
        recognition_model=FaceRecognitionModel.RECOGNITION_04,  # The latest recognition model.
        return_face_id=True,
        return_face_attributes=[
            FaceAttributeTypeDetection03.HEAD_POSE,
            FaceAttributeTypeDetection03.MASK,
            FaceAttributeTypeRecognition04.QUALITY_FOR_RECOGNITION,
        ],
        return_face_landmarks=True,
        return_recognition_model=True,
        face_id_time_to_live=120,
    )

    print(f"Detect faces from the file: {sample_file_path}")
    for idx, face in enumerate(result):
        print(f"----- Detection result: #{idx+1} -----")
        print(f"Face: {face.as_dict()}")

活体检测

人脸活体检测可用于确定输入视频流中的人脸是真实的(活体)还是虚假的(伪造)。活体检测的目标是确保在身份验证时系统与一个实际存在的活人互动。整个身份验证过程称为会话。

认证有两个不同的组件:前端应用程序和应用程序服务器/编排器。在上传视频流之前,应用程序服务器必须创建一个会话,然后前端客户端可以上传带有会话授权令牌的有效负载以调用活体检测。应用程序服务器可以在会话被删除之前随时查询活体检测结果和审计日志。

活体检测操作不仅可以确认输入是活体还是伪造,还可以验证输入是否属于预期人员的脸,这称为带有人脸验证的活体检测。有关详细信息,请参阅教程

此包仅负责应用程序服务器创建、查询、删除会话以及获取审计日志。有关如何将UI和代码集成到您的原生前端应用程序中,请参阅教程

以下是一个创建会话并获取活体检测结果的示例。

import uuid

from azure.core.credentials import AzureKeyCredential
from azure.ai.vision.face import FaceSessionClient
from azure.ai.vision.face.models import CreateLivenessSessionContent, LivenessOperationMode

endpoint = "<your endpoint>"
key = "<your api key>"

with FaceSessionClient(endpoint=endpoint, credential=AzureKeyCredential(key)) as face_session_client:
    # Create a session.
    print("Create a new liveness session.")
    created_session = face_session_client.create_liveness_session(
        CreateLivenessSessionContent(
            liveness_operation_mode=LivenessOperationMode.PASSIVE,
            device_correlation_id=str(uuid.uuid4()),
            send_results_to_client=False,
            auth_token_time_to_live_in_seconds=60,
        )
    )
    print(f"Result: {created_session}")

    # Get the liveness detection result.
    print("Get the liveness detection result.")
    liveness_result = face_session_client.get_liveness_session_result(created_session.session_id)
    print(f"Result: {liveness_result}")

以下是一个带有人脸验证的活体检测的示例。

import uuid

from azure.core.credentials import AzureKeyCredential
from azure.ai.vision.face import FaceSessionClient
from azure.ai.vision.face.models import CreateLivenessSessionContent, LivenessOperationMode

endpoint = "<your endpoint>"
key = "<your api key>"

with FaceSessionClient(endpoint=endpoint, credential=AzureKeyCredential(key)) as face_session_client:
    sample_file_path = "<your verify image file>"
    with open(sample_file_path, "rb") as fd:
        file_content = fd.read()

    # Create a session.
    print("Create a new liveness with verify session with verify image.")

    created_session = face_session_client.create_liveness_with_verify_session(
        CreateLivenessSessionContent(
            liveness_operation_mode=LivenessOperationMode.PASSIVE,
            device_correlation_id=str(uuid.uuid4()),
            send_results_to_client=False,
            auth_token_time_to_live_in_seconds=60,
        ),
        verify_image=file_content,
    )
    print(f"Result: {created_session}")

    # Get the liveness detection and verification result.
    print("Get the liveness detection and verification result.")
    liveness_result = face_session_client.get_liveness_with_verify_session_result(created_session.session_id)
    print(f"Result: {liveness_result}")

故障排除

常规

人脸客户端库将抛出在Azure Core中定义的异常。人脸服务引发的错误代码和消息可以在服务文档中找到。

日志记录

此库使用标准的logging库进行日志记录。

HTTP会话的基本信息(URL、头等)在INFO级别进行记录。

详细的DEBUG级别日志记录,包括请求/响应体和未修改的头,可以通过使用logging_enable关键字参数在客户端或每个操作中进行启用。

有关示例,请参阅完整的SDK日志记录文档此处

import sys
import logging

from azure.ai.vision.face import FaceClient
from azure.core.credentials import AzureKeyCredential

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    stream=sys.stdout)

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")
face_client = FaceClient(endpoint, credential)

face.detect(..., logging_enable=True)

可选配置

可以在客户端和每个操作级别传递可选关键字参数。azure-core 参考文档描述了重试、日志记录、传输协议等可用的配置。

下一步操作

更多示例代码

请参阅示例README,其中包含了一些展示Face Python API常用模式的代码片段。

其他文档

有关Azure AI Face的更详细文档,请参阅learn.microsoft.com上的Face文档

贡献

本项目欢迎贡献和建议。大多数贡献都需要您同意贡献者许可协议(CLA),声明您有权并且实际上确实授予我们使用您贡献的权利。有关详细信息,请访问https://cla.microsoft.com

当您提交拉取请求时,CLA机器人将自动判断您是否需要提供CLA,并适当装饰PR(例如,标签、注释)。只需遵循机器人提供的说明。您只需在整个使用我们的CLA的仓库中这样做一次。

本项目采用了Microsoft开源行为准则。有关更多信息,请参阅行为准则FAQ或联系opencode@microsoft.com以提出任何额外的问题或评论。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解安装包的更多信息。

源分发

azure-ai-vision-face-1.0.0b1.tar.gz (116.1 kB 查看哈希值)

上传时间

构建分发

azure_ai_vision_face-1.0.0b1-py3-none-any.whl (108.2 kB 查看哈希值)

上传时间 Python 3

支持者:

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面