Onenote实现OCR识别图片
OCR识别推荐两个软件:
1. Tesseract:一个开源的,由谷歌维护的OCR软件。
2. Onenote:微软Office附带或者可以自己独立安装。
3. ONOM:别人封装的onenote api接口
这次讲Onenote实现的OCR识别。github地址:https://github.com/everywan/Extraction.OCR
注:2010版及其以后版本OCR实现方式类似:office将其转换为特定xm格式,然后提取想要的节点就ok了;onenote2007识别比较简单:通过MODI API接口直接之别。
我这里是实现了 office2007和office2010的ocr识别函数。
源程序下载:坚果云连接(.net4.5,vs2017RC。本机环境:windows10)
1 public class ExtractionOCR 2 { 3 #region 4 private static readonly ExtractionOCR instance = new ExtractionOCR(); 5 public static ExtractionOCR Instance { get { return instance; } } 6 public static string section_path { get; set; } 7 public static int waitTime = 3 * 1000; 8 #endregion 9 /// <summary> 10 /// office2007 MODI组件OCR识别 11 /// </summary> 12 /// <param name="imgPath"></param> 13 /// <returns></returns> 14 public string Ocr_2007(string imgPath) 15 { 16 try 17 { 18 var imgType = imgPath.Substring(imgPath.Length - 3); 19 var data = File.ReadAllBytes(imgPath); 20 string imgInfo = ""; 21 int i = 0; 22 var localimgFile = AppDomain.CurrentDomain.BaseDirectory + @"\" + Guid.NewGuid().ToString() + "." + imgType; 23 while (!imgInfo.Equals("转换成功") && i < 3) 24 { 25 ++i; 26 imgInfo = this.GetBase64(data, imgType, localimgFile); 27 } 28 MODI.Document doc = new MODI.Document(); 29 doc.Create(localimgFile); 30 MODI.Image image; 31 MODI.Layout layout; 32 doc.OCR(MODI.MiLANGUAGES.miLANG_CHINESE_SIMPLIFIED, true, true); 33 StringBuilder sb = new StringBuilder(); 34 image = (MODI.Image)doc.Images[0]; 35 layout = image.Layout; 36 sb.Append(layout.Text); 37 doc = null; 38 var localFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\" + Guid.NewGuid().ToString() + ".txt"; 39 File.WriteAllText(localFilePath, sb.ToString()); 40 Console.WriteLine(sb.ToString()); 41 return localFilePath; 42 } 43 catch (Exception e) 44 { 45 File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", e.ToString()); 46 return ""; 47 } 48 finally 49 { 50 GC.Collect(); 51 } 52 } 53 /// <summary> 54 /// onenote 2010,注意需要先在onenote中创建笔记本,并且将至转换为onenote2007格式 55 /// 推荐使用onenote2016(个人版即可),API与2010类似,(去掉XMLSchema.xs2007参数即可)其他可参考API参数命名。 56 /// 注意1:一定要将dll属性中的“嵌入互操作类型”属性关闭 57 /// </summary> 58 /// <param name="imgPath"></param> 59 /// <returns></returns> 60 public string Ocr_2010(string imgPath) 61 { 62 try 63 { 64 #region 确定section_path存在 65 section_path = @"C:\Users\zhensheng\Desktop\打杂\ocr\ocr.one"; 66 if (string.IsNullOrEmpty(section_path)) 67 { 68 Console.WriteLine("请先建立笔记本"); 69 File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "需要先在onenote中创建笔记本,并且将至转换为onenote2007格式,且将.one文件得路径赋值给section_path"); 70 return ""; 71 } 72 #endregion 73 #region 准备数据 74 //后缀 75 var imgType = Path.GetExtension(imgPath); 76 imgPath = imgPath.Replace(".", ""); 77 var data = File.ReadAllBytes(imgPath); 78 //根据大小确定重试次数 79 int fileSize = Convert.ToInt32(data.Length / 1024 / 1024); // 文件大小 单位M 80 string guid = Guid.NewGuid().ToString(); 81 string pageID = "{" + guid + "}{1}{B0}"; // 格式 {guid}{tab}{??} 82 string pageXml; 83 XNamespace ns; 84 var onenoteApp = new Microsoft.Office.Interop.OneNote.Application(); //onenote提供的API 85 if (onenoteApp == null) 86 { 87 File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "Microsoft.Office.Interop.OneNote.Application()创建失败"); 88 return ""; 89 } 90 //重试使用 91 XmlNode xmlNode; 92 int retry = 0; 93 #endregion 94 do 95 { 96 #region 创建页面并返回pageID 97 string sectionID; 98 onenoteApp.OpenHierarchy(section_path, null, out sectionID, CreateFileType.cftSection); 99 onenoteApp.CreateNewPage(sectionID, out pageID); 100 #endregion 101 #region 获取onenote页面xml结构格式 102 string notebookXml; 103 onenoteApp.GetHierarchy(null, HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2007); 104 var doc = XDocument.Parse(notebookXml); 105 ns = doc.Root.Name.Namespace; 106 #endregion 107 #region 将图片插入页面 108 Tuple<string, int, int> imgInfo = this.GetBase64(data, imgType); 109 var page = new XDocument(new XElement(ns + "Page", 110 new XElement(ns + "Outline", 111 new XElement(ns + "OEChildren", 112 new XElement(ns + "OE", 113 new XElement(ns + "Image", 114 new XAttribute("format", imgType), new XAttribute("originalPageNumber", "0"), 115 new XElement(ns + "Position", 116 new XAttribute("x", "0"), new XAttribute("y", "0"), new XAttribute("z", "0")), 117 new XElement(ns + "Size", 118 new XAttribute("width", imgInfo.Item2), new XAttribute("height", imgInfo.Item3)), 119 new XElement(ns + "Data", imgInfo.Item1))))))); 120 page.Root.SetAttributeValue("ID", pageID); 121 onenoteApp.UpdatePageContent(page.ToString(), DateTime.MinValue, XMLSchema.xs2007); 122 #endregion 123 #region 通过轮询访问获取OCR识别的结果,轮询超时次数为6次 124 int count = 0; 125 do 126 { 127 System.Threading.Thread.Sleep(waitTime * (fileSize > 1 ? fileSize : 1)); // 小于1M的都默认1M 128 onenoteApp.GetPageContent(pageID, out pageXml, PageInfo.piBinaryData, XMLSchema.xs2007); 129 } 130 while (pageXml == "" && count++ < 6); 131 #endregion 132 #region 删除页面 133 onenoteApp.DeleteHierarchy(pageID, DateTime.MinValue); 134 //onenoteApp = null; 135 #endregion 136 #region 从xml中提取OCR识别后的文档信息,然后输出到string中 137 XmlDocument xmlDoc = new XmlDocument(); 138 xmlDoc.LoadXml(pageXml); 139 XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); 140 nsmgr.AddNamespace("one", ns.ToString()); 141 xmlNode = xmlDoc.SelectSingleNode("//one:Image//one:OCRText", nsmgr); 142 #endregion 143 } 144 //如果OCR没有识别出信息,则重试三次(个人测试2010失败率为0.2~0.3) 145 while (xmlNode == null && retry++ < 3); 146 if (xmlNode == null) 147 { 148 File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", "OCR没有识别出值"); 149 return ""; 150 } 151 var localFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\" + Guid.NewGuid().ToString() + ".txt"; 152 File.WriteAllText(localFilePath, xmlNode.InnerText.ToString()); 153 Console.WriteLine(xmlNode.InnerText.ToString()); 154 return localFilePath; 155 } 156 catch (Exception e) 157 { 158 File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"\log.txt", e.ToString()); 159 return ""; 160 } 161 } 162 private string GetBase64(byte[] data, string imgType, string filePath) 163 { 164 using (MemoryStream ms = new MemoryStream()) 165 { 166 MemoryStream ms1 = new MemoryStream(data); 167 Bitmap bp = (Bitmap)Image.FromStream(ms1); 168 switch (imgType.ToLower()) 169 { 170 case "jpg": 171 bp.Save(ms, ImageFormat.Jpeg); 172 break; 173 case "jpeg": 174 bp.Save(ms, ImageFormat.Jpeg); 175 break; 176 case "gif": 177 bp.Save(ms, ImageFormat.Gif); 178 break; 179 case "bmp": 180 bp.Save(ms, ImageFormat.Bmp); 181 break; 182 case "tiff": 183 bp.Save(ms, ImageFormat.Tiff); 184 break; 185 case "png": 186 bp.Save(ms, ImageFormat.Png); 187 break; 188 case "emf": 189 bp.Save(ms, ImageFormat.Emf); 190 break; 191 default: 192 return "不支持的图片格式。"; 193 } 194 byte[] buffer = ms.ToArray(); 195 File.WriteAllBytes(filePath, buffer); 196 ms1.Close(); 197 ms.Close(); 198 return "转换成功"; 199 //return new Tuple<string, int, int>(Convert.ToBase64String(buffer), bp.Width, bp.Height); 200 } 201 } 202 private Tuple<string, int, int> GetBase64(byte[] data, string imgType) 203 { 204 using (MemoryStream ms = new MemoryStream()) 205 { 206 MemoryStream ms1 = new MemoryStream(data); 207 Bitmap bp = (Bitmap)Image.FromStream(ms1); 208 switch (imgType.ToLower()) 209 { 210 case "jpg": 211 bp.Save(ms, ImageFormat.Jpeg); 212 break; 213 case "jpeg": 214 bp.Save(ms, ImageFormat.Jpeg); 215 break; 216 case "gif": 217 bp.Save(ms, ImageFormat.Gif); 218 break; 219 case "bmp": 220 bp.Save(ms, ImageFormat.Bmp); 221 break; 222 case "tiff": 223 bp.Save(ms, ImageFormat.Tiff); 224 break; 225 case "png": 226 bp.Save(ms, ImageFormat.Png); 227 break; 228 case "emf": 229 bp.Save(ms, ImageFormat.Emf); 230 break; 231 default: 232 return new Tuple<string, int, int>("不支持的图片格式。", 0, 0); 233 } 234 byte[] buffer = ms.ToArray(); 235 ms1.Close(); 236 ms.Close(); 237 return new Tuple<string, int, int>(Convert.ToBase64String(buffer), bp.Width, bp.Height); 238 } 239 } 240 }
View Code
注意:
1. office2007需要安装office sp2补丁。
2. 谨记 关闭onenote.dll的 嵌入互操作类型 关闭
3. 如果是在服务器上使用office/onenote,需要开启 桌面体验 功能。
4. 如果是在服务器上使用onenote 2007,需要注意的是该组件是32位的,也就是说直接调用这个接口的必须是32位程序。
5. 如果是在服务器上使用onenote 2010,出现了(Retrieving the COM class factory for component with CLSID {D7FAC39E-7FF1-49AA-98CF-A1DDD316337E} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)))这个异常,请在调用此dll的服务登陆身份修改为管理员账号,并且用此账号创建onenote笔记本,另外,本示例代码需要笔记本格式为onenote2007
a.
6. 如果有其他异常,参阅微软文档: 错误代码
参考:
1. onenote 2010 ocr实现
2. 浅谈OCR之onenote 2010
3. Creating OneNote 2010 Extensions with the OneNote Object Model
4. 64位进程调用32位dll的解决方法 / 程序64位化带来的问题和思考
5. ONOM :封装的onenote api类
转载于:https://www.cnblogs.com/jiangtu/p/6523507.html
Onenote实现OCR识别图片相关推荐
- 百度云 OCR 识别图片验证码
操作系统:Mac OS Python版本:3.7.2 OCR:百度云 遇到的问题: API测试过程中,遇到API Resopnse 为图片验证码的情况,需要对图片进行识别得到text code,进行断 ...
- Python之ocr识别图片并转为excel文件
环境准备 1.开通腾讯文字识别服务 按照官网步骤进行开通:https://cloud.tencent.com/product/generalocr/getting-started 开通 ...
- 在ubuntu20.10系统下实现一键OCR识别图片截图中的内容使之转换为文本可以复制粘贴
目的:因为最近主要使用ubuntu系统,想要将视频中的文字提取出来,实现一键OCR识别图片截图中的内容使之转换为文本可以复制粘贴. 主要思路 利用截图软件gnome-screenshot 进行截取需要 ...
- python—简单数据抓取四(利用超级鹰的ocr识别图片验证码模拟登录超级鹰网站、利用百度云的ocr识别自如租房网价格图片获取到自如网的价格)
学习目标: python学习二十四 -简单数据抓取四 学习内容: 1.利用超级鹰的ocr识别图片验证码模拟登录超级鹰网站 2.利用百度云的ocr识别自如租房网的价格图片,获取到自如网的价格数据 1.利 ...
- Python OCR识别图片验证码(二)
操作系统:Windows Python:3.5 欢迎加入学习交流QQ群:657341423 上节讲到验证码的简单识别 但对于一些复杂的验证码,我们需要做一些简单的图片处理才能识别. 例如,我要识别这些 ...
- python实现OCR识别图片验证码
用cv2模块读取和显示模块 #导包cv2拓展模块 import cv2#先给窗体起名字 cv2.namedWindow("ShowImage1") cv2.namedWindow( ...
- 用Tesseract OCR识别图片文字
用tesseract ocr识别图片中的文字 准备 OCR与Tesseract介绍 将图片翻译成文字一般被称为光学文字识别(Optical Character Recognition,OCR).可以 ...
- C++调用Asprise OCR识别图片
在一个识别软件中发现了Asprise OCR的"身影",上官网查了一下相关信息,发现功能挺强大的,识别印刷体应该不错,遗憾的是好像不能识别中文,不过不知道它对扭曲后的英文识别能力怎 ...
- python3 ocr_python3 ocr 识别图片文字(CSDN验证码90%通过)
[实例简介] 上次下载了个pytesser_v0.0.1,它是 python2的,我给改成python3的.并且做成子目录下的模块吧. 这样不显得目录乱. 放在开发目录下就能用了 ocr. impor ...
- 百度OCR识别图片文字,解决image format error错误
文章目录 1 方法一 1.1 新建HttpUtils,用来发送post请求 1.2 获取 access token 1.3 获取图片的文字信息 1.4 测试 1.5 结果 2 方法二使用jsoup 2 ...
最新文章
- how tomcat works
- leetcode 1603. 设计停车系统
- 判断Python输入是否为数字
- 查找子串在母串中的位置、编写一个函数实现字符串拼接【数据结构实验报告算法详解】
- ES19-Java API全文搜索
- 微软不愿意提及的软肋:Win10的语音识别
- python 中 * 的使用和表示含义
- Mac新手教程:Adobe Illustrator 如何创建文件
- 基于大数据的人工智能象棋
- Sensor信号输出YUV、RGB、RAW DATA、JPEG 4种方式区别---转
- 数据库设计员工管理系统
- laypage分页java例子_laypage分页控件使用实例详解
- 转载英文单词备忘录词汇
- GBase 8c开发接口简述
- jump label
- 国科大《模式识别》课程总结
- 成功解决ValueError: pos_label=1 is not a valid label: array([‘0‘, ‘1‘], dtype=‘<U1‘)
- [Android Input系统]MotionEvent的序列化传送
- 统计之 - 离均差平方和
- Linux系统实现访问localhost(127.0.0.1)浏览WWW网站目录
热门文章
- AD14简明使用教程(同样试用于手工制板)
- 复杂网络分析 05 无标度网络
- 车标&车辆品牌检测Python[完整源码&视频安装教程&车标数据集&完整文档]
- 如何在windows10系统将用户名改为英文
- access更新查询非汉族加分_Access更新查询
- coreldraw x4怎么会蓝屏_电脑蓝屏怎么办 七种方案轻松搞定【图文】
- vscode安装程序员鼓励师插件
- AMS:startActivity桌面启动应用
- 【Pix4d精品教程】Pix4d中央子午线细化设置(测区跨两个分带)
- CREO:CREO软件之零件【编辑】之修饰、用户定义特征的简介及其使用方法(图文教程)之详细攻略