您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用计算机视觉 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 上的认知服务 Csharp 视觉存储库下载本指南中的代码作为完整的示例应用。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 APIThe 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.

原始 JSON 输出的示例,请参阅 API 快速入门:使用 C# 分析本地图像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.