快速入門:使用 Face REST API 和 C# 偵測影像中的臉部Quickstart: Detect faces in an image using the Face REST API and C#

在本快速入門中,您將使用 Azure Face REST API 搭配 C# 來偵測影像中的人臉。In this quickstart, you will use the Azure Face REST API with C# to detect human faces in an image.

如果您沒有 Azure 訂用帳戶,請在開始前建立 免費帳戶If you don't have an Azure subscription, create a free account before you begin.

必要條件Prerequisites

建立 Visual Studio 專案Create the Visual Studio project

  1. 在 Visual Studio 中建立新的主控台應用程式 (.NET Framework) 專案,並將其命名為 FaceDetectionIn Visual Studio, create a new Console app (.NET Framework) project and name it FaceDetection.
  2. 如果您的解決方案中有其他專案,請選取此專案作為單一啟始專案。If there are other projects in your solution, select this one as the single startup project.

新增臉部偵測程式碼Add face detection code

開啟新專案的 Program.cs 檔案。Open the new project's Program.cs file. 在這裡,您將新增載入影像及偵測臉部所需的程式碼。Here, you will add the code needed to load images and detect faces.

包含命名空間Include namespaces

Program.cs 檔案的頂端新增下列 using 陳述式。Add the following using statements to the top of your Program.cs file.

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

新增必要欄位Add essential fields

新增包含下列欄位的 Program 類別。Add the Program class containing the following fields. 這項資料會指定連線到 Face 服務的方式,以及接收輸入資料的位置。This data specifies how to connect to the Face service and where to get the input data. 您將需要以訂用帳戶金鑰更新 subscriptionKey 欄位的值,而且可能需要變更 uriBase 字串,使其包含正確的區域識別碼 (請參閱臉部 API 文件以取得所有區域端點的清單)。You'll need to update the subscriptionKey field with the value of your subscription key, and you may need to change the uriBase string so that it contains the correct region identifier (see the Face API docs for a list of all region endpoints).

namespace DetectFace
{
    class Program
    {

        // Replace <Subscription Key> with your valid subscription key.
        const string subscriptionKey = "<Subscription Key>";

        // NOTE: You must use the same region in your REST call as you used to
        // obtain your subscription keys. For example, if you obtained your
        // subscription keys from westus, replace "westcentralus" in the URL
        // below with "westus".
        //
        // Free trial subscription keys are generated in the "westus" region.
        // If you use a free trial subscription key, you shouldn't need to change
        // this region.
        const string uriBase =
            "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";

接收影像輸入Receive image input

Program 類別的 Main 方法新增下列程式碼。Add the following code to the Main method of the Program class. 此程式碼會將提示字元寫入主控台,並要求使用者輸入影像 URL。This code writes a prompt to the console asking the user to enter an image URL. 然後呼叫另一種方法:MakeAnalysisRequest,以處理該位置上的影像。Then it calls another method, MakeAnalysisRequest, to process the image at that location.

        static void Main(string[] args)
        {

            // Get the path and filename to process from the user.
            Console.WriteLine("Detect faces:");
            Console.Write(
                "Enter the path to an image with faces that you wish to analyze: ");
            string imageFilePath = Console.ReadLine();

            if (File.Exists(imageFilePath))
            {
                try
                {
                    MakeAnalysisRequest(imageFilePath);
                    Console.WriteLine("\nWait a moment for the results to appear.\n");
                }
                catch (Exception e)
                {
                    Console.WriteLine("\n" + e.Message + "\nPress Enter to exit...\n");
                }
            }
            else
            {
                Console.WriteLine("\nInvalid file path.\nPress Enter to exit...\n");
            }
            Console.ReadLine();
        }

呼叫臉部偵測 REST APICall the face detection REST API

將下列方法新增至 Program 類別。Add the following method to the Program class. 此方法會建構對臉部 API 發出的 REST 呼叫,以偵測遠端影像中的臉部資訊 (requestParameters 字串會指定要擷取的臉部屬性)。It constructs a REST call to the Face API to detect face information in the remote image (the requestParameters string specifies which face attributes to retrieve). 然後將輸出資料寫入 JSON 字串。Then it writes the output data to a JSON string.

您將在下列步驟中定義協助程式方法。You will define the helper methods in the following steps.

        // Gets the analysis of the specified image by using the Face REST API.
        static async void MakeAnalysisRequest(string imageFilePath)
        {
            HttpClient client = new HttpClient();

            // Request headers.
            client.DefaultRequestHeaders.Add(
                "Ocp-Apim-Subscription-Key", subscriptionKey);

            // Request parameters. A third optional parameter is "details".
            string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
                "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
                "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";

            // Assemble the URI for the REST API Call.
            string uri = uriBase + "?" + requestParameters;

            HttpResponseMessage response;

            // Request body. Posts a locally stored JPEG image.
            byte[] byteData = GetImageAsByteArray(imageFilePath);

            using (ByteArrayContent content = new ByteArrayContent(byteData))
            {
                // This example uses content type "application/octet-stream".
                // The other content types you can use are "application/json"
                // and "multipart/form-data".
                content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                // Execute the REST API call.
                response = await client.PostAsync(uri, content);

                // Get the JSON response.
                string contentString = await response.Content.ReadAsStringAsync();

                // Display the JSON response.
                Console.WriteLine("\nResponse:\n");
                Console.WriteLine(JsonPrettyPrint(contentString));
                Console.WriteLine("\nPress Enter to exit...");
            }
        }

處理輸入影像資料Process the input image data

將下列方法新增至 Program 類別。Add the following method to the Program class. 此方法會將位於指定 URL 的影像轉換成位元組陣列。This method converts the image at the specified URL into a byte array.

