Image Analysis In ASP.NET Core 5.0 Using Azure Cognitive Service



Azure’s computer vision services give a wide range of options to do image analysis. These AI services enable you to discover the content and analyze images and videos in real time. Using computer vision, which is a part of Azure cognitive services, we can do image processing to label content with objects, moderate content, identify objects in image, extract text, generate details descriptions of the image, orientations, people movements and so on.
The word “cognitive” means mental action or the process of acquiring knowledge and understanding through thoughts, experience, and the senses. (Copied from Wikipedia). Thinking, Visualizing, Knowing, Learning, Judging, and discovering, deciding etc. are the actions of cognitive.

Azure Cognitive Services

Azure Cognitive Services are cloud-based AI services which are developed by Microsoft to enable cognitive intelligence into any application through REST APIs or client library SDKs. This means, we can build AI applications without knowing Artificial intelligence and Data science algorithms or skills. In another way, these services are ready-made AI services to use in applications of any platform or language and enable AI and cognitive features in your solutions. There are various cognitive services which are mainly divided into five categories: vision, speech, language, decision, and search. More details here.

Computer Vision

Computer vison, which is part of the Azure cognitive service vision category, provides advanced processing of images and videos with advance algorithms to extract text, do OCR, visual features from image like objects, faces, adult content, and auto-generate image descriptions. Additionally, this cognitive service analyzes videos and identify the movement and presence of object.
In this article, I will do image analyzes using computer vision in core solution.

Features of Image analysis of Computer vision

Detect Object: Using this service, we can identify the object in the image. The service will return the bounding box coordinate of each object. The detection operation returns the coordinates of the objects like animals and person from the image which can further extend to create relation among those objects.
  • Tagging
    This service can identify and tag visual features like scenes, living things, furniture, tools, gadgets, and so on.

  • Face Detection
    This service can identify and detect the face and some properties like age, gender, face gestures from image.

  • Detect Brands
    There are numerous commercial brands and logs are stored in the database and this service can detect famous brands.

  • Image Description
    This service returns the comprehensive description of an entire image in natural language. It evaluates the image and provides complete information.

  • Color Scheme detection
    this service detects image color scheme like black/white or color image, also provide information on the accent and dominant colors.

  • Image categorization
    This service can be used for image categorization using category taxonomy to entire image.

  • Image Type detection
    This is another feature of this service that can detect the characteristics of images. For example, the image is a clip art or line drawing.

  • Thumbnail Generation
    This cognitive service creates high-quality thumbnail based on the analysis of the image and area of interest. It crops the image based on area of interest and generates the thumbnail of different aspect ratio compared to the original image.

  • Domain-Specific content detection
    Using this service, we can identify the domain of image content like celebrities and landmarks.

  • Area of Interest
    This feature returns the area of interest of the image by analyzing the contents. This will give the bounding box coordinates of the area of interest.

  • Detect Moderate Content
    This service can be used to detect the adult content in an image. This feature can be useful to know the confidence of moderate content and set a threshold for flagging.
Image categorization and tagging is only supported in English language.
Now we will create a real project to implementing image analysis using computer vision.
  • Azure subscription (you can create trial one for free)
  • Visual Studio (I am using Visual Studio 2019, however, it will be same for other versions as well)
  • .NET 5.0 (ASP.NET core 5.0)
I will be doing this tutorial with core 5.0

Create Computer Vision Cognitive Service in Azure

Let us first create Azure Computer vision API service from Azure Portal.
Login to Azure Portal.
We can search with Cognitive service or computer vision as illustrated below. In this demonstration, we will be using computer vision, an azure cognitive service.
Create a new cognitive service, then it will display the marketplace. Simply we can search computer vision and select it.
Then, we will get option to create this service.
Create computer vision by filling the necessary information as portrayed.
There is free tier as well for development which you will get in pricing tier, however, in my case, I have already utilized free in another demo. Therefore, I will choose standard one.
Subsequently, we will get option to choose virtual network option, based on your convenience, select one option.
Finally, we will review and create as shown:
Free tier has following quota,
With free tier, we can do 5000 calls per 30 days.
Most importantly, we need to get subscription key and endpoint for accessing this computer vision service/API. We can navigate to keys and endpoint tab get the required information as illustrated.
To run the service from core, we basically need this two information: Key (also called subscription key) and Endpoint URL. Therefore, we can keep this in some note or can login again in azure portal and collect the information.
Then again, let us create core 5.0 project to implement computer vision.

Implementing Image analysis using Client library in core 5.0

