Cognitive Services – Optical Character Recognition (OCR) From An Image Using Computer Vision API And C#

Introduction
 
In our previous article, we learned how to Analyze an Image Using Computer Vision API With ASP.Net Core & C#. In this article, we are going to learn how to extract printed text, also known as optical character recognition (OCR), from an image using one of the important Cognitive Services API called Computer Vision API. So, we need a valid subscription key for accessing this feature in an image.
 
Optical Character Recognition (OCR)
 
Optical Character Recognition (OCR) detects text in an image and extracts the recognized characters into a machine-usable character stream.
 
Prerequisites
  1. Subscription key ( Azure Portal )
  2. Visual Studio 2015 or 2017
Subscription Key Free Trail
 
If you don’t have Microsoft Azure Subscription and want to test the Computer Vision API because it requires a valid Subscription key for processing the image information, don’t worry! Microsoft gives a 7-day trial Subscription Key ( Click here ). We can use that Subscription key for testing purposes. If you sign up using the Computer Vision free trial, then your subscription keys are valid for the west-central region (https://westcentralus.api.cognitive.microsoft.com ). 
 
Requirements
 
These are the major requirements mentioned in the Microsoft docs.
  1. Supported input methods: Raw image binary in the form of an application/octet-stream or image URL.
  2. Supported image formats: JPEG, PNG, GIF, BMP.
  3. Image file size: Less than 4 MB.
  4. Image dimension: Greater than 50 x 50 pixels.
Computer Vision API
 
First, we need to log into the Azure Portal with our Azure credentials. Then we need to create an Azure Computer Vision Subscription Key in the Azure portal.

Cognitive service

Click on "Create a resource" on the left side menu and it will open an "Azure Marketplace". There, we can see the list of services. Click "AI + Machine Learning" then click on the "Computer Vision".
 
Provision a Computer Vision Subscription Key
 
After clicking the "Computer Vision", It will open another section. There, we need to provide the basic information about Computer Vision API.

Cognitive service
  • Name - Name of the Computer Vision API ( Eg. OCRApp ).
  • Subscription - We can select our Azure subscription for Computer Vision API creation.
  • Location - We can select our location for the resource group. The best thing is we can choose a location closest to our customer.
  • Pricing tier - Select an appropriate pricing tier for our requirement.
  • Resource group - We can create a new resource group or choose from an existing one.
  • Now click on the "OCRApp" in dashboard page and it will redirect to the details page of OCRApp ( "Overview" ). Here, we can see the Manage Key ( Subscription key details ) & Endpoint details. Click on the Show access keys links and it will redirect to another page.
Cognitive service

We can use any of the subscription keys or regenerate the given key for getting image information using Computer Vision API.

Cognitive service

Endpoint

As we mentioned above the location is the same for all the free trial Subscription Keys. In Azure, we can choose available locations while creating a Computer Vision API. We have used the following endpoint in our code.
  1. https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr  
View Model

The following model will contain the API image response information.
  1. using System.Collections.Generic;  
  2.    
  3. namespace OCRApp.Models  
  4. {  
  5.     public class Word  
  6.     {  
  7.         public string boundingBox { getset; }  
  8.         public string text { getset; }  
  9.     }  
  10.    
  11.     public class Line  
  12.     {  
  13.         public string boundingBox { getset; }  
  14.         public List<Word> words { getset; }  
  15.     }  
  16.    
  17.     public class Region  
  18.     {  
  19.         public string boundingBox { getset; }  
  20.         public List<Line> lines { getset; }  
  21.     }  
  22.    
  23.     public class ImageInfoViewModel  
  24.     {  
  25.         public string language { getset; }  
  26.         public string orientation { getset; }  
  27.         public int textAngle { getset; }  
  28.         public List<Region> regions { getset; }  
  29.     }  
  30. }  
Request URL

We can add additional parameters or request parameters ( optional ) in our API "endPoint" and it will provide more information for the given image.
  1. https://[location].api.cognitive.microsoft.com/vision/v1.0/ocr[?language][&detectOrientation ]  
Request parameters

These are the following optional parameters available in Computer Vision API.
  1. language
  2. detectOrientation
language

The service will detect 26 languages of the text in the image and It will contain "unk" as the default value. That means the service will auto-detect the language of the text in the image.
 
The following are the supported language mention in the Microsoft API documentation.
  1. unk (AutoDetect)
  2. en (English)
  3. zh-Hans (ChineseSimplified)
  4. zh-Hant (ChineseTraditional)
  5. cs (Czech)
  6. da (Danish)
  7. nl (Dutch)
  8. fi (Finnish)
  9. fr (French)
  10. de (German)
  11. el (Greek)
  12. hu (Hungarian)
  13. it (Italian)
  14. ja (Japanese)
  15. ko (Korean)
  16. nb (Norwegian)
  17. pl (Polish)
  18. pt (Portuguese,
  19. ru (Russian)
  20. es (Spanish)
  21. sv (Swedish)
  22. tr (Turkish)
  23. ar (Arabic)
  24. ro (Romanian)
  25. sr-Cyrl (SerbianCyrillic)
  26. sr-Latn (SerbianLatin)
  27. sk (Slovak) 
detectOrientation

This will detect the text orientation in the image, for this feature we need to add detectOrientation=true in the service URL or Request URL as we discussed earlier.

Vision API Service

The following code will process and generate image information using Computer Vision API and its response is mapped into the "ImageInfoViewModel". We can add the valid Computer Vision API Subscription Key into the following code.
  1. using Newtonsoft.Json;  
  2. using OCRApp.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.IO;  
  6. using System.Net.Http;  
  7. using System.Net.Http.Headers;  
  8. using System.Threading.Tasks;  
  9.    
  10. namespace OCRApp.Business_Layer  
  11. {  
  12.     public class VisionApiService  
  13.     {  
  14.         // Replace <Subscription Key> with your valid subscription key.  
  15.         const string subscriptionKey = "<Subscription Key>";  
  16.    
  17.         // You must use the same region in your REST call as you used to  
  18.         // get your subscription keys. The paid subscription keys you will get  
  19.         // it from microsoft azure portal.  
  20.         // Free trial subscription keys are generated in the westcentralus region.  
  21.         // If you use a free trial subscription key, you shouldn't need to change  
  22.         // this region.  
  23.         const string endPoint =  
  24.             "https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr";  
  25.    
  26.         ///   
  27. <summary>  
  28.         /// Gets the text visible in the specified image file by using  
  29.         /// the Computer Vision REST API.  
  30.         /// </summary>  
  31.    
  32.         public async Task<string> MakeOCRRequest()  
  33.         {  
  34.             string imageFilePath = @"C:\Users\rajeesh.raveendran\Desktop\bill.jpg";  
  35.             var errors = new List<string>();  
  36.             string extractedResult = "";  
  37.             ImageInfoViewModel responeData = new ImageInfoViewModel();  
  38.    
  39.             try  
  40.             {  
  41.                 HttpClient client = new HttpClient();  
  42.    
  43.                 // Request headers.  
  44.                 client.DefaultRequestHeaders.Add(  
  45.                     "Ocp-Apim-Subscription-Key", subscriptionKey);  
  46.    
  47.                 // Request parameters.  
  48.                 string requestParameters = "language=unk&detectOrientation=true";  
  49.    
  50.                 // Assemble the URI for the REST API Call.  
  51.                 string uri = endPoint + "?" + requestParameters;  
  52.    
  53.                 HttpResponseMessage response;  
  54.    
  55.                 // Request body. Posts a locally stored JPEG image.  
  56.                 byte[] byteData = GetImageAsByteArray(imageFilePath);  
  57.    
  58.                 using (ByteArrayContent content = new ByteArrayContent(byteData))  
  59.                 {  
  60.                     // This example uses content type "application/octet-stream".  
  61.                     // The other content types you can use are "application/json"  
  62.                     // and "multipart/form-data".  
  63.                     content.Headers.ContentType =  
  64.                         new MediaTypeHeaderValue("application/octet-stream");  
  65.    
  66.                     // Make the REST API call.  
  67.                     response = await client.PostAsync(uri, content);  
  68.                 }  
  69.    
  70.                 // Get the JSON response.  
  71.                 string result = await response.Content.ReadAsStringAsync();  
  72.    
  73.                 //If it is success it will execute further process.  
  74.                 if (response.IsSuccessStatusCode)  
  75.                 {  
  76.                     // The JSON response mapped into respective view model.  
  77.                     responeData = JsonConvert.DeserializeObject<ImageInfoViewModel>(result,  
  78.                         new JsonSerializerSettings  
  79.                         {  
  80.                             NullValueHandling = NullValueHandling.Include,  
  81.                             Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs earg)  
  82.                             {  
  83.                                 errors.Add(earg.ErrorContext.Member.ToString());  
  84.                                 earg.ErrorContext.Handled = true;  
  85.                             }  
  86.                         }  
  87.                     );  
  88.    
  89.                     var linesCount = responeData.regions[0].lines.Count;  
  90.                     for (int i = 0; i < linesCount; i++)  
  91.                     {  
  92.                         var wordsCount = responeData.regions[0].lines[i].words.Count;  
  93.                         for (int j = 0; j < wordsCount; j++)  
  94.                         {  
  95.                             //Appending all the lines content into one.  
  96.                             extractedResult += responeData.regions[0].lines[i].words[j].text + " ";  
  97.                         }  
  98.                         extractedResult += Environment.NewLine;  
  99.                     }  
  100.    
  101.                 }  
  102.             }  
  103.             catch (Exception e)  
  104.             {  
  105.                 Console.WriteLine("\n" + e.Message);  
  106.             }  
  107.             return extractedResult;  
  108.         }  
  109.    
  110.         ///   
  111. <summary>  
  112.         /// Returns the contents of the specified file as a byte array.  
  113.         /// </summary>  
  114.    
  115.         /// <param name="imageFilePath">The image file to read.</param>  
  116.         /// <returns>The byte array of the image data.</returns>  
  117.         static byte[] GetImageAsByteArray(string imageFilePath)  
  118.         {  
  119.             using (FileStream fileStream =  
  120.                 new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))  
  121.             {  
  122.                 BinaryReader binaryReader = new BinaryReader(fileStream);  
  123.                 return binaryReader.ReadBytes((int)fileStream.Length);  
  124.             }  
  125.         }  
  126.     }  
  127.    
  128. }  
