语言
文本识别(也称为光学字符识别(OCR)受一组 Windows AI API 支持,这些 API 可以检测和提取图像中的文本并将其转换为计算机可读字符流。
这些 API 可以标识字符、字词、行、多边形文本边界,并为每个匹配提供置信度。 它们专门在具有神经处理单元(NPU)的设备上运行,使其比旧版Windows更快、更准确。Windows 平台 SDK 中的 Media.Ocr.OcrEngine API。
有关 API 详细信息,请参阅 文本识别(OCR)API 参考。
AI Dev Gallery 允许你运行交互式文本识别示例、查看其 C# 源代码,并将示例导出为 Visual Studio 项目。
探索文本识别功能
使用文本识别功能来识别和识别图像中的文本。 还可以获取已识别文本的文本边界及置信度分数。
注意
无法辨认或大小较小的字符可能会生成不准确的结果。
从文件中创建 ImageBuffer
在此 WinUI 示例中,我们调用一个 LoadImageBufferFromFileAsync 函数来从图像文件获取 ImageBuffer 。
在 LoadImageBufferFromFileAsync 函数中,我们会完成以下步骤:
- 从指定的文件路径创建 StorageFile 对象。
- 使用 OpenAsync 在 StorageFile 上打开流。
- 为流创建 BitmapDecoder。
- 调用位图解码器上的 GetSoftwareBitmapAsync,以获取 SoftwareBitmap 对象。
- 从 CreateForSoftwareBitmap 返回图像缓冲区。
using Microsoft.Windows.AI.Imaging;
using Microsoft.Graphics.Imaging;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
public async Task<ImageBuffer> LoadImageBufferFromFileAsync(string filePath)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
SoftwareBitmap bitmap = await decoder.GetSoftwareBitmapAsync();
if (bitmap == null)
{
return null;
}
return ImageBuffer.CreateForSoftwareBitmap(bitmap);
}
#include <iostream>
#include <sstream>
#include <winrt/Microsoft.Windows.AI.Imaging.h>
#include <winrt/Windows.Graphics.Imaging.h>
#include <winrt/Microsoft.Graphics.Imaging.h>
#include <winrt/Microsoft.UI.Xaml.Controls.h>
#include<winrt/Microsoft.UI.Xaml.Media.h>
#include<winrt/Microsoft.UI.Xaml.Shapes.h>
using namespace winrt;
using namespace Microsoft::UI::Xaml;
using namespace Microsoft::Windows::AI;
using namespace Microsoft::Windows::AI::Imaging;
using namespace winrt::Microsoft::UI::Xaml::Controls;
using namespace winrt::Microsoft::UI::Xaml::Media;
winrt::Windows::Foundation::IAsyncOperation<winrt::hstring>
MainWindow::RecognizeTextFromSoftwareBitmap(
Windows::Graphics::Imaging::SoftwareBitmap const& bitmap)
{
winrt::Microsoft::Windows::AI::Imaging::TextRecognizer textRecognizer =
EnsureModelIsReady().get();
Microsoft::Graphics::Imaging::ImageBuffer imageBuffer =
Microsoft::Graphics::Imaging::ImageBuffer::CreateForSoftwareBitmap(bitmap);
RecognizedText recognizedText =
textRecognizer.RecognizeTextFromImage(imageBuffer);
std::wstringstream stringStream;
for (const auto& line : recognizedText.Lines())
{
stringStream << line.Text().c_str() << std::endl;
}
co_return winrt::hstring{ stringStream.str()};
}
识别位图图像中的文本
以下示例显示了如何将 SoftwareBitmap 对象中的某些文本识别为单个字符串值:
- 通过调用 函数创建
EnsureModelIsReady对象,该函数还会确认系统上存在语言模型。 - 使用在之前的代码片段中获取的位图,我们可调用
RecognizeTextFromSoftwareBitmap函数。 - 在位图上调用 CreateForSoftwareBitmap 以获取 ImageBuffer 对象。
- 调用 RecognizeTextFromImage 从 ImageBuffer 获取已识别的文本。
- 创建 wstringstream 对象,并使用已识别的文本进行加载。
- 返回字符串。
注意
该 EnsureModelIsReady 函数检查文本识别模型的就绪状态(并在必要时安装)。
using Microsoft.Windows.AI.Imaging;
using Microsoft.Windows.AI;
using Microsoft.Graphics.Imaging;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
public async Task<string> RecognizeTextFromSoftwareBitmap(SoftwareBitmap bitmap)
{
TextRecognizer textRecognizer = await EnsureModelIsReady();
ImageBuffer imageBuffer = ImageBuffer.CreateForSoftwareBitmap(bitmap);
RecognizedText recognizedText = textRecognizer.RecognizeTextFromImage(imageBuffer);
StringBuilder stringBuilder = new StringBuilder();
foreach (var line in recognizedText.Lines)
{
stringBuilder.AppendLine(line.Text);
}
return stringBuilder.ToString();
}
public async Task<TextRecognizer> EnsureModelIsReady()
{
if (TextRecognizer.GetReadyState() == AIFeatureReadyState.NotReady)
{
var loadResult = await TextRecognizer.EnsureReadyAsync();
if (loadResult.Status != AIFeatureReadyResultState.Success)
{
throw new Exception(loadResult.ExtendedError.Message);
}
}
return await TextRecognizer.CreateAsync();
}
winrt::Windows::Foundation::IAsyncOperation<winrt::Microsoft::Windows::AI::Imaging::TextRecognizer> MainWindow::EnsureModelIsReady()
{
if (winrt::Microsoft::Windows::AI::Imaging::TextRecognizer::GetReadyState() == AIFeatureReadyState::NotReady)
{
auto loadResult = TextRecognizer::EnsureReadyAsync().get();
if (loadResult.Status() != AIFeatureReadyResultState::Success)
{
throw winrt::hresult_error(loadResult.ExtendedError());
}
}
return winrt::Microsoft::Windows::AI::Imaging::TextRecognizer::CreateAsync();
}
获取字词边界和置信度
下面介绍了如何将 SoftwareBitmap 对象中每个词的 BoundingBox 可视化为 Grid 元素上彩色编码多边形的集合。
注意
在本示例中,我们假设已创建 TextRecognizer,并已将其传入函数。
using Microsoft.Windows.AI.Imaging;
using Microsoft.Graphics.Imaging;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
public void VisualizeWordBoundariesOnGrid(
SoftwareBitmap bitmap,
Grid grid,
TextRecognizer textRecognizer)
{
ImageBuffer imageBuffer = ImageBuffer.CreateForSoftwareBitmap(bitmap);
RecognizedText result = textRecognizer.RecognizeTextFromImage(imageBuffer);
SolidColorBrush greenBrush = new SolidColorBrush(Microsoft.UI.Colors.Green);
SolidColorBrush yellowBrush = new SolidColorBrush(Microsoft.UI.Colors.Yellow);
SolidColorBrush redBrush = new SolidColorBrush(Microsoft.UI.Colors.Red);
foreach (var line in result.Lines)
{
foreach (var word in line.Words)
{
PointCollection points = new PointCollection();
var bounds = word.BoundingBox;
points.Add(bounds.TopLeft);
points.Add(bounds.TopRight);
points.Add(bounds.BottomRight);
points.Add(bounds.BottomLeft);
Polygon polygon = new Polygon();
polygon.Points = points;
polygon.StrokeThickness = 2;
if (word.MatchConfidence < 0.33)
{
polygon.Stroke = redBrush;
}
else if (word.MatchConfidence < 0.67)
{
polygon.Stroke = yellowBrush;
}
else
{
polygon.Stroke = greenBrush;
}
grid.Children.Add(polygon);
}
}
}
void MainWindow::VisualizeWordBoundariesOnGrid(
Windows::Graphics::Imaging::SoftwareBitmap const& bitmap,
Grid const& grid,
TextRecognizer const& textRecognizer)
{
Microsoft::Graphics::Imaging::ImageBuffer imageBuffer =
Microsoft::Graphics::Imaging::ImageBuffer::CreateForSoftwareBitmap(bitmap);
RecognizedText result = textRecognizer.RecognizeTextFromImage(imageBuffer);
auto greenBrush = SolidColorBrush(winrt::Microsoft::UI::Colors::Green());
auto yellowBrush = SolidColorBrush(winrt::Microsoft::UI::Colors::Yellow());
auto redBrush = SolidColorBrush(winrt::Microsoft::UI::Colors::Red());
for (const auto& line : result.Lines())
{
for (const auto& word : line.Words())
{
PointCollection points;
const auto& bounds = word.BoundingBox();
points.Append(bounds.TopLeft);
points.Append(bounds.TopRight);
points.Append(bounds.BottomRight);
points.Append(bounds.BottomLeft);
winrt::Microsoft::UI::Xaml::Shapes::Polygon polygon{};
polygon.Points(points);
polygon.StrokeThickness(2);
if (word.MatchConfidence() < 0.33)
{
polygon.Stroke(redBrush);
}
else if (word.MatchConfidence() < 0.67)
{
polygon.Stroke(yellowBrush);
}
else
{
polygon.Stroke(greenBrush);
}
grid.Children().Append(polygon);
}
}
}
负责任的人工智能
我们遵循 了Microsoft负责任的 AI 标准 中所述的核心原则和做法,以确保这些 API 可信、安全且负责任地构建。 有关向应用添加文本识别的指南,请参阅Windows 上负责任的生成式 AI 开发。