Quickly, we will create a new core 5.0 razor pages project with Visual Studio 2019.
Open Visual studio >> Create a new Project.
Please Note: Here I am selecting ASP.NET Core with Razor pages (not with MVC).
Then we will get option for project name and location. You can give any name and choose location.
Then, we will get option to select the target framework. Here, we will select .NET 5.0 which is a current version.
We have successfully created the ASP.NET core 5.0 web application with Razor pages.
Once the solution is created, then quickly, you can build and run the solution.
We need to add client library from NuGet packages for accessing computer vision service.
We can add this package by right clicking on the project, selecting Manage NuGet Packages and browser with the above name as depicted.
After installing NuGet package, I will create service for computer vision. Create a folder name Service and add Interface and classes as shown.
We will add Dto (data transfer object) for image analysis result.
  1. using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;  
  3. namespace computervision.aspcore.Services.Dto  
  4. {  
  5.     public class ImageAnalysisViewModel  
  6.     {  
  7.         public ImageAnalysis imageAnalysisResult { getset; }  
  8.     }  
  9. }  
We will follow the folder/files structure as shown above. Then, we have added interface for computer vision service.
  1. using computervision.aspcore.Services.Dto;  
  2. using System.IO;  
  3. using System.Threading.Tasks;  
  5. namespace computervision.aspcore.Services  
  6. {  
  7.     public interface ICompuerVisionService  
  8.     {  
  9.         Task<ImageAnalysisViewModel> AnalyzeImageUrl(string imageUrl);  
  10.     }  
  11. }  
Then, in service class, we will first do authentication of client using key and endpoint URL. This service class is implementation of the above Interface.
Authentication code for client.
  1. // Add your Computer Vision subscription key and endpoint    
  2. private string subscriptionKey = "PASTE_YOUR_COMPUTER_VISION_SUBSCRIPTION_KEY_HERE";  
  3. private string endpoint = " PASTE_YOUR_COMPUTER_VISION_ENDPOINT_HERE";  
  4. /*  
  6.  * Creates a Computer Vision client used by each example.  
  7.  */  
  8. public ComputerVisionClient Authenticate() {  
  9.     ComputerVisionClient client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey)) {  
  10.         Endpoint = endpoint  
  11.     };  
  12.     return client;  
  13. }   
We have these subscription key and endpoints URL from Azure portal as shown in earlier steps.
Subsequently, we will use the client authentication to analyze the image. The following code will be used for analyzing the image.
Function for Analyzing the image from URL as shown,
  1. public async Task < ImageAnalysisViewModel > AnalyzeImageUrl(string imageUrl) {  
  2.     try {  
  3.         // Creating a list that defines the features to be extracted from the image.     
  4.         ComputerVisionClient client = Authenticate();  
  5.         List < VisualFeatureTypes ? > features = new List < VisualFeatureTypes ? > () {  
  6.             VisualFeatureTypes.Categories, VisualFeatureTypes.Description,  
  7.                 VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,  
  8.                 VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,  
  9.                 VisualFeatureTypes.Color, VisualFeatureTypes.Brands,  
  10.                 VisualFeatureTypes.Objects  
  11.         };  
  12.         ImageAnalysis results;  
  13.         using(Stream imageStream = File.OpenRead(imageUrl)) {  
  14.             results = await client.AnalyzeImageInStreamAsync(imageStream, visualFeatures: features);  
  15.             //imageStream.Close();    
  16.         }  
  17.         ImageAnalysisViewModel imageAnalysis = new ImageAnalysisViewModel();  
  18.         imageAnalysis.imageAnalysisResult = results;  
  19.         return imageAnalysis;  
  20.     } catch (System.Exception ex) {  
  21.         // add your log capture code    
  22.         throw;  
  23.     }  
  24. }   
Let me explain the above function. Firstly, I am doing authentication, then defining the feature which will be sent to analysis service of computer vision as shown,
  1. ComputerVisionClient client = Authenticate();  
  2. List < VisualFeatureTypes ? > features = new List < VisualFeatureTypes ? > () {  
  3.     VisualFeatureTypes.Categories, VisualFeatureTypes.Description,  
  4.         VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,  
  5.         VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,  
  6.         VisualFeatureTypes.Color, VisualFeatureTypes.Brands,  
  7.         VisualFeatureTypes.Objects  
  8. };   