API Response – Based on the given Image

The successful JSON response.
  1. {  
  2.   "language""en",  
  3.   "orientation""Up",  
  4.   "textAngle": 0,  
  5.   "regions": [  
  6.     {  
  7.       "boundingBox""306,69,292,206",  
  8.       "lines": [  
  9.         {  
  10.           "boundingBox""306,69,292,24",  
  11.           "words": [  
  12.             {  
  13.               "boundingBox""306,69,17,19",  
  14.               "text""\"I"  
  15.             },  
  16.             {  
  17.               "boundingBox""332,69,45,19",  
  18.               "text""Will"  
  19.             },  
  20.             {  
  21.               "boundingBox""385,69,88,24",  
  22.               "text""Always"  
  23.             },  
  24.             {  
  25.               "boundingBox""482,69,94,19",  
  26.               "text""Choose"  
  27.             },  
  28.             {  
  29.               "boundingBox""585,74,13,14",  
  30.               "text""a"  
  31.             }  
  32.           ]  
  33.         },  
  34.         {  
  35.           "boundingBox""329,100,246,24",  
  36.           "words": [  
  37.             {  
  38.               "boundingBox""329,100,56,24",  
  39.               "text""Lazy"  
  40.             },  
  41.             {  
  42.               "boundingBox""394,100,85,19",  
  43.               "text""Person"  
  44.             },  
  45.             {  
  46.               "boundingBox""488,100,24,19",  
  47.               "text""to"  
  48.             },  
  49.             {  
  50.               "boundingBox""521,100,32,19",  
  51.               "text""Do"  
  52.             },  
  53.             {  
  54.               "boundingBox""562,105,13,14",  
  55.               "text""a"  
  56.             }  
  57.           ]  
  58.         },  
  59.         {  
  60.           "boundingBox""310,131,284,19",  
  61.           "words": [  
  62.             {  
  63.               "boundingBox""310,131,95,19",  
  64.               "text""Difficult"  
  65.             },  
  66.             {  
  67.               "boundingBox""412,131,182,19",  
  68.               "text""Job....Because"  
  69.             }  
  70.           ]  
  71.         },  
  72.         {  
  73.           "boundingBox""326,162,252,24",  
  74.           "words": [  
  75.             {  
  76.               "boundingBox""326,162,31,19",  
  77.               "text""He"  
  78.             },  
  79.             {  
  80.               "boundingBox""365,162,44,19",  
  81.               "text""Will"  
  82.             },  
  83.             {  
  84.               "boundingBox""420,162,52,19",  
  85.               "text""Find"  
  86.             },  
  87.             {  
  88.               "boundingBox""481,167,28,14",  
  89.               "text""an"  
  90.             },  
  91.             {  
  92.               "boundingBox""520,162,58,24",  
  93.               "text""Easy"  
  94.             }  
  95.           ]  
  96.         },  
  97.         {  
  98.           "boundingBox""366,193,170,24",  
  99.           "words": [  
  100.             {  
  101.               "boundingBox""366,193,52,24",  
  102.               "text""way"  
  103.             },  
  104.             {  
  105.               "boundingBox""426,193,24,19",  
  106.               "text""to"  
  107.             },  
  108.             {  
  109.               "boundingBox""459,193,33,19",  
  110.               "text""Do"  
  111.             },  
  112.             {  
  113.               "boundingBox""501,193,35,19",  
  114.               "text""It!\""  
  115.             }  
  116.           ]  
  117.         },  
  118.         {  
  119.           "boundingBox""462,256,117,19",  
  120.           "words": [  
  121.             {  
  122.               "boundingBox""462,256,37,19",  
  123.               "text""Bill"  
  124.             },  
  125.             {  
  126.               "boundingBox""509,256,70,19",  
  127.               "text""Gates"  
  128.             }  
  129.           ]  
  130.         }  
  131.       ]  
  132.     }  
  133.   ]  
  134. }  
Download
Output

Optical Character Recognition (OCR) from an image using Computer Vision API.
 
Cognitive service
Reference
See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.

Summary

From this article, we have learned Optical Character Recognition (OCR) from an image using One of the important Cognitive Services API (Computer Vision API). I hope this article is useful for all Azure Cognitive Services API beginners.


Similar Articles