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. ASP.NET Core - 关于Tag Helper值得了解的五点

    如果您开发过ASP.NET Core Web应用程序,您应该已经熟悉了Tag Helper.ASP.NET Core应用程序依赖Tag Helper来呈现表单和表单字段是很常见的.所以,一个视图通常包 ...

  2. RabbitMQ详解(一)------简介与安装

    RabbitMQ 这个消息中间件,其实公司最近的项目中有用到,但是一直没有系统的整理,最近看完了<RabbitMQ实战  高效部署分布式消息队列>这本书,所以顺便写写. 那么关于 Rabb ...

  3. 记录一次.Net框架Bug发现和提交过程:.Net Framework和.Net Core均受影响

    SmtpClient一处代码编写错误导致异步发送邮件时DeliveryFormat配置项无法正确工作,异步操作已经完全不受我们设置属性控制了,UTF-8内容(如中文)转不转码完全看对方邮件服务器心情! ...

  4. ASP.NET MVC5+EF6+EasyUI 后台管理系统-WebApi的用法与调试

    1:ASP.NET MVC5+EF6+EasyUI 后台管理系统(1)-WebApi与Unity注入 使用Unity是为了使用我们后台的BLL和DAL层 2:ASP.NET MVC5+EF6+Easy ...

  5. eclipse 执行自带的maven命令无效

    原文地址:https://blog.csdn.net/qq_26386171/article/details/78262702 下面加上(前提是你的环境变量里已经配置过) -Dmaven.multiM ...

  6. Quartz-Spring定时任务器持久化,通过Service动态添加,删除,启动暂停任务

    原文地址:https://blog.csdn.net/ljqwstc/article/details/78257091 首先添加maven的依赖: <!--quartz定时任务--> &l ...

  7. c++入门之初话结构体

    结构体是一种具有一定数据结构思想的数据类型,我们在对待结构体的时候,用该从数据结构的思想去审视结构体.下面给出结构体的定义 struct mystruct {]; int score; double ...

  8. 【RSYSLOG】The Property Replacer【转】

    最近在调整日志平台的日志格式,一下是RSYSLOG的 Property Replacer 说明.鉴于RSYSLOG官网略坑,转发一下,原地址忘记了- - ||| The property replac ...

  9. rest-framework的权限组件

    权限组件 写在开头: 首先要在models表中添加一个用户类型的字段: class User(models.Model): name=models.CharField(max_length=32) p ...

  10. C99标准的柔性数组 (Flexible Array)

    [什么是柔性数组(Fliexible Array)] 柔性数组在C99中的定义是: 6.7.2.1 Structure and union specifiers As a special case, ...