How To Analyze An Image Using Azure Computer Vision SDK and C#

Azure Computer Vision services provide algorithms that process and return information of the images. You can either specify the image URL or upload an image to analyze the image. Here, we have used Computer Vision SDK and C# to analyze an image.

Creating a Visual C# Console App in Visual Studio

  • Open Visual Studio ->Create a new project.

How To Analyze An Image Using Azure Computer Vision SDK and C#
  • Select Console App (.NET Core) and click "Next".

How To Analyze An Image Using Azure Computer Vision SDK and C#

  • Enter the project name, location, and solution name.

  • Click "Create".

How To Analyze An Image Using Azure Computer Vision SDK and C#

Installing Microsoft.Azure.CognitiveServices.Vision.ComputerVision SDK

  • Go to Project -> Manage NuGet Packages.

  • Click the "Browse" tab and search for Microsoft.Azure.CognitiveServices.Vision.ComputerVision.

  • You will see Microsoft.Azure.CognitiveServices.Vision.ComputerVision SDK listed in the search results; click the "Install" button.

  • Now, click the "I Accept" button to accept the license agreement.

  • It will take a few minutes to install the SDK in our project.

How To Analyze An Image Using Azure Computer Vision SDK and C#

Creating Cognitive Service Account

Get Computer Vision Access key

  • Go to Azure portal, click All Resources from the left pane. Select the type of Cognitive Service that you have created.

How To Analyze An Image Using Azure Computer Vision SDK and C#

  • Click "Keys" from Resource Management section and copy the access key.

How To Analyze An Image Using Azure Computer Vision SDK and C#

  • Here, we used AnalyzeImageAsync and AnalyzeImageInStreamAsync methods which wrap the Analyze Image REST API for remote and local images respectively

Open program.cs file and type the following code.
  1. using System;  
  2. using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;  
  3. using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;  
  4. using System.Collections.Generic;  
  5. using System.IO;  
  6. using System.Threading.Tasks;  
  7.   
  8.   
  9. namespace CS_AnalyzeImage  
  10. {  
  11.     class Program  
  12.     {  
  13.   
  14.         // subscriptionKey = "0123456789abcdef0123456789ABCDEF"  
  15.         private const string subscriptionKey = "< Enter your subscription key>";  
  16.   
  17.         // localImagePath = @"C:\Documents\LocalImage.jpg"  
  18.         private const string localImagePath = @"<LocalImage>";  
  19.   
  20.         private const string remoteImageUrl ="< Enter the remote image url>";  
  21.   
  22.         // Specify the features to return  
  23.         private static readonly List<VisualFeatureTypes> features =  
  24.             new List<VisualFeatureTypes>()  
  25.         {  
  26.             VisualFeatureTypes.Categories, VisualFeatureTypes.Description,  
  27.             VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,  
  28.             VisualFeatureTypes.Tags  
  29.         };  
  30.   
  31.           
  32.         static void Main(string[] args)  
  33.         {  
  34.             ComputerVisionClient computerVision = new ComputerVisionClient(  
  35.                 new ApiKeyServiceClientCredentials(subscriptionKey),  
  36.                 new System.Net.Http.DelegatingHandler[] { });  
  37.   
  38.             // You must use the same region as you used to get your subscription  
  39.             // keys. For example, if you got your subscription keys from westus,  
  40.             // replace "westcentralus" with "westus".  
  41.             //  
  42.             // Free trial subscription keys are generated in the "westus"  
  43.             // region. If you use a free trial subscription key, you shouldn't  
  44.             // need to change the region.  
  45.   
  46.             // Specify the Azure region  
  47.             computerVision.Endpoint = "https://centralindia.api.cognitive.microsoft.com";  
  48.   
  49.             Console.WriteLine("Images being analyzed ...");  
  50.             var t1 = AnalyzeRemoteAsync(computerVision, remoteImageUrl);  
  51.             var t2 = AnalyzeLocalAsync(computerVision, localImagePath);  
  52.   
  53.             Task.WhenAll(t1, t2).Wait(5000);  
  54.             Console.WriteLine("Press ENTER to exit");  
  55.             Console.ReadLine();  
  56.         }  
  57.   
  58.         // Analyze a remote image  
  59.         private static async Task AnalyzeRemoteAsync(  
  60.             ComputerVisionClient computerVision, string imageUrl)  
  61.         {  
  62.             if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))  
  63.             {  
  64.                 Console.WriteLine(  
  65.                     "\nInvalid remoteImageUrl:\n{0} \n", imageUrl);  
  66.                 return;  
  67.             }  
  68.   
  69.             ImageAnalysis analysis =  
  70.                 await computerVision.AnalyzeImageAsync(imageUrl, features);  
  71.             DisplayResults(analysis, imageUrl);  
  72.         }  
  73.   
  74.         // Analyze a local image  
  75.         private static async Task AnalyzeLocalAsync(  
  76.             ComputerVisionClient computerVision, string imagePath)  
  77.         {  
  78.             if (!File.Exists(imagePath))  
  79.             {  
  80.                 Console.WriteLine(  
  81.                     "\nUnable to open or read localImagePath:\n{0} \n", imagePath);  
  82.                 return;  
  83.             }  
  84.   
  85.             using (Stream imageStream = File.OpenRead(imagePath))  
  86.             {  
  87.                 ImageAnalysis analysis = await computerVision.AnalyzeImageInStreamAsync(  
  88.                     imageStream, features);  
  89.                 DisplayResults(analysis, imagePath);  
  90.             }  
  91.         }  
  92.   
  93.         // Display the most relevant caption for the image  
  94.         private static void DisplayResults(ImageAnalysis analysis, string imageUri)  
  95.         {  
  96.             Console.WriteLine(imageUri);  
  97.             if (analysis.Description.Captions.Count != 0)  
  98.             {  
  99.                 Console.WriteLine(analysis.Description.Captions[0].Text + "\n");  
  100.             }  
  101.             else  
  102.             {  
  103.                 Console.WriteLine("No description generated.");  
  104.             }  
  105.         }  
  106.     }  
  107. }  
  • Replace the <Subscription key> with your valid subscription key.

  • Change the Computer.Endpoint to the Azure region associated with your subscription key.

  • Replace <Local Image> with the path and file name of the local image.

  • Optionally, set remoteImageUrl to try the different image URL.

That's it. Now, run the web application, go to Debug menu, and click on "Start without Debugging" or press F5. This will display the below result.

How To Analyze An Image Using Azure Computer Vision SDK and C#

I hope you have learned how to analyze an image (local or remote) using the Computer Vision SDK and C#. Feel free to fill up the comment box below with your feedback or query. 


Similar Articles