빠른 시작: Face 서비스 사용
중요
Microsoft 제품 또는 서비스를 사용하여 생체 인식 데이터를 처리하는 경우 (i) 보존 기간 및 소멸을 포함하여 데이터 주체에 통지 (ii) 데이터 주체로부터 동의 얻기 및 (iii) 적용 가능한 데이터 보호 요구 사항에 따라 적절하고 필요한 모든 생체 인식 데이터 삭제와 같은 책임이 있습니다. "생체 인식 데이터"는 GDPR 제4조에 명시된 의미를 가지며, 해당하는 경우 다른 데이터 보호 요구 사항에서 동등한 조건을 갖습니다. 관련 정보는 Face의 데이터 및 개인 정보를 참조하세요.
주의
Face 서비스 액세스는 책임 있는 AI 원칙을 지원하기 위해 자격 및 사용 기준에 따라 제한됩니다. Face 서비스는 Microsoft 관리 고객 및 파트너만 사용할 수 있습니다. 얼굴 인식 접수 양식을 사용하여 액세스를 적용합니다. 자세한 내용은 얼굴 제한 액세스 페이지를 참조하세요.
.NET용 Face 클라이언트 라이브러리를 사용하여 얼굴 인식을 시작합니다. Face 서비스는 이미지에서 사람의 얼굴을 감지하고 인식하기 위한 고급 알고리즘에 대한 액세스를 제공합니다. 다음 단계에 따라 패키지를 설치하고 원격 이미지를 사용하여 기본 얼굴 식별을 위한 예제 코드를 사용해봅니다.
참조 설명서 | 라이브러리 소스 코드 | 패키지(NuGet) | 샘플
사전 요구 사항
- Azure 구독 - 체험 구독 만들기
- Visual Studio IDE 또는 현재 버전의 .NET Core.
- 책임 있는 AI 조건에 동의하고 리소스를 만들려면 Azure 계정에 Cognitive Services 기여자 역할이 할당되어 있어야 합니다. 이 역할을 계정에 할당하려면 역할 할당의 단계를 수행하거나 관리자에게 문의하세요.
- Azure 구독이 있으면 Azure Portal에서 Face 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 클릭합니다.
- 애플리케이션을 Face API에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다.
- 평가판 가격 책정 계층(
F0
)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
환경 변수 만들기
이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.
Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동 단추를 클릭합니다. 리소스 관리 아래에 있는 리소스의 키 및 엔드포인트 페이지에서 키 및 엔드포인트를 찾을 수 있습니다. 리소스 키는 Azure 구독 ID와 동일하지 않습니다.
팁
키를 코드에 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Cognitive Services 보안 문서를 참조하세요.
키 및 엔드포인트에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.
VISION_KEY
환경 변수를 설정하려면your-key
를 리소스에 대한 키 중 하나로 바꿉니다.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 파일에 추가합니다.
참고
접수 양식을 사용하여 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을 동일한 등록 이미지를 가진 매개 변수로 지정하여 다시 학습할 수 있습니다.
리소스 정리
Cognitive Services 구독을 정리하고 제거하려면 리소스나 리소스 그룹을 삭제하면 됩니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.
이 빠른 시작에서 만든 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에서 찾을 수 있습니다.
JavaScript용 Face 클라이언트 라이브러리를 사용하여 얼굴 인식을 시작합니다. 이러한 단계에 따라 패키지를 설치하고 기본 작업을 위한 예제 코드를 사용해 봅니다. Face 서비스는 이미지에서 사람의 얼굴을 감지하고 인식하기 위한 고급 알고리즘에 대한 액세스를 제공합니다. 다음 단계에 따라 패키지를 설치하고 원격 이미지를 사용하여 기본 얼굴 식별을 위한 예제 코드를 사용해봅니다.
참조 설명서 | 라이브러리 소스 코드 | 패키지(npm) | 샘플
필수 구성 요소
- Azure 구독 - 체험 구독 만들기
- 최신 버전의 Node.js
- 책임 있는 AI 조건에 동의하고 리소스를 만들려면 Azure 계정에 Cognitive Services 기여자 역할이 할당되어 있어야 합니다. 이 역할을 계정에 할당하려면 역할 할당의 단계를 수행하거나 관리자에게 문의하세요.
- Azure 구독을 보유한 후에는 Azure Portal에서 Face 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 클릭합니다.
- 애플리케이션을 Face API에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다.
- 평가판 가격 책정 계층(
F0
)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
환경 변수 만들기
이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.
Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동 단추를 클릭합니다. 리소스 관리 아래에 있는 리소스의 키 및 엔드포인트 페이지에서 키 및 엔드포인트를 찾을 수 있습니다. 리소스 키는 Azure 구독 ID와 동일하지 않습니다.
팁
키를 코드에 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Cognitive Services 보안 문서를 참조하세요.
키 및 엔드포인트에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.
VISION_KEY
환경 변수를 설정하려면your-key
를 리소스에 대한 키 중 하나로 바꿉니다.VISION_ENDPOINT
환경 변수를 설정하려면your-endpoint
를 리소스에 대한 엔드포인트로 바꿉니다.
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint
환경 변수가 추가되면 콘솔 창을 포함하여 환경 변수를 읽는 실행 중인 프로그램을 다시 시작해야 할 수 있습니다.
얼굴 식별 및 확인
새 Node.js 애플리케이션 만들기
콘솔 창(예: cmd, PowerShell 또는 Bash)에서 앱에 대한 새 디렉터리를 만들고 이 디렉터리로 이동합니다.
mkdir myapp && cd myapp
package.json
파일을 사용하여 노드 애플리케이션을 만들려면npm init
명령을 실행합니다.npm init
ms-rest-azure
및azure-cognitiveservices-face
NPM 패키지를 설치합니다.npm install @azure/cognitiveservices-face @azure/ms-rest-js uuid
종속성이 있는 앱의
package.json
파일이 업데이트됩니다.index.js
라는 이름의 파일을 만들고 텍스트 편집기에서 열고 다음 코드를 붙여넣습니다.참고
접수 양식을 사용하여 Face 서비스에 대한 액세스 권한을 받지 못한 경우 이러한 기능 중 일부는 작동하지 않습니다.
'use strict'; const msRest = require("@azure/ms-rest-js"); const Face = require("@azure/cognitiveservices-face"); const { v4: uuid } = require('uuid'); const key = process.env.VISION_KEY; const endpoint = process.env.VISION_ENDPOINT; const credentials = new msRest.ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': key } }); const client = new Face.FaceClient(credentials, endpoint); const image_base_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/"; const person_group_id = uuid(); function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function DetectFaceRecognize(url) { // Detect faces from image URL. Since only recognizing, use the recognition model 4. // We use detection model 3 because we are only retrieving the qualityForRecognition attribute. // Result faces with quality for recognition lower than "medium" are filtered out. let detected_faces = await client.face.detectWithUrl(url, { detectionModel: "detection_03", recognitionModel: "recognition_04", returnFaceAttributes: ["QualityForRecognition"] }); return detected_faces.filter(face => face.faceAttributes.qualityForRecognition == 'high' || face.faceAttributes.qualityForRecognition == 'medium'); } async function AddFacesToPersonGroup(person_dictionary, person_group_id) { console.log ("Adding faces to person group..."); // The similar faces will be grouped into a single person group person. await Promise.all (Object.keys(person_dictionary).map (async function (key) { const value = person_dictionary[key]; let person = await client.personGroupPerson.create(person_group_id, { name : key }); console.log("Create a persongroup person: " + key + "."); // Add faces to the person group person. await Promise.all (value.map (async function (similar_image) { // Wait briefly so we do not exceed rate limits. await sleep (1000); // Check if the image is of sufficent quality for recognition. let sufficientQuality = true; let detected_faces = await client.face.detectWithUrl(image_base_url + similar_image, { returnFaceAttributes: ["QualityForRecognition"], detectionModel: "detection_03", recognitionModel: "recognition_03" }); detected_faces.forEach(detected_face => { if (detected_face.faceAttributes.qualityForRecognition != 'high'){ sufficientQuality = false; } }); // Wait briefly so we do not exceed rate limits. await sleep (1000); // Quality is sufficent, add to group. if (sufficientQuality){ console.log("Add face to the person group person: (" + key + ") from image: " + similar_image + "."); await client.personGroupPerson.addFaceFromUrl(person_group_id, person.personId, image_base_url + similar_image); } // Wait briefly so we do not exceed rate limits. await sleep (1000); })); })); console.log ("Done adding faces to person group."); } async function WaitForPersonGroupTraining(person_group_id) { // Wait so we do not exceed rate limits. console.log ("Waiting 10 seconds..."); await sleep (10000); let result = await client.personGroup.getTrainingStatus(person_group_id); console.log("Training status: " + result.status + "."); if (result.status !== "succeeded") { await WaitForPersonGroupTraining(person_group_id); } } /* NOTE This function 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. */ async function IdentifyInPersonGroup() { console.log("========IDENTIFY FACES========"); console.log(); // Create a dictionary for all your images, grouping similar ones under the same key. const person_dictionary = { "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. let source_image_file_name = "identification1.jpg"; // Create a person group. console.log("Creating a person group with ID: " + person_group_id); await client.personGroup.create(person_group_id, person_group_id, {recognitionModel : "recognition_04" }); await AddFacesToPersonGroup(person_dictionary, person_group_id); // Start to train the person group. console.log(); console.log("Training person group: " + person_group_id + "."); await client.personGroup.train(person_group_id); await WaitForPersonGroupTraining(person_group_id); console.log(); // Detect faces from source image url and only take those with sufficient quality for recognition. let face_ids = (await DetectFaceRecognize(image_base_url + source_image_file_name)).map (face => face.faceId); // Identify the faces in a person group. let results = await client.face.identify(face_ids, { personGroupId : person_group_id}); await Promise.all (results.map (async function (result) { try{ let person = await client.personGroupPerson.get(person_group_id, result.candidates[0].personId); console.log("Person: " + person.name + " is identified for face in: " + source_image_file_name + " with ID: " + result.faceId + ". Confidence: " + result.candidates[0].confidence + "."); // Verification: let verifyResult = await client.face.verifyFaceToPerson(result.faceId, person.personId, {personGroupId : person_group_id}); console.log("Verification result between face "+ result.faceId +" and person "+ person.personId+ ": " +verifyResult.isIdentical + " with confidence: "+ verifyResult.confidence); } catch(error) { //console.log("no persons identified for face with ID " + result.faceId); console.log(error.toString()); } })); console.log(); } async function main() { await IdentifyInPersonGroup(); console.log ("Done."); } main();
quickstart 파일의
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.
Waiting 10 seconds...
Training status: succeeded.
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.
리소스 정리
Cognitive Services 구독을 정리하고 제거하려면 리소스나 리소스 그룹을 삭제하면 됩니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.
다음 단계
이 빠른 시작에서는 JavaScript용 Face 클라이언트 라이브러리를 사용하여 기본 얼굴 식별을 수행하는 방법을 알아보았습니다. 다음으로, 다양한 얼굴 감지 모델과 사용 사례에 적합한 모델을 지정하는 방법을 알아봅니다.
- Face 서비스란?
- 더 광범위한 샘플 코드는 GitHub에서 찾을 수 있습니다.
Python용 Face 클라이언트 라이브러리를 사용하여 얼굴 인식을 시작합니다. 이러한 단계에 따라 패키지를 설치하고 기본 작업을 위한 예제 코드를 사용해 봅니다. Face 서비스는 이미지에서 사람의 얼굴을 감지하고 인식하기 위한 고급 알고리즘에 대한 액세스를 제공합니다. 다음 단계에 따라 패키지를 설치하고 원격 이미지를 사용하여 기본 얼굴 식별을 위한 예제 코드를 사용해봅니다.
참조 설명서 | 라이브러리 소스 코드 | 패키지(PiPy) | 샘플
사전 요구 사항
- Azure 구독 - 체험 구독 만들기
- Python 3.x
- Python 설치에 pip가 포함되어야 합니다. 명령줄에서
pip --version
을 실행하여 pip가 설치되어 있는지 확인할 수 있습니다. 최신 버전의 Python을 설치하여 pip를 받으세요.
- Python 설치에 pip가 포함되어야 합니다. 명령줄에서
- 책임 있는 AI 조건에 동의하고 리소스를 만들려면 Azure 계정에 Cognitive Services 기여자 역할이 할당되어 있어야 합니다. 이 역할을 계정에 할당하려면 역할 할당의 단계를 수행하거나 관리자에게 문의하세요.
- Azure 구독이 있으면 Azure Portal에서 Face 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 클릭합니다.
- 애플리케이션을 Face API에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다.
- 평가판 가격 책정 계층(
F0
)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
환경 변수 만들기
이 예제에서는 애플리케이션을 실행하는 로컬 컴퓨터의 환경 변수에 자격 증명을 작성합니다.
Azure Portal로 이동합니다. 필수 구성 요소 섹션에서 만든 리소스가 성공적으로 배포된 경우 다음 단계 아래에서 리소스로 이동 단추를 클릭합니다. 리소스 관리 아래에 있는 리소스의 키 및 엔드포인트 페이지에서 키 및 엔드포인트를 찾을 수 있습니다. 리소스 키는 Azure 구독 ID와 동일하지 않습니다.
팁
키를 코드에 직접 포함하지 말고 공개적으로 게시하지 마세요. Azure Key Vault와 같은 추가 인증 옵션은 Cognitive Services 보안 문서를 참조하세요.
키 및 엔드포인트에 대한 환경 변수를 설정하려면 콘솔 창을 열고 운영 체제 및 개발 환경에 대한 지침을 따릅니다.
VISION_KEY
환경 변수를 설정하려면your-key
를 리소스에 대한 키 중 하나로 바꿉니다.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에서 이 파일을 열고, 다음 코드를 붙여넣습니다.
참고
접수 양식을 사용하여 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.
리소스 정리
Cognitive Services 구독을 정리하고 제거하려면 리소스나 리소스 그룹을 삭제하면 됩니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.
이 빠른 시작에서 만든 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에서 찾을 수 있습니다.
Face REST API를 사용하여 얼굴 인식을 시작합니다. Face 서비스는 이미지에서 사람의 얼굴을 감지하고 인식하기 위한 고급 알고리즘에 대한 액세스를 제공합니다.
참고
이 빠른 시작에서는 cURL 명령을 사용하여 REST API를 호출합니다. 프로그래밍 언어를 사용하여 REST API를 호출할 수도 있습니다. 얼굴 식별과 같은 복잡한 시나리오는 언어 SDK를 사용하여 구현하는 것이 더 쉽습니다. C#, Python, Java, JavaScript, Go의 예는 GitHub 샘플을 참조하세요.
필수 구성 요소
- Azure 구독 - 체험 구독 만들기
- 책임 있는 AI 조건에 동의하고 리소스를 만들려면 Azure 계정에 Cognitive Services 기여자 역할이 할당되어 있어야 합니다. 이 역할을 계정에 할당하려면 역할 할당의 단계를 수행하거나 관리자에게 문의하세요.
- Azure 구독이 있으면 Azure Portal에서 Face 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 클릭합니다.
- 애플리케이션을 Face API에 연결하려면 생성한 리소스의 키와 엔드포인트가 필요합니다. 이 빠른 시작의 뒷부분에 나오는 코드에 키와 엔드포인트를 붙여넣습니다.
- 평가판 가격 책정 계층(
F0
)을 통해 서비스를 사용해보고, 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
- PowerShell 버전 6.0 이상 또는 유사한 명령줄 애플리케이션.
얼굴 식별 및 확인
참고
접수 양식을 사용하여 Face 서비스에 대한 액세스 권한을 받지 못한 경우 이러한 기능 중 일부는 작동하지 않습니다.
먼저 원본 얼굴에서 검색 Detect API를 호출합니다. 이것은 더 큰 그룹에서 식별하려고 시도할 얼굴입니다. 다음 명령을 텍스트 편집기에 복사하고, 자체 키를 삽입한 다음, 셸 창에 복사하여 실행합니다.
curl -v -X POST "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes={string}&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을 만들어야 합니다. 이 개체는 여러 사람의 집계된 얼굴 데이터를 저장합니다. 다음 명령을 실행하여 자체 키를 삽입합니다. 필요에 따라 요청 본문에서 그룹의 이름과 메타데이터를 변경합니다.
curl -v -X PUT "https://westus.api.cognitive.microsoft.com/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_03\" }"
생성된 그룹의 반환된 ID를 임시 위치에 저장합니다.
다음으로, 그룹에 속한 Person 개체를 만듭니다. 다음 명령을 실행하여 이전 단계의 LargePersonGroup ID와 자체 키를 삽입합니다. 이 명령은 "Family1-Dad"라는 Person을 만듭니다.
curl -v -X POST "https://westus.api.cognitive.microsoft.com/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.\" }"
이 명령을 실행한 후 다른 입력 데이터로 다시 실행하여 더 많은 Person 개체("Family1-Mom", "Family1-Son", "Family1-Daughter", "Family2-Lady", "Family2-Man")를 만듭니다.
만든 각 Person의 ID를 저장합니다. 어떤 사람의 이름에 어떤 ID가 있는지 추적하는 것이 중요합니다.
다음으로 새 얼굴을 감지하고 존재하는 Person 개체와 연결해야 합니다. 다음 명령은 Family1-Dad.jpg 이미지에서 얼굴을 감지하여 해당 인물에 추가합니다. "Family1-Dad" Person 개체를 만들 때 반환된 ID로
personId
를 지정해야 합니다. 이미지 이름은 생성된 Person의 이름에 해당합니다. 또한 적절한 필드에 LargePersonGroup ID와 키를 입력합니다.curl -v -X POST "https://westus.api.cognitive.microsoft.com/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-Dad.jpg\"}'
그런 다음, 다른 원본 이미지와 대상 Person을 사용하여 위의 명령을 다시 실행합니다. 사용 가능한 이미지는 Family1-Dad1.jpg, Family1-Dad2.jpgFamily1-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이 요청 본문에 있는 이미지 파일의 이름과 일치하는지 확인합니다.
이 단계가 끝나면 제공된 이미지에서 직접 감지된 하나 이상의 해당 얼굴이 있는 여러 Person 개체가 있어야 합니다.
다음으로, 현재 얼굴 데이터를 사용하여 LargePersonGroup을 학습시킵니다. 학습 작업은 얼굴 특징(때로는 여러 원본 이미지에서 집계됨)을 각각의 개인과 연결하는 방법을 모델에 알려줍니다. 명령을 실행하기 전에 LargePersonGroup ID 및 키를 삽입합니다.
curl -v -X POST "https://westus.api.cognitive.microsoft.com/face/v1.0/largepersongroups/{largePersonGroupId}/train" -H "Ocp-Apim-Subscription-Key: {subscription key}"
이제 첫 번째 단계의 원본 얼굴 ID와 LargePersonGroup ID를 사용하여 Identify API를 호출할 준비가 되었습니다. 이 값을 요청 본문의 적절한 필드에 삽입하고 키를 삽입합니다.
curl -v -X POST "https://westus.api.cognitive.microsoft.com/face/v1.0/identify" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{ \"largePersonGroupId\": \"INSERT_PERSONGROUP_NAME\", \"faceIds\": [ \"INSERT_SOURCE_FACE_ID\" ], \"maxNumOfCandidatesReturned\": 1, \"confidenceThreshold\": 0.5 }"
응답은 원본 얼굴로 식별된 사람을 나타내는 Person ID를 제공해야 합니다. "Family1-Dad" 인물에 해당하는 ID여야 합니다. 원본 얼굴이 그 인물의 얼굴이기 때문입니다.
얼굴 확인을 수행하려면 이전 단계에서 반환된 사람 ID, LargePersonGroup ID 및 원본 얼굴 ID를 사용합니다. 이 값을 요청 본문의 필드에 삽입하고 키를 삽입합니다.
curl -v -X POST "https://westus.api.cognitive.microsoft.com/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 - 삭제 호출을 실행합니다.
curl -v -X DELETE "https://westus.api.cognitive.microsoft.com/face/v1.0/largepersongroups/{largePersonGroupId}" -H "Ocp-Apim-Subscription-Key: {subscription key}"
Cognitive Services 구독을 정리하고 제거하려면 리소스나 리소스 그룹을 삭제하면 됩니다. 리소스 그룹을 삭제하면 해당 리소스 그룹에 연결된 다른 모든 리소스가 함께 삭제됩니다.
다음 단계
이 빠른 시작에서는 Face REST API를 사용하여 기본 얼굴 인식 작업을 수행하는 방법을 알아보았습니다. 다음으로, 다양한 얼굴 감지 모델과 사용 사례에 적합한 모델을 지정하는 방법을 알아봅니다.
Vision Studio를 사용하여 얼굴을 식별합니다. 이는 얼굴 식별 기능의 간소화된 버전입니다. 한 사람에 대해서만 모델을 학습시킨 다음 새 얼굴이 그 사람과 일치하는지 확인할 수 있습니다. 일반적으로 여러 사람에 대해 모델을 학습한 다음 모든 사람에 대해 새 이미지를 확인합니다. 전체 식별 시나리오를 수행하려면 REST API 또는 클라이언트 SDK를 사용합니다.
사전 요구 사항
- Azure 구독 및 Cognitive Services 리소스로 Vision Studio에 로그인합니다. 이 단계에서 도움이 필요하면 개요의 시작 섹션을 참조하세요.
- 사람의 얼굴 이미지가 3개 이상 필요합니다. 모델을 학습하는 데 2개 이상, 테스트에 1개가 필요합니다.
얼굴 식별
- Face 탭을 선택하고 특정 인물 인식이라는 패널을 선택합니다.
- 체험 환경을 사용하려면 리소스를 선택하고 가격 책정 계층에 따라 사용량이 발생함을 인정해야 합니다.
- 다음으로 사람의 이름을 지정하고 얼굴 이미지를 업로드합니다. 그런 다음 얼굴 등록을 선택하고 모델이 학습을 마칠 때까지 기다립니다.
- 마지막으로 하단 창에 다른 이미지를 업로드하면 서비스에서 해당 이미지가 학습을 받은 사람에게 속하는지 확인합니다.
- 일치 결과 및 신뢰도 점수는 검색된 특성 창을 참조하세요.
- 시험 사용 환경 아래에는 고유의 애플리케이션에서 이 기능을 사용하기 시작하는 다음 단계가 나와 있습니다.
다음 단계
이 빠른 시작에서는 Vision Studio를 사용하여 기본적인 얼굴 인식 작업을 수행하는 방법을 알아보았습니다. 다음으로, 다양한 얼굴 감지 모델과 사용 사례에 적합한 모델을 지정하는 방법을 알아봅니다.