Hızlı Başlangıç: Yüz Tanıma hizmetini kullanma

Önemli

Biyometrik Verileri işlemek için Microsoft ürünlerini veya hizmetlerini kullanıyorsanız, şunlardan sorumlusunuz: (i) saklama süreleri ve yok etme de dahil olmak üzere veri konularına bildirim sağlamak; (ii) veri öznelerinden onay almak; ve (iii) Geçerli Veri Koruma Gereksinimleri kapsamında uygun ve gerekli olan Biyometrik Verileri silme. "Biyometrik Veriler", GDPR'nin 4. Maddesinde belirtilen anlamlara ve varsa diğer veri koruma gereksinimlerindeki eşdeğer koşullara sahip olacaktır. İlgili bilgiler için bkz . Yüz için Veri ve Gizlilik.

Dikkat

Yüz tanıma hizmeti erişimi, Sorumlu yapay zeka ilkelerimizi desteklemek için uygunluk ve kullanım ölçütlerine göre sınırlıdır. Yüz tanıma hizmeti yalnızca Microsoft tarafından yönetilen müşteriler ve iş ortakları tarafından kullanılabilir. Erişim için başvurmak için Yüz Tanıma giriş formunu kullanın. Daha fazla bilgi için Yüz sınırlı erişim sayfasına bakın.

.NET için Yüz Tanıma istemci kitaplığını kullanarak yüz tanımayı kullanmaya başlayın. Yüz Tanıma hizmeti, görüntülerdeki insan yüzlerini algılamak ve tanımak için gelişmiş algoritmalara erişmenizi sağlar. Paketi yüklemek için bu adımları izleyin ve uzak görüntüleri kullanarak temel yüz tanımaya yönelik örnek kodu deneyin.

Başvuru belgeleri | Kitaplık kaynak kodu | Paketi (NuGet)Örnekleri |

Önkoşullar

  • Azure aboneliği - Ücretsiz olarak oluşturun
  • Visual Studio IDE veya .NET Core'un geçerli sürümü.
  • Sorumlu yapay zeka koşullarını kabul edebilmeniz ve kaynak oluşturabilmeniz için Azure hesabınızın atanmış bir Cognitive Services Contributor rolü olmalıdır. Bu rolün hesabınıza atanmasını sağlamak için Rol atama belgelerindeki adımları izleyin veya yöneticinize başvurun.
  • Azure aboneliğinizi aldıktan sonra anahtarınızı ve uç noktanızı almak için Azure portalında bir Yüz Tanıma kaynağı oluşturun. Dağıtıldıktan sonra Kaynağa git'i seçin.
    • Uygulamanızı Yüz Tanıma API'sine bağlamak için oluşturduğunuz kaynaktan anahtara ve uç noktaya ihtiyacınız olacaktır.
    • Hizmeti denemek ve daha sonra üretim için ücretli bir katmana yükseltmek için ücretsiz fiyatlandırma katmanını (F0) kullanabilirsiniz.

Ortam değişkenlerini oluşturma

Bu örnekte, kimlik bilgilerinizi uygulamayı çalıştıran yerel makinedeki ortam değişkenlerine yazın.

Azure portalına gidin. Önkoşullar bölümünde oluşturduğunuz kaynak başarıyla dağıtıldıysa, Sonraki Adımlar'ın altında Kaynağa git'i seçin. Anahtarınızı ve uç noktanızı Anahtarlar ve Uç Nokta sayfasındaki Kaynak Yönetimi'nin altında bulabilirsiniz. Kaynak anahtarınız Azure abonelik kimliğiniz ile aynı değildir.

İpucu

Anahtarı doğrudan kodunuz içinde eklemeyin ve asla herkese açık olarak göndermeyin. Azure Key Vault gibi daha fazla kimlik doğrulama seçeneği için Azure AI hizmetleri güvenlik makalesine bakın.

Anahtarınızın ve uç noktanızın ortam değişkenini ayarlamak için bir konsol penceresi açın ve işletim sisteminiz ve geliştirme ortamınıza yönelik yönergeleri izleyin.

  1. Ortam değişkenini VISION_KEY ayarlamak için değerini kaynağınızın anahtarlarından biriyle değiştirin your-key .
  2. Ortam değişkenini VISION_ENDPOINT ayarlamak için değerini kaynağınızın uç noktasıyla değiştirin your-endpoint .
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint

Ortam değişkenlerini ekledikten sonra, konsol penceresi de dahil olmak üzere ortam değişkenlerini okuyacak tüm çalışan programları yeniden başlatmanız gerekebilir.

Yüzleri tanımlama ve doğrulama

  1. Yeni bir C# uygulaması oluşturma

    Visual Studio'yu kullanarak yeni bir .NET Core uygulaması oluşturun.

    İstemci kitaplığını yükleme

    Yeni bir proje oluşturduktan sonra, Çözüm Gezgini proje çözümüne sağ tıklayıp NuGet Paketlerini Yönet'i seçerek istemci kitaplığını yükleyin. Açılan paket yöneticisinde Gözat’ı seçip Ön sürümü dahil et seçeneğini işaretleyin ve Microsoft.Azure.CognitiveServices.Vision.Face için arama yapın. En son sürümü ve ardından Yükle'yi seçin.

  2. aşağıdaki kodu Program.cs dosyasına ekleyin.

    Not

    Giriş formunu kullanarak Yüz Tanıma hizmetine erişim almadıysanız, bu işlevlerden bazıları çalışmaz.

    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();
            }
        }
    }
    
  3. Uygulamayı çalıştırma

    IDE penceresinin üst kısmındaki Hata Ayıkla düğmesine tıklayarak uygulamayı çalıştırın.

Çıktı

========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.

İpucu

Yüz Tanıma API'si, doğası gereği statik olan önceden oluşturulmuş bir dizi model üzerinde çalışır (hizmet çalıştırıldığında modelin performansı gerilemez veya iyileşmez). Microsoft modelin arka ucu tamamen yeni bir model sürümüne geçmeden güncelleştirirse modelin ürettiği sonuçlar değişebilir. Modelin daha yeni bir sürümünden yararlanmak için PersonGroup'unuzu yeniden eğitebilir ve daha yeni modeli aynı kayıt görüntülerine sahip bir parametre olarak belirtebilirsiniz.

Kaynakları temizleme

Azure AI hizmetleri aboneliğini temizlemek ve kaldırmak istiyorsanız, kaynağı veya kaynak grubunu silebilirsiniz. Kaynak grubunun silinmesi, kaynak grubuyla ilişkili diğer tüm kaynakları da siler.

Bu hızlı başlangıçta oluşturduğunuz PersonGroup'u silmek için programınızda aşağıdaki kodu çalıştırın:

// At end, delete person groups in both regions (since testing only)
Console.WriteLine("========DELETE PERSON GROUP========");
Console.WriteLine();
DeletePersonGroup(client, personGroupId).Wait();

Silme yöntemini aşağıdaki kodla tanımlayın:

/*
 * 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}.");
}

Sonraki adımlar

Bu hızlı başlangıçta, temel yüz belirlemeyi yapmak için .NET için Yüz Tanıma istemci kitaplığını kullanmayı öğrendiniz. Ardından farklı yüz algılama modelleri ve kullanım örneğiniz için doğru modeli belirtme hakkında bilgi edinin.

JavaScript için Yüz Tanıma istemci kitaplığını kullanarak yüz tanımayı kullanmaya başlayın. Paketi yüklemek ve temel görevler için örnek kodu denemek için bu adımları izleyin. Yüz Tanıma hizmeti, görüntülerdeki insan yüzlerini algılamak ve tanımak için gelişmiş algoritmalara erişmenizi sağlar. Paketi yüklemek için bu adımları izleyin ve uzak görüntüleri kullanarak temel yüz tanımaya yönelik örnek kodu deneyin.

Başvuru belgeleri | Kitaplık kaynak kodu | Paketi (npm)Örnekler |

Önkoşullar

  • Azure aboneliği - Ücretsiz olarak oluşturun
  • Node.js'nin en son sürümü
  • Sorumlu yapay zeka koşullarını kabul edebilmeniz ve kaynak oluşturabilmeniz için Azure hesabınızın atanmış bir Cognitive Services Contributor rolü olmalıdır. Bu rolün hesabınıza atanmasını sağlamak için Rol atama belgelerindeki adımları izleyin veya yöneticinize başvurun.
  • Azure aboneliğinizi aldıktan sonra anahtarınızı ve uç noktanızı almak için Azure portalında Yüz Tanıma kaynağı oluşturun. Dağıtıldıktan sonra Kaynağa git'i seçin.
    • Uygulamanızı Yüz Tanıma API'sine bağlamak için oluşturduğunuz kaynaktan anahtara ve uç noktaya ihtiyacınız olacaktır.
    • Hizmeti denemek ve daha sonra üretim için ücretli bir katmana yükseltmek için ücretsiz fiyatlandırma katmanını (F0) kullanabilirsiniz.

Ortam değişkenlerini oluşturma

Bu örnekte, kimlik bilgilerinizi uygulamayı çalıştıran yerel makinedeki ortam değişkenlerine yazın.

Azure portalına gidin. Önkoşullar bölümünde oluşturduğunuz kaynak başarıyla dağıtıldıysa, Sonraki Adımlar'ın altında Kaynağa git'i seçin. Anahtarınızı ve uç noktanızı Anahtarlar ve Uç Nokta sayfasındaki Kaynak Yönetimi'nin altında bulabilirsiniz. Kaynak anahtarınız Azure abonelik kimliğiniz ile aynı değildir.

İpucu

Anahtarı doğrudan kodunuz içinde eklemeyin ve asla herkese açık olarak göndermeyin. Azure Key Vault gibi daha fazla kimlik doğrulama seçeneği için Azure AI hizmetleri güvenlik makalesine bakın.

Anahtarınızın ve uç noktanızın ortam değişkenini ayarlamak için bir konsol penceresi açın ve işletim sisteminiz ve geliştirme ortamınıza yönelik yönergeleri izleyin.

  1. Ortam değişkenini VISION_KEY ayarlamak için değerini kaynağınızın anahtarlarından biriyle değiştirin your-key .
  2. Ortam değişkenini VISION_ENDPOINT ayarlamak için değerini kaynağınızın uç noktasıyla değiştirin your-endpoint .
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint

Ortam değişkenlerini ekledikten sonra, konsol penceresi de dahil olmak üzere ortam değişkenlerini okuyacak tüm çalışan programları yeniden başlatmanız gerekebilir.

Yüzleri tanımlama ve doğrulama

  1. Yeni bir Node.js uygulaması oluşturma

    Konsol penceresinde (cmd, PowerShell veya Bash gibi), uygulamanız için yeni bir dizin oluşturun ve bu dizine gidin.

    mkdir myapp && cd myapp
    

    Bir package.json dosyası ile bir düğüm uygulaması oluşturmak için npm init komutunu çalıştırın.

    npm init
    
  2. ms-rest-azure ve azure-cognitiveservices-face npm paketlerini yükleyin:

    npm install @azure/cognitiveservices-face @azure/ms-rest-js uuid
    

    Uygulamanızın package.json dosyası bağımlılıklarla güncelleştirilir.

  3. adlı index.jsbir dosya oluşturun, dosyayı bir metin düzenleyicisinde açın ve aşağıdaki kodu yapıştırın:

    Not

    Giriş formunu kullanarak Yüz Tanıma hizmetine erişim almadıysanız, bu işlevlerden bazıları çalışmaz.

    '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();
    
  4. Uygulamayı hızlı başlangıç dosyanızdaki node komutuyla çalıştırın.

    node index.js
    

Çıktı

========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.

Kaynakları temizleme

Azure AI hizmetleri aboneliğini temizlemek ve kaldırmak istiyorsanız, kaynağı veya kaynak grubunu silebilirsiniz. Kaynak grubunun silinmesi, kaynak grubuyla ilişkili diğer tüm kaynakları da siler.

Sonraki adımlar

Bu hızlı başlangıçta, temel yüz belirlemeyi yapmak için JavaScript için Yüz Tanıma istemci kitaplığını kullanmayı öğrendiniz. Ardından farklı yüz algılama modelleri ve kullanım örneğiniz için doğru modeli belirtme hakkında bilgi edinin.

Python için Yüz Tanıma istemci kitaplığını kullanarak yüz tanımaya başlayın. Paketi yüklemek ve temel görevler için örnek kodu denemek için bu adımları izleyin. Yüz Tanıma hizmeti, görüntülerdeki insan yüzlerini algılamak ve tanımak için gelişmiş algoritmalara erişmenizi sağlar. Paketi yüklemek için bu adımları izleyin ve uzak görüntüleri kullanarak temel yüz tanımaya yönelik örnek kodu deneyin.

Başvuru belgeleri | Kitaplık kaynak kodu | Paketi (PiPy)Örnekler |

Önkoşullar

  • Azure aboneliği - Ücretsiz olarak oluşturun
  • Python 3.x
    • Python yüklemeniz pip içermelidir. Pip'in yüklü olup olmadığını denetlemek için komut satırında komutunu çalıştırabilirsiniz pip --version . Python'ın en son sürümünü yükleyerek pip alın.
  • Sorumlu yapay zeka koşullarını kabul edebilmeniz ve kaynak oluşturabilmeniz için Azure hesabınızın atanmış bir Cognitive Services Contributor rolü olmalıdır. Bu rolün hesabınıza atanmasını sağlamak için Rol atama belgelerindeki adımları izleyin veya yöneticinize başvurun.
  • Azure aboneliğinizi aldıktan sonra anahtarınızı ve uç noktanızı almak için Azure portalında bir Yüz Tanıma kaynağı oluşturun. Dağıtıldıktan sonra Kaynağa git'i seçin.
    • Uygulamanızı Yüz Tanıma API'sine bağlamak için oluşturduğunuz kaynaktan anahtara ve uç noktaya ihtiyacınız olacaktır.
    • Hizmeti denemek ve daha sonra üretim için ücretli bir katmana yükseltmek için ücretsiz fiyatlandırma katmanını (F0) kullanabilirsiniz.

Ortam değişkenlerini oluşturma

Bu örnekte, kimlik bilgilerinizi uygulamayı çalıştıran yerel makinedeki ortam değişkenlerine yazın.

Azure portalına gidin. Önkoşullar bölümünde oluşturduğunuz kaynak başarıyla dağıtıldıysa, Sonraki Adımlar'ın altında Kaynağa git'i seçin. Anahtarınızı ve uç noktanızı Anahtarlar ve Uç Nokta sayfasındaki Kaynak Yönetimi'nin altında bulabilirsiniz. Kaynak anahtarınız Azure abonelik kimliğiniz ile aynı değildir.

İpucu

Anahtarı doğrudan kodunuz içinde eklemeyin ve asla herkese açık olarak göndermeyin. Azure Key Vault gibi daha fazla kimlik doğrulama seçeneği için Azure AI hizmetleri güvenlik makalesine bakın.

Anahtarınızın ve uç noktanızın ortam değişkenini ayarlamak için bir konsol penceresi açın ve işletim sisteminiz ve geliştirme ortamınıza yönelik yönergeleri izleyin.

  1. Ortam değişkenini VISION_KEY ayarlamak için değerini kaynağınızın anahtarlarından biriyle değiştirin your-key .
  2. Ortam değişkenini VISION_ENDPOINT ayarlamak için değerini kaynağınızın uç noktasıyla değiştirin your-endpoint .
setx VISION_KEY your-key
setx VISION_ENDPOINT your-endpoint

Ortam değişkenlerini ekledikten sonra, konsol penceresi de dahil olmak üzere ortam değişkenlerini okuyacak tüm çalışan programları yeniden başlatmanız gerekebilir.

Yüzleri tanımlama ve doğrulama

  1. İstemci kitaplığını yükleme

    Python yükledikten sonra şunları kullanarak istemci kitaplığını yükleyebilirsiniz:

    pip install --upgrade azure-cognitiveservices-vision-face
    
  2. Yeni Python uygulaması oluşturma

    Örneğin, quickstart-file.py yeni bir Python betiği oluşturun. Ardından tercih ettiğiniz düzenleyicide veya IDE'de açın ve aşağıdaki kodu yapıştırın.

    Not

    Giriş formunu kullanarak Yüz Tanıma hizmetine erişim almadıysanız, bu işlevlerden bazıları çalışmaz.

    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.')
    
    
  3. komutunu kullanarak python yüz tanıma uygulamanızı uygulama dizininden çalıştırın.

    python quickstart-file.py
    

    İpucu

    Yüz Tanıma API'si, doğası gereği statik olan önceden oluşturulmuş bir dizi model üzerinde çalışır (hizmet çalıştırıldığında modelin performansı gerilemez veya iyileşmez). Microsoft modelin arka ucu tamamen yeni bir model sürümüne geçmeden güncelleştirirse modelin ürettiği sonuçlar değişebilir. Modelin daha yeni bir sürümünden yararlanmak için PersonGroup'unuzu yeniden eğitebilir ve daha yeni modeli aynı kayıt görüntülerine sahip bir parametre olarak belirtebilirsiniz.

Çıktı

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.

Kaynakları temizleme

Azure AI hizmetleri aboneliğini temizlemek ve kaldırmak istiyorsanız, kaynağı veya kaynak grubunu silebilirsiniz. Kaynak grubunun silinmesi, kaynak grubuyla ilişkili diğer tüm kaynakları da siler.

Bu hızlı başlangıçta oluşturduğunuz PersonGroup'u silmek için betiğinizde aşağıdaki kodu çalıştırın:

# 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()

Sonraki adımlar

Bu hızlı başlangıçta, temel yüz belirlemeyi yapmak için Python için Yüz Tanıma istemci kitaplığını kullanmayı öğrendiniz. Ardından farklı yüz algılama modelleri ve kullanım örneğiniz için doğru modeli belirtme hakkında bilgi edinin.

Yüz Tanıma REST API'sini kullanarak yüz tanımayı kullanmaya başlayın. Yüz Tanıma hizmeti, görüntülerdeki insan yüzlerini algılamak ve tanımak için gelişmiş algoritmalara erişmenizi sağlar.

Not

Bu hızlı başlangıçta REST API'yi çağırmak için cURL komutları kullanılır. Rest API'yi bir programlama dili kullanarak da çağırabilirsiniz. Yüz belirleme gibi karmaşık senaryoların dil SDK'sı kullanılarak uygulanması daha kolaydır. C#, Python, Java, JavaScript ve Go örnekleri için GitHub örneklerine bakın.

Önkoşullar

  • Azure aboneliği - Ücretsiz olarak oluşturun
  • Sorumlu yapay zeka koşullarını kabul edebilmeniz ve kaynak oluşturabilmeniz için Azure hesabınızın atanmış bir Cognitive Services Contributor rolü olmalıdır. Bu rolün hesabınıza atanmasını sağlamak için Rol atama belgelerindeki adımları izleyin veya yöneticinize başvurun.
  • Azure aboneliğinizi aldıktan sonra anahtarınızı ve uç noktanızı almak için Azure portalında bir Yüz Tanıma kaynağı oluşturun. Dağıtıldıktan sonra Kaynağa git'i seçin.
    • Uygulamanızı Yüz Tanıma API'sine bağlamak için oluşturduğunuz kaynaktan anahtara ve uç noktaya ihtiyacınız olacaktır. Anahtarınızı ve uç noktanızı hızlı başlangıcın ilerleyen bölümlerinde aşağıdaki koda yapıştıracaksınız.
    • Hizmeti denemek ve daha sonra üretim için ücretli bir katmana yükseltmek için ücretsiz fiyatlandırma katmanını (F0) kullanabilirsiniz.
  • PowerShell sürüm 6.0+ veya benzer bir komut satırı uygulaması.

Yüzleri tanımlama ve doğrulama

Not

Giriş formunu kullanarak Yüz Tanıma hizmetine erişim almadıysanız, bu işlevlerden bazıları çalışmaz.

  1. İlk olarak, kaynak yüzde Detect API'sini çağırın. Bu, büyük gruptan tanımlamaya çalışacağımız yüzdür. Aşağıdaki komutu bir metin düzenleyicisine kopyalayın, kendi anahtarınızı ekleyin ve ardından bir kabuk penceresine kopyalayıp çalıştırın.

    curl -v -X POST "https://westus.api.cognitive.microsoft.com/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\"}'
    

    Döndürülen yüz kimliği dizesini geçici bir konuma kaydedin. Sonunda tekrar kullanacaksınız.

  2. Ardından bir LargePersonGroup oluşturmanız gerekir. Bu nesne, birkaç kişinin toplu yüz verilerini depolar. Kendi anahtarınızı ekleyerek aşağıdaki komutu çalıştırın. İsteğe bağlı olarak, istek gövdesinde grubun adını ve meta verilerini değiştirin.

    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\"
    }"
    

    Oluşturulan grubun döndürülen kimliğini geçici bir konuma kaydedin.

  3. Ardından, gruba ait Kişi nesneleri oluşturacaksınız. Önceki adımda kendi anahtarınızı ve LargePersonGroup kimliğini ekleyerek aşağıdaki komutu çalıştırın. Bu komut "Family1-Dad" adlı bir Kişi oluşturur.

    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.\"
    }"
    

    Bu komutu çalıştırdıktan sonra, daha fazla Kişi nesnesi oluşturmak için farklı giriş verileriyle yeniden çalıştırın: "Family1-Mom", "Family1-Son", "Family1-Daughter", "Family2-Lady" ve "Family2-Man".

    Oluşturulan her Kişinin kimliklerini kaydedin; hangi kişi adının hangi kimliğe sahip olduğunu izlemek önemlidir.

  4. Ardından yeni yüzleri algılamanız ve bunları var olan Kişi nesneleriyle ilişkilendirmeniz gerekir. Aşağıdaki komut, görüntü Family1-Dad1.jpg bir yüzü algılar ve ilgili kişiye ekler. "Family1-Dad" Person nesnesini oluştururken döndürülen kimlik olarak değerini belirtmeniz personId gerekir. Resim adı, oluşturulan Kişinin adına karşılık gelir. Ayrıca uygun alanlara LargePersonGroup Kimliğini ve anahtarınızı girin.

    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-Dad1.jpg\"}'
    

    Ardından, yukarıdaki komutu farklı bir kaynak görüntüyle yeniden çalıştırın ve Kişi'yi hedefleyin. Kullanılabilir görüntüler şunlardır: 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 ve Family2-Man2.jpg. API çağrısında kimliğini belirttiğiniz Kişinin , istek gövdesindeki görüntü dosyasının adıyla eşleştiğinden emin olun.

    Bu adımın sonunda, her birinin doğrudan sağlanan görüntülerden algılanan bir veya daha fazla karşılık gelen yüzü olan birden çok Kişi nesnesine sahip olmanız gerekir.

  5. Ardından LargePersonGroup'ı geçerli yüz verileriyle eğitin. Eğitim işlemi modele, bazen birden çok kaynak görüntüden toplanan yüz özelliklerini tek tek her bir kişiyle ilişkilendirmeyi öğretir. Komutu çalıştırmadan önce LargePersonGroup Kimliğini ve anahtarınızı ekleyin.

    curl -v -X POST "https://westus.api.cognitive.microsoft.com/face/v1.0/largepersongroups/{largePersonGroupId}/train" -H "Ocp-Apim-Subscription-Key: {subscription key}"
    
  6. Şimdi ilk adımdaki kaynak yüz kimliğini ve LargePersonGroup Kimliğini kullanarak Tanımlama API'sini çağırmaya hazırsınız. Bu değerleri istek gövdesindeki uygun alanlara ekleyin ve anahtarınızı ekleyin.

    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
    }"
    

    Yanıt size kaynak yüzle tanımlanan kişiyi belirten bir Kişi Kimliği vermelidir. Bu, "Aile1-Baba" kişisine karşılık gelen kimlik olmalıdır, çünkü kaynak yüz o kişinin yüzüdür.

  7. Yüz doğrulama yapmak için, önceki adımda döndürülen Kişi Kimliğini, LargePersonGroup Kimliğini ve ayrıca kaynak yüz kimliğini kullanacaksınız. Bu değerleri istek gövdesindeki alanlara ekleyin ve anahtarınızı ekleyin.

    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\"
    }"
    

    Yanıt size bir boole doğrulama sonucu ve güvenilirlik değeri vermelidir.

Kaynakları temizleme

Bu alıştırmada oluşturduğunuz LargePersonGroup'u silmek için LargePersonGroup - Delete çağrısını çalıştırın.

curl -v -X DELETE "https://westus.api.cognitive.microsoft.com/face/v1.0/largepersongroups/{largePersonGroupId}" -H "Ocp-Apim-Subscription-Key: {subscription key}"

Azure AI hizmetleri aboneliğini temizlemek ve kaldırmak istiyorsanız, kaynağı veya kaynak grubunu silebilirsiniz. Kaynak grubunun silinmesi, kaynak grubuyla ilişkili diğer tüm kaynakları da siler.

Sonraki adımlar

Bu hızlı başlangıçta Yüz Tanıma REST API'sini kullanarak temel yüz tanıma görevlerini gerçekleştirmeyi öğrendiniz. Ardından farklı yüz algılama modelleri ve kullanım örneğiniz için doğru modeli belirtme hakkında bilgi edinin.