        // Returns the contents of the specified file as a byte array.
        static byte[] GetImageAsByteArray(string imageFilePath)
        {
            using (FileStream fileStream =
                new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
            {
                BinaryReader binaryReader = new BinaryReader(fileStream);
                return binaryReader.ReadBytes((int)fileStream.Length);
            }
        }

剖析 JSON 回應Parse the JSON response

將下列方法新增至 Program 類別。Add the following method to the Program class. 此方法會格式化 JSON 輸入,以便閱讀。This method formats the JSON input to be more easily readable. 您的應用程式會將此字串資料寫入主控台。Your app will write this string data to the console. 然後您就可以關閉類別和命名空間。You can then close the class and namespace.

        // Formats the given JSON string by adding line breaks and indents.
        static string JsonPrettyPrint(string json)
        {
            if (string.IsNullOrEmpty(json))
                return string.Empty;

            json = json.Replace(Environment.NewLine, "").Replace("\t", "");

            StringBuilder sb = new StringBuilder();
            bool quote = false;
            bool ignore = false;
            int offset = 0;
            int indentLength = 3;

            foreach (char ch in json)
            {
                switch (ch)
                {
                    case '"':
                        if (!ignore) quote = !quote;
                        break;
                    case '\'':
                        if (quote) ignore = !ignore;
                        break;
                }

                if (quote)
                    sb.Append(ch);
                else
                {
                    switch (ch)
                    {
                        case '{':
                        case '[':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', ++offset * indentLength));
                            break;
                        case '}':
                        case ']':
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', --offset * indentLength));
                            sb.Append(ch);
                            break;
                        case ',':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', offset * indentLength));
                            break;
                        case ':':
                            sb.Append(ch);
                            sb.Append(' ');
                            break;
                        default:
                            if (ch != ' ') sb.Append(ch);
                            break;
                    }
                }
            }

            return sb.ToString().Trim();
        }
    }
}

執行應用程式Run the app

成功的回應會以可輕鬆閱讀的 JSON 格式顯示臉部資料。A successful response will display Face data in easily readable JSON format. 例如︰For example:

[
   {
      "faceId": "f7eda569-4603-44b4-8add-cd73c6dec644",
      "faceRectangle": {
         "top": 131,
         "left": 177,
         "width": 162,
         "height": 162
      },
      "faceAttributes": {
         "smile": 0.0,
         "headPose": {
            "pitch": 0.0,
            "roll": 0.1,
            "yaw": -32.9
         },
         "gender": "female",
         "age": 22.9,
         "facialHair": {
            "moustache": 0.0,
            "beard": 0.0,
            "sideburns": 0.0
         },
         "glasses": "NoGlasses",
         "emotion": {
            "anger": 0.0,
            "contempt": 0.0,
            "disgust": 0.0,
            "fear": 0.0,
            "happiness": 0.0,
            "neutral": 0.986,
            "sadness": 0.009,
            "surprise": 0.005
         },
         "blur": {
            "blurLevel": "low",
            "value": 0.06
         },
         "exposure": {
            "exposureLevel": "goodExposure",
            "value": 0.67
         },
         "noise": {
            "noiseLevel": "low",
            "value": 0.0
         },
         "makeup": {
            "eyeMakeup": true,
            "lipMakeup": true
         },
         "accessories": [

         ],
         "occlusion": {
            "foreheadOccluded": false,
            "eyeOccluded": false,
            "mouthOccluded": false
         },
         "hair": {
            "bald": 0.0,
            "invisible": false,
            "hairColor": [
               {
                  "color": "brown",
                  "confidence": 1.0
               },
               {
                  "color": "black",
                  "confidence": 0.87
               },
               {
                  "color": "other",
                  "confidence": 0.51
               },
               {
                  "color": "blond",
                  "confidence": 0.08
               },
               {
                  "color": "red",
                  "confidence": 0.08
               },
               {
                  "color": "gray",
                  "confidence": 0.02
               }
            ]
         }
      }
   }
]

後續步驟Next steps

在此快速入門中,您已建立簡單的 .NET 主控台應用程式來搭配使用 REST 呼叫和 Azure 臉部 API,進而偵測影像中的臉部並傳回其屬性。In this quickstart, you created a simple .NET console application that uses REST calls with the Azure Face API to detect faces in an image and return their attributes. 接下來,請瀏覽臉部 API 參考文件,以深入了解支援的案例。Next, explore the Face API reference documentation to learn more about the supported scenarios.