Introduction

By using Optical Character Recognition (OCR), you can detect and extract handwritten and printed text present in an image. The API works with different surfaces and backgrounds. To use OCR as a service, you have to get a subscription key from the Microsoft Cognitive Service portal. Steps of registration and obtaining the API keys are mentioned in my previous article, "Analyzing Image Content Programmatically: Using the Microsoft Cognitive Vision API."

In this post, I will demonstrate handwriting and text recognition by uploading a locally stored image consuming the Cognitive API.

Embedded Text Recognition Inside an Image

Step 1

Five Reasons to Adopt Hybrid Cloud Storage for Your Data Center
 
 

Create a new ASP.NET Web application in Visual Studio. Add a new ASPX page named TextRecognition.aspx. Then, replace the HTML code of TextRecognition.aspx with the following code.

In the following ASPX code, I have created an ASP panel. Inside that panel, I have added an Image, TextBox, a file upload control, and Submit button. Locally browsed images with handwritten or printed text will be displayed in the image control. A textbox will display text present in the image after the Submit button is clicked.

  1. <%@ Page Language="C#" AutoEventWireup="true"
  2. CodeBehind="TextRecognition.aspx.cs"
  3. Inherits="TextRecognition.TextRecognition" %>
  4. <!DOCTYPE html>
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7. <title>OCR Recognition</title>
  8. </head>
  9. <body>
  10. <form id="myform" runat="server">
  11. <div>
  12. </div>
  13. <asp:Panel ID="ImagePanel" runat="server"
  14. Height="375px">
  15. <asp:Image ID="MyImage" runat="server"
  16. Height="342px" Width="370px" />
  17. <asp:TextBox ID="MyTestBox" runat="server"
  18. Height="337px" Width="348px"></asp:TextBox>
  19. <br />
  20. <input id="MyFileUpload" type="file"
  21. runat="server" />
  22. <input id="btnSubmit" runat ="server"
  23. type="submit" value="Submit"
  24. onclick="btnSubmit_Click"  />
  25. <br />
  26. </asp:Panel>
  27. </form>
  28. </body>
  29. </html>

Step 2

Add the following namespaces in your TextRecognition.aspx.cs code file.

- Advertisement -
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using System.Diagnostics;

Step 3

Add the following app setting entries in your Web.config file. I have used an existing subscription key generated long back; you have to add your own subscription key registered from Azure Portal. The APIuri parameter key value is the endpoint of the ODR cognitive service.

  1. <appSettings>
  2. <add key="RequestParameters"
  3. value="language=unk&amp;detectOrientation =true"/>
  4. <add key="APIuri"
  5. value="https://westcentralus.api.cognitive.microsoft.com/
  6. vision/v1.0/ocr?"/>
  7. <add key="Subscription-Key"
  8. value="ce765f110a1e4a1c8eb5d2928a765c61"/>
  9. <add key ="Contenttypes" value="application/json"/>
  10. </appSettings>

Step 4

