LoginSignup
1
0

.NET C#でOCR

Posted at

環境

Windows 11 Pro (64bit)
Visual Studio Community 2022

手順

適当なプロジェクト名のディレクトリを用意する。
例:C:\Projects\.NET\OcrSample

dotnet new console
OcrSample.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

WinRTを使うためTargetFrameworkをnet8.0-windows10.0.22000.0とする。

Program.cs
using Windows.Graphics.Imaging;
using Windows.Media.Ocr;
using Windows.Storage;

try {
	var dir = Directory.GetCurrentDirectory();
	var folder = await StorageFolder.GetFolderFromPathAsync(dir);
	var file = await folder.GetFileAsync("hoge.png");

	using var stream = await file.OpenAsync(FileAccessMode.Read);
	var decoder = await BitmapDecoder.CreateAsync(stream);
	var bmp = await decoder.GetSoftwareBitmapAsync();

	var engine = OcrEngine.TryCreateFromUserProfileLanguages();
	var result = await engine.RecognizeAsync(bmp);	// OcrResult
	Console.WriteLine("<{0}>", result.Text);
}
catch (Exception e) {
	Console.WriteLine(e);
	return;
}
dotnet build

適当な画像ファイルを用意する。
例:hoge.png

bin\Debug\net8.0-windows10.0.22000.0\OcrSample.exe
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0