用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;
}

  

posted @   [Blowfish]  阅读(456)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示