Now, add the following code in your TextRecognition.aspx.cs codebehind file. All static functions will return appSettings key values, as mentioned in Step 3. The BtnSubmit_Click event will occur once the Submit button is clicked. It will call the CallAPIforOCR async function. By using the GetByteArray function, the local image will be converted to bytes and that would be passed to Cognitive Services for recognition.

  1. public partial class TextRecognition : System.Web.UI.Page
  2. {
  3. static string responsetext;
  4. static string responsehandwritting;
  5. static string Subscriptionkey()
  6. {
  7. return System.Configuration.ConfigurationManager
  8. .AppSettings["Subscription-Key"];
  9. }
  10. static string RequestParameters()
  11. {
  12. return System.Configuration.ConfigurationManager
  13. .AppSettings["RequestParameters"];
  14. }
  15. static string ReadURI()
  16. {
  17. return System.Configuration.ConfigurationManager
  18. .AppSettings["APIuri"];
  19. }
  20. static string Contenttypes()
  21. {
  22. return System.Configuration.ConfigurationManager
  23. .AppSettings["Contenttypes"];
  24. }
  25. protected void btnSubmit_Click(object sender, EventArgs e)
  26. {
  27. string fileName = System.IO.Path.GetFileName
  28. (MyFileUpload.PostedFile.FileName);
  29. MyFileUpload.PostedFile.SaveAs(Server.MapPath
  30. ("~/images/" + fileName));
  31. MyImage.ImageUrl = "~/images/" + fileName;
  32. CallAPIforOCR("~/images/" + fileName);
  33. MyTestBox.Text = responsetext;
  34. }
  35. static byte[] GetByteArray(string LocalimageFilePath)
  36. {
  37. FileStream ImagefileStream = new
  38. FileStream(LocalimageFilePath, FileMode.Open,
  39. FileAccess.Read);
  40. BinaryReader ImagebinaryReader = new
  41. BinaryReader(ImagefileStream);
  42. return ImagebinaryReader.ReadBytes((int)
  43. ImagefileStream.Length);
  44. }
  45. // Optical Character Reader
  46. static async void CallAPIforOCR(string LocalimageFilePath)
  47. {
  48. var ComputerVisionAPIclient = new HttpClient();
  49. try {
  50. ComputerVisionAPIclient.DefaultRequestHeaders
  51. .Add("Ocp-Apim-Subscription- Key",
  52. Subscriptionkey());
  53. string requestParameters = RequestParameters();
  54. string APIuri = ReadURI() + requestParameters;
  55. HttpResponseMessage myresponse;
  56. byte[] byteData = GetByteArray(LocalimageFilePath);
  57. var content = new ByteArrayContent(byteData);
  58. content.Headers.ContentType = new
  59. MediaTypeHeaderValue(Contenttypes());
  60. myresponse = await
  61. ComputerVisionAPIclient.PostAsync
  62. (APIuri, content);
  63. myresponse.EnsureSuccessStatusCode();
  64. responsetext = await myresponse.Content
  65. .ReadAsStringAsync();
  66. }
  67. catch (Exception e)
  68. {
  69. EventLog.WriteEntry("Text Recognition Error",
  70. e.Message + "Trace" + e.StackTrace,
  71. EventLogEntryType.Error, 121, short.MaxValue);
  72. }
  73. }

Step 5

Now, set TextRecognition.aspx as the default page and execute the Web application. After the page is displayed, click the browser button and open an local image with printed text on it. Click the Submit button to see the output.

To show the demo, I have used the following image downloaded from the Internet. Successful execution of the Cognitive Services API call returns OCR, including text, a bounding box for regions, lines, and words. On the right side of the panel, you can see the embedded test displayed in the text box.


Figure 1: Output of OCR recognition

Following is the JSON response from Cognitive Services.

  1. {
  2. "TextAngle": 0.0,
  3. "Orientation": "NotDetected",
  4. "Language": "en",
  5. "Regions": [
  6. {
  7. "BoundingBox": "21,246,550,132",
  8. "Lines": [
  9. {
  10. "BoundingBox": "21,246,550,33",
  11. "Words": [
  12. {
  13. "BoundingBox": "21,247,85,32",
  14. "Text": "How"
  15. },
  16. {
  17. "BoundingBox": "118,246,140,33",
  18. "Text": "Sundar"
  19. },
  20. {
  21. "BoundingBox": "273,246,121,33",
  22. "Text": "Pichai"
  23. },
  24. {
  25. "BoundingBox": "410,247,161,32",
  26. "Text": "Became"
  27. }
  28. ]
  29. },
  30. {
  31. "BoundingBox": "39,292,509,33",
  32. "Words": [
  33. {
  34. "BoundingBox": "39,293,72,32",
  35. "Text": "The"
  36. },
  37. {
  38. "BoundingBox": "126,293,99,32",
  39. "Text": "Most"
  40. },
  41. {
  42. "BoundingBox": "240,292,172,33",
  43. "Text": "Powerful"
  44. },
  45. {
  46. "BoundingBox": "428,292,120,33",
  47. "Text": "Indian"
  48. }
  49. ]
  50. },
  51. {
  52. "BoundingBox": "155,338,294,40",
  53. "Words": [
  54. {
  55. "BoundingBox": "155,338,118,33",
  56. "Text": "Inside"
  57. },
  58. {
  59. "BoundingBox": "287,338,162,40",
  60. "Text": "Google?"
  61. }
  62. ]
  63. }
  64. ]
  65. }
  66. ]
  67. }

Recognize Handwriting

For handwriting recognition from text present in an image, I have used the same application, but you have to change the APIuri path to point to the correct endpoint and update the RequestParameters key value added in the previous step.

  1. <appSettings>
  2. <add key="RequestParameters" value="handwriting=true"/>
  3. <add key="APIuri"
  4. value="https://westcentralus.api.cognitive
  5. .microsoft.com/vision/v1.0/recognizeText?"/>
  6. <add key="Subscription-Key"
  7. value="ce765f110a1e4a1c8eb5d2928a765c61"/>
  8. <add key ="Contenttypes" value="application/json"/>
  9. </appSettings>

Also, add the following ReadHandwritttingFromImage async method. This function will replace the CallAPIforOCR function call present in the btnSubmit_Click event.

  1. static async void ReadHandwritttingFromImage(string LocalimageFilePath)
  2. {
  3. HttpResponseMessage myresponse = null;
  4. IEnumerable<string> myresponseValues = null;
  5. string operationLocation = null;
  6. var ComputerVisionAPIclient = new HttpClient();
  7. ComputerVisionAPIclient.DefaultRequestHeaders.Add
  8. ("Ocp-Apim-Subscription-Key", Subscriptionkey());
  9. string requestParameters = RequestParameters();
  10. string APIuri = ReadURI() + requestParameters;
  11. byte[] byteData = GetByteArray(LocalimageFilePath);
  12. var content = new ByteArrayContent(byteData);
  13. content.Headers.ContentType = new
  14. MediaTypeHeaderValue(Contenttypes());
  15. try
  16. {
  17. myresponse = await ComputerVisionAPIclient
  18. .PostAsync(APIuri, content);
  19. myresponseValues = myresponse.Headers
  20. .GetValues("Operation-Location");
  21. }
  22. catch (Exception e)
  23. {
  24. EventLog.WriteEntry("Handwritting Recognition Error",
  25. e.Message + "Trace" + e.StackTrace,
  26. EventLogEntryType.Error, 121, short.MaxValue);
  27. }
  28. foreach (var value in myresponseValues)
  29. {
  30. operationLocation = value;
  31. break;
  32. }
  33. try
  34. {
  35. myresponse = await ComputerVisionAPIclient
  36. .GetAsync(operationLocation);
  37. responsehandwritting = await myresponse.Content
  38. .ReadAsStringAsync();
  39. }
  40. catch (Exception e)
  41. {
  42. EventLog.WriteEntry("Handwritting Recognition Error",
  43. e.Message + "Trace" + e.StackTrace,
  44. EventLogEntryType.Error, 121, short.MaxValue);
  45. }
  46. }

Now, execute the Web application again. After the page is displayed, click the browser button and open an local image with handwritten text on it. Click the Submit button to see the output.


Figure 2: Output of handwriting recognition

Reading Text from Images Using C#的更多相关文章

  1. Suspended Animation——《The Economist》阅读积累(考研英语二·2010 Reading Text 1)

    [知识小百科] Damien Hirst(达米恩●赫斯特):生于1965年,是新一代英国艺术家的主要代表人物之一.他主导了90年代英国艺术发展并享有很高的国际声誉.赫斯特在1986年9月就读于伦敦大学 ...

  2. read content in a text file in python

    ** read text file in pythoncapability: reading =text= from a text file 1. open the IDLE text editor  ...

  3. 【深度学习Deep Learning】资料大全

    最近在学深度学习相关的东西,在网上搜集到了一些不错的资料,现在汇总一下: Free Online Books  by Yoshua Bengio, Ian Goodfellow and Aaron C ...

  4. (转) Awesome - Most Cited Deep Learning Papers

    转自:https://github.com/terryum/awesome-deep-learning-papers Awesome - Most Cited Deep Learning Papers ...

  5. python3.4 build in functions from 官方文档 翻译中

    2. Built-in Functions https://docs.python.org/3.4/library/functions.html?highlight=file The Python i ...

  6. ios异常(crash)输出

    最近突然想起友盟的sdk附带的一个功能:将闪退异常情况上报服务器,(stackflow,github)找了一些资料,自己写了一个demo,想起来好久没有写过blog了,顺便分享. 其实不止是ios,a ...

  7. python3的文件操作

    open的原型定义在bultin.py中,是一种内建函数,用于处理文件 open(file, mode='r', buffering=None, encoding=None, errors=None, ...

  8. python27读书笔记0.3

    #-*- coding:utf-8 -*- ##D.has_key(k): A predicate that returns True if D has a key k.##D.items(): Re ...

  9. LOAD DATA INFILE Syntax--官方

    LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name' [REPLACE | IGNORE] INTO TABLE tbl_n ...

随机推荐

  1. win7 64位操作系统 电脑桌面出现this computer is being attacked的窗口

    本人为win7 64位操作系统,戴尔笔记本电脑. 昨天在教室写程序来着,突然桌面上出现this computer is being attacked的窗口,如下所示.每隔半分钟左右出现在电脑桌面上转两 ...

  2. WPF touch Scroll -触摸滚动

    借鉴地址:http://matthamilton.net/touchscrolling-for-scrollviewer 改造后支持上下和左右鼠标拖动滚动: using System; using S ...

  3. React 系列教程

    英文版:https://reactjs.org/docs/create-a-new-react-app.html 中文版:https://doc.react-china.org/docs/hello- ...

  4. Java线程和线程池

    Android中创建线程的方式有,new Thread,new Thread(Runnable),new Thread(Callable)的形式. A. 直接new Thread简单方便. B. ne ...

  5. c语言之sizeof的细节

    关于sizeof,我们知道sizeof并不是一个函数,尽管通常我们会用sizeof()用法(这是c语言的坑),在此关于sizeof的一些关键不被认知的进行一下总结: # include "i ...

  6. 【问题解决方案】之 cmd 窗口问题汇总

    cmd窗口C盘切不到其他盘的解决方案: 1.切换盘符,直接键入其他盘,如:>>D: (回车) 2.强行切换>>cd /d D: 或者 >>pushd C:

  7. JQuery动态修改样式

    JQuery动态修改样式 SetStyle(); function SetStyle() { $(".toolbar").remove(); $(".placeholde ...

  8. Servlet--HttpServlet实现doGet和doPost请求的原理

    转:https://blog.csdn.net/m0_38039437/article/details/75264012 一.HttpServlet简介 1.HttpServlet是GenericSe ...

  9. [转帖]前端-chromeF12 谷歌开发者工具详解 Console篇

    前端-chromeF12 谷歌开发者工具详解 Console篇 https://blog.csdn.net/qq_39892932/article/details/82655866 趁着搞 cloud ...

  10. [转帖]CentOS 6 服务器安全配置指南(通用)

    CentOS 6 服务器安全配置指南(通用) http://seanlook.com/2014/09/07/linux-security-general-settings/  发表于 2014-09- ...