介绍 (Introduction)

Optical Character Recognition (OCR) is one of the Windows Runtime features that is currently accessible to WPF and WinForms applications. This is made possible thanks to the Windows 10 WinRT API Pack which provides quick and easy access to a number of WinRT APIs, including the OCR API. This article will take a look at how to go about using the OCR API in a WPF application.

光学字符识别(OCR)是WPF和WinForms应用程序当前可访问的Windows运行时功能之一。 Windows 10 WinRT API Pack使得这一切成为可能,它提供了快速简便的访问许多WinRT API的方法 ,包括OCR API。 本文将介绍如何在WPF应用程序中使用OCR API。

背景 (Background)

The sample project for this article is a .NET Core WPF application which contains a button for launching an open file dialog, used to select an image; a combo box for selecting the language to use for text extraction; a button for executing text extraction; and a button for copying the extracted text onto the clipboard. The language codes listed in the combo box represent languages installed on a device.

本文的示例项目是.NET Core WPF应用程序,其中包含用于启动打开文件对话框的按钮,该按钮用于选择图像。 一个组合框,用于选择用于文本提取的语言; 用于执行文本提取的按钮; 一个按钮,用于将提取的文本复制到剪贴板上。 组合框中列出的语言代码代表设备上安装的语言。

Sample application
样品申请

WinRT OCR (WinRT OCR)

The WinRT OCR API is a highly optimized optical character recognition system that currently supports 26 languages and works without requiring an internet connection. The API can extract text from a wide variety of images; from scanned documents to photos with text in natural scene images.

WinRT OCR API是高度优化的光学字符识别系统,当前支持26种语言,并且无需互联网即可运行。 该API可以从各种图像中提取文本。 从扫描的文档到自然场景图像中带有文字的照片。

Natural scene image text extraction
自然场景图像文本提取

To use the API in a WPF application, you have to reference the Microsoft.Windows.SDK.Contracts NuGet package and install languages which you intend to use for text extraction. If you attempt to do an extraction using a language that isn't installed on a device or isn't supported by the API, the extraction process will fail.

若要在WPF应用程序中使用该API,必须引用Microsoft.Windows.SDK.Contracts NuGet程序包并安装要用于文本提取的语言。 如果您尝试使用设备上未安装的语言或API不支持的语言进行提取,提取过程将失败。

Some languages installed on a machine
机器上安装的某些语言

提取文字 (Extracting Text)

With the Microsoft.Windows.SDK.Contracts package installed, using the OCR API is a very simple affair. In the sample project, the ExtractText() method in the OcrService class calls the RecognizeAsync() method, of the API's OcrEngine class, to extract text from a specified image using a specific language code.

安装了Microsoft.Windows.SDK.Contracts程序包后,使用OCR API是一件非常简单的事情。 在示例项目中, OcrService类中的ExtractText()方法调用API的OcrEngine类的RecognizeAsync()方法,以使用特定语言代码从指定图像中提取文本。

      public async Task<string> ExtractText(string image, string languageCode){... if (!GlobalizationPreferences.Languages.Contains(languageCode))throw new ArgumentOutOfRangeException($"{languageCode} is not installed.");StringBuilder text = new StringBuilder();await using (var fileStream = File.OpenRead(image)){var bmpDecoder = await BitmapDecoder.CreateAsync(fileStream.AsRandomAccessStream());var softwareBmp = await bmpDecoder.GetSoftwareBitmapAsync();var ocrEngine = OcrEngine.TryCreateFromLanguage(new Language(languageCode));var ocrResult = await ocrEngine.RecognizeAsync(softwareBmp);foreach (var line in ocrResult.Lines) text.AppendLine(line.Text);}return text.ToString();}    

In ExtractText, an ArgumentOutOfRangeException is thrown if the specified language code doesn't represent any language installed on a device. To get the resultant text to closely match the layout of the text in the image, I'm getting each line of extracted text and adding it to a StringBuilder before returning the overall text.

ExtractText ,如果指定的语言代码不代表设备上安装的任何语言,则抛出ArgumentOutOfRangeException 。 为了使生成的文本与图像中文本的布局紧密匹配,我获取了提取文本的每一行并将其添加到StringBuilder然后返回整个文本。

Text can also be extracted from an image by using a device's first preferred language. This is done by calling the OcrEngine's TryCreateFromUserProfileLanguages() method.

