Created
January 14, 2025 17:15
-
-
Save ksasao/707d16870e5301804f134e66be6ec425 to your computer and use it in GitHub Desktop.
UWPで日本語OCR。XAMLは適当に作ってください。https://x.com/ksasao/status/1879207301850259523
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Windows.Graphics.Imaging; | |
using Windows.Media.Ocr; | |
using Windows.Storage.Pickers; | |
using Windows.Storage.Streams; | |
using Windows.Storage; | |
using Windows.UI.Xaml; | |
using Windows.UI.Xaml.Controls; | |
using System.Text; | |
// 空白ページの項目テンプレートについては、https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x411 を参照してください | |
namespace WinOCR | |
{ | |
/// <summary> | |
/// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。 | |
/// </summary> | |
public sealed partial class MainPage : Page | |
{ | |
public MainPage() | |
{ | |
this.InitializeComponent(); | |
} | |
private async void Button_Click(object sender, RoutedEventArgs e) | |
{ | |
// 画像ファイルの選択 | |
FileOpenPicker picker = new FileOpenPicker(); | |
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; | |
picker.ViewMode = PickerViewMode.Thumbnail; | |
picker.FileTypeFilter.Add(".jpg"); | |
picker.FileTypeFilter.Add(".png"); | |
var file = await picker.PickSingleFileAsync(); | |
if (file == null) | |
{ | |
return; | |
} | |
// SoftwareBitmapに画像を読み込み | |
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) | |
{ | |
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); | |
SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); | |
OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("ja")); | |
// OCR実行 | |
OcrResult ocrResult = await ocrEngine.RecognizeAsync(softwareBitmap); | |
StringBuilder sb = new StringBuilder(); | |
foreach (var line in ocrResult.Lines) { | |
sb.AppendLine(line.Text); | |
} | |
// 結果を表示 | |
RecognizedTextBlock.Text = sb.ToString(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment