Azure認知服務:Face API

Face API是Azure認知服務之一,Face API有兩個主要功能:
-
人臉檢測
Face API可在圖像中以高精度人臉位置檢測多達64個人臉。圖像可以通過文件以字節或有效的URL指定。面部檢測提取一系列與面部相關的屬性,例如姿勢,性別,年齡,頭部姿勢,面部毛發和眼鏡。
-
人臉識別
人臉識別廣泛用於許多場景,包括安全性,自然用戶界面,圖像內容分析和管理,移動應用程序和機器人。Face API提供了四種人臉識別功能:人臉驗證,查找相似的人臉,臉部分組和人物識別。
申請密鑰
Azure Face API的國際站訪問地址,點擊試用按鈕,進入申請界面能夠獲取到API地址和密鑰。

以下是中國站訪問地址,登錄門戶網站創建認知服務訂閱,同樣也能獲取到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);
}
}
}
效果展示

示例項目
示例項目是一個Windows客戶端的應用,Face API的每個功能進行了展示,如果一開始不想編寫代碼,可以使用這個項目進行體驗。效果如下:



可以看到,不論是單人還是多人,不論是檢測還是識別,Azure Face API都給出了極好的結果。運用好它,可以實現豐富的應用,你也來試試吧!
Face API文檔:https://docs.microsoft.com/zh-cn/azure/cognitive-services/Face/overview
