用C++调用Windows.Media.Ocr接口实现图片的OCR识别
这个接口最开始是给UWP程序用的。C++里需要用C++/WinRT方式调用。默认参数的识别率也不是很高的样子。只支持Win10+。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <winrt/Windows.Storage.h> #include <winrt/Windows.Storage.Streams.h> #include <winrt/Windows.Graphics.Imaging.h> #include <winrt/Windows.Media.Ocr.h> #include <winrt/Windows.Globalization.h> #include <winrt/Windows.Foundation.h> #include <iostream> #include <locale.h> using namespace winrt; using namespace Windows::Storage; using namespace Windows::Storage::Streams; using namespace Windows::Graphics::Imaging; using namespace Windows::Media::Ocr; using namespace Windows::Globalization; using namespace winrt::Windows::Foundation; void InitializeWinRT() { init_apartment(); } SoftwareBitmap LoadImage( const winrt::hstring& imagePath) { StorageFile imageFile = StorageFile::GetFileFromPathAsync(imagePath).get(); IRandomAccessStream fileStream = imageFile.OpenAsync(FileAccessMode::Read).get(); BitmapDecoder decoder = BitmapDecoder::CreateAsync(fileStream).get(); SoftwareBitmap softwareBitmap = decoder.GetSoftwareBitmapAsync().get(); return softwareBitmap; } winrt::hstring PerformOcr( const SoftwareBitmap& softwareBitmap) { winrt::hstring languageTag = L "zh-CN" ; Windows::Globalization::Language lang(languageTag); OcrEngine ocrEngine = OcrEngine::TryCreateFromLanguage(lang); OcrResult ocrResult = ocrEngine.RecognizeAsync(softwareBitmap).get(); return ocrResult.Text(); } int main() { _wsetlocale(LC_ALL, L "zh-CN" ); InitializeWinRT(); winrt::hstring imagePath = L "c:\\test.jpg" ; SoftwareBitmap softwareBitmap = LoadImage(imagePath); winrt::hstring resultText = PerformOcr(softwareBitmap); std::wcout << L "识别结果:" << resultText.c_str() << std::endl; return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性