
Background
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 asp.net 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.
Note
Image categorization and tagging is only supported in English language.
Now we will create a real project to implementing image analysis using computer vision.
Prerequisites
- 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)
Note
I will be doing this tutorial with asp.net 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 asp.net 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 asp.net core 5.0 project to implement computer vision.
Implementing Image analysis using Client library in asp.net core 5.0
Quickly, we will create a new asp.net 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.
Microsoft.Azure.CognitiveServices.Vision.ComputerVision
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.
ImageAnalysisViewModel.cs
- using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
- namespace computervision.aspcore.Services.Dto
- {
- public class ImageAnalysisViewModel
- {
- public ImageAnalysis imageAnalysisResult { get; set; }
- }
- }
We will follow the folder/files structure as shown above. Then, we have added interface for computer vision service.
IComputerVisionService.cs
- using computervision.aspcore.Services.Dto;
- using System.IO;
- using System.Threading.Tasks;
- namespace computervision.aspcore.Services
- {
- public interface ICompuerVisionService
- {
- Task<ImageAnalysisViewModel> AnalyzeImageUrl(string imageUrl);
- }
- }
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.
- // Add your Computer Vision subscription key and endpoint
- private string subscriptionKey = "PASTE_YOUR_COMPUTER_VISION_SUBSCRIPTION_KEY_HERE";
- private string endpoint = " PASTE_YOUR_COMPUTER_VISION_ENDPOINT_HERE";
- /*
- * AUTHENTICATE
- * Creates a Computer Vision client used by each example.
- */
- public ComputerVisionClient Authenticate() {
- ComputerVisionClient client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey)) {
- Endpoint = endpoint
- };
- return client;
- }
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,
- public async Task < ImageAnalysisViewModel > AnalyzeImageUrl(string imageUrl) {
- try {
- // Creating a list that defines the features to be extracted from the image.
- ComputerVisionClient client = Authenticate();
- List < VisualFeatureTypes ? > features = new List < VisualFeatureTypes ? > () {
- VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
- VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,
- VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,
- VisualFeatureTypes.Color, VisualFeatureTypes.Brands,
- VisualFeatureTypes.Objects
- };
- ImageAnalysis results;
- using(Stream imageStream = File.OpenRead(imageUrl)) {
- results = await client.AnalyzeImageInStreamAsync(imageStream, visualFeatures: features);
- //imageStream.Close();
- }
- ImageAnalysisViewModel imageAnalysis = new ImageAnalysisViewModel();
- imageAnalysis.imageAnalysisResult = results;
- return imageAnalysis;
- } catch (System.Exception ex) {
- // add your log capture code
- throw;
- }
- }
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,
- ComputerVisionClient client = Authenticate();
- List < VisualFeatureTypes ? > features = new List < VisualFeatureTypes ? > () {
- VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
- VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,
- VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,
- VisualFeatureTypes.Color, VisualFeatureTypes.Brands,
- VisualFeatureTypes.Objects
- };
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
- using computervision.aspcore.Services.Dto;
- using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
- using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
- using System.Collections.Generic;
- using System.IO;
- using System.Threading.Tasks;
- namespace computervision.aspcore.Services {
- public class CompterVisionService: ICompuerVisionService {
- // Add your Computer Vision subscription key and endpoint
- private string subscriptionKey = "05b6ca4476c447eeb8c841e16119d101";
- private string endpoint = "https://autotagingdemo.cognitiveservices.azure.com/";
- /*
- * AUTHENTICATE
- * Creates a Computer Vision client used by each example.
- */
- public ComputerVisionClient Authenticate() {
- ComputerVisionClient client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey)) {
- Endpoint = endpoint
- };
- return client;
- }
- public async Task < ImageAnalysisViewModel > AnalyzeImageUrl(string imageUrl) {
- try {
- // Creating a list that defines the features to be extracted from the image.
- ComputerVisionClient client = Authenticate();
- List < VisualFeatureTypes ? > features = new List < VisualFeatureTypes ? > () {
- VisualFeatureTypes.Categories, VisualFeatureTypes.Description,
- VisualFeatureTypes.Faces, VisualFeatureTypes.ImageType,
- VisualFeatureTypes.Tags, VisualFeatureTypes.Adult,
- VisualFeatureTypes.Color, VisualFeatureTypes.Brands,
- VisualFeatureTypes.Objects
- };
- ImageAnalysis results;
- using(Stream imageStream = File.OpenRead(imageUrl)) {
- results = await client.AnalyzeImageInStreamAsync(imageStream, visualFeatures: features);
- //imageStream.Close();
- }
- ImageAnalysisViewModel imageAnalysis = new ImageAnalysisViewModel();
- imageAnalysis.imageAnalysisResult = results;
- return imageAnalysis;
- } catch (System.Exception ex) {
- // add your log capture code
- throw;
- }
- }
- }
- }





Narayan NyaupanePosted Aug 2, 2021, 4:56 PM
Great work. Thank you so much. I have a few requests for you. I want to build an application analysis of medical images. Using this service we only analyze general-purpose images. Can you please help me using custom vision like this.