Azure认知服务之Face API上手体验

时间:2023-03-08 16:35:30

Azure认知服务:Face API

Azure认知服务之Face API上手体验

Face API是Azure认知服务之一,Face API有两个主要功能:

  • 人脸检测

    Face API可在图像中以高精度人脸位置检测多达64个人脸。图像可以通过文件以字节或有效的URL指定。面部检测提取一系列与面部相关的属性,例如姿势,性别,年龄,头部姿势,面部毛发和眼镜。

  • 人脸识别

    人脸识别广泛用于许多场景,包括安全性,自然用户界面,图像内容分析和管理,移动应用程序和机器人。Face API提供了四种人脸识别功能:人脸验证,查找相似的人脸,脸部分组和人物识别。

申请密钥


Azure Face API的国际站访问地址,点击试用按钮,进入申请界面能够获取到API地址和密钥。

Azure认知服务之Face API上手体验

以下是中国站访问地址,登录门户网站创建认知服务订阅,同样也能获取到API地址和密钥。

Azure认知服务之Face API上手体验

样本素材和示例项目


打开Github地址:https://github.com/Microsoft/Cognitive-Face-Windows,clone或者下载该项目,"/data"就是照片样本目录,其中"/Data/\PersonGroup"是一家人的照片目录,注意它的存放要求,每个人按身份命名还有独立的子目录。

代码片段


授权API调用

faceServiceClient = new FaceServiceClient("<Subscription Key>");

定义PersonGroup

// Create an empty PersonGroup
string personGroupId = "myfamily";
await faceServiceClient.CreatePersonGroupAsync(personGroupId, "My Family"); // Define Dad
CreatePersonResult dad = await faceServiceClient.CreatePersonAsync(
// Id of the PersonGroup that the person belonged to
personGroupId,
// Name of the person
"Dad"
); // Define Mom, Son and Daughter in the same way

检测人脸并将每一张脸进行注册

// Directory contains image files of Anna
const string DadImageDir = @"D:\Data\PersonGroup\Family1-Dad\"; foreach (string imagePath in Directory.GetFiles(DadImageDir, "*.jpg"))
{
using (Stream s = File.OpenRead(imagePath))
{
// Detect faces in the image and add to Dad
await faceServiceClient.AddPersonFaceAsync(
personGroupId, dad.PersonId, s);
}
}
// Define Mom, Son and Daughter in the same way

训练PersonGroup模型

await faceServiceClient.TrainPersonGroupAsync(personGroupId);
TrainingStatus trainingStatus = null;
while(true)
{
trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); if (trainingStatus.Status != Status.Running)
{
break;
} await Task.Delay(1000);
}

根据定义的PersonGroup识别每一张脸

string testImageFile = @"D:\Data\\identification1.jpg";

using (Stream s = File.OpenRead(testImageFile))
{
var faces = await faceServiceClient.DetectAsync(s);
var faceIds = faces.Select(face => face.FaceId).ToArray(); var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds);
foreach (var identifyResult in results)
{
Console.WriteLine("Result of face: {0}", identifyResult.FaceId);
if (identifyResult.Candidates.Length == 0)
{
Console.WriteLine("No one identified");
}
else
{
// Get top 1 among all candidates returned
var candidateId = identifyResult.Candidates[0].PersonId;
var person = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);
Console.WriteLine("Identified as {0}", person.Name);
}
}
}

效果展示

Azure认知服务之Face API上手体验

示例项目


示例项目是一个Windows客户端的应用,Face API的每个功能进行了展示,如果一开始不想编写代码,可以使用这个项目进行体验。效果如下:

Azure认知服务之Face API上手体验

Azure认知服务之Face API上手体验

Azure认知服务之Face API上手体验

可以看到,不论是单人还是多人,不论是检测还是识别,Azure Face API都给出了极好的结果。运用好它,可以实现丰富的应用,你也来试试吧!

Face API文档:https://docs.microsoft.com/zh-cn/azure/cognitive-services/Face/overview