也可以使用设备的首选首选语言从图像中提取文本。 这是通过调用OcrEngineTryCreateFromUserProfileLanguages()方法来完成的。

public async Task<string> ExtractText(string image)
{...StringBuilder text = new StringBuilder();await using (var fileStream = File.OpenRead(image)){var bmpDecoder =await BitmapDecoder.CreateAsync(fileStream.AsRandomAccessStream());var softwareBmp = await bmpDecoder.GetSoftwareBitmapAsync();var ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();var ocrResult = await ocrEngine.RecognizeAsync(softwareBmp);foreach (var line in ocrResult.Lines) text.AppendLine(line.Text);}return text.ToString();
}

Using the code above, if a device's first preferred language is simplified Chinese, and the text in the image is also simplified Chinese, then the text extraction will be done successfully. The sample project's MainWindowViewModel uses the ExtractText() method that requires a language code to be passed as a parameter.

使用上面的代码,如果设备的首选语言是简体中文,并且图像中的文本也是简体中文,则文本提取将成功完成。 示例项目的MainWindowViewModel使用ExtractText()方法,该方法要求将语言代码作为参数传递。

public class MainWindowViewModel : ViewModelBase
{private readonly IDialogService dialogService;private readonly IOcrService ocrService;public MainWindowViewModel(IDialogService dialogSvc, IOcrService ocrSvc){dialogService = dialogSvc;ocrService = ocrSvc;}// Language codes of installed languages.public List<string> InstalledLanguages => GlobalizationPreferences.Languages.ToList();private string _imageLanguageCode;public string ImageLanguageCode{get => _imageLanguageCode;set{_imageLanguageCode = value;OnPropertyChanged();}}private string _selectedImage;public string SelectedImage{get => _selectedImage;set{_selectedImage = value;OnPropertyChanged();}}private string _extractedText;public string ExtractedText{get => _extractedText;set{_extractedText = value;OnPropertyChanged();}}#region Select Image Commandprivate RelayCommand _selectImageCommand;public RelayCommand SelectImageCommand =>_selectImageCommand ??= new RelayCommand(_ => SelectImage());private void SelectImage(){string image = dialogService.OpenFile("Select Image","Image (*.jpg; *.jpeg; *.png; *.bmp)|*.jpg; *.jpeg; *.png; *.bmp");if (string.IsNullOrWhiteSpace(image)) return;SelectedImage = image;ExtractedText = string.Empty;}#endregion#region Extract Text Commandprivate RelayCommandAsync _extractTextCommand;public RelayCommandAsync ExtractTextCommand =>_extractTextCommand ??= new RelayCommandAsync(ExtractText, _ => CanExtractText());private async Task ExtractText(){ExtractedText = await ocrService.ExtractText(SelectedImage, ImageLanguageCode);}private bool CanExtractText() => !string.IsNullOrWhiteSpace(ImageLanguageCode) &&!string.IsNullOrWhiteSpace(SelectedImage);#endregion#region Copy Text to Clipboard Commandprivate RelayCommand _copyTextToClipboardCommand;public RelayCommand CopyTextToClipboardCommand => _copyTextToClipboardCommand ??=new RelayCommand(_ => CopyTextToClipboard(), _ => CanCopyTextToClipboard());private void CopyTextToClipboard() => Clipboard.SetData(DataFormats.Text, _extractedText);private bool CanCopyTextToClipboard() => !string.IsNullOrWhiteSpace(_extractedText);#endregion
}

结论 (Conclusion)

As you can see, using the WinRT OCR API is quite a simple affair and it also works quite well in most cases. In comparison to Tesseract, I think it's a far better option, especially if you intend on extracting text from natural scene images.

如您所见,使用WinRT OCR API相当简单,并且在大多数情况下也能很好地工作。 与Tesseract相比,我认为这是一个更好的选择,尤其是如果您打算从自然场景图像中提取文本。

翻译自: https://www.codeproject.com/Articles/5276805/OCR-in-WPF-using-the-WinRT-OCR-API