In this above visual feature, I am selecting categories, descriptions, faces, Image type, tags, adult, color, brands, and objects. In other words, the response of the client analysis will return the above features using computer vision cognitive services.
Complete code of service class, CompterVisionService.cs
  1. using computervision.aspcore.Services.Dto;  
  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. namespace computervision.aspcore.Services {  
  8.     public class CompterVisionService: ICompuerVisionService {  
  9.         // Add your Computer Vision subscription key and endpoint    
  10.         private string subscriptionKey = "05b6ca4476c447eeb8c841e16119d101";  
  11.         private string endpoint = "";  
  12.         /*  
  13.          * AUTHENTICATE  
  14.          * Creates a Computer Vision client used by each example.  
  15.          */  
  16.         public ComputerVisionClient Authenticate() {  
  17.             ComputerVisionClient client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey)) {  
  18.                 Endpoint = endpoint  
  19.             };  
  20.             return client;  
  21.         }  
  22.         public async Task < ImageAnalysisViewModel > AnalyzeImageUrl(string imageUrl) {  
  23.             try {  
  24.                 // Creating a list that defines the features to be extracted from the image.     
  25.                 ComputerVisionClient client = Authenticate();  
  26.                 List < VisualFeatureTypes ? > features = new List < VisualFeatureTypes ? > () {  
  27.                     VisualFeatureTypes.Categories, VisualFeatureTypes.Description,  
  28.                         VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,  
  29.                         VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,  
  30.                         VisualFeatureTypes.Color, VisualFeatureTypes.Brands,  
  31.                         VisualFeatureTypes.Objects  
  32.                 };  
  33.                 ImageAnalysis results;  
  34.                 using(Stream imageStream = File.OpenRead(imageUrl)) {  
  35.                     results = await client.AnalyzeImageInStreamAsync(imageStream, visualFeatures: features);  
  36.                     //imageStream.Close();    
  37.                 }  
  38.                 ImageAnalysisViewModel imageAnalysis = new ImageAnalysisViewModel();  
  39.                 imageAnalysis.imageAnalysisResult = results;  
  40.                 return imageAnalysis;  
  41.             } catch (System.Exception ex) {  
  42.                 // add your log capture code    
  43.                 throw;  
  44.             }  
  45.         }  
  46.     }  
  47. }   
