.NET MAUIでAndroidでOCRを実行する方法

チャクニット・ビン
チャクニット・ビン
2024年5月20日
更新済み 2024年12月10日
共有:
This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to .NET MAUIでAndroidでOCRを実行する方法

.NET MAUI(マルチプラットフォーム アプリ UI)は、Xamarin.Forms フレームワークの進化版であり、.NET を使用して Android、iOS、macOS、Windows 向けのクロスプラットフォーム アプリを作成するために設計されています。 .NET MAUIは、複数のプラットフォームで実行できるネイティブユーザーインターフェイスの構築プロセスを簡素化することを目指しています。

IronOcr.AndroidパッケージはOCRサポートをAndroidに提供します!!

IronOCR Androidパッケージ

IronOcr.Android パッケージは、.NET クロスプラットフォーム プロジェクトを介して Android デバイスで OCR 機能を実現します。 バニラのIronOCRパッケージは必要ありません。

PM > Install-Package IronOcr.Android
C# NuGetライブラリ for PDF

NuGetでインストール

Install-Package IronOcr.Android

.NET MAUIプロジェクトを作成

Visual Studio を開き、「新しいプロジェクトの作成」をクリックしてください。 MAUIを検索し、.NET MAUI Appを選択して「次へ」をクリックします。

.NET MAUI アプリプロジェクトを作成する

Include the IronOCR.Androidライブラリ

ライブラリはさまざまな方法で追加できます。 おそらく最も簡単なのは、NuGetを使用することです。

  1. Visual Studio内で、「Dependencies」を右クリックして、「NuGetパッケージの管理...」を選択します。

  2. 「参照」タブを選択し、「IronOcr.Android」を検索します。

  3. "IronOcr.Android"パッケージを選択し、「インストール」をクリックします。

    IronOcr.Android パッケージをダウンロード

    他のプラットフォームでの問題を防ぐために、csprojファイルを修正し、Androidプラットフォームをターゲットにしている場合にのみパッケージを含めるようにしてください。 そうするためには:

  4. プロジェクトを右クリックし、「プロジェクト ファイルの編集」を選択します。

  5. 次のとおり、新しい ItemGroup 要素を作成します:
    <ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    </ItemGroup>
XML
  1. 「IronOcr.Android」PackageReference を、私たちが今作成した ItemGroup の中に移動してください。

    上記の手順により、「IronOcr.Android」パッケージがiOSプラットフォームなどで使用されるのを防ぎます(そのためには、代わりにIronOcr.iOSをインストールしてください)。

「MainActivity.cs」を編集

  • Platforms -> Androidに移動して、「MainActivity.cs」ファイルを開きます。
  • MainActivityメソッドを追加し、Initializeメソッドを呼び出します。
