Partager via


Commencez avec la reconnaissance de texte par intelligence artificielle (OCR)

La reconnaissance de texte, également appelée reconnaissance optique de caractères (OCR), est prise en charge dans Windows AI Foundry par le biais d’un ensemble d’API d’intelligence artificielle (IA) qui peuvent détecter et extraire du texte dans des images et les convertir en flux de caractères lisibles par ordinateur.

Ces API peuvent identifier des caractères, des mots, des lignes, des limites de texte polygonal et fournir des niveaux de confiance pour chaque correspondance. Ils sont également pris en charge exclusivement par l’accélération matérielle dans les appareils avec une unité de traitement neuronale (NPU), ce qui les rend plus rapides et plus précis que les API Windows.Media.Ocr.OcrEngine héritées dans le SDK de plateforme Windows.

Pour plus d’informations sur l’API, consultez la référence d’API pour la reconnaissance de texte (OCR).

Important

Voici une liste des fonctionnalités Windows AI et de la version du Kit de développement logiciel (SDK) d’application Windows dans laquelle elles sont actuellement prises en charge.

Version 1.8 Expérimentale (1.8.0-experimental1) - Effacement d'objets, Phi Silica, Ajustement fin LoRA pour Phi Silica, Synthèse des conversations (Text Intelligence)

Accès anticipé privé - Recherche sémantique

Version 1.7.1 (1.7.250401001) - Toutes les autres API

Ces API ne seront fonctionnelles que sur les appareils Windows Insider Preview (WIP) qui ont reçu la mise à jour du 7 mai. Le 28 au 29 mai, une mise à jour facultative sera publiée sur les appareils non WIP, suivie de la mise à jour du 10 juin. Cette mise à jour apporte avec elle les modèles IA requis pour que les API d’IA Windows fonctionnent. Ces mises à jour nécessitent également que toute application utilisant des API Windows AI ne puisse pas le faire tant que l’application n’a pas reçu l’identité du package au moment de l’exécution.

Que puis-je faire avec la reconnaissance de texte IA ?

Utilisez les fonctionnalités de reconnaissance de texte IA pour identifier et reconnaître du texte dans une image. Vous pouvez également obtenir les délimitations du texte et les scores de confiance pour le texte reconnu.

Créer un ImageBuffer à partir d’un fichier

Dans cet exemple WinUI, nous appelons une LoadImageBufferFromFileAsync fonction pour obtenir un ImageBuffer à partir d’un fichier image.

Dans la fonction LoadImageBufferFromFileAsync, nous effectuons les étapes suivantes :

  1. Créez un objet StorageFile à partir du chemin d’accès de fichier spécifié.
  2. Ouvrez un flux sur StorageFile à l’aide d’OpenAsync.
  3. Créez un BitmapDecoder pour le flux.
  4. Appelez GetSoftwareBitmapAsync sur le décodeur d’image bitmap pour obtenir un objet SoftwareBitmap.
  5. Renvoyez une mémoire tampon d’image à partir de CreateBufferAttachedToBitmap.
using Microsoft.Windows.Vision;
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.CreateBufferAttachedToBitmap(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()};
}

Reconnaître du texte dans une image bitmap

L’exemple suivant montre comment reconnaître du texte dans un objet SoftwareBitmap en tant que valeur de chaîne unique en procédant comme suit :

  1. Créez un objet TextRecognizer via un appel à la fonction EnsureModelIsReady, qui confirme également qu’un modèle de langage est présent sur le système.
  2. À l’aide de l’image bitmap obtenue dans l’extrait de code précédent, nous appelons la fonction RecognizeTextFromSoftwareBitmap.
  3. Appelez CreateBufferAttachedToBitmap sur le fichier image pour obtenir un objet ImageBuffer.
  4. Appelez RecognizeTextFromImage pour obtenir le texte reconnu à partir d’ImageBuffer.
  5. Créez un objet wstringstream et chargez-le avec le texte reconnu.
  6. Retourne la chaîne.

Remarque

La fonction EnsureModelIsReady est utilisée pour vérifier l’état de préparation du modèle de reconnaissance de texte (et l’installer si nécessaire).

using Microsoft.Windows.Vision;
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.CreateBufferAttachedToBitmap(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.EnsureNeeded)
    {
        var loadResult = await TextRecognizer.EnsureReadyAsync();
        if (loadResult.Status != PackageDeploymentStatus.CompletedSuccess)
        {
            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();
}

Obtenir les limites de mots et la confiance

Ici, nous montrons comment visualiser les BoundingBox de chaque mot dans un objet SoftwareBitmap sous la forme d’une collection de polygones codés en couleur sur un élément Grid.

Remarque

Pour cet exemple, nous supposons qu’un objet TextRecognizer a déjà été créé et transmis à la fonction.

using Microsoft.Windows.Vision;
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.CreateBufferAttachedToBitmap(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.Confidence < 0.33)
            {
                polygon.Stroke = redBrush;
            }
            else if (word.Confidence < 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);
        }
    }
}

Intelligence artificielle responsable

Nous avons utilisé une combinaison des étapes suivantes pour garantir que ces API d’imagerie sont fiables, sécurisées et générées de manière responsable. Nous vous recommandons de consulter les meilleures pratiques décrites dans développement d’IA responsable sur Windows lors de l’implémentation de fonctionnalités IA dans votre application.

Voir aussi