This is how we have completed the image analysis function for computer vision cognitive services.
Now, I will create file upload functionality to upload file and send to computer vision service for analyzing it.
To upload files in core please check this link
We will add file upload model index.cshtml.cs for file upload as shown,
  1. public class FileUpload {  
  2.     [Required]  
  3.     [Display(Name = "File")]  
  4.     public IFormFile FormFile {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string SuccessMessage {  
  9.         get;  
  10.         set;  
  11.     }  
  12. }   
Then, we will do dependency injection of ComputerVisionService through interface in Index.cshtml.cs page constructor.
  1. private readonly ILogger < IndexModel > _logger;  
  2. private readonly ICompuerVisionService _compuerVisionService;  
  3. private readonly IWebHostEnvironment _hostEnvironment;  
  4. public IndexModel(ILogger < IndexModel > logger, IWebHostEnvironment hostEnvironment) {  
  5.     _logger = logger;  
  6.     _compuerVisionService = new CompterVisionService();  
  7.     this._hostEnvironment = hostEnvironment;  
  8. }   
Eventually, we will use this service in upload method to upload and do image analysis same time. The upload method is as shown below,
  1. public async Task < IActionResult > OnPostUpload(FileUpload fileUpload) {  
  2.     string fullPath = _hostEnvironment.WebRootPath + "/UploadImages/";  
  3.     if (!Directory.Exists(fullPath)) {  
  4.         Directory.CreateDirectory(fullPath);  
  5.     }  
  6.     var formFile = fileUpload.FormFile;  
  7.     if (formFile.Length > 0) {  
  8.         var filePath = Path.Combine(fullPath, formFile.FileName);  
  9.         ViewData["ImageUrl"] = formFile.FileName;  
  10.         using(var stream = new FileStream(filePath, FileMode.Create)) {  
  11.             await formFile.CopyToAsync(stream);  
  12.         }  
  13.         // using service to analyze the image    
  14.         var imageAnalysis = await _compuerVisionService.AnalyzeImageUrl(filePath);  
  15.         if (imageAnalysis.imageAnalysisResult != null) ViewData["ImageAnalysisViewModel"] = imageAnalysis;  
  16.     }  
  17.     ViewData["SuccessMessage"] = fileUpload.FormFile.FileName.ToString() + " file uploaded!!";  
  18.     return Page();  
  19. }   
Let me explain this method. This method is straight forward, first, I am creating folder for uploading the file. Subsequently, I am using method AnalyzeImageUrl from CompterVisionService which will return analysis result using computer vision cognitive service, explained earlier.
Here the complete code for index.cshtml.cs
  1. using computervision.aspcore.Services;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.AspNetCore.Http;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.AspNetCore.Mvc.RazorPages;  
  6. using Microsoft.Extensions.Logging;  
  7. using System.ComponentModel.DataAnnotations;  
  8. using System.IO;  
  9. using System.Threading.Tasks;  
  11. namespace computervision.aspcore.Pages  
  12. {  
  13.     public class IndexModel : PageModel  
  14.     {  
  15.         private readonly ILogger<IndexModel> _logger;  
  16.         private readonly ICompuerVisionService _compuerVisionService;  
  17.         private readonly IWebHostEnvironment _hostEnvironment;  
  18.         public IndexModel(ILogger<IndexModel> logger, IWebHostEnvironment hostEnvironment)  
  19.         {  
  20.             _logger = logger;  
  21.             _compuerVisionService = new CompterVisionService();  
  22.             this._hostEnvironment = hostEnvironment;  
  24.         }  
  25.         [BindProperty]  
  26.         public FileUpload fileUpload { getset; }  
  27.         public void OnGet()  
  28.         {  
  29.             ViewData["SuccessMessage"] = "";  
  30.         }  
  31.         public async Task<IActionResult> OnPostUpload(FileUpload fileUpload)  
  32.         {  
  33.             string fullPath = _hostEnvironment.WebRootPath + "/UploadImages/";  
  34.             if (!Directory.Exists(fullPath))  
  35.             {  
  36.                 Directory.CreateDirectory(fullPath);  
  37.             }  
  38.             var formFile = fileUpload.FormFile;  
  39.             if (formFile.Length > 0)  
  40.             {  
  41.                 var filePath = Path.Combine(fullPath, formFile.FileName);  
  42.                 ViewData["ImageUrl"] = formFile.FileName;  
  43.                 using (var stream = new FileStream(filePath, FileMode.Create))  
  44.                 {  
  45.                     await formFile.CopyToAsync(stream);  
  46.                 }  
  48.                // using service to analyze the image  
  49.                 var imageAnalysis =await _compuerVisionService.AnalyzeImageUrl(filePath);  
  50.                 if (imageAnalysis.imageAnalysisResult != null)  
  51.                     ViewData["ImageAnalysisViewModel"] = imageAnalysis;  
  52.             }  
  54.             ViewData["SuccessMessage"] = fileUpload.FormFile.FileName.ToString() + " file uploaded!!";  
  57.             return Page();  
  58.         }  
  59.         public class FileUpload  
  60.         {  
  61.             [Required]  
  62.             [Display(Name = "File")]  
  63.             public IFormFile FormFile { getset; }  
  64.             public string SuccessMessage { getset; }  
  65.         }  
  68.     }  
  69. }  
Similarly, the complete code of razor page, index.cshtml
  1. @page  
  2. @model IndexModel  
  3. @using computervision.aspcore.Services.Dto;  
  4. @{  
  5.     ViewData["Title"] = "Home page";  
  6. }  
  8. <div class="text-center">  
  9.     <h4> | Image Analysis using cognive service in core 5.0</h4>  
  10.     <p>Learn about <a href="">building Web apps with ASP.NET Core</a>.</p>  
  11. </div>  
  12. <form enctype="multipart/form-data" method="post">  
  13.    @*File Upload part*@  
  14.     <div class="form-group">  
  15.         <label class="file">  
  16.             <input type="file" asp-for="fileUpload.FormFile" multiple aria-label="File browser example">  
  17.             <span class="file-custom"></span>  
  18.         </label>  
  19.         <input asp-page-handler="Upload" class="btn btn-primary" type="submit" value="Upload">  
  20.     </div>  
  22.     @{  
  23.         if (ViewData["SuccessMessage"] != null)  
  24.         {  
  25.             <span class="badge badge-success"> @ViewData["SuccessMessage"]</span>  
  26.         }  
  27.     }  
  29.     @*Displaying Analysis results*@  
  30.     <div class="row">  
  31.         <div class="col-sm-6">  
  33.             @if (ViewData["ImageUrl"] != null)  
  34.             {  
  35.                 var imageUrl = Convert.ToString(ViewData["ImageUrl"]);  
  36.                 <img src="UploadImages/@imageUrl" alt="" class="img-thumbnail" />  
  37.             }  
  38.         </div>  
  39.         <div class="col-sm-6 small">  
  40.             <p>  
  41.                 @if (ViewData["ImageAnalysisViewModel"] != null)  
  42.                 {  
  43.                     var imageAnalysisView = (ImageAnalysisViewModel)ViewData["ImageAnalysisViewModel"];  
  44.                     <h5>Description</h5>  
  45.                     foreach (var caption in imageAnalysisView.imageAnalysisResult.Description.Captions)  
  46.                     {  
  47.                         <span class="text-info"> @caption.Text: with confidence @caption.Confidence</span><br />  
  48.                     }  
  49.                     <h5>Category:</h5>  
  50.                     foreach (var category in imageAnalysisView.imageAnalysisResult.Categories)  
  51.                     {  
  52.                         <span class="text-success"> @category.Name with confidence: @category.Score</span><br />  
  53.                     }  
  54.                     <h5>Tags</h5>  
  55.                     foreach (var tag in imageAnalysisView.imageAnalysisResult.Tags)  
  56.                     {  
  57.                         <span class="badge badge-success">@tag.Name - @tag.Confidence</span>  
  58.                     }  
  59.                     <h5>Object Detection</h5>  
  60.                     foreach (var obj in imageAnalysisView.imageAnalysisResult.Objects)  
  61.                     {  
  63.                         <span class="badge badge-warning">@obj.ObjectProperty with Confidence @obj.Confidence</span>  
  64.                     }  
  65.                     <h5>Face Detection</h5>  
  66.                     foreach (var face in imageAnalysisView.imageAnalysisResult.Faces)  
  67.                     {  
  68.                         <span class="badge badge-info">  
  69.                             A @face.Gender of age @face.Age at location @face.FaceRectangle.Left, @face.FaceRectangle.Top, @face.FaceRectangle.Width, @face.FaceRectangle.Top, @face.FaceRectangle.Height  
  70.                         </span>  
  71.                     }  
  73.                     <h5>Image color scheme</h5>  
  74.                     <span class="badge badge-secondary">Is black and white?:@imageAnalysisView.imageAnalysisResult.Color.IsBWImg</span>  
  75.                     <span class="badge badge-secondary">Accent color:@imageAnalysisView.imageAnalysisResult.Color.AccentColor</span>  
  76.                     <span class="badge badge-secondary">Dominant background color:@imageAnalysisView.imageAnalysisResult.Color.DominantColorBackground</span>  
  77.                     <span class="badge badge-secondary">Dominant foreground color:@imageAnalysisView.imageAnalysisResult.Color.DominantColorForeground</span>  
  79.                     <h5>Image Type</h5>  
  80.                     <span class="badge badge-secondary">Clip Art Type: @imageAnalysisView.imageAnalysisResult.ImageType.ClipArtType</span>  
  81.                     <span class="badge badge-secondary">Line Drawing Type: @imageAnalysisView.imageAnalysisResult.ImageType.LineDrawingType</span>  
  83.                 }  
  84.             </p>  
  85.         </div>  
  86.     </div>  
  87. </form>  
Let me explain this razor page. There are mainly two parts, file upload and analysis results which I have commented in the page.
Now, our image analysis solution is ready to use. Azure cognitive service has made it comfortable to develop AI solutions without having deep knowledge on Artificial Intelligence or machine learning. Using these services, we can include AI features in our applications effortlessly. Additionally, there are numerous other services that can be implemented in any applications regardless of framework, platform, or language to build AI features.
Since our application is ready to do check with some images and analyze with results.
I have uploaded the complete solution to GitHub, please download and use it.
Let me run this solution.
 Now, I will select a picture and do analysis.
Let me elaborate on the analysis result.
In my AnalyzeImageUrl method of computer vision service, I have requested following features:
  • Categories
  • Description
  • Faces
  • Image Type
  • Tags
  • Adult
  • Color
  • Brands
  • Objects
This is done by defining the features parameters as defined in that method,
  1. List < VisualFeatureTypes ? > features = new List < VisualFeatureTypes ? > () {  
  2.     VisualFeatureTypes.Categories, VisualFeatureTypes.Description,  
  3.         VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,  
  4.         VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,  
  5.         VisualFeatureTypes.Color, VisualFeatureTypes.Brands,  
  6.         VisualFeatureTypes.Objects  
  7. };   
Based on these features, the analysis result of my solution,
Every finding in this response is with confidence factor which shows the percentage of confidence of data or output.
Now, let try the analysis of another complex image.
The analysis of this is also done with many useful information and tags.
This is how we can do image analysis in any application using computer vision.


Including AI features in any application has become quite simple using azure cognitive services without having much knowledge of AI or machine learning. In this article, I have explained image analysis with its feature and computer vision service. Furthermore, I have portrayed how to create a cognitive service, computer vision from the Azure portal. Additionally, I have implemented the service in core 5.0 using visual studio with examples. Finally, I have done some image analysis and explored the analysis results.