使用WinRT OCR API的WPF中的OCR相关推荐

  1. 使用UWP人脸检测API在WPF中进行人脸检测

    目录 介绍 先决条件 背景 人脸检测 标记人脸 查看模型 视图 结论 Download repository 介绍 通用Windows平台的Windows.Media.FaceAnalysis名称空间 ...

  2. 一些WPF中的滤镜特效——Effect Library

    原文:一些WPF中的滤镜特效--Effect Library WPF支持类似PhotoShop的滤镜功能,称之为Effect.在.Net 4.0中,WPF就废弃了对BitMapEffect的支持,转向 ...

  3. 基于ArcGIS API for WPF路径分析源码实例

    说明: 本实例主要演示网络分析数据集制作,服务发布,最后基于ArcGIS API for WPF做路径分析. 本实例参考ArcGIS官方文档,想了解GIS网络分析可查阅官方文档. 本实例数据为西藏道路 ...

  4. 中安OCR文字识别系统V5.0 ——OCR文字识别开发包SDK

    一.中安OCR文字识别系统V5.0简介 中安OCR文字识别系统V5.0是一种光学字符识别(OCR)软件开发包(OCR SDK):中安OCR文字识别系统V5.0为软件开发人员.系统集成商.数据加工商(B ...

  5. WPF制作文字OCR软件(一):本地图片OCR识别

    WPF制作文字OCR软件(一):本地图片OCR识别 一.前言 上一篇文章,我使用python来进行文字OCR,但是python在图形化编程方面并不友好,所以我打算放弃使用python来搭建一款文字OC ...

  6. WPF中获取鼠标相对于屏幕的位置

    WPF中获取鼠标相对于屏幕的位置                                   周银辉 WPF编程时,我们经常使用Mouse.GetPosition(IInputElement ...

  7. 了解 WPF 中的路由事件和命令

    目录 路由事件概述 WPF 元素树 事件路由 路由事件和组合 附加事件 路由命令概述 操作中的路由命令 命令路由 定义命令 命令插入 路由命令的局限 避免命令出错 超越路由命令 路由处理程序示例 要想 ...

  8. 深入WPF中的图像画刷(ImageBrush)之1——ImageBrush使用举例

    深入WPF中的图像画刷(ImageBrush)之1--ImageBrush使用举例 2010年06月11日 星期五 15:20 昨天我在<简述WPF中的画刷(Brush) >中简要介绍了W ...

  9. WPF 中使用附加属性,将任意 UI 元素或控件裁剪成圆形(椭圆)

    原文:WPF 中使用附加属性,将任意 UI 元素或控件裁剪成圆形(椭圆) 版权声明:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可.欢迎转载.使用.重新发布,但务必保 ...

最新文章

  1. Java Data Base Connection(JDBC)
  2. leetcode915. 分割数组
  3. Linux关闭Tomcat服务器出现无法关闭 :8005端口未启动
  4. “不差钱”华为刷屏 拟募资60亿!
  5. Linux内核分析课程期中总结
  6. 理解Java的几张图
  7. 关于两个JS对象指向一个属性
  8. python怎么编程hello world用geany_第一个Hello World 程序
  9. php 同义词词库,php实现seo伪原创,同义词替换 | 学步园
  10. jquery发送ajax请求并设置请求头
  11. 经此一疫,互联网公司格局发生了哪些变化?
  12. Java设计模式的一些积累
  13. 哔哩哔哩android4.3,哔哩哔哩(tv.danmaku.bili) - 6.26.0 - 应用 - 酷安
  14. rabbitmq安装rabbitmq_delayed_message_exchange插件
  15. python3 模拟 ajax post请求
  16. Android 发展史:“吃货”就是这么练成的
  17. 数字化转型巨浪拍岸,成长型企业如何“渡河”?
  18. Fedora30 安装 WPS Office 2019 For Linux
  19. 如何使用JTable
  20. 多媒体——视频——使用摄像机录制视频

热门文章

  1. Can I debug relocated code at source-level with DS-5 Debugger?
  2. 做了一个app,返回三国武将的排序网页,记录一下,省得以后找不到
  3. 答题对战方案java_使用WebSocket实现实时多人答题对战游戏
  4. 熊孩子太调皮,送他Airblock无人机变身小神童
  5. linux性能监控工具-nmon安装使用详细教程
  6. LeetCode Day01:一年中的第几天
  7. 若能坚定信念,就能开创美好的未来
  8. 中国人误传了数千年的七句话(不可不看!) 转帖
  9. flask+python 实时视频流输出到前台
  10. wsl 2 中安装docker