namespace MAUIIronOCRAndroidSample
{
    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize 
 ConfigChanges.Orientation 
 ConfigChanges.UiMode 
 ConfigChanges.ScreenLayout 
 ConfigChanges.SmallestScreenSize 
 ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
        public MainActivity()
        {
            IronTesseract.Initialize(this);
        }
    }
}
namespace MAUIIronOCRAndroidSample
{
    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize 
 ConfigChanges.Orientation 
 ConfigChanges.UiMode 
 ConfigChanges.ScreenLayout 
 ConfigChanges.SmallestScreenSize 
 ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
        public MainActivity()
        {
            IronTesseract.Initialize(this);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

「MainPage.xaml」を編集

XAMLファイルを編集して、ボタンとOCR結果を表示するラベルを追加します。 例えば:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MAUIIronOCRAndroidSample.MainPage">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button
            Text="Import File"
            Clicked="ReadFileOnImport"
            Grid.Row="0"
            HorizontalOptions="Center"
            Margin="20, 20, 20, 10"/>

        <ScrollView
            Grid.Row="1"
            BackgroundColor="LightGray"
            Padding="10"
            Margin="10, 10, 10, 30">
            <Label x:Name="OutputText"/>
        </ScrollView>
    </Grid>

</ContentPage>
XML

"MainPage.xaml.cs"を編集

まず、IronTesseractオブジェクトのインスタンスを作成します。 クラス内でIronTesseractが一度初期化されていることを、以下のコード例に示すように確認してください。 メソッド内でインスタンス化すると、非効率的で予期しないエラーの原因となる場合があります。

次に、FilePicker.PickAsync メソッドを使用してファイルを選択し、FileResult から読み取りストリームを開きます。 新しいOcrInputオブジェクトを作成し、その中に画像を読み込みます。 テッセラクトインスタンスを使用して画像のOCRを実行し、テキストを取得します。 最終的に、結果のテキストをラベルに表示します。

現在の実装は、画像ファイルのみをサポートしていることにご注意ください。 このパッケージはまだPDFドキュメントをサポートしていません。 したがって、PDF関連の設定はデフォルトで無効化されており、そのままにしておくべきです。

using IronOcr;

namespace MAUIIronOCRAndroidSample;

public partial class MainPage : ContentPage
{
    // Initialize IronTesseract once in a class
    private IronTesseract ocrTesseract = new IronTesseract();

    public MainPage()
    {
        InitializeComponent();
        // Apply License key
        IronOcr.License.LicenseKey = "IRONOCR.MYLICENSE.KEY.1EF01";
    }

    private async void ReadFileOnImport(object sender, EventArgs e)
    {
        try
        {
            var options = new PickOptions
            {
                PickerTitle = "Please select a file"
            };
            var result = await FilePicker.PickAsync(options);
            if (result != null)
            {
                using var stream = await result.OpenReadAsync();
                // Instantiate OcrInput
                using var ocrInput = new OcrInput();
                // Load image stream
                ocrInput.LoadImage(stream);
                // Perform OCR
                var ocrResult = ocrTesseract.Read(ocrInput);
                OutputText.Text = ocrResult.Text;
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
}
using IronOcr;

namespace MAUIIronOCRAndroidSample;

public partial class MainPage : ContentPage
{
    // Initialize IronTesseract once in a class
    private IronTesseract ocrTesseract = new IronTesseract();

    public MainPage()
    {
        InitializeComponent();
        // Apply License key
        IronOcr.License.LicenseKey = "IRONOCR.MYLICENSE.KEY.1EF01";
    }

    private async void ReadFileOnImport(object sender, EventArgs e)
    {
        try
        {
            var options = new PickOptions
            {
                PickerTitle = "Please select a file"
            };
            var result = await FilePicker.PickAsync(options);
            if (result != null)
            {
                using var stream = await result.OpenReadAsync();
                // Instantiate OcrInput
                using var ocrInput = new OcrInput();
                // Load image stream
                ocrInput.LoadImage(stream);
                // Perform OCR
                var ocrResult = ocrTesseract.Read(ocrInput);
                OutputText.Text = ocrResult.Text;
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
}
Imports IronOcr

Namespace MAUIIronOCRAndroidSample

	Partial Public Class MainPage
		Inherits ContentPage

		' Initialize IronTesseract once in a class
		Private ocrTesseract As New IronTesseract()

		Public Sub New()
			InitializeComponent()
			' Apply License key
			IronOcr.License.LicenseKey = "IRONOCR.MYLICENSE.KEY.1EF01"
		End Sub

		Private Async Sub ReadFileOnImport(ByVal sender As Object, ByVal e As EventArgs)
			Try
				Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
				Dim result = Await FilePicker.PickAsync(options)
				If result IsNot Nothing Then
					Dim stream = Await result.OpenReadAsync()
					' Instantiate OcrInput
					Dim ocrInput As New OcrInput()
					' Load image stream
					ocrInput.LoadImage(stream)
					' Perform OCR
					Dim ocrResult = ocrTesseract.Read(ocrInput)
					OutputText.Text = ocrResult.Text
				End If
			Catch ex As Exception
				' Handle exceptions
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

最後に、.csprojファイルで、プロジェクトをAndroid用にのみビルドしていることを確認してください。 パッケージはAndroid用のみで追加されたため、すべてのプラットフォーム向けにプロジェクトをビルドすると失敗します。

プロジェクトを実行

これは、プロジェクトを実行してOCRを行う方法を示します。

.NET MAUIアプリプロジェクトを実行する

.NET MAUI アプリプロジェクトをダウンロード

このガイドの完全なコードをダウンロードできます。これは.zipファイルとして提供され、Visual Studioで.NET MAUIアプリプロジェクトとして開くことができます。

プロジェクトをダウンロードするにはここをクリックしてください。

AvaloniaでIronOCR for Androidを使用する

次のMAUIと同様に、IronOCR.Androidは上記で説明したのと同じ設定でAvaloniaプロジェクトに使用できます。

iOSでOCRを実行したい場合は、次の記事にアクセスして詳細をご確認ください:「.NET MAUIでiOSにOCRを実行する方法

チャクニット・ビン
ソフトウェアエンジニア
ChaknithはIronXLとIronBarcodeで作業しています。彼はC#と.NETに深い専門知識を持ち、ソフトウェアの改善と顧客サポートを支援しています。ユーザーとの対話から得た彼の洞察は、より良い製品、文書、および全体的な体験に貢献しています。