OCR英文全称是Optical Character Recognition,中文叫做光学字符识别。它是利用光学技术和计算机技术把印在或写在纸上的文字读取出来,并转换成一种计算机能够接受、人又可以理解的格式。文字识别是计算机视觉研究领域的分支之一。
NuGet包:PaddleOCRSharp
引用此包后会自动加载进所需的第三方依赖包
OCR文字识别库有很多,包括在线的,比较好的是百度的,为什么选用这个主要是,考虑的离线环境,PaddleOCR 的识别率还是不错的。
在使用的时候也遇到了一些问题,比如 内存释放不及时 等
底层的C++逻辑对内存的管理有一些小瑕疵,会有内存溢出的问题,通常不会出现
<Window x:Class="PaddleOCRWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="OCR离线版" Height="450" Width="900" WindowStartupLocation="CenterScreen">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*"/>
<ColumnDefinition/>
Grid.ColumnDefinitions>
<GroupBox Grid.Column="0" Header="预览" Margin="10,10,5,10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="1*"/>
Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,5">
<Button x:Name="BtnOCR" Content="打开图片" Height="30" Width="120" Margin="0,0,10,0" Click="BtnOCR_Click"/>
<Button x:Name="BtnClose" Content="清除" Height="30" Width="120" Click="BtnClose_Click"/>
StackPanel>
<Image Name="ImgPreview" Grid.Row="1" Margin="5"/>
Grid>
GroupBox>
<GroupBox Grid.Column="1" Header="识别结果" Margin="5,10,10,10">
<TextBox x:Name="TxtPreview" TextWrapping="Wrap" BorderThickness="0" IsReadOnly="True"/>
GroupBox>
Grid>
Window>
using Microsoft.Win32;
using PaddleOCRSharp;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
namespace PaddleOCRWPF
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnOCR_Click(object sender, RoutedEventArgs e)
{
StartDistinguish();
}
private void BtnClose_Click(object sender, RoutedEventArgs e)
{
ImgPreview.Source = null;
TxtPreview.Text = "";
}
///
/// 调用核心
///
private void StartDistinguish()
{
OpenFileDialog openFile = new()
{
Filter = "图片(*.bmp;*.jpg;*.jpeg;*.png)|*.bmp;*.jpg;*.jpeg;*.png"
};
if (!(bool)openFile.ShowDialog()) return;
Dispatcher.BeginInvoke(new Action(() =>
{
ImgPreview.Source = new BitmapImage(new Uri(openFile.FileName, UriKind.RelativeOrAbsolute));
}));
Task.Run(() =>
{
var imagebyte = File.ReadAllBytes(openFile.FileName);
Bitmap bitmap = new(new MemoryStream(imagebyte));
OCRModelConfig? config = null;
OCRParameter oCRParameter = new();
OCRResult ocrResult = new();
using (PaddleOCREngine engine = new(config, oCRParameter))
{
ocrResult = engine.DetectText(bitmap);
}
if (ocrResult != null)
{
Dispatcher.BeginInvoke(new Action(() =>
{
TxtPreview.Text = ocrResult.Text;
}));
}
});
}
}
}
追求高质量的识别效果建议使用百度的,想要练练手写些日常小工具还是比较推荐的