快速入門:使用電腦視覺 SDK 和 C# 來分析影像Quickstart: Analyze an image using the Computer Vision SDK and C#

在本快速入門中,您會使用 C# 電腦視覺用戶端程式庫,來分析要擷取視覺功能的本機與遠端影像。In this quickstart, you will analyze both a local and a remote image to extract visual features using the Computer Vision client library for C#. 如果您想要的話,也可以從 GitHub 上的 Cognitive Services Csharp Vision 存放庫下載本指南中的程式碼,來作為完整應用程式範例。If you wish, you can download the code in this guide as a complete sample app from the Cognitive Services Csharp Vision repo on GitHub.

必要條件Prerequisites

建立並執行範例應用程式Create and run the sample application

若要執行範例,請執行下列步驟:To run the sample, do the following steps:

  1. 在 Visual Studio 中建立 Visual C# 主控台應用程式。Create a new Visual C# Console App in Visual Studio.

  2. 安裝「電腦視覺」用戶端程式庫 NuGet 套件。Install the Computer Vision client library NuGet package.

    1. 在功能表中,按一下 [工具],選取 [NuGet 套件管理員],然後選取 [管理解決方案的 NuGet 套件]。On the menu, click Tools, select NuGet Package Manager, then Manage NuGet Packages for Solution.
    2. 按一下 [瀏覽] 索引標籤,然後在 [搜尋] 方塊中,鍵入 "Microsoft.Azure.CognitiveServices.Vision.ComputerVision"。Click the Browse tab, and in the Search box type "Microsoft.Azure.CognitiveServices.Vision.ComputerVision".
    3. 顯示時選取 [Microsoft.Azure.CognitiveServices.Vision.ComputerVision],按一下專案名稱旁邊的核取方塊,然後按一下 [安裝]。Select Microsoft.Azure.CognitiveServices.Vision.ComputerVision when it displays, then click the checkbox next to your project name, and Install.
  3. 以下列程式碼取代 Program.cs 的內容。Replace the contents of Program.cs with the following code. AnalyzeImageAsyncAnalyzeImageInStreamAsync 方法可分別針對遠端和本機影像包裝分析影像 REST API (英文)。The AnalyzeImageAsync and AnalyzeImageInStreamAsync methods wrap the Analyze Image REST API for remote and local images, respectively.

    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace ImageAnalyze
    {
        class Program
        {
            // subscriptionKey = "0123456789abcdef0123456789ABCDEF"
            private const string subscriptionKey = "<SubscriptionKey>";
    
            // localImagePath = @"C:\Documents\LocalImage.jpg"
            private const string localImagePath = @"<LocalImage>";
    
            private const string remoteImageUrl =
                "https://upload.wikimedia.org/wikipedia/commons/3/3c/Shaki_waterfall.jpg";
    
            // Specify the features to return
            private static readonly List<VisualFeatureTypes> features =
                new List<VisualFeatureTypes>()
            {
                VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
                VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,
                VisualFeatureTypes.Tags
            };
    
            static void Main(string[] args)
            {
                ComputerVisionClient computerVision = new ComputerVisionClient(
                    new ApiKeyServiceClientCredentials(subscriptionKey),
                    new System.Net.Http.DelegatingHandler[] { });
    
                // You must use the same region as you used to get your subscription
                // keys. For example, if you got your subscription keys from westus,
                // replace "westcentralus" 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 the region.
    
                // Specify the Azure region
                computerVision.Endpoint = "https://westcentralus.api.cognitive.microsoft.com";
    
                Console.WriteLine("Images being analyzed ...");
                var t1 = AnalyzeRemoteAsync(computerVision, remoteImageUrl);
                var t2 = AnalyzeLocalAsync(computerVision, localImagePath);
    
                Task.WhenAll(t1, t2).Wait(5000);
                Console.WriteLine("Press ENTER to exit");
                Console.ReadLine();
            }
    
            // Analyze a remote image
            private static async Task AnalyzeRemoteAsync(
                ComputerVisionClient computerVision, string imageUrl)
            {
                if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
                {
                    Console.WriteLine(
                        "\nInvalid remoteImageUrl:\n{0} \n", imageUrl);
                    return;
                }
    
                ImageAnalysis analysis =
                    await computerVision.AnalyzeImageAsync(imageUrl, features);
                DisplayResults(analysis, imageUrl);
            }
    
            // Analyze a local image
            private static async Task AnalyzeLocalAsync(
                ComputerVisionClient computerVision, string imagePath)
            {
                if (!File.Exists(imagePath))
                {
                    Console.WriteLine(
                        "\nUnable to open or read localImagePath:\n{0} \n", imagePath);
                    return;
                }
    
                using (Stream imageStream = File.OpenRead(imagePath))
                {
                    ImageAnalysis analysis = await computerVision.AnalyzeImageInStreamAsync(
                        imageStream, features);
                    DisplayResults(analysis, imagePath);
                }
            }
    
            // Display the most relevant caption for the image
            private static void DisplayResults(ImageAnalysis analysis, string imageUri)
            {
                Console.WriteLine(imageUri);
                if (analysis.Description.Captions.Count != 0)
                {
                    Console.WriteLine(analysis.Description.Captions[0].Text + "\n");
                }
                else
                {
                    Console.WriteLine("No description generated.");
                }
            }
        }
    }
    
  4. <Subscription Key> 換成您的有效訂用帳戶金鑰。Replace <Subscription Key> with your valid subscription key.

  5. 必要時,請將 computerVision.Endpoint 變更為與您的訂用帳戶金鑰相關聯的 Azure 區域。Change computerVision.Endpoint to the Azure region associated with your subscription keys, if necessary.

  6. 使用本機影像的路徑和檔案名稱來取代 <LocalImage>Replace <LocalImage> with the path and file name of a local image.

  7. (選擇性) 將 remoteImageUrl 設為不同的影像 URL。Optionally, set remoteImageUrl to a different image URL.

  8. 執行程式。Run the program.

檢查回應Examine the response

成功的回應會顯示每個影像的最相關標題。A successful response displays the most relevant caption for each image. 您可以變更 DisplayResults 方法來輸出不同的影像資料。You can change the DisplayResults method to output different image data. 若要深入了解,請參閱 AnalyzeLocalAsync 方法。See the AnalyzeLocalAsync method to learn more.

請參閱 API 快速入門:使用 C# 來分析本機影像,以取得原始 JSON 輸出範例。See API Quickstarts: Analyze a local image with C# for an example of a raw JSON output.

https://upload.wikimedia.org/wikipedia/commons/3/3c/Shaki_waterfall.jpg
a large waterfall over a rocky cliff

後續步驟Next steps

探索用來分析影像、偵測名人和地標、建立縮圖及擷取印刷和手寫文字的「電腦視覺 API」。Explore the Computer Vision APIs used to analyze an image, detect celebrities and landmarks, create a thumbnail, and extract printed and handwritten text.