C# 手写识别方案整理_天天热门

中年农码工   2023-05-13 23:59:39


(相关资料图)

书写识别,网上的大佬们都有输出。

书写识别存在的2个问题:

直接拿官网的案例(将 Windows Ink 笔划识别为文本和形状 - Windows apps | Microsoft Learn),会发现输出准确度不高。 另外如果书写过快,词组识别也是个问题,毕竟无法准确分割字之间的笔迹。

我结合之前开发经验,整理下书写识别比较完善的方案。

单个字的识别方案

1     private ListRecognize(StrokeCollection strokes) 2     { 3         if (strokes == null || strokes.Count == 0) 4             return null; 5         // 创建识别器 6         var recognizers = new Recognizers(); 7         var chineseRecognizer = recognizers.GetDefaultRecognizer(0x0804); 8         using var recContext = chineseRecognizer.CreateRecognizerContext(); 9         // 根据StrokeCollection构造 Ink 类型的笔迹数据。10         using var stream = new MemoryStream();11         strokes.Save(stream);12         using var inkStorage = new Ink();13         inkStorage.Load(stream.ToArray());14         using var inkStrokes = inkStorage.Strokes;15         //设置笔画数据16         using (recContext.Strokes = inkStrokes)17         {18             //识别笔画数据19             var recognitionResult = recContext.Recognize(out var statusResult);20             // 如果识别过程中出现问题,则返回null21             return statusResult == RecognitionStatus.NoError ?22                 recognitionResult.GetAlternatesFromSelection().OfType().Select(i =>i.ToString()).ToList() :23                 null;24         }25     }

这里单字识别,想要提高识别率,可以将stroke合并成一个:

1     var points = new StylusPointCollection();2     foreach (var stroke in strokes)3     {4         points.Add(new StylusPointCollection(stroke.StylusPoints));5     }6     var newStroke = new StrokeCollection7     {8         new Stroke(points)9     };

多字的识别方案

1     public IEnumerableRecognize(StrokeCollection strokes) 2     { 3         if (strokes == null || strokes.Count == 0) 4             return null; 5  6         using var analyzer = new InkAnalyzer(); 7         analyzer.AddStrokes(strokes,0x0804); 8         analyzer.SetStrokesType(strokes, StrokeType.Writing); 9         var status = analyzer.Analyze();10         if (status.Successful)11         {12             var alternateCollection = analyzer.GetAlternates();13             return alternateCollection.OfType().Select(x =>x.RecognizedString);14         }15         return null;16     }

看下效果图

环境及DLL引用

引用的命名空间是:Windows.Ink和MicroSoft.Ink,需要引用的DLL文件有四个。可点击下载:InkRecognizeDependencies.rar

IACore.dll、IALoader.dll、IAWinFX.dll,这三个DLL文件都是Intel集成显卡驱动的重要组成部分,包含了图形处理模块,尤其是IAWinFX为WPF应用提供了支持硬件加速的图形渲染。 Microsoft.Ink.dll

值得说明一下,Windows.Ink与Microsoft.Ink在平台支持上不同,如果有要适配不同版本的windows,需要去上方代码修改下

Microsoft.Ink支持Windows XP、Vista 和 Win7 等旧版 Windows,兼容性高。但Win10及以上版本,官方推荐使用Windows.Ink Windows.Ink,则仅支持Win8以上版本

引用了上面4个DLL文件后,还有2个环境问题:

在App.config文件中,对节点startup添加属性 useLegacyV2RuntimeActivationPolicy=\"true\" 修改项目配置为x86