クイック スタート: Face サービスを使用する
重要
Microsoft 製品またはサービスを使用して生体認証データを処理する場合は、お客様の責任において、次のことを行っていただく必要があります: (i) 保有期間や破棄に関するものを含め、データ主体に通知する、(ii) データ主体から同意を得る、(iii) 生体認証データを削除する (該当するデータ保護要件に基づき、必要に応じてすべて)。 ''生体認証データ'' は、GDPR の第 4 条に規定されている意味を持ち、該当する場合は、他のデータ保護要件における同義語となります。 関連情報については、「Face のデータとプライバシー」を参照してください。
注意事項
Microsoft の責任ある AI の原則をサポートするために、Face サービスの利用は、適格性と使用基準に基づいて制限されています。 Face サービスは、Microsoft が管理する顧客とパートナーのみが利用できます。 顔認識受付フォームを使用して利用申請を行ってください。 詳細については、「Face の制限付きアクセス」ページを参照してください。
.NET 用 Face クライアント ライブラリを使用して顔認識を開始します。 Azure AI Face サービスを使うと、画像内の人間の顔を検出して認識するための高度なアルゴリズムにアクセスできます。 以下の手順に従って、パッケージをインストールし、リモート画像を使用した基本的な顔識別のためのコード例を試してみましょう。
リファレンスのドキュメント | ライブラリのソース コード | パッケージ (NuGet) | サンプル
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- Visual Studio IDE または現在のバージョンの .NET Core。
- 責任ある AI のご契約条件に同意してリソースを作成するためには、Azure アカウントに
Cognitive Services Contributor
ロールが割り当てられている必要があります。 このロールをアカウントに割り当てるには、ロールの割り当てに関するドキュメントの手順に従うか、管理者にお問い合わせください。 - Azure サブスクリプションを入手したら、Azure portal で Face リソースを作成し、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
- 対象のアプリケーションを Face API に接続するには、作成したリソースのキーとエンドポイントが必要です。
- Free 価格レベル (
F0
) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。
環境変数を作成する
この例では、アプリケーションを実行しているローカル コンピューター上の環境変数に資格情報を書き込みます。
Azure portal に移動します。 「前提条件」 セクションで作成したリソースが正常にデプロイされた場合、[次の手順] の下にある [リソースに移動] を選択します。 キーとエンドポイントは、[キーとエンドポイント] ページの [リソース管理] にあります。 リソース キーは Azure サブスクリプション ID と同じではありません。
ヒント
キーは、コードに直接含めないようにし、公開しないでください。 Azure Key Vault などのその他の認証オプションについては、Azure AI サービスのセキュリティに関する記事を参照してください。
キーとエンドポイントの環境変数を設定するには、コンソール ウィンドウを開き、オペレーティング システムと開発環境の指示に従います。
VISION_KEY
環境変数を設定するには、your-key
をリソースのキーの 1 つに置き換えます。VISION_ENDPOINT
環境変数を設定するには、your-endpoint
をリソースのエンドポイントに置き換えます。
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint
実行中のプログラムのうち、環境変数の読み取りを必要とするプログラム (コンソール ウィンドウを含む) については、環境変数を読み込む再起動が必要となる場合があります。
顔を識別して検証する
新しい C# アプリケーションを作成する
Visual Studio を使用して、新しい .NET Core アプリケーションを作成します。
クライアント ライブラリをインストールする
新しいプロジェクトを作成したら、ソリューション エクスプローラーでプロジェクト ソリューションを右クリックし、 [NuGet パッケージの管理] を選択して、クライアント ライブラリをインストールします。 パッケージ マネージャーが開いたら、[参照] を選択し、[プレリリースを含める] をオンにして、
Microsoft.Azure.CognitiveServices.Vision.Face
を検索します。 最新バージョンを選択し、[インストール] を選択します。Program.cs ファイルに次のコードを追加します。
Note
取り込みフォームを使用して Face サービスへのアクセスを受け取っていない場合、これらの関数の一部は機能しません。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.CognitiveServices.Vision.Face; using Microsoft.Azure.CognitiveServices.Vision.Face.Models; namespace FaceQuickstart { class Program { static string personGroupId = Guid.NewGuid().ToString(); // URL path for the images. const string IMAGE_BASE_URL = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/"; // From your Face subscription in the Azure portal, get your subscription key and endpoint. const string SUBSCRIPTION_KEY = Environment.GetEnvironmentVariable("VISION_KEY"); const string ENDPOINT = Environment.GetEnvironmentVariable("VISION_ENDPOINT"); static void Main(string[] args) { // Recognition model 4 was released in 2021 February. // It is recommended since its accuracy is improved // on faces wearing masks compared with model 3, // and its overall accuracy is improved compared // with models 1 and 2. const string RECOGNITION_MODEL4 = RecognitionModel.Recognition04; // Authenticate. IFaceClient client = Authenticate(ENDPOINT, SUBSCRIPTION_KEY); // Identify - recognize a face(s) in a person group (a person group is created in this example). IdentifyInPersonGroup(client, IMAGE_BASE_URL, RECOGNITION_MODEL4).Wait(); Console.WriteLine("End of quickstart."); } /* * AUTHENTICATE * Uses subscription key and region to create a client. */ public static IFaceClient Authenticate(string endpoint, string key) { return new FaceClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint }; } // Detect faces from image url for recognition purposes. This is a helper method for other functions in this quickstart. // Parameter `returnFaceId` of `DetectWithUrlAsync` must be set to `true` (by default) for recognition purposes. // Parameter `FaceAttributes` is set to include the QualityForRecognition attribute. // Recognition model must be set to recognition_03 or recognition_04 as a result. // Result faces with insufficient quality for recognition are filtered out. // The field `faceId` in returned `DetectedFace`s will be used in Face - Face - Verify and Face - Identify. // It will expire 24 hours after the detection call. private static async Task<List<DetectedFace>> DetectFaceRecognize(IFaceClient faceClient, string url, string recognition_model) { // Detect faces from image URL. Since only recognizing, use the recognition model 1. // We use detection model 3 because we are not retrieving attributes. IList<DetectedFace> detectedFaces = await faceClient.Face.DetectWithUrlAsync(url, recognitionModel: recognition_model, detectionModel: DetectionModel.Detection03, returnFaceAttributes: new List<FaceAttributeType> { FaceAttributeType.QualityForRecognition }); List<DetectedFace> sufficientQualityFaces = new List<DetectedFace>(); foreach (DetectedFace detectedFace in detectedFaces){ var faceQualityForRecognition = detectedFace.FaceAttributes.QualityForRecognition; if (faceQualityForRecognition.HasValue && (faceQualityForRecognition.Value >= QualityForRecognition.Medium)){ sufficientQualityFaces.Add(detectedFace); } } Console.WriteLine($"{detectedFaces.Count} face(s) with {sufficientQualityFaces.Count} having sufficient quality for recognition detected from image `{Path.GetFileName(url)}`"); return sufficientQualityFaces.ToList(); } /* * IDENTIFY FACES * To identify faces, you need to create and define a person group. * The Identify operation takes one or several face IDs from DetectedFace or PersistedFace and a PersonGroup and returns * a list of Person objects that each face might belong to. Returned Person objects are wrapped as Candidate objects, * which have a prediction confidence value. */ public static async Task IdentifyInPersonGroup(IFaceClient client, string url, string recognitionModel) { Console.WriteLine("========IDENTIFY FACES========"); Console.WriteLine(); // Create a dictionary for all your images, grouping similar ones under the same key. Dictionary<string, string[]> personDictionary = new Dictionary<string, string[]> { { "Family1-Dad", new[] { "Family1-Dad1.jpg", "Family1-Dad2.jpg" } }, { "Family1-Mom", new[] { "Family1-Mom1.jpg", "Family1-Mom2.jpg" } }, { "Family1-Son", new[] { "Family1-Son1.jpg", "Family1-Son2.jpg" } }, { "Family1-Daughter", new[] { "Family1-Daughter1.jpg", "Family1-Daughter2.jpg" } }, { "Family2-Lady", new[] { "Family2-Lady1.jpg", "Family2-Lady2.jpg" } }, { "Family2-Man", new[] { "Family2-Man1.jpg", "Family2-Man2.jpg" } } }; // A group photo that includes some of the persons you seek to identify from your dictionary. string sourceImageFileName = "identification1.jpg"; // Create a person group. Console.WriteLine($"Create a person group ({personGroupId})."); await client.PersonGroup.CreateAsync(personGroupId, personGroupId, recognitionModel: recognitionModel); // The similar faces will be grouped into a single person group person. foreach (var groupedFace in personDictionary.Keys) { // Limit TPS await Task.Delay(250); Person person = await client.PersonGroupPerson.CreateAsync(personGroupId: personGroupId, name: groupedFace); Console.WriteLine($"Create a person group person '{groupedFace}'."); // Add face to the person group person. foreach (var similarImage in personDictionary[groupedFace]) { Console.WriteLine($"Check whether image is of sufficient quality for recognition"); IList<DetectedFace> detectedFaces1 = await client.Face.DetectWithUrlAsync($"{url}{similarImage}", recognitionModel: recognitionModel, detectionModel: DetectionModel.Detection03, returnFaceAttributes: new List<FaceAttributeType> { FaceAttributeType.QualityForRecognition }); bool sufficientQuality = true; foreach (var face1 in detectedFaces1) { var faceQualityForRecognition = face1.FaceAttributes.QualityForRecognition; // Only "high" quality images are recommended for person enrollment if (faceQualityForRecognition.HasValue && (faceQualityForRecognition.Value != QualityForRecognition.High)){ sufficientQuality = false; break; } } if (!sufficientQuality){ continue; } // add face to the person group Console.WriteLine($"Add face to the person group person({groupedFace}) from image `{similarImage}`"); PersistedFace face = await client.PersonGroupPerson.AddFaceFromUrlAsync(personGroupId, person.PersonId, $"{url}{similarImage}", similarImage); } } // Start to train the person group. Console.WriteLine(); Console.WriteLine($"Train person group {personGroupId}."); await client.PersonGroup.TrainAsync(personGroupId); // Wait until the training is completed. while (true) { await Task.Delay(1000); var trainingStatus = await client.PersonGroup.GetTrainingStatusAsync(personGroupId); Console.WriteLine($"Training status: {trainingStatus.Status}."); if (trainingStatus.Status == TrainingStatusType.Succeeded) { break; } } Console.WriteLine(); List<Guid> sourceFaceIds = new List<Guid>(); // Detect faces from source image url. List<DetectedFace> detectedFaces = await DetectFaceRecognize(client, $"{url}{sourceImageFileName}", recognitionModel); // Add detected faceId to sourceFaceIds. foreach (var detectedFace in detectedFaces) { sourceFaceIds.Add(detectedFace.FaceId.Value); } // Identify the faces in a person group. var identifyResults = await client.Face.IdentifyAsync(sourceFaceIds, personGroupId); foreach (var identifyResult in identifyResults) { if (identifyResult.Candidates.Count==0) { Console.WriteLine($"No person is identified for the face in: {sourceImageFileName} - {identifyResult.FaceId},"); continue; } Person person = await client.PersonGroupPerson.GetAsync(personGroupId, identifyResult.Candidates[0].PersonId); Console.WriteLine($"Person '{person.Name}' is identified for the face in: {sourceImageFileName} - {identifyResult.FaceId}," + $" confidence: {identifyResult.Candidates[0].Confidence}."); VerifyResult verifyResult = await client.Face.VerifyFaceToPersonAsync(identifyResult.FaceId, person.PersonId, personGroupId); Console.WriteLine($"Verification result: is a match? {verifyResult.IsIdentical}. confidence: {verifyResult.Confidence}"); } Console.WriteLine(); } } }
アプリケーションの実行
IDE ウィンドウの上部にある [デバッグ] ボタンをクリックして、アプリケーションを実行します。
出力
========IDENTIFY FACES========
Create a person group (3972c063-71b3-4328-8579-6d190ee76f99).
Create a person group person 'Family1-Dad'.
Add face to the person group person(Family1-Dad) from image `Family1-Dad1.jpg`
Add face to the person group person(Family1-Dad) from image `Family1-Dad2.jpg`
Create a person group person 'Family1-Mom'.
Add face to the person group person(Family1-Mom) from image `Family1-Mom1.jpg`
Add face to the person group person(Family1-Mom) from image `Family1-Mom2.jpg`
Create a person group person 'Family1-Son'.
Add face to the person group person(Family1-Son) from image `Family1-Son1.jpg`
Add face to the person group person(Family1-Son) from image `Family1-Son2.jpg`
Create a person group person 'Family1-Daughter'.
Create a person group person 'Family2-Lady'.
Add face to the person group person(Family2-Lady) from image `Family2-Lady1.jpg`
Add face to the person group person(Family2-Lady) from image `Family2-Lady2.jpg`
Create a person group person 'Family2-Man'.
Add face to the person group person(Family2-Man) from image `Family2-Man1.jpg`
Add face to the person group person(Family2-Man) from image `Family2-Man2.jpg`
Train person group 3972c063-71b3-4328-8579-6d190ee76f99.
Training status: Succeeded.
4 face(s) with 4 having sufficient quality for recognition detected from image `identification1.jpg`
Person 'Family1-Dad' is identified for face in: identification1.jpg - 994bfd7a-0d8f-4fae-a5a6-c524664cbee7, confidence: 0.96725.
Person 'Family1-Mom' is identified for face in: identification1.jpg - 0c9da7b9-a628-429d-97ff-cebe7c638fb5, confidence: 0.96921.
No person is identified for face in: identification1.jpg - a881259c-e811-4f7e-a35e-a453e95ca18f,
Person 'Family1-Son' is identified for face in: identification1.jpg - 53772235-8193-46eb-bdfc-1ebc25ea062e, confidence: 0.92886.
End of quickstart.
ヒント
Face API は、本質的に静的な一連の事前構築済みモデルで実行されます (サービスの実行中にモデルのパフォーマンスが低下したり改善されたりすることはありません)。 Microsoft により、まったく新しいモデル バージョンに移行することなくモデルのバックエンドが更新されると、モデルによって生成される結果が変わる可能性があります。 より新しいバージョンのモデルを利用するには、同じ登録画像でより新しいモデルをパラメーターとして指定し、PersonGroup を再トレーニングすることができます。
リソースをクリーンアップする
Azure AI サービス サブスクリプションをクリーンアップして削除したい場合は、リソースまたはリソース グループを削除することができます。 リソース グループを削除すると、それに関連付けられている他のリソースも削除されます。
このクイック スタートで作成した PersonGroup を削除するには、プログラムで次のコードを実行します。
// At end, delete person groups in both regions (since testing only)
Console.WriteLine("========DELETE PERSON GROUP========");
Console.WriteLine();
DeletePersonGroup(client, personGroupId).Wait();
次のコードを使用して削除メソッドを定義します。
/*
* DELETE PERSON GROUP
* After this entire example is executed, delete the person group in your Azure account,
* otherwise you cannot recreate one with the same name (if running example repeatedly).
*/
public static async Task DeletePersonGroup(IFaceClient client, String personGroupId)
{
await client.PersonGroup.DeleteAsync(personGroupId);
Console.WriteLine($"Deleted the person group {personGroupId}.");
}
次のステップ
このクイックスタートでは、.NET 用の Face クライアント ライブラリを使用して基本的な顔識別を行う方法について学習しました。 次に、さまざまな顔検出モデルと、ユース ケースに適したモデルを指定する方法について学習します。
- Face サービスとは
- より広範なサンプル コードが GitHub にあります。
Python 用 Face クライアント ライブラリを使用して顔認識を開始します。 以下の手順に従って、パッケージをインストールし、基本タスクのコード例を試してみましょう。 Face サービスは、画像内の人間の顔を検出および認識するための高度なアルゴリズムへのアクセスを提供します。 以下の手順に従って、パッケージをインストールし、リモート画像を使用した基本的な顔識別のためのコード例を試してみましょう。
リファレンス ドキュメント | ライブラリのソース コード | パッケージ (PiPy) | サンプル
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- Python 3.x
- Python のインストールには、pip が含まれている必要があります。 pip がインストールされているかどうかを確認するには、コマンド ラインで
pip --version
を実行します。 最新バージョンの Python をインストールして pip を入手してください。
- Python のインストールには、pip が含まれている必要があります。 pip がインストールされているかどうかを確認するには、コマンド ラインで
- 責任ある AI のご契約条件に同意してリソースを作成するためには、Azure アカウントに
Cognitive Services Contributor
ロールが割り当てられている必要があります。 このロールをアカウントに割り当てるには、ロールの割り当てに関するドキュメントの手順に従うか、管理者にお問い合わせください。 - Azure サブスクリプションを入手したら、Azure portal で Face リソースを作成し、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
- 対象のアプリケーションを Face API に接続するには、作成したリソースのキーとエンドポイントが必要です。
- Free 価格レベル (
F0
) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。
環境変数を作成する
この例では、アプリケーションを実行しているローカル コンピューター上の環境変数に資格情報を書き込みます。
Azure portal に移動します。 「前提条件」 セクションで作成したリソースが正常にデプロイされた場合、[次の手順] の下にある [リソースに移動] を選択します。 キーとエンドポイントは、[キーとエンドポイント] ページの [リソース管理] にあります。 リソース キーは Azure サブスクリプション ID と同じではありません。
ヒント
キーは、コードに直接含めないようにし、公開しないでください。 Azure Key Vault などのその他の認証オプションについては、Azure AI サービスのセキュリティに関する記事を参照してください。
キーとエンドポイントの環境変数を設定するには、コンソール ウィンドウを開き、オペレーティング システムと開発環境の指示に従います。
VISION_KEY
環境変数を設定するには、your-key
をリソースのキーの 1 つに置き換えます。VISION_ENDPOINT
環境変数を設定するには、your-endpoint
をリソースのエンドポイントに置き換えます。
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint
実行中のプログラムのうち、環境変数の読み取りを必要とするプログラム (コンソール ウィンドウを含む) については、環境変数を読み込む再起動が必要となる場合があります。
顔を識別して検証する
クライアント ライブラリをインストールする
Python をインストールしたら、次を使用してクライアント ライブラリをインストールすることができます。
pip install --upgrade azure-cognitiveservices-vision-face
新しい Python アプリケーションを作成する
新しい Python スクリプト (たとえば quickstart-file.py) を作成します。 次に、それを任意のエディターまたは IDE で開き、次のコードを貼り付けます。
Note
取り込みフォームを使用して Face サービスへのアクセスを受け取っていない場合、これらの関数の一部は機能しません。
import asyncio import io import os import sys import time import uuid import requests from urllib.parse import urlparse from io import BytesIO # To install this module, run: # python -m pip install Pillow from PIL import Image, ImageDraw from azure.cognitiveservices.vision.face import FaceClient from msrest.authentication import CognitiveServicesCredentials from azure.cognitiveservices.vision.face.models import TrainingStatusType, Person, QualityForRecognition # This key will serve all examples in this document. KEY = os.environ["VISION_KEY"] # This endpoint will be used in all examples in this quickstart. ENDPOINT = os.environ["VISION_ENDPOINT"] # Base url for the Verify and Facelist/Large Facelist operations IMAGE_BASE_URL = 'https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/' # Used in the Person Group Operations and Delete Person Group examples. # You can call list_person_groups to print a list of preexisting PersonGroups. # SOURCE_PERSON_GROUP_ID should be all lowercase and alphanumeric. For example, 'mygroupname' (dashes are OK). PERSON_GROUP_ID = str(uuid.uuid4()) # assign a random ID (or name it anything) # Used for the Delete Person Group example. TARGET_PERSON_GROUP_ID = str(uuid.uuid4()) # assign a random ID (or name it anything) # Create an authenticated FaceClient. face_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY)) ''' Create the PersonGroup ''' # Create empty Person Group. Person Group ID must be lower case, alphanumeric, and/or with '-', '_'. print('Person group:', PERSON_GROUP_ID) face_client.person_group.create(person_group_id=PERSON_GROUP_ID, name=PERSON_GROUP_ID, recognition_model='recognition_04') # Define woman friend woman = face_client.person_group_person.create(PERSON_GROUP_ID, name="Woman") # Define man friend man = face_client.person_group_person.create(PERSON_GROUP_ID, name="Man") # Define child friend child = face_client.person_group_person.create(PERSON_GROUP_ID, name="Child") ''' Detect faces and register them to each person ''' # Find all jpeg images of friends in working directory (TBD pull from web instead) woman_images = ["https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Mom1.jpg", "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Mom2.jpg"] man_images = ["https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Dad1.jpg", "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Dad2.jpg"] child_images = ["https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Son1.jpg", "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Son2.jpg"] # Add to woman person for image in woman_images: # Check if the image is of sufficent quality for recognition. sufficientQuality = True detected_faces = face_client.face.detect_with_url(url=image, detection_model='detection_03', recognition_model='recognition_04', return_face_attributes=['qualityForRecognition']) for face in detected_faces: if face.face_attributes.quality_for_recognition != QualityForRecognition.high: sufficientQuality = False break face_client.person_group_person.add_face_from_url(PERSON_GROUP_ID, woman.person_id, image) print("face {} added to person {}".format(face.face_id, woman.person_id)) if not sufficientQuality: continue # Add to man person for image in man_images: # Check if the image is of sufficent quality for recognition. sufficientQuality = True detected_faces = face_client.face.detect_with_url(url=image, detection_model='detection_03', recognition_model='recognition_04', return_face_attributes=['qualityForRecognition']) for face in detected_faces: if face.face_attributes.quality_for_recognition != QualityForRecognition.high: sufficientQuality = False break face_client.person_group_person.add_face_from_url(PERSON_GROUP_ID, man.person_id, image) print("face {} added to person {}".format(face.face_id, man.person_id)) if not sufficientQuality: continue # Add to child person for image in child_images: # Check if the image is of sufficent quality for recognition. sufficientQuality = True detected_faces = face_client.face.detect_with_url(url=image, detection_model='detection_03', recognition_model='recognition_04', return_face_attributes=['qualityForRecognition']) for face in detected_faces: if face.face_attributes.quality_for_recognition != QualityForRecognition.high: sufficientQuality = False print("{} has insufficient quality".format(face)) break face_client.person_group_person.add_face_from_url(PERSON_GROUP_ID, child.person_id, image) print("face {} added to person {}".format(face.face_id, child.person_id)) if not sufficientQuality: continue ''' Train PersonGroup ''' # Train the person group print("pg resource is {}".format(PERSON_GROUP_ID)) rawresponse = face_client.person_group.train(PERSON_GROUP_ID, raw= True) print(rawresponse) while (True): training_status = face_client.person_group.get_training_status(PERSON_GROUP_ID) print("Training status: {}.".format(training_status.status)) print() if (training_status.status is TrainingStatusType.succeeded): break elif (training_status.status is TrainingStatusType.failed): face_client.person_group.delete(person_group_id=PERSON_GROUP_ID) sys.exit('Training the person group has failed.') time.sleep(5) ''' Identify a face against a defined PersonGroup ''' # Group image for testing against test_image = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/identification1.jpg" print('Pausing for 10 seconds to avoid triggering rate limit on free account...') time.sleep (10) # Detect faces face_ids = [] # We use detection model 3 to get better performance, recognition model 4 to support quality for recognition attribute. faces = face_client.face.detect_with_url(test_image, detection_model='detection_03', recognition_model='recognition_04', return_face_attributes=['qualityForRecognition']) for face in faces: # Only take the face if it is of sufficient quality. if face.face_attributes.quality_for_recognition == QualityForRecognition.high or face.face_attributes.quality_for_recognition == QualityForRecognition.medium: face_ids.append(face.face_id) # Identify faces results = face_client.face.identify(face_ids, PERSON_GROUP_ID) print('Identifying faces in image') if not results: print('No person identified in the person group') for identifiedFace in results: if len(identifiedFace.candidates) > 0: print('Person is identified for face ID {} in image, with a confidence of {}.'.format(identifiedFace.face_id, identifiedFace.candidates[0].confidence)) # Get topmost confidence score # Verify faces verify_result = face_client.face.verify_face_to_person(identifiedFace.face_id, identifiedFace.candidates[0].person_id, PERSON_GROUP_ID) print('verification result: {}. confidence: {}'.format(verify_result.is_identical, verify_result.confidence)) else: print('No person identified for face ID {} in image.'.format(identifiedFace.face_id)) print() print('End of quickstart.')
python
コマンドを使用して、アプリケーション ディレクトリから顔認識アプリを実行します。python quickstart-file.py
ヒント
Face API は、本質的に静的な一連の事前構築済みモデルで実行されます (サービスの実行中にモデルのパフォーマンスが低下したり改善されたりすることはありません)。 Microsoft により、まったく新しいモデル バージョンに移行することなくモデルのバックエンドが更新されると、モデルによって生成される結果が変わる可能性があります。 より新しいバージョンのモデルを利用するには、同じ登録画像でより新しいモデルをパラメーターとして指定し、PersonGroup を再トレーニングすることができます。
出力
Person group: c8e679eb-0b71-43b4-aa91-ab8200cae7df
face 861d769b-d014-40e8-8b4a-7fd3bc9b425b added to person f80c1cfa-b8cb-46f8-9f7f-e72fbe402bc3
face e3c356a4-1ac3-4c97-9219-14648997f195 added to person f80c1cfa-b8cb-46f8-9f7f-e72fbe402bc3
face f9119820-c374-4c4d-b795-96ae2fec5069 added to person be4084a7-0c7b-4cf9-9463-3756d2e28e17
face 67d626df-3f75-4801-9364-601b63c8296a added to person be4084a7-0c7b-4cf9-9463-3756d2e28e17
face 19e2e8cc-5029-4087-bca0-9f94588fb850 added to person 3ff07c65-6193-4d3e-bf18-d7c106393cd5
face dcc61e80-16b1-4241-ae3f-9721597bae4c added to person 3ff07c65-6193-4d3e-bf18-d7c106393cd5
pg resource is c8e679eb-0b71-43b4-aa91-ab8200cae7df
<msrest.pipeline.ClientRawResponse object at 0x00000240DAD47310>
Training status: running.
Training status: succeeded.
Pausing for 10 seconds to avoid triggering rate limit on free account...
Identifying faces in image
Person for face ID 40582995-d3a8-41c4-a9d1-d17ae6b46c5c is identified in image, with a confidence of 0.96725.
Person for face ID 7a0368a2-332c-4e7a-81c4-2db3d74c78c5 is identified in image, with a confidence of 0.96921.
No person identified for face ID c4a3dd28-ef2d-457e-81d1-a447344242c4 in image.
Person for face ID 360edf1a-1e8f-402d-aa96-1734d0c21c1c is identified in image, with a confidence of 0.92886.
リソースをクリーンアップする
Azure AI サービス サブスクリプションをクリーンアップして削除したい場合は、リソースまたはリソース グループを削除することができます。 リソース グループを削除すると、それに関連付けられている他のリソースも削除されます。
このクイック スタートで作成した PersonGroup を削除するには、スクリプトで次のコードを実行します。
# Delete the main person group.
face_client.person_group.delete(person_group_id=PERSON_GROUP_ID)
print("Deleted the person group {} from the source location.".format(PERSON_GROUP_ID))
print()
次の手順
このクイックスタートでは、Python 用の Face クライアント ライブラリを使用して基本的な顔識別を行う方法について学習しました。 次に、さまざまな顔検出モデルと、ユース ケースに適したモデルを指定する方法について学習します。
- Face サービスとは
- より広範なサンプル コードが GitHub にあります。
JavaScript 用 Face クライアント ライブラリを使用して顔認識を開始します。 以下の手順に従って、パッケージをインストールし、基本タスクのコード例を試してみましょう。 Face サービスは、画像内の人間の顔を検出および認識するための高度なアルゴリズムへのアクセスを提供します。 以下の手順に従って、パッケージをインストールし、リモート画像を使用した基本的な顔識別のためのコード例を試してみましょう。
リファレンスのドキュメント | ライブラリのソース コード | パッケージ (npm) | サンプル
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- 最新バージョンの Node.js
- 責任ある AI のご契約条件に同意してリソースを作成するためには、Azure アカウントに
Cognitive Services Contributor
ロールが割り当てられている必要があります。 このロールをアカウントに割り当てるには、ロールの割り当てに関するドキュメントの手順に従うか、管理者にお問い合わせください。 - Azure サブスクリプションを入手したら、Azure portal で Face リソースを作成して、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
- 対象のアプリケーションを Face API に接続するには、作成したリソースのキーとエンドポイントが必要です。
- Free 価格レベル (
F0
) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。
環境変数を作成する
この例では、アプリケーションを実行しているローカル コンピューター上の環境変数に資格情報を書き込みます。
Azure portal に移動します。 「前提条件」 セクションで作成したリソースが正常にデプロイされた場合、[次の手順] の下にある [リソースに移動] を選択します。 キーとエンドポイントは、[キーとエンドポイント] ページの [リソース管理] にあります。 リソース キーは Azure サブスクリプション ID と同じではありません。
ヒント
キーは、コードに直接含めないようにし、公開しないでください。 Azure Key Vault などのその他の認証オプションについては、Azure AI サービスのセキュリティに関する記事を参照してください。
キーとエンドポイントの環境変数を設定するには、コンソール ウィンドウを開き、オペレーティング システムと開発環境の指示に従います。
VISION_KEY
環境変数を設定するには、your-key
をリソースのキーの 1 つに置き換えます。VISION_ENDPOINT
環境変数を設定するには、your-endpoint
をリソースのエンドポイントに置き換えます。
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint
実行中のプログラムのうち、環境変数の読み取りを必要とするプログラム (コンソール ウィンドウを含む) については、環境変数を読み込む再起動が必要となる場合があります。
顔を識別して検証する
新しい Node.js アプリケーションを作成する
コンソール ウィンドウ (cmd、PowerShell、Bash など) で、ご利用のアプリ用に新しいディレクトリを作成し、そこに移動します。
mkdir myapp && cd myapp
npm init
コマンドを実行し、package.json
ファイルを使用して node アプリケーションを作成します。npm init
@azure-rest/ai-vision-face
npm パッケージをインストールします。npm install @azure-rest/ai-vision-face
アプリの
package.json
ファイルが依存関係によって更新されます。index.js
という名前のファイルを作成し、テキスト エディターで開き、次のコードを貼り付けます。Note
取り込みフォームを使用して Face サービスへのアクセスを受け取っていない場合、これらの関数の一部は機能しません。
const { randomUUID } = require("crypto"); const { AzureKeyCredential } = require("@azure/core-auth"); const createFaceClient = require("@azure-rest/ai-vision-face").default, { FaceAttributeTypeRecognition04, getLongRunningPoller } = require("@azure-rest/ai-vision-face"); /** * NOTE This sample might not work with the free tier of the Face service because it might exceed the rate limits. * If that happens, try inserting calls to sleep() between calls to the Face service. */ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const main = async () => { const endpoint = process.env["FACE_ENDPOINT"] ?? "<endpoint>"; const apikey = process.env["FACE_APIKEY"] ?? "<apikey>"; const credential = new AzureKeyCredential(apikey); const client = createFaceClient(endpoint, credential); const imageBaseUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/"; const personGroupId = randomUUID(); console.log("========IDENTIFY FACES========"); console.log(); // Create a dictionary for all your images, grouping similar ones under the same key. const personDictionary = { "Family1-Dad": ["Family1-Dad1.jpg", "Family1-Dad2.jpg"], "Family1-Mom": ["Family1-Mom1.jpg", "Family1-Mom2.jpg"], "Family1-Son": ["Family1-Son1.jpg", "Family1-Son2.jpg"], "Family1-Daughter": ["Family1-Daughter1.jpg", "Family1-Daughter2.jpg"], "Family2-Lady": ["Family2-Lady1.jpg", "Family2-Lady2.jpg"], "Family2-Man": ["Family2-Man1.jpg", "Family2-Man2.jpg"], }; // A group photo that includes some of the persons you seek to identify from your dictionary. const sourceImageFileName = "identification1.jpg"; // Create a person group. console.log(`Creating a person group with ID: ${personGroupId}`); await client.path("/persongroups/{personGroupId}", personGroupId).put({ body: { name: personGroupId, recognitionModel: "recognition_04", }, }); // The similar faces will be grouped into a single person group person. console.log("Adding faces to person group..."); await Promise.all( Object.keys(personDictionary).map(async (name) => { console.log(`Create a persongroup person: ${name}`); const createPersonGroupPersonResponse = await client .path("/persongroups/{personGroupId}/persons", personGroupId) .post({ body: { name }, }); const { personId } = createPersonGroupPersonResponse.body; await Promise.all( personDictionary[name].map(async (similarImage) => { // Check if the image is of sufficent quality for recognition. const detectResponse = await client.path("/detect").post({ contentType: "application/json", queryParameters: { detectionModel: "detection_03", recognitionModel: "recognition_04", returnFaceId: false, returnFaceAttributes: [FaceAttributeTypeRecognition04.QUALITY_FOR_RECOGNITION], }, body: { url: `${imageBaseUrl}${similarImage}` }, }); const sufficientQuality = detectResponse.body.every( (face) => face.faceAttributes?.qualityForRecognition === "high", ); if (!sufficientQuality) { return; } // Quality is sufficent, add to group. console.log( `Add face to the person group person: (${name}) from image: (${similarImage})`, ); await client .path( "/persongroups/{personGroupId}/persons/{personId}/persistedfaces", personGroupId, personId, ) .post({ queryParameters: { detectionModel: "detection_03" }, body: { url: `${imageBaseUrl}${similarImage}` }, }); }), ); }), ); console.log("Done adding faces to person group."); // Start to train the person group. console.log(); console.log(`Training person group: ${personGroupId}`); const trainResponse = await client .path("/persongroups/{personGroupId}/train", personGroupId) .post(); const poller = await getLongRunningPoller(client, trainResponse); await poller.pollUntilDone(); console.log(`Training status: ${poller.getOperationState().status}`); if (poller.getOperationState().status !== "succeeded") { return; } // Detect faces from source image url and only take those with sufficient quality for recognition. const detectResponse = await client.path("/detect").post({ contentType: "application/json", queryParameters: { detectionModel: "detection_03", recognitionModel: "recognition_04", returnFaceId: true, }, body: { url: `${imageBaseUrl}${sourceImageFileName}` }, }); const faceIds = detectResponse.body.map((face) => face.faceId); // Identify the faces in a person group. const identifyResponse = await client.path("/identify").post({ body: { faceIds, personGroupId }, }); await Promise.all( identifyResponse.body.map(async (result) => { try { const getPersonGroupPersonResponse = await client .path( "/persongroups/{personGroupId}/persons/{personId}", personGroupId, result.candidates[0].personId, ) .get(); const person = getPersonGroupPersonResponse.body; console.log( `Person: ${person.name} is identified for face in: ${sourceImageFileName} with ID: ${result.faceId}. Confidence: ${result.candidates[0].confidence}`, ); // Verification: const verifyResponse = await client.path("/verify").post({ body: { faceId: result.faceId, personGroupId, personId: person.personId, }, }); console.log( `Verification result between face ${result.faceId} and person ${person.personId}: ${verifyResponse.body.isIdentical} with confidence: ${verifyResponse.body.confidence}`, ); } catch (error) { console.log(`No persons identified for face with ID ${result.faceId}`); } }), ); console.log(); // Delete person group. console.log(`Deleting person group: ${personGroupId}`); await client.path("/persongroups/{personGroupId}", personGroupId).delete(); console.log(); console.log("Done."); }; main().catch(console.error);
クイック スタート ファイルで
node
コマンドを使用して、アプリケーションを実行します。node index.js
出力
========IDENTIFY FACES========
Creating a person group with ID: c08484e0-044b-4610-8b7e-c957584e5d2d
Adding faces to person group...
Create a persongroup person: Family1-Dad.
Create a persongroup person: Family1-Mom.
Create a persongroup person: Family2-Lady.
Create a persongroup person: Family1-Son.
Create a persongroup person: Family1-Daughter.
Create a persongroup person: Family2-Man.
Add face to the person group person: (Family1-Son) from image: Family1-Son2.jpg.
Add face to the person group person: (Family1-Dad) from image: Family1-Dad2.jpg.
Add face to the person group person: (Family1-Mom) from image: Family1-Mom1.jpg.
Add face to the person group person: (Family2-Man) from image: Family2-Man1.jpg.
Add face to the person group person: (Family1-Son) from image: Family1-Son1.jpg.
Add face to the person group person: (Family2-Lady) from image: Family2-Lady2.jpg.
Add face to the person group person: (Family1-Mom) from image: Family1-Mom2.jpg.
Add face to the person group person: (Family1-Dad) from image: Family1-Dad1.jpg.
Add face to the person group person: (Family2-Man) from image: Family2-Man2.jpg.
Add face to the person group person: (Family2-Lady) from image: Family2-Lady1.jpg.
Done adding faces to person group.
Training person group: c08484e0-044b-4610-8b7e-c957584e5d2d.
Training status: succeeded.
No persons identified for face with ID 259dd648-be70-499c-9942-3512594e21eb
Person: Family1-Mom is identified for face in: identification1.jpg with ID: b7f7f542-c338-4a40-ad52-e61772bc6e14. Confidence: 0.96921.
Person: Family1-Son is identified for face in: identification1.jpg with ID: 600dc1b4-b2c4-4516-87de-edbbdd8d7632. Confidence: 0.92886.
Person: Family1-Dad is identified for face in: identification1.jpg with ID: e83b494f-9ad2-473f-9d86-3de79c01e345. Confidence: 0.96725.
Verification result between face bb7f7f542-c338-4a40-ad52-e61772bc6e14 and person de1d7dea-a393-4f69-9062-10cb66d4cf17: true with confidence: 0.96921
Verification result between face 600dc1b4-b2c4-4516-87de-edbbdd8d7632 and person 05fd84e4-41b0-4716-b767-4376e33fa207: true with confidence: 0.92886
Verification result between face e83b494f-9ad2-473f-9d86-3de79c01e345 and person c5124fe2-39dd-47ba-9163-1ed2998fdeb2: true with confidence: 0.96725
Deleting person group: c08484e0-044b-4610-8b7e-c957584e5d2d
Done.
リソースをクリーンアップする
Azure AI サービス サブスクリプションをクリーンアップして削除したい場合は、リソースまたはリソース グループを削除することができます。 リソース グループを削除すると、それに関連付けられている他のリソースも削除されます。
次のステップ
このクイックスタートでは、JavaScript 用の Face クライアント ライブラリを使用して基本的な顔識別を行う方法について学習しました。 次に、さまざまな顔検出モデルと、ユース ケースに適したモデルを指定する方法について学習します。
- Face サービスとは
- より広範なサンプル コードが GitHub にあります。
Face REST API を使用して顔認識を開始します。 Face サービスは、画像内の人間の顔を検出および認識するための高度なアルゴリズムへのアクセスを提供します。
Note
このクイックスタートでは、cURL コマンドを使用して REST API を呼び出します。 また、プログラミング言語を使用して REST API を呼び出すこともできます。 顔識別などの複雑なシナリオは、言語 SDK を使用して実装する方が簡単です。 GitHub のサンプルを参照して、
前提条件
- Azure サブスクリプション - 無料アカウントを作成します
- 責任ある AI のご契約条件に同意してリソースを作成するためには、Azure アカウントに
Cognitive Services Contributor
ロールが割り当てられている必要があります。 このロールをアカウントに割り当てるには、ロールの割り当てに関するドキュメントの手順に従うか、管理者にお問い合わせください。 - Azure サブスクリプションを入手したら、Azure portal で Face リソースを作成し、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
- 対象のアプリケーションを Face API に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
- Free 価格レベル (
F0
) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。
- PowerShell バージョン 6.0 以降、または同様のコマンド ライン アプリケーション。
- インストールされた cURL。
顔を識別して検証する
Note
取り込みフォームを使用して Face サービスへのアクセスを受け取っていない場合、これらの関数の一部は機能しません。
まず、ソースの顔の検出 API を呼び出します。 これは、より大きなグループから識別しようとする顔です。 次のコマンドをテキスト エディターにコピーし、独自のキーとエンドポイントを挿入してから、シェル ウィンドウにコピーして実行します。
curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&recognitionModel=recognition_04&returnRecognitionModel=false&detectionModel=detection_03&faceIdTimeToLive=86400" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{""url"":""https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/identification1.jpg""}"
返された顔 ID 文字列を一時的な場所に保存します。 これは最後にもう一度使用します。
次に、LargePersonGroup を作成し、正規表現パターン
^[a-z0-9-_]+$
に一致する任意の ID を指定する必要があります。 このオブジェクトには、複数の人物の集計された顔データが格納されます。 次のコマンドを実行し、独自のキーを挿入します。 必要に応じて、要求本文のグループの名前とメタデータを変更します。curl.exe -v -X PUT "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{ ""name"": ""large-person-group-name"", ""userData"": ""User-provided data attached to the large person group."", ""recognitionModel"": ""recognition_04"" }"
作成されたグループの指定された ID を一時的な場所に保存します。
次に、グループに属する Person オブジェクトを作成します。 次のコマンドを実行し、独自のキーと、前の手順の LargePersonGroup の ID を挿入します。 このコマンドによって、"Family1-Dad" という名前の Person が作成されます。
curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}/persons" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{ ""name"": ""Family1-Dad"", ""userData"": ""User-provided data attached to the person."" }"
このコマンドを実行した後、別の入力データを使用してもう一度実行して、"Family1-Mom"、"Family1-Son"、"Family1-Daughter"、"Family2-Lady"、"Family2-Man" などの Person オブジェクトをさらに作成します。
作成した各 Person の ID を保存します。どの個人名がどの ID を持つのかを追跡することが重要です。
次に、新しい顔を検出し、それらを存在する Person オブジェクトに関連付ける必要があります。 次のコマンドは、画像 Family1-Dad1.jpg から顔を検出し、対応する人物に追加します。 "Family1-Dad" Person オブジェクトを作成したときに返された ID として
personId
を指定する必要があります。 画像名は、作成された Person.の名前に対応します。 また、LargePersonGroup ID とキーを適切なフィールドに入力します。curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces?detectionModel=detection_03" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{""url"":""https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Dad1.jpg""}"
次に、別のソース イメージとターゲットの Person を使用して、上記のコマンドをもう一度実行します。 使用可能なイメージは、Family1-Dad1.jpg、Family1-Dad2.jpg、Family1-Mom1.jpg、Family1-Mom2.jpg、Family1-Son1.jpg、Family1-Son2.jpg、Family1-Daughter1.jpg、Family1-Daughter2.jpg、Family2-Lady1.jpg、Family2-Lady2.jpg、Family2-Man1.jpg、および Family2-Man2.jpg です。 API 呼び出しで指定した ID を持つ Person が、要求本文のイメージ ファイルの名前と一致していることを確認します。
この手順の最後に、指定された画像から直接検出された 1 つ以上の対応する顔を持つ複数の Person オブジェクトが必要です。
次に、現在の顔データを使用して LargePersonGroup をトレーニングします。 トレーニング操作では、複数のソース画像から集計された場合もある顔の特徴を単一の人物に関連付ける方法をモデルに指示します。 コマンドを実行する前に、LargePersonGroup ID とキーを挿入します。
トレーニングの状態が成功したかどうかを確認します。 そうでない場合は、しばらく待ってから、もう一度クエリを実行します。
これで、最初の手順のソースの顔 ID と LargePersonGroup ID を使用して、Identify API を呼び出す準備ができました。 これらの値を要求本文の適切なフィールドに挿入し、キーを挿入します。
curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/identify" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{ ""largePersonGroupId"": ""INSERT_PERSONGROUP_ID"", ""faceIds"": [ ""INSERT_SOURCE_FACE_ID"" ], ""maxNumOfCandidatesReturned"": 1, ""confidenceThreshold"": 0.5 }"
応答では、ソースの顔で識別された人物を示す Person ID が提供されるはずです。 これは、"Family1-Dad" の人物に対応する ID であるはずです。これは、ソースの顔はその人のものであるためです
顔検証を行うには、前の手順で返された人物 ID、LargePersonGroup ID を使用し、ソースの顔 ID も使用します。 これらの値を要求本文のフィールドに挿入し、自分のキーを挿入します。
curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/verify" ` -H "Content-Type: application/json" ` -H "Ocp-Apim-Subscription-Key: {subscription key}" ` --data-ascii "{ ""faceId"": ""INSERT_SOURCE_FACE_ID"", ""personId"": ""INSERT_PERSON_ID"", ""largePersonGroupId"": ""INSERT_PERSONGROUP_ID"" }"
応答では、信頼度値と共に、ブール値の検証結果が返されます。
リソースをクリーンアップする
この演習で作成した LargePersonGroup を削除するには、LargePersonGroup - Delete 呼び出しを実行します。
curl.exe -v -X DELETE "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}" -H "Ocp-Apim-Subscription-Key: {subscription key}"
Azure AI サービス サブスクリプションをクリーンアップして削除したい場合は、リソースまたはリソース グループを削除することができます。 リソース グループを削除すると、それに関連付けられている他のリソースも削除されます。
次のステップ
このクイックスタートでは、Face REST API を使用して基本的な顔認識タスクを行う方法について学習しました。 次に、さまざまな顔検出モデルと、ユース ケースに適したモデルを指定する方法について学習します。
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示