التشغيل السريع: استخدم خدمة Face

هام

إذا كنت تستخدم منتجات أو خدمات Microsoft لمعالجة البيانات البيومترية، فأنت مسؤول عن: (1) تقديم إشعار لموضوعات البيانات، بما في ذلك فيما يتعلق بفترات الاستبقاء والتدمير؛ (1) تقديم إشعار لمواضيع البيانات، بما في ذلك فيما يتعلق بفترات الاستبقاء والتدمير؛ (1) تقديم إشعار لمواضيع البيانات؛ (2) تقديم إشعار إلى مواضيع البيانات؛ (2) تقديم إشعار إلى مواضيع البيانات؛ '2' تقديم إشعار إلى موضوعات البيانات، بما في ذلك فيما يتعلق بفترات الاستبقاء والتدمير؛ '2' الحصول على موافقة من مواضيع البيانات؛ و(3) حذف البيانات البيومترية، كل ذلك حسب الاقتضاء والمطلوب بموجب متطلبات حماية البيانات المعمول بها. سيكون ل "البيانات البيومترية" المعنى المنصوص عليه في المادة 4 من القانون العام لحماية البيانات (GDPR) ومصطلحات مكافئة، إن أمكن، في متطلبات حماية البيانات الأخرى. للحصول على معلومات ذات صلة، راجع البيانات والخصوصية للوجه.

تنبيه

الوصول إلى خدمة Face محدود استنادا إلى معايير الأهلية والاستخدام من أجل دعم مبادئنا الذكاء الاصطناعي المسؤولة. تتوفر خدمة Face فقط للعملاء والشركاء المدارين من Microsoft. استخدم نموذج إدخال التعرف على الوجوه لتقديم طلب للوصول. لمزيد من المعلومات، راجع صفحة Face ذات الوصول المحدود.

ابدأ بالتعرف على الوجه باستخدام مكتبة عميل Face لـ ‎.NET. توفر لك خدمة Azure الذكاء الاصطناعي Face إمكانية الوصول إلى الخوارزميات المتقدمة للكشف عن الوجوه البشرية والتعرف عليها في الصور. اتبع هذه الخطوات لتثبيت الحزمة وتجربة التعليمة البرمجية المثال للتعرف على الوجه الأساسي باستخدام الصور البعيدة.

الوثائق المرجعية | التعليمات البرمجية لمصدر المكتبة | حزمة (NuGet) | نماذج

المتطلبات الأساسية

  • اشتراك Azure - إنشاء اشتراك مجانًا
  • إصدار Visual Studio IDE أو الإصدار الحالي من .NET Core.
  • يجب أن يكون Cognitive Services Contributor لحساب Azure دور معين لكي توافق على شروط الذكاء الاصطناعي المسؤولة وإنشاء مورد. للحصول على هذا الدور المعين لحسابك، اتبع الخطوات الواردة في وثائق تعيين الأدوار، أو اتصل بالمسؤول.
  • بمجرد أن يكون لديك اشتراك Azure، قم بإنشاء مورد Face في مدخل Microsoft Azure للحصول على المفتاح ونقطة النهاية. بعد انتشاره، حدد "Go to resource".
    • ستحتاج إلى المفتاح ونقطة النهاية من المورد الذي تنشئه لتوصيل التطبيق بواجهة برمجة تطبيقات Face.
    • يمكنك استخدام مستوى التسعير الحر (F0) لتجربة الخدمة، والترقية لاحقًا إلى مستوى مدفوع للإنتاج.

إنشاء متغيرات البيئة

في هذا المثال، اكتب بيانات الاعتماد الخاصة بك إلى متغيرات البيئة على الجهاز المحلي الذي يقوم بتشغيل التطبيق.

انتقل إلى مدخل Azure. إذا تم نشر المورد الذي أنشأته في قسم المتطلبات الأساسية بنجاح، فحدد الانتقال إلى المورد ضمن الخطوات التالية. يمكنك العثور على المفتاح ونقطة النهاية ضمن إدارة الموارد في صفحة المفاتيح ونقطة النهاية. مفتاح المورد الخاص بك ليس هو نفسه معرف اشتراك Azure الخاص بك.

تلميح

لا تقم بتضمين المفتاح مباشرة في التعليمات البرمجية الخاصة بك، ولا تنشره بشكل عام. راجع مقالة أمان خدمات Azure الذكاء الاصطناعي لمزيد من خيارات المصادقة مثل Azure Key Vault.

لتعيين متغير البيئة للمفتاح ونقطة النهاية، افتح نافذة وحدة التحكم واتبع الإرشادات الخاصة بنظام التشغيل وبيئة التطوير.

  1. لتعيين FACE_APIKEY متغير البيئة، استبدل <your_key> بأحد مفاتيح المورد الخاص بك.
  2. لتعيين FACE_ENDPOINT متغير البيئة، استبدل <your_endpoint> بنقطة النهاية للمورد الخاص بك.
setx FACE_APIKEY <your_key>
setx FACE_ENDPOINT <your_endpoint>

بعد إضافة متغيرات البيئة، قد تحتاج إلى إعادة تشغيل أي برامج قيد التشغيل ستقرأ متغيرات البيئة، بما في ذلك نافذة وحدة التحكم.

تحديد الوجوه والتحقق منها

  1. إنشاء تطبيق C# جديد

    باستخدام Visual Studio، قم بإنشاء تطبيق .NET Core جديد.

    تثبيت مكتبة العميل

    بمجرد إنشاء مشروع جديد، تثبيت مكتبة العميل بالنقر بزر الماوس الأيمن فوق حل المشروع في "Solution Explorer" وتحديد "Manage NuGet Packages". في إدارة الحزمة التي يتم فتحها، حدد تصفح، وحدد تضمين الإصدار التجريبي، وابحث عن Azure.AI.Vision.Face. حدد أحدث إصدار، ثم قم بتثبيت.

  2. أضف التعليمات البرمجية التالية إلى ملف Program.cs.

    إشعار

    إذا لم تكن قد حصلت على حق الوصول إلى خدمة Face باستخدام نموذج الاستيعاب، فلن تعمل بعض هذه الوظائف.

    using System.Net.Http.Headers;
    using System.Text;
    
    using Azure;
    using Azure.AI.Vision.Face;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace FaceQuickstart
    {
        class Program
        {
            static readonly string largePersonGroupId = 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.
            static readonly string SUBSCRIPTION_KEY = Environment.GetEnvironmentVariable("FACE_APIKEY") ?? "<apikey>";
            static readonly string ENDPOINT = Environment.GetEnvironmentVariable("FACE_ENDPOINT") ?? "<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.
                FaceRecognitionModel RECOGNITION_MODEL4 = FaceRecognitionModel.Recognition04;
    
                // Authenticate.
                FaceClient client = Authenticate(ENDPOINT, SUBSCRIPTION_KEY);
    
                // Identify - recognize a face(s) in a large person group (a large person group is created in this example).
                IdentifyInLargePersonGroup(client, IMAGE_BASE_URL, RECOGNITION_MODEL4).Wait();
    
                Console.WriteLine("End of quickstart.");
            }
    
            /*
             *	AUTHENTICATE
             *	Uses subscription key and region to create a client.
             */
            public static FaceClient Authenticate(string endpoint, string key)
            {
                return new FaceClient(new Uri(endpoint), new AzureKeyCredential(key));
            }
    
            // Detect faces from image url for recognition purposes. This is a helper method for other functions in this quickstart.
            // Parameter `returnFaceId` of `DetectAsync` must be set to `true` (by default) for recognition purposes.
            // Parameter `returnFaceAttributes` 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 Verify and Identify.
            // It will expire 24 hours after the detection call.
            private static async Task<List<FaceDetectionResult>> DetectFaceRecognize(FaceClient faceClient, string url, FaceRecognitionModel recognition_model)
            {
                // Detect faces from image URL.
                Response<IReadOnlyList<FaceDetectionResult>> response = await faceClient.DetectAsync(new Uri(url), FaceDetectionModel.Detection03, recognition_model, returnFaceId: true, [FaceAttributeType.QualityForRecognition]);
                IReadOnlyList<FaceDetectionResult> detectedFaces = response.Value;
                List<FaceDetectionResult> sufficientQualityFaces = new List<FaceDetectionResult>();
                foreach (FaceDetectionResult detectedFace in detectedFaces)
                {
                    var faceQualityForRecognition = detectedFace.FaceAttributes.QualityForRecognition;
                    if (faceQualityForRecognition.HasValue && (faceQualityForRecognition.Value != QualityForRecognition.Low))
                    {
                        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;
            }
    
            /*
             * IDENTIFY FACES
             * To identify faces, you need to create and define a large person group.
             * The Identify operation takes one or several face IDs from DetectedFace or PersistedFace and a LargePersonGroup 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 IdentifyInLargePersonGroup(FaceClient client, string url, FaceRecognitionModel 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" } }
                        };
                // A group photo that includes some of the persons you seek to identify from your dictionary.
                string sourceImageFileName = "identification1.jpg";
    
                // Create a large person group.
                Console.WriteLine($"Create a person group ({largePersonGroupId}).");
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", SUBSCRIPTION_KEY);
                using (var content = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new Dictionary<string, object> { ["name"] = largePersonGroupId, ["recognitionModel"] = recognitionModel.ToString() }))))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    await httpClient.PutAsync($"{ENDPOINT}/face/v1.0/largepersongroups/{largePersonGroupId}", content);
                }
                // The similar faces will be grouped into a single large person group person.
                foreach (var groupedFace in personDictionary.Keys)
                {
                    // Limit TPS
                    await Task.Delay(250);
                    string? personId = null;
                    using (var content = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new Dictionary<string, object> { ["name"] = groupedFace }))))
                    {
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        using (var response = await httpClient.PostAsync($"{ENDPOINT}/face/v1.0/largepersongroups/{largePersonGroupId}/persons", content))
                        {
                            string contentString = await response.Content.ReadAsStringAsync();
                            personId = (string?)(JsonConvert.DeserializeObject<Dictionary<string, object>>(contentString)?["personId"]);
                        }
                    }
                    Console.WriteLine($"Create a person group person '{groupedFace}'.");
    
                    // Add face to the large person group person.
                    foreach (var similarImage in personDictionary[groupedFace])
                    {
                        Console.WriteLine($"Check whether image is of sufficient quality for recognition");
                        Response<IReadOnlyList<FaceDetectionResult>> response = await client.DetectAsync(new Uri($"{url}{similarImage}"), FaceDetectionModel.Detection03, recognitionModel, returnFaceId: false, [FaceAttributeType.QualityForRecognition]);
                        IReadOnlyList<FaceDetectionResult> detectedFaces1 = response.Value;
                        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;
                        }
    
                        if (detectedFaces1.Count != 1)
                        {
                            continue;
                        }
    
                        // add face to the large person group
                        Console.WriteLine($"Add face to the person group person({groupedFace}) from image `{similarImage}`");
                        using (var content = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new Dictionary<string, object> { ["url"] = $"{url}{similarImage}" }))))
                        {
                            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                            await httpClient.PostAsync($"{ENDPOINT}/face/v1.0/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces?detectionModel=detection_03", content);
                        }
                    }
                }
    
                // Start to train the large person group.
                Console.WriteLine();
                Console.WriteLine($"Train person group {largePersonGroupId}.");
                await httpClient.PostAsync($"{ENDPOINT}/face/v1.0/largepersongroups/{largePersonGroupId}/train", null);
    
                // Wait until the training is completed.
                while (true)
                {
                    await Task.Delay(1000);
                    string? trainingStatus = null;
                    using (var response = await httpClient.GetAsync($"{ENDPOINT}/face/v1.0/largepersongroups/{largePersonGroupId}/training"))
                    {
                        string contentString = await response.Content.ReadAsStringAsync();
                        trainingStatus = (string?)(JsonConvert.DeserializeObject<Dictionary<string, object>>(contentString)?["status"]);
                    }
                    Console.WriteLine($"Training status: {trainingStatus}.");
                    if ("succeeded".Equals(trainingStatus)) { break; }
                }
                Console.WriteLine();
    
                Console.WriteLine("Pausing for 60 seconds to avoid triggering rate limit on free account...");
                await Task.Delay(60000);
    
                List<Guid> sourceFaceIds = new List<Guid>();
                // Detect faces from source image url.
                List<FaceDetectionResult> 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 large person group.
                List<Dictionary<string, object>> identifyResults = new List<Dictionary<string, object>>();
                using (var content = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new Dictionary<string, object> { ["faceIds"] = sourceFaceIds, ["largePersonGroupId"] = largePersonGroupId }))))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    using (var response = await httpClient.PostAsync($"{ENDPOINT}/face/v1.0/identify", content))
                    {
                        string contentString = await response.Content.ReadAsStringAsync();
                        identifyResults = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(contentString) ?? [];
                    }
                }
    
                foreach (var identifyResult in identifyResults)
                {
                    string faceId = (string)identifyResult["faceId"];
                    List<Dictionary<string, object>> candidates = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(((JArray)identifyResult["candidates"]).ToString()) ?? [];
                    if (candidates.Count == 0)
                    {
                        Console.WriteLine($"No person is identified for the face in: {sourceImageFileName} - {faceId},");
                        continue;
                    }
    
                    string? personName = null;
                    using (var response = await httpClient.GetAsync($"{ENDPOINT}/face/v1.0/largepersongroups/{largePersonGroupId}/persons/{candidates.First()["personId"]}"))
                    {
                        string contentString = await response.Content.ReadAsStringAsync();
                        personName = (string?)(JsonConvert.DeserializeObject<Dictionary<string, object>>(contentString)?["name"]);
                    }
                    Console.WriteLine($"Person '{personName}' is identified for the face in: {sourceImageFileName} - {faceId}," +
                        $" confidence: {candidates.First()["confidence"]}.");
    
                    Dictionary<string, object> verifyResult = new Dictionary<string, object>();
                    using (var content = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new Dictionary<string, object> { ["faceId"] = faceId, ["personId"] = candidates.First()["personId"], ["largePersonGroupId"] = largePersonGroupId }))))
                    {
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        using (var response = await httpClient.PostAsync($"{ENDPOINT}/face/v1.0/verify", content))
                        {
                            string contentString = await response.Content.ReadAsStringAsync();
                            verifyResult = JsonConvert.DeserializeObject<Dictionary<string, object>>(contentString) ?? [];
                        }
                    }
                    Console.WriteLine($"Verification result: is a match? {verifyResult["isIdentical"]}. confidence: {verifyResult["confidence"]}");
                }
                Console.WriteLine();
    
                // Delete large person group.
                Console.WriteLine("========DELETE PERSON GROUP========");
                Console.WriteLine();
                await httpClient.DeleteAsync($"{ENDPOINT}/face/v1.0/largepersongroups/{largePersonGroupId}");
                Console.WriteLine($"Deleted the person group {largePersonGroupId}.");
                Console.WriteLine();
            }
        }
    }
    
  3. شغّل التطبيق

    قم بتشغيل التطبيق بنقر الزر Debug أعلى نافذة IDE.

المخرجات

========IDENTIFY FACES========

Create a person group (18d1c443-a01b-46a4-9191-121f74a831cd).
Create a person group person 'Family1-Dad'.
Check whether image is of sufficient quality for recognition
Add face to the person group person(Family1-Dad) from image `Family1-Dad1.jpg`
Check whether image is of sufficient quality for recognition
Add face to the person group person(Family1-Dad) from image `Family1-Dad2.jpg`
Create a person group person 'Family1-Mom'.
Check whether image is of sufficient quality for recognition
Add face to the person group person(Family1-Mom) from image `Family1-Mom1.jpg`
Check whether image is of sufficient quality for recognition
Add face to the person group person(Family1-Mom) from image `Family1-Mom2.jpg`
Create a person group person 'Family1-Son'.
Check whether image is of sufficient quality for recognition
Add face to the person group person(Family1-Son) from image `Family1-Son1.jpg`
Check whether image is of sufficient quality for recognition
Add face to the person group person(Family1-Son) from image `Family1-Son2.jpg`

Train person group 18d1c443-a01b-46a4-9191-121f74a831cd.
Training status: succeeded.

Pausing for 60 seconds to avoid triggering rate limit on free account...
4 face(s) with 4 having sufficient quality for recognition detected from image `identification1.jpg`
Person 'Family1-Dad' is identified for the face in: identification1.jpg - ad813534-9141-47b4-bfba-24919223966f, confidence: 0.96807.
Verification result: is a match? True. confidence: 0.96807
Person 'Family1-Mom' is identified for the face in: identification1.jpg - 1a39420e-f517-4cee-a898-5d968dac1a7e, confidence: 0.96902.
Verification result: is a match? True. confidence: 0.96902
No person is identified for the face in: identification1.jpg - 889394b1-e30f-4147-9be1-302beb5573f3,
Person 'Family1-Son' is identified for the face in: identification1.jpg - 0557d87b-356c-48a8-988f-ce0ad2239aa5, confidence: 0.9281.
Verification result: is a match? True. confidence: 0.9281

========DELETE PERSON GROUP========

Deleted the person group 18d1c443-a01b-46a4-9191-121f74a831cd.

End of quickstart.

تلميح

يتم تشغيل واجهة برمجة التطبيقات Face على مجموعة من الطرازات التي تم إنشاؤها مسبقًا والثابتة بطبيعتها (لن يتراجع أداء الطراز أو يتحسن في أثناء تشغيل الخدمة). قد تتغير النتائج التي ينتجها الطراز إذا قامت Microsoft بتحديث الخلفية للطراز دون الترحيل إلى إصدار طراز جديد تمامًا. للاستفادة من إصدار أحدث من طراز، يمكنك إعادة تدريب PersonGroup، وتحديد الطراز الأحدث كمعلمة بنفس صور التسجيل.

تنظيف الموارد

إذا كنت ترغب في تنظيف اشتراك خدمات Azure الذكاء الاصطناعي وإزالته، يمكنك حذف المورد أو مجموعة الموارد. يؤدي حذف مجموعة الموارد إلى حذف أية موارد أخرى مقترنة بها أيضًا.

الخطوات التالية

في هذا البدء السريع، تعلمت كيفية استخدام مكتبة عميل Face لـ ‎.NET للقيام بالتعرف على الوجه الأساسي. بعد ذلك، تعرفت على نماذج كشف الوجه المختلفة وكيفية تحديد الطراز المناسب لحالة الاستخدام.

ابدأ بالتعرف على الوجه باستخدام مكتبة عميل Face لـ Python. اتبع هذه الخطوات لتثبيت الحزمة وتجربة نموذج تعليمات البرمجة للمهام الأساسية. توفر لك خدمة Face إمكانية الوصول إلى الخوارزميات المتقدمة للكشف عن الوجوه البشرية والتعرف عليها في الصور. اتبع هذه الخطوات لتثبيت الحزمة وتجربة التعليمة البرمجية المثال للتعرف على الوجه الأساسي باستخدام الصور البعيدة.

Reference documentation | Library source code | Package (PiPy) | Samples

المتطلبات الأساسية

  • اشتراك Azure - إنشاء اشتراك مجانًا
  • Python 3.x
    • يجب أن يتضمن تثبيت Python خاصتك pip. يمكنك التحقق مما إذا كانت لديك نقطة مثبتة عن طريق تشغيل pip --version على سطر الأوامر. الحصول على نقطة عن طريق تثبيت أحدث إصدار من Python.
  • يجب أن يكون Cognitive Services Contributor لحساب Azure دور معين لكي توافق على شروط الذكاء الاصطناعي المسؤولة وإنشاء مورد. للحصول على هذا الدور المعين لحسابك، اتبع الخطوات الواردة في وثائق تعيين الأدوار، أو اتصل بالمسؤول.
  • بمجرد اشتراكك في Azure، أنشئ مورد Face في مدخل Microsoft Azure للحصول على المفتاح ونقطة النهاية. بعد انتشاره، حدد "Go to resource".
    • ستحتاج إلى المفتاح ونقطة النهاية من المورد الذي تنشئه لتوصيل التطبيق بواجهة برمجة تطبيقات Face.
    • يمكنك استخدام مستوى التسعير الحر (F0) لتجربة الخدمة، والترقية لاحقًا إلى مستوى مدفوع للإنتاج.

إنشاء متغيرات البيئة

في هذا المثال، اكتب بيانات الاعتماد الخاصة بك إلى متغيرات البيئة على الجهاز المحلي الذي يقوم بتشغيل التطبيق.

انتقل إلى مدخل Azure. إذا تم نشر المورد الذي أنشأته في قسم المتطلبات الأساسية بنجاح، فحدد الانتقال إلى المورد ضمن الخطوات التالية. يمكنك العثور على المفتاح ونقطة النهاية ضمن إدارة الموارد في صفحة المفاتيح ونقطة النهاية. مفتاح المورد الخاص بك ليس هو نفسه معرف اشتراك Azure الخاص بك.

تلميح

لا تقم بتضمين المفتاح مباشرة في التعليمات البرمجية الخاصة بك، ولا تنشره بشكل عام. راجع مقالة أمان خدمات Azure الذكاء الاصطناعي لمزيد من خيارات المصادقة مثل Azure Key Vault.

لتعيين متغير البيئة للمفتاح ونقطة النهاية، افتح نافذة وحدة التحكم واتبع الإرشادات الخاصة بنظام التشغيل وبيئة التطوير.

  1. لتعيين FACE_APIKEY متغير البيئة، استبدل <your_key> بأحد مفاتيح المورد الخاص بك.
  2. لتعيين FACE_ENDPOINT متغير البيئة، استبدل <your_endpoint> بنقطة النهاية للمورد الخاص بك.
setx FACE_APIKEY <your_key>
setx FACE_ENDPOINT <your_endpoint>

بعد إضافة متغيرات البيئة، قد تحتاج إلى إعادة تشغيل أي برامج قيد التشغيل ستقرأ متغيرات البيئة، بما في ذلك نافذة وحدة التحكم.

تحديد الوجوه والتحقق منها

  1. تثبيت مكتبة العميل

    بعد تثبيت Python، يمكنك تثبيت مكتبة العميل عن طريق:

    pip install --upgrade azure-ai-vision-face
    
  2. إنشاء تطبيق Python جديد

    قم بإنشاء برنامج Python نصي جديد quickstart-file.py، على سبيل المثال. ثم افتحه في المحرر المفضل لديك أو IDE والصقه في التعليمة البرمجية التالية.

    إشعار

    إذا لم تكن قد حصلت على حق الوصول إلى خدمة Face باستخدام نموذج الاستيعاب، فلن تعمل بعض هذه الوظائف.

    import os
    import time
    import uuid
    import requests
    
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.vision.face import FaceClient
    from azure.ai.vision.face.models import (
        FaceAttributeTypeRecognition04,
        FaceDetectionModel,
        FaceRecognitionModel,
        QualityForRecognition,
    )
    
    
    # This key will serve all examples in this document.
    KEY = os.environ["FACE_APIKEY"]
    
    # This endpoint will be used in all examples in this quickstart.
    ENDPOINT = os.environ["FACE_ENDPOINT"]
    
    # Used in the Large Person Group Operations and Delete Large Person Group examples.
    # LARGE_PERSON_GROUP_ID should be all lowercase and alphanumeric. For example, 'mygroupname' (dashes are OK).
    LARGE_PERSON_GROUP_ID = str(uuid.uuid4())  # assign a random ID (or name it anything)
    
    HEADERS = {"Ocp-Apim-Subscription-Key": KEY, "Content-Type": "application/json"}
    
    # Create an authenticated FaceClient.
    with FaceClient(endpoint=ENDPOINT, credential=AzureKeyCredential(KEY)) as face_client:
        '''
        Create the LargePersonGroup
        '''
        # Create empty Large Person Group. Large Person Group ID must be lower case, alphanumeric, and/or with '-', '_'.
        print("Person group:", LARGE_PERSON_GROUP_ID)
        response = requests.put(
            ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}",
            headers=HEADERS,
            json={"name": LARGE_PERSON_GROUP_ID, "recognitionModel": "recognition_04"})
        response.raise_for_status()
    
        # Define woman friend
        response = requests.post(ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}/persons", headers=HEADERS, json={"name": "Woman"})
        response.raise_for_status()
        woman = response.json()
        # Define man friend
        response = requests.post(ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}/persons", headers=HEADERS, json={"name": "Man"})
        response.raise_for_status()
        man = response.json()
        # Define child friend
        response = requests.post(ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}/persons", headers=HEADERS, json={"name": "Child"})
        response.raise_for_status()
        child = response.json()
    
        '''
        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",  # noqa: E501
            "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Mom2.jpg",  # noqa: E501
        ]
        man_images = [
            "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Dad1.jpg",  # noqa: E501
            "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Dad2.jpg",  # noqa: E501
        ]
        child_images = [
            "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Son1.jpg",  # noqa: E501
            "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Son2.jpg",  # noqa: E501
        ]
    
        # 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.detect_from_url(
                url=image,
                detection_model=FaceDetectionModel.DETECTION_03,
                recognition_model=FaceRecognitionModel.RECOGNITION_04,
                return_face_id=True,
                return_face_attributes=[FaceAttributeTypeRecognition04.QUALITY_FOR_RECOGNITION])
            for face in detected_faces:
                if face.face_attributes.quality_for_recognition != QualityForRecognition.HIGH:
                    sufficientQuality = False
                    break
    
            if not sufficientQuality:
                continue
    
            if len(detected_faces) != 1:
                continue
    
            response = requests.post(
                ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}/persons/{woman['personId']}/persistedFaces",
                headers=HEADERS,
                json={"url": image})
            response.raise_for_status()
            print(f"face {face.face_id} added to person {woman['personId']}")
    
    
        # 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.detect_from_url(
                url=image,
                detection_model=FaceDetectionModel.DETECTION_03,
                recognition_model=FaceRecognitionModel.RECOGNITION_04,
                return_face_id=True,
                return_face_attributes=[FaceAttributeTypeRecognition04.QUALITY_FOR_RECOGNITION])
            for face in detected_faces:
                if face.face_attributes.quality_for_recognition != QualityForRecognition.HIGH:
                    sufficientQuality = False
                    break
    
            if not sufficientQuality:
                continue
    
            if len(detected_faces) != 1:
                continue
    
            response = requests.post(
                ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}/persons/{man['personId']}/persistedFaces",
                headers=HEADERS,
                json={"url": image})
            response.raise_for_status()
            print(f"face {face.face_id} added to person {man['personId']}")
    
        # 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.detect_from_url(
                url=image,
                detection_model=FaceDetectionModel.DETECTION_03,
                recognition_model=FaceRecognitionModel.RECOGNITION_04,
                return_face_id=True,
                return_face_attributes=[FaceAttributeTypeRecognition04.QUALITY_FOR_RECOGNITION])
            for face in detected_faces:
                if face.face_attributes.quality_for_recognition != QualityForRecognition.HIGH:
                    sufficientQuality = False
                    break
            if not sufficientQuality:
                continue
    
            if len(detected_faces) != 1:
                continue
    
            response = requests.post(
                ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}/persons/{child['personId']}/persistedFaces",
                headers=HEADERS,
                json={"url": image})
            response.raise_for_status()
            print(f"face {face.face_id} added to person {child['personId']}")
    
        '''
        Train LargePersonGroup
        '''
        # Train the large person group
        print(f"Train the person group {LARGE_PERSON_GROUP_ID}")
        response = requests.post(ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}/train", headers=HEADERS)
        response.raise_for_status()
    
        while (True):
            response = requests.get(ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}/training", headers=HEADERS)
            response.raise_for_status()
            training_status = response.json()["status"]
            if training_status == "succeeded":
                break
        print(f"The person group {LARGE_PERSON_GROUP_ID} is trained successfully.")
    
        '''
        Identify a face against a defined LargePersonGroup
        '''
        # Group image for testing against
        test_image = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/identification1.jpg"  # noqa: E501
    
        print("Pausing for 60 seconds to avoid triggering rate limit on free account...")
        time.sleep(60)
    
        # Detect faces
        face_ids = []
        # We use detection model 03 to get better performance, recognition model 04 to support quality for
        # recognition attribute.
        faces = face_client.detect_from_url(
            url=test_image,
            detection_model=FaceDetectionModel.DETECTION_03,
            recognition_model=FaceRecognitionModel.RECOGNITION_04,
            return_face_id=True,
            return_face_attributes=[FaceAttributeTypeRecognition04.QUALITY_FOR_RECOGNITION])
        for face in faces:
            # Only take the face if it is of sufficient quality.
            if face.face_attributes.quality_for_recognition != QualityForRecognition.LOW:
                face_ids.append(face.face_id)
    
        # Identify faces
        response = requests.post(
            ENDPOINT + f"/face/v1.0/identify",
            headers=HEADERS,
            json={"faceIds": face_ids, "largePersonGroupId": LARGE_PERSON_GROUP_ID})
        response.raise_for_status()
        results = response.json()
        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(f"Person is identified for face ID {identifiedFace['faceId']} in image, with a confidence of "
                      f"{identifiedFace['candidates'][0]['confidence']}.")  # Get topmost confidence score
    
                # Verify faces
                response = requests.post(
                    ENDPOINT + f"/face/v1.0/verify",
                    headers=HEADERS,
                    json={"faceId": identifiedFace["faceId"], "personId": identifiedFace["candidates"][0]["personId"], "largePersonGroupId": LARGE_PERSON_GROUP_ID})
                response.raise_for_status()
                verify_result = response.json()
                print(f"verification result: {verify_result['isIdentical']}. confidence: {verify_result['confidence']}")
            else:
                print(f"No person identified for face ID {identifiedFace['faceId']} in image.")
    
        print()
    
        # Delete the large person group
        response = requests.delete(ENDPOINT + f"/face/v1.0/largepersongroups/{LARGE_PERSON_GROUP_ID}", headers=HEADERS)
        response.raise_for_status()
        print(f"The person group {LARGE_PERSON_GROUP_ID} is deleted.")
    
        print()
        print("End of quickstart.")
    
    
  3. قم بتشغيل التطبيق التعرف على الوجه الخاص بك من دليل التطبيق باستخدام الأمرpython.

    python quickstart-file.py
    

    تلميح

    يتم تشغيل واجهة برمجة التطبيقات Face على مجموعة من الطرازات التي تم إنشاؤها مسبقًا والثابتة بطبيعتها (لن يتراجع أداء الطراز أو يتحسن في أثناء تشغيل الخدمة). قد تتغير النتائج التي ينتجها الطراز إذا قامت Microsoft بتحديث الخلفية للطراز دون الترحيل إلى إصدار طراز جديد تمامًا. للاستفادة من إصدار أحدث من طراز، يمكنك إعادة تدريب PersonGroup، وتحديد الطراز الأحدث كمعلمة بنفس صور التسجيل.

المخرجات

Person group: ad12b2db-d892-48ec-837a-0e7168c18224
face 335a2cb1-5211-4c29-9c45-776dd014b2af added to person 9ee65510-81a5-47e5-9e50-66727f719465
face df57eb50-4a13-4f93-b804-cd108327ad5a added to person 9ee65510-81a5-47e5-9e50-66727f719465
face d8b7b8b8-3ca6-4309-b76e-eeed84f7738a added to person 00651036-4236-4004-88b9-11466c251548
face dffbb141-f40b-4392-8785-b6c434fa534e added to person 00651036-4236-4004-88b9-11466c251548
face 9cdac36e-5455-447b-a68d-eb1f5e2ec27d added to person 23614724-b132-407a-aaa0-67003987ce93
face d8208412-92b7-4b8d-a2f8-3926c839c87e added to person 23614724-b132-407a-aaa0-67003987ce93
Train the person group ad12b2db-d892-48ec-837a-0e7168c18224
The person group ad12b2db-d892-48ec-837a-0e7168c18224 is trained successfully.
Pausing for 60 seconds to avoid triggering rate limit on free account...
Identifying faces in image
Person is identified for face ID bc52405a-5d83-4500-9218-557468ccdf99 in image, with a confidence of 0.96726.
verification result: True. confidence: 0.96726
Person is identified for face ID dfcc3fc8-6252-4f3a-8205-71466f39d1a7 in image, with a confidence of 0.96925.
verification result: True. confidence: 0.96925
No person identified for face ID 401c581b-a178-45ed-8205-7692f6eede88 in image.
Person is identified for face ID 8809d9c7-e362-4727-8c95-e1e44f5c2e8a in image, with a confidence of 0.92898.
verification result: True. confidence: 0.92898

The person group ad12b2db-d892-48ec-837a-0e7168c18224 is deleted.

End of quickstart.

تنظيف الموارد

إذا كنت ترغب في تنظيف اشتراك خدمات Azure الذكاء الاصطناعي وإزالته، يمكنك حذف المورد أو مجموعة الموارد. يؤدي حذف مجموعة الموارد إلى حذف أية موارد أخرى مقترنة بها أيضًا.

الخطوات التالية

في هذا البدء السريع، تعلمت كيفية استخدام مكتبة عميل Face لـ ‎.Python للقيام بالتعرف على الوجه الأساسي. بعد ذلك، تعرفت على نماذج كشف الوجه المختلفة وكيفية تحديد الطراز المناسب لحالة الاستخدام.

ابدأ بالتعرف على الوجه باستخدام مكتبة عميل Face لـ JavaScript. اتبع هذه الخطوات لتثبيت الحزمة وتجربة نموذج تعليمات البرمجة للمهام الأساسية. توفر لك خدمة Face إمكانية الوصول إلى الخوارزميات المتقدمة للكشف عن الوجوه البشرية والتعرف عليها في الصور. اتبع هذه الخطوات لتثبيت الحزمة وتجربة التعليمة البرمجية المثال للتعرف على الوجه الأساسي باستخدام الصور البعيدة.

الوثائق المرجعية | التعليمات البرمجية لمصدر المكتبة | الحزمة (npm) | النماذج

المتطلبات الأساسية

  • اشتراك Azure - إنشاء اشتراك مجانًا
  • أحدث نسخة من Node.js.
  • يجب أن يكون Cognitive Services Contributor لحساب Azure دور معين لكي توافق على شروط الذكاء الاصطناعي المسؤولة وإنشاء مورد. للحصول على هذا الدور المعين لحسابك، اتبع الخطوات الواردة في وثائق تعيين الأدوار، أو اتصل بالمسؤول.
  • بمجرد اشتراكك في Azure، أنشئ مورد Face في مدخل Azure للحصول على المفتاح ونقطة النهاية. بعد انتشاره، حدد "Go to resource".
    • ستحتاج إلى المفتاح ونقطة النهاية من المورد الذي تنشئه لتوصيل التطبيق بواجهة برمجة تطبيقات Face.
    • يمكنك استخدام مستوى التسعير الحر (F0) لتجربة الخدمة، والترقية لاحقًا إلى مستوى مدفوع للإنتاج.

إنشاء متغيرات البيئة

في هذا المثال، اكتب بيانات الاعتماد الخاصة بك إلى متغيرات البيئة على الجهاز المحلي الذي يقوم بتشغيل التطبيق.

انتقل إلى مدخل Azure. إذا تم نشر المورد الذي أنشأته في قسم المتطلبات الأساسية بنجاح، فحدد الانتقال إلى المورد ضمن الخطوات التالية. يمكنك العثور على المفتاح ونقطة النهاية ضمن إدارة الموارد في صفحة المفاتيح ونقطة النهاية. مفتاح المورد الخاص بك ليس هو نفسه معرف اشتراك Azure الخاص بك.

تلميح

لا تقم بتضمين المفتاح مباشرة في التعليمات البرمجية الخاصة بك، ولا تنشره بشكل عام. راجع مقالة أمان خدمات Azure الذكاء الاصطناعي لمزيد من خيارات المصادقة مثل Azure Key Vault.

لتعيين متغير البيئة للمفتاح ونقطة النهاية، افتح نافذة وحدة التحكم واتبع الإرشادات الخاصة بنظام التشغيل وبيئة التطوير.

  1. لتعيين FACE_APIKEY متغير البيئة، استبدل <your_key> بأحد مفاتيح المورد الخاص بك.
  2. لتعيين FACE_ENDPOINT متغير البيئة، استبدل <your_endpoint> بنقطة النهاية للمورد الخاص بك.
setx FACE_APIKEY <your_key>
setx FACE_ENDPOINT <your_endpoint>

بعد إضافة متغيرات البيئة، قد تحتاج إلى إعادة تشغيل أي برامج قيد التشغيل ستقرأ متغيرات البيئة، بما في ذلك نافذة وحدة التحكم.

تحديد الوجوه والتحقق منها

  1. إنشاء تطبيق Node.js جديد

    في إطار نافذة وحدة التحكم (مثل cmd أو PowerShell أو Bash)، يمكنك إنشاء دليل جديد لتطبيقك وانتقل إليه.

    mkdir myapp && cd myapp
    

    شغّل الأمر npm init لإنشاء تطبيق node باستخدام ملف package.json.

    npm init
    
  2. @azure-rest/ai-vision-face تثبيت حزم npm:

    npm install @azure-rest/ai-vision-face
    

    يتم تحديث ملف تطبيقك package.json باستخدام التبعيات.

  3. أنشئ ملفًا باسم index.js، وافتحه في محرر نص، والصقه في التعليمات البرمجية التالية:

    إشعار

    إذا لم تكن قد حصلت على حق الوصول إلى خدمة Face باستخدام نموذج الاستيعاب، فلن تعمل بعض هذه الوظائف.

    const { randomUUID } = require("crypto");
    
    const { AzureKeyCredential } = require("@azure/core-auth");
    
    const createFaceClient = require("@azure-rest/ai-vision-face").default,
      { getLongRunningPoller } = require("@azure-rest/ai-vision-face");
    
    const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    
    const main = async () => {
      const endpoint = process.env["FACE_ENDPOINT"] ?? "<endpoint>";
      const apikey = process.env["FACE_APIKEY"] ?? "<apikey>";
      const credential = new AzureKeyCredential(apikey);
      const client = createFaceClient(endpoint, credential);
    
      const imageBaseUrl =
        "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/";
      const largePersonGroupId = randomUUID();
    
      console.log("========IDENTIFY FACES========");
      console.log();
    
      // Create a dictionary for all your images, grouping similar ones under the same key.
      const personDictionary = {
        "Family1-Dad": ["Family1-Dad1.jpg", "Family1-Dad2.jpg"],
        "Family1-Mom": ["Family1-Mom1.jpg", "Family1-Mom2.jpg"],
        "Family1-Son": ["Family1-Son1.jpg", "Family1-Son2.jpg"],
      };
    
      // A group photo that includes some of the persons you seek to identify from your dictionary.
      const sourceImageFileName = "identification1.jpg";
    
      // Create a large person group.
      console.log(`Creating a person group with ID: ${largePersonGroupId}`);
      await client.path("/largepersongroups/{largePersonGroupId}", largePersonGroupId).put({
        body: {
          name: largePersonGroupId,
          recognitionModel: "recognition_04",
        },
      });
    
      // The similar faces will be grouped into a single large person group person.
      console.log("Adding faces to person group...");
      await Promise.all(
        Object.keys(personDictionary).map(async (name) => {
          console.log(`Create a persongroup person: ${name}`);
          const createLargePersonGroupPersonResponse = await client
            .path("/largepersongroups/{largePersonGroupId}/persons", largePersonGroupId)
            .post({
              body: { name },
            });
    
          const { personId } = createLargePersonGroupPersonResponse.body;
    
          await Promise.all(
            personDictionary[name].map(async (similarImage) => {
              // Check if the image is of sufficent quality for recognition.
              const detectResponse = await client.path("/detect").post({
                contentType: "application/json",
                queryParameters: {
                  detectionModel: "detection_03",
                  recognitionModel: "recognition_04",
                  returnFaceId: false,
                  returnFaceAttributes: ["qualityForRecognition"],
                },
                body: { url: `${imageBaseUrl}${similarImage}` },
              });
    
              const sufficientQuality = detectResponse.body.every(
                (face) => face.faceAttributes?.qualityForRecognition === "high",
              );
              if (!sufficientQuality) {
                return;
              }
    
              if (detectResponse.body.length != 1) {
                return;
              }
    
              // Quality is sufficent, add to group.
              console.log(
                `Add face to the person group person: (${name}) from image: (${similarImage})`,
              );
              await client
                .path(
                  "/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces",
                  largePersonGroupId,
                  personId,
                )
                .post({
                  queryParameters: { detectionModel: "detection_03" },
                  body: { url: `${imageBaseUrl}${similarImage}` },
                });
            }),
          );
        }),
      );
      console.log("Done adding faces to person group.");
    
      // Start to train the large person group.
      console.log();
      console.log(`Training person group: ${largePersonGroupId}`);
      const trainResponse = await client
        .path("/largepersongroups/{largePersonGroupId}/train", largePersonGroupId)
        .post();
      const poller = await getLongRunningPoller(client, trainResponse);
      await poller.pollUntilDone();
      console.log(`Training status: ${poller.getOperationState().status}`);
      if (poller.getOperationState().status !== "succeeded") {
        return;
      }
    
      console.log("Pausing for 60 seconds to avoid triggering rate limit on free account...");
      await sleep(60000);
    
      // Detect faces from source image url and only take those with sufficient quality for recognition.
      const detectResponse = await client.path("/detect").post({
        contentType: "application/json",
        queryParameters: {
          detectionModel: "detection_03",
          recognitionModel: "recognition_04",
          returnFaceId: true,
          returnFaceAttributes: ["qualityForRecognition"],
        },
        body: { url: `${imageBaseUrl}${sourceImageFileName}` },
      });
      const faceIds = detectResponse.body.filter((face) => face.faceAttributes?.qualityForRecognition !== "low").map((face) => face.faceId);
    
      // Identify the faces in a large person group.
      const identifyResponse = await client.path("/identify").post({
        body: { faceIds, largePersonGroupId: largePersonGroupId },
      });
      await Promise.all(
        identifyResponse.body.map(async (result) => {
          try {
            const getLargePersonGroupPersonResponse = await client
              .path(
                "/largepersongroups/{largePersonGroupId}/persons/{personId}",
                largePersonGroupId,
                result.candidates[0].personId,
              )
              .get();
            const person = getLargePersonGroupPersonResponse.body;
            console.log(
              `Person: ${person.name} is identified for face in: ${sourceImageFileName} with ID: ${result.faceId}. Confidence: ${result.candidates[0].confidence}`,
            );
    
            // Verification:
            const verifyResponse = await client.path("/verify").post({
              body: {
                faceId: result.faceId,
                largePersonGroupId: largePersonGroupId,
                personId: person.personId,
              },
            });
            console.log(
              `Verification result between face ${result.faceId} and person ${person.personId}: ${verifyResponse.body.isIdentical} with confidence: ${verifyResponse.body.confidence}`,
            );
          } catch (error) {
            console.log(`No persons identified for face with ID ${result.faceId}`);
          }
        }),
      );
      console.log();
    
      // Delete large person group.
      console.log(`Deleting person group: ${largePersonGroupId}`);
      await client.path("/largepersongroups/{largePersonGroupId}", largePersonGroupId).delete();
      console.log();
    
      console.log("Done.");
    };
    
    main().catch(console.error);
    
  4. شغّل التطبيق باستخدام الأمر node المُتاح على ملف التشغيل السريع.

    node index.js
    

المخرجات

========IDENTIFY FACES========

Creating a person group with ID: a230ac8b-09b2-4fa0-ae04-d76356d88d9f
Adding faces to person group...
Create a persongroup person: Family1-Dad
Create a persongroup person: Family1-Mom
Create a persongroup person: Family1-Son
Add face to the person group person: (Family1-Dad) from image: (Family1-Dad1.jpg)
Add face to the person group person: (Family1-Mom) from image: (Family1-Mom1.jpg)
Add face to the person group person: (Family1-Son) from image: (Family1-Son1.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-Mom2.jpg)
Add face to the person group person: (Family1-Son) from image: (Family1-Son2.jpg)
Done adding faces to person group.

Training person group: a230ac8b-09b2-4fa0-ae04-d76356d88d9f
Training status: succeeded
Pausing for 60 seconds to avoid triggering rate limit on free account...
No persons identified for face with ID 56380623-8bf0-414a-b9d9-c2373386b7be
Person: Family1-Dad is identified for face in: identification1.jpg with ID: c45052eb-a910-4fd3-b1c3-f91ccccc316a. Confidence: 0.96807
Person: Family1-Son is identified for face in: identification1.jpg with ID: 8dce9b50-513f-4fe2-9e19-352acfd622b3. Confidence: 0.9281
Person: Family1-Mom is identified for face in: identification1.jpg with ID: 75868da3-66f6-4b5f-a172-0b619f4d74c1. Confidence: 0.96902
Verification result between face c45052eb-a910-4fd3-b1c3-f91ccccc316a and person 35a58d14-fd58-4146-9669-82ed664da357: true with confidence: 0.96807
Verification result between face 8dce9b50-513f-4fe2-9e19-352acfd622b3 and person 2d4d196c-5349-431c-bf0c-f1d7aaa180ba: true with confidence: 0.9281
Verification result between face 75868da3-66f6-4b5f-a172-0b619f4d74c1 and person 35d5de9e-5f92-4552-8907-0d0aac889c3e: true with confidence: 0.96902

Deleting person group: a230ac8b-09b2-4fa0-ae04-d76356d88d9f

Done.

تنظيف الموارد

إذا كنت ترغب في تنظيف اشتراك خدمات Azure الذكاء الاصطناعي وإزالته، يمكنك حذف المورد أو مجموعة الموارد. يؤدي حذف مجموعة الموارد إلى حذف أية موارد أخرى مقترنة بها أيضًا.

الخطوات التالية

في هذا البدء السريع، تعلمت كيفية استخدام مكتبة عميل Face لـ ‎.JavaScript للقيام بالتعرف على الوجه الأساسي. بعد ذلك، تعرفت على نماذج كشف الوجه المختلفة وكيفية تحديد الطراز المناسب لحالة الاستخدام.

ابدأ بالتعرف على الوجه باستخدام Face REST API. توفر لك خدمة Face إمكانية الوصول إلى الخوارزميات المتقدمة للكشف عن الوجوه البشرية والتعرف عليها في الصور.

إشعار

يستخدم هذا التشغيل السريع أوامر cURL لاستدعاء REST API. يمكنك أيضاً استدعاء REST API باستخدام لغة برمجة. من الأسهل تنفيذ السيناريوهات المعقدة مثل التعرف على الوجه باستخدام لغة SDK. راجع نماذج GitHub للحصول على أمثلة في C#‎ وPython و Java وJavaScript وGo.

المتطلبات الأساسية

  • اشتراك Azure - إنشاء اشتراك مجانًا
  • يجب أن يكون Cognitive Services Contributor لحساب Azure دور معين لكي توافق على شروط الذكاء الاصطناعي المسؤولة وإنشاء مورد. للحصول على هذا الدور المعين لحسابك، اتبع الخطوات الواردة في وثائق تعيين الأدوار، أو اتصل بالمسؤول.
  • بمجرد أن يكون لديك اشتراك Azure، قم بإنشاء مورد Face في مدخل Microsoft Azure للحصول على المفتاح ونقطة النهاية. بعد انتشاره، حدد "Go to resource".
    • ستحتاج إلى المفتاح ونقطة النهاية من المورد الذي تنشئه لتوصيل التطبيق بواجهة برمجة تطبيقات Face. ستلصق المفتاح ونقطة النهاية في التعليمات البرمجية أدناه لاحقًا في التشغيل السريع.
    • يمكنك استخدام مستوى التسعير الحر (F0) لتجربة الخدمة، والترقية لاحقًا إلى مستوى مدفوع للإنتاج.
  • الإصدار 6.0+ من PowerShell، أو تطبيق سطر أوامر مشابهة.
  • تم تثبيت cURL.

تحديد الوجوه والتحقق منها

إشعار

إذا لم تكن قد حصلت على حق الوصول إلى خدمة Face باستخدام نموذج الاستيعاب، فلن تعمل بعض هذه الوظائف.

  1. أولًا، قم باستدعاء واجهة برمجة التطبيقات Detect على الوجه المصدر. هذا هو الوجه الذي سنحاول تحديده من المجموعة الأكبر. انسخ الأمر التالي إلى محرر نص، وأدرج المفتاح ونقطة النهاية الخاصة بك، ثم انسخه في نافذة shell وقم بتشغيله.

    curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&recognitionModel=recognition_04&returnRecognitionModel=false&detectionModel=detection_03&faceIdTimeToLive=86400" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{""url"":""https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/identification1.jpg""}"
    

    احفظ سلسلة معرف الوجه الذي تم إرجاعه في موقع مؤقت. ستستخدمه مرة أخرى في النهاية.

  2. بعد ذلك، ستحتاج إلى إنشاء LargePersonGroup وإعطائها معرفا عشوائيا يطابق نمط ^[a-z0-9-_]+$regex . سيقوم هذا الكائن بتخزين بيانات الوجه المجمعة لعدة أشخاص. قم بتشغيل الأمر التالي، مع إدخال مفتاحك الخاص. اختياريًا، قم بتغيير اسم المجموعة وبيانات التعريف في نص الطلب.

    curl.exe -v -X PUT "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{
        ""name"": ""large-person-group-name"",
        ""userData"": ""User-provided data attached to the large person group."",
        ""recognitionModel"": ""recognition_04""
    }"
    

    احفظ المعرف المحدد للمجموعة التي تم إنشاؤها في موقع مؤقت.

  3. بعد ذلك، ستقوم بإنشاء كائنات Person التي تنتمي إلى المجموعة. قم بتشغيل الأمر التالي، مع إدخال المفتاح الخاص بك ومعرف LargePersonGroup من الخطوة السابقة. يقوم هذا الأمر بإنشاء شخص يسمى "Family1-Dad".

    curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}/persons" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{
        ""name"": ""Family1-Dad"",
        ""userData"": ""User-provided data attached to the person.""
    }"
    

    بعد تشغيل هذا الأمر، قم بتشغيله مرة أخرى باستخدام بيانات إدخال مختلفة لإنشاء المزيد من كائنات Person : "Family1-Mom" و"Family1-Son" و"Family1-Son" و"Family2-Lady" و"Family2-Man".

    احفظ معرفات كل شخص تم إنشاؤه؛ من المهم تتبع اسم الشخص الذي يحتوي على المعرف.

  4. بعد ذلك، ستحتاج إلى الكشف عن وجوه جديدة وربطها بعناصر Person الموجودة. يكتشف الأمر التالي وجها من الصورة Family1-Dad1.jpg ويضيفه إلى الشخص المقابل. تحتاج إلى تحديد personId كمعرف الذي تم إرجاعه عند إنشاء كائن "Family1-Dad" Person . يتوافق اسم الصورة مع اسم الشخص الذي تم إنشاؤه. أدخل أيضاً معرّف LargePersonGroup والمفتاح في الحقول المناسبة.

    curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces?detectionModel=detection_03" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{""url"":""https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/Face/images/Family1-Dad1.jpg""}"
    

    ثم قم بتشغيل الأمر أعلاه مرة أخرى مع صورة مصدر مختلفة وشخص الهدف. الصور المتوفرة هي: Family1-Dad1.jpg، Family1-Dad2.jpg Family1-Mom1.jpg، Family1-Mom2.jpg، Family1-Son1.jpg، Family1-Son2.jpg، Family1-Daughter1.jpg، Family1-Daughter2.jpg، Family2-Lady1.jpg، Family2-Lady2.jpg، Family2-Man1.jpg، Family2-Man2.jpg. تأكد من أن الشخص الذي تحدد معرفه في استدعاء واجهة برمجة التطبيقات يطابق اسم ملف الصورة في نص الطلب.

    في نهاية هذه الخطوة، يجب أن يكون لديك كائنات شخص متعددة تحتوي كل منها على وجه واحد أو أكثر من الوجوه المقابلة، والتي تم اكتشافها مباشرة من الصور المتوفرة.

  5. بعد ذلك، قم بتدريب LargePersonGroup ببيانات الوجه الحالية. تعلم عملية التدريب النموذج كيفية إقران ميزات الوجه، التي يتم تجميعها أحيانًا من صور متعددة المصدر، بكل شخص واحد. أدخل معرف LargePersonGroup والمفتاح قبل تشغيل الأمر.

    curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}/train" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data ""
    
  6. تحقق مما إذا كانت حالة التدريب ناجحة أم لا. إذا لم يكن الأمر كما هو، فانتظر لفترة ثم استعلم مرة أخرى.

    curl.exe -v "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}/training" -H "Ocp-Apim-Subscription-Key: {subscription key}"
    
  7. أنت الآن جاهز لاستدعاء واجهة برمجة تطبيقات التعريف، باستخدام معرف الوجه المصدر من الخطوة الأولى ومعرف LargePersonGroup . أدخل هذه القيم في الحقول المناسبة في نص الطلب، وأدخل مفتاحك.

    curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/identify" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {subscription key}" --data-ascii "{
        ""largePersonGroupId"": ""INSERT_PERSONGROUP_ID"",
        ""faceIds"": [
            ""INSERT_SOURCE_FACE_ID""
        ],
        ""maxNumOfCandidatesReturned"": 1,
        ""confidenceThreshold"": 0.5
    }"
    

    يجب أن يمنحك الرد معرف شخص يشير إلى الشخص المحدد بوجه المصدر. يجب أن يكون المعرف هو الذي يتوافق مع شخص "Family1-Dad"، لأن الوجه المصدر لهذا الشخص.

  8. لإجراء التحقق من الوجه، ستستخدم معرف الشخص الذي تم إرجاعه في الخطوة السابقة، ومعرف LargePersonGroup ، وكذلك معرف الوجه المصدر. إدراج هذه القيم في الحقول في نص الطلب، وإدراج المفتاح الخاص بك.

    curl.exe -v -X POST "https://{resource endpoint}/face/v1.0/verify" `
    -H "Content-Type: application/json" `
    -H "Ocp-Apim-Subscription-Key: {subscription key}" `
    --data-ascii "{
        ""faceId"": ""INSERT_SOURCE_FACE_ID"",
        ""personId"": ""INSERT_PERSON_ID"",
        ""largePersonGroupId"": ""INSERT_PERSONGROUP_ID""
    }"
    

    يجب أن تمنحك الاستجابة نتيجة تحقق منطقية مع قيمة ثقة.

تنظيف الموارد

لحذف LargePersonGroup التي أنشأتها في هذا التمرين، قم بتشغيل استدعاء LargePersonGroup - Delete.

curl.exe -v -X DELETE "https://{resource endpoint}/face/v1.0/largepersongroups/{largePersonGroupId}" -H "Ocp-Apim-Subscription-Key: {subscription key}"

إذا كنت ترغب في تنظيف اشتراك خدمات Azure الذكاء الاصطناعي وإزالته، يمكنك حذف المورد أو مجموعة الموارد. يؤدي حذف مجموعة الموارد إلى حذف أية موارد أخرى مقترنة بها أيضًا.

الخطوات التالية

في هذا التشغيل السريع، تعلمت كيفية استخدام Face REST API للقيام بمهام التعرف على الوجه الأساسية. بعد ذلك، تعرفت على نماذج كشف الوجه المختلفة وكيفية تحديد الطراز المناسب لحالة الاستخدام.