C#でバーコードやQRコードをOCRで読む方法

IronOCRを使ってC#でBarCodeとQRコードを読み取る方法

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronOCRはReadBarCodes = trueを設定することにより、C#でバーコードとQRコードを読み取ります。 QRコード、Code 128、Data Matrixを含む20以上のバーコード形式をサポートしています。

クイックスタート: PDF からバーコードを即座に読み取る

1つの設定でBarCode検出を有効にし、IronOCRでPDFをスキャンしてください。 以下のコードは、BarCode読み取りをオンにし、PDFを処理し、デコードされた値を取得する方法を示しています。

Nuget Icon今すぐ NuGet で PDF を作成してみましょう:

  1. NuGet パッケージ マネージャーを使用して IronOCR をインストールします

    PM > Install-Package IronOcr

  2. このコード スニペットをコピーして実行します。

    var result = new IronOcr.IronTesseract() { Configuration = new IronOcr.TesseractConfiguration { ReadBarCodes = true } }.Read(new IronOcr.OcrPdfInput("document.pdf"));
    foreach(var bc in result.Barcodes) Console.WriteLine(bc.Value);
  3. 実際の環境でテストするためにデプロイする

    今すぐ無料トライアルでプロジェクトに IronOCR を使い始めましょう
    arrow pointer


どのように PDF ドキュメントから BarCode を読み取りますか?

IronTesseractオブジェクトを作成し、読み取りを実行します。 バーコード検出を有効にするには、ReadBarCodes プロパティを true に設定します。 OcrPdfInput コンストラクタを使ってPDFドキュメントをインポートします。 取り込んだPDFに対してOCRを実行するには、Readメソッドを使います。

以下は、このPDF文書を使用した例です:

:path=/static-assets/ocr/content-code-examples/how-to/barcodes-read-barcodes.cs
using IronOcr;
using System;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Enable barcode reading
ocrTesseract.Configuration.ReadBarCodes = true;

// Add PDF
using var imageInput = new OcrPdfInput("pdfWithBarcodes.pdf");

// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Output detected barcodes and text values
Console.WriteLine("Extracted text:");
Console.WriteLine(ocrResult.Text);
Console.WriteLine("Extracted barcodes:");
foreach (var barcode in ocrResult.Barcodes)
{
    Console.WriteLine(barcode.Value);
}
Imports IronOcr
Imports System

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Enable barcode reading
ocrTesseract.Configuration.ReadBarCodes = True

' Add PDF
Dim imageInput = New OcrPdfInput("pdfWithBarcodes.pdf")

' Perform OCR
Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Output detected barcodes and text values
Console.WriteLine("Extracted text:")
Console.WriteLine(ocrResult.Text)
Console.WriteLine("Extracted barcodes:")
For Each barcode In ocrResult.Barcodes
	Console.WriteLine(barcode.Value)
Next barcode
$vbLabelText   $csharpLabel
IronOCRのデバッグ出力はPDFからテキストと3つのバーコード(A,B,C)を抽出したものです。

複数の BarCode 値がバーコードの下に表示され、抽出されたテキストに含まれます。

なぜIronOCRはテキストとBarCodeの両方の値を抽出するのですか?

IronOCRの二重抽出は包括的な文書分析を提供します。 テキストとバーコードの両方を含むドキュメントを処理する場合、ライブラリは standard OCR text extraction を実行し、同時にバーコード シンボロジーをデコードします。 この統一されたアプローチにより、複数の処理パスや個別のライブラリが不要になります。

テキスト抽出は人間が読める要素をキャプチャし、BarCode検出は機械が読めるデータを識別してデコードします。 これは、バーコードの値が印刷されたテキストと関連する請求書、出荷ラベル、在庫報告書などの文書に役立ちます。 OcrResultクラスは、これらの出力を分離し、Textプロパティを通してテキストにアクセスし、Barcodesコレクションを通してバーコードデータにアクセスします。

どのような BarCode フォーマットがサポートされていますか?

IronOCRは20以上のバーコード形式をサポートしています:

1次元BarCode:

  • コード128、コード39、コード93
  • EAN-13、EAN-8
  • UPC-A、UPC-E
  • コードバー
  • ITF(インターリーブ2/5)
  • 三井住友海上
  • プレッシー

2Dバーコード:

  • QRコード
  • データマトリックス
  • PDF417
  • アステカコード
  • MaxiCode

MICR小切手の読み取りアイデンティティ文書の処理のような特殊なアプリケーションでは、IronOCRのバーコード機能がテキスト抽出機能を補完します。

バーコード読み取り専用ライブラリの代わりに OCR を使用すべきなのはどのような場合ですか?

IronOCRの統合バーコード読み取りをお選びください:

1.混合コンテンツ処理:テキストとBarCodeの両方を含む文書(出荷ラベル、請求書、またはスキャンされた文書)。 2.単一ライブラリ優先:依存関係を最小限に抑え、1つのソリューションを使用したい。 3.PDF処理: あなたはすでにPDFのOCRテキスト抽出にIronOCRを使用しています。 4.複雑なドキュメントレイアウト:文書には、テキスト領域やテーブル内にバーコードが埋め込まれています。

以下の場合は、専用の BarCode ライブラリを使用してください:

  • バーコードのみの大量画像の処理
  • リアルタイムの BarCode スキャンが必要(応答時間 50ms 未満)
  • 特殊なアルゴリズムを必要とする、破損したバーコードや低品質のバーコードの処理
  • カメラの最適化によるモバイルバーコードスキャニングの実装

文書から QR コードを読み取るにはどうすればよいですか?

. <! -- ドキュメントからqrコードを読み取る方法を実演するスクリーンショット? IronPdfで-->。 <!ステップバイステップのプロセスを示すスクリーンショット -->。

バーコード読み取りと同様に、ReadBarCodes プロパティを true に設定します。 ファイルパス以外のコード変更は必要ありません。 このPDF文書をQRコードで処理します:

:path=/static-assets/ocr/content-code-examples/how-to/barcodes-read-qr-codes.cs
using IronOcr;
using System;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Enable barcode reading
ocrTesseract.Configuration.ReadBarCodes = true;

// Add PDF
using var imageInput = new OcrPdfInput("pdfWithQrCodes.pdf");

// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Output detected barcodes and text values
Console.WriteLine("Extracted text:");
Console.WriteLine(ocrResult.Text);
Console.WriteLine("Extracted barcodes:");
foreach (var barcode in ocrResult.Barcodes)
{
    Console.WriteLine(barcode.Value);
}
Imports IronOcr
Imports System

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Enable barcode reading
ocrTesseract.Configuration.ReadBarCodes = True

' Add PDF
Dim imageInput = New OcrPdfInput("pdfWithQrCodes.pdf")

' Perform OCR
Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Output detected barcodes and text values
Console.WriteLine("Extracted text:")
Console.WriteLine(ocrResult.Text)
Console.WriteLine("Extracted barcodes:")
For Each barcode In ocrResult.Barcodes
	Console.WriteLine(barcode.Value)
Next barcode
$vbLabelText   $csharpLabel
Visual StudioでのIronOCR出力。ドキュメントから抽出されたテキストと正常にデコードされたQRコードA、B、Cを示す。

なぜ同じ設定が BarCode と QR コードの両方で機能するのですか?

IronOCRの統一バーコード検出エンジンは、すべての機械読み取り可能なコードを同等に扱います。 The ReadBarCodes configuration activates a comprehensive symbology detector that recognizes both 1D (linear barcodes) and 2D (QR codes, Data Matrix) formats without requiring format-specific settings. このデザインは、実装を簡素化し、構成の複雑さを軽減します。

検出アルゴリズムは自動的に

  • パターン認識に基づいてシンボルタイプを識別
  • 適切なデコードアルゴリズムを適用
  • 方向とサイズのバリエーションに対応
  • バーコードの種類に関係なく、一貫した形式で結果を返します。

このアプローチは、コンピュータ ビジョン モデルが、普遍的な検出機能を提供するために複数のフォーマットでトレーニングする方法を反映しています。

OCRでQRコードを読み取るときによくある問題とは

QRコードを処理する際の一般的な課題には、次のようなものがあります:

1.解決課題:PDF の QR コードは、最小モジュール サイズ以下にダウンサンプリングされることがあります。DPI 設定を使用して、適切な解像度を確保してください (300 DPI 以上を推奨)。

2.画質:スキャンされたQRコードは、ぼやけやノイズ、歪みに悩まされることがよくあります。 画像補正フィルターを適用して、明瞭度を高めます:

// Apply filters to improve QR code readability
ocrTesseract.Configuration.ReadBarCodes = true;
var input = new OcrImageInput("qr-code-scan.jpg");
input.DeNoise();
input.Sharpen();
input.EnhanceResolution();

var result = ocrTesseract.Read(input);
// Apply filters to improve QR code readability
ocrTesseract.Configuration.ReadBarCodes = true;
var input = new OcrImageInput("qr-code-scan.jpg");
input.DeNoise();
input.Sharpen();
input.EnhanceResolution();

var result = ocrTesseract.Read(input);
' Apply filters to improve QR code readability
ocrTesseract.Configuration.ReadBarCodes = True
Dim input As New OcrImageInput("qr-code-scan.jpg")
input.DeNoise()
input.Sharpen()
input.EnhanceResolution()

Dim result = ocrTesseract.Read(input)
$vbLabelText   $csharpLabel

3.向きの問題:角度のあるQRコードは正しくデコードできないことがあります。 ページ回転検出を有効にして、ずれたドキュメントを処理します。

4.混在コンテンツの干渉:QRコードに重なるテキストやグラフィックは、検出を妨げる可能性があります。 必要に応じて、切り抜き領域を使用してQRコード領域を切り分けます。

QRコードの認識精度を高めるにはどうすればよいですか?

これらのテクニックを使用してQRコード認識を最適化します:

1.画像の前処理フィルターウィザードを使用して、最適なエンハンスメント設定を決定します:

// Enhanced QR code reading with preprocessing
var ocrTesseract = new IronTesseract();
ocrTesseract.Configuration.ReadBarCodes = true;

// Configure for better QR detection
var input = new OcrImageInput("document-with-qr.pdf");
input.TargetDPI = 300; // Ensure sufficient resolution
input.Binarize(); // Convert to black and white
input.DeNoise(); // Remove image artifacts

var result = ocrTesseract.Read(input);
// Enhanced QR code reading with preprocessing
var ocrTesseract = new IronTesseract();
ocrTesseract.Configuration.ReadBarCodes = true;

// Configure for better QR detection
var input = new OcrImageInput("document-with-qr.pdf");
input.TargetDPI = 300; // Ensure sufficient resolution
input.Binarize(); // Convert to black and white
input.DeNoise(); // Remove image artifacts

var result = ocrTesseract.Read(input);
Imports IronTesseract

' Enhanced QR code reading with preprocessing
Dim ocrTesseract = New IronTesseract()
ocrTesseract.Configuration.ReadBarCodes = True

' Configure for better QR detection
Dim input = New OcrImageInput("document-with-qr.pdf")
input.TargetDPI = 300 ' Ensure sufficient resolution
input.Binarize() ' Convert to black and white
input.DeNoise() ' Remove image artifacts

Dim result = ocrTesseract.Read(input)
$vbLabelText   $csharpLabel

2.複数のページを扱う複数ページにまたがるQRコードのある文書の場合:

// Process multi-page documents efficiently
using var pdfInput = new OcrPdfInput("multi-page-qr-document.pdf");
pdfInput.TargetDPI = 300;

var results = ocrTesseract.Read(pdfInput);
foreach (var page in results.Pages)
{
    Console.WriteLine($"Page {page.PageNumber}:");
    foreach (var barcode in page.Barcodes)
    {
        Console.WriteLine($"  QR Code: {barcode.Value}");
        Console.WriteLine($"  Location: X={barcode.X}, Y={barcode.Y}");
    }
}
// Process multi-page documents efficiently
using var pdfInput = new OcrPdfInput("multi-page-qr-document.pdf");
pdfInput.TargetDPI = 300;

var results = ocrTesseract.Read(pdfInput);
foreach (var page in results.Pages)
{
    Console.WriteLine($"Page {page.PageNumber}:");
    foreach (var barcode in page.Barcodes)
    {
        Console.WriteLine($"  QR Code: {barcode.Value}");
        Console.WriteLine($"  Location: X={barcode.X}, Y={barcode.Y}");
    }
}
Imports System

' Process multi-page documents efficiently
Using pdfInput As New OcrPdfInput("multi-page-qr-document.pdf")
    pdfInput.TargetDPI = 300

    Dim results = ocrTesseract.Read(pdfInput)
    For Each page In results.Pages
        Console.WriteLine($"Page {page.PageNumber}:")
        For Each barcode In page.Barcodes
            Console.WriteLine($"  QR Code: {barcode.Value}")
            Console.WriteLine($"  Location: X={barcode.X}, Y={barcode.Y}")
        Next
    Next
End Using
$vbLabelText   $csharpLabel

3.非同期処理:複数のドキュメントでより良いパフォーマンスを得るには、非同期メソッドを使用してください:

// Asynchronous QR code reading
var result = await ocrTesseract.ReadAsync(imageInput);
// Asynchronous QR code reading
var result = await ocrTesseract.ReadAsync(imageInput);
' Asynchronous QR code reading
Dim result = Await ocrTesseract.ReadAsync(imageInput)
$vbLabelText   $csharpLabel

4.デバッグ認識の問題: 結果のハイライトを有効にして、IronOCRが何を検出したかを視覚化してください:

result.SaveAsHighlightedImage("qr-detection-debug.png");
result.SaveAsHighlightedImage("qr-detection-debug.png");
result.SaveAsHighlightedImage("qr-detection-debug.png")
$vbLabelText   $csharpLabel

大規模 BarCode 処理のパフォーマンス最適化

BarCode や QR コードを含む数千のドキュメントを処理する場合は、以下の最適化戦略を実行します:

1.マルチスレッドマルチスレッド処理を活用して、複数のドキュメントを同時に処理します:

// Process multiple documents in parallel
var documents = new[] { "doc1.pdf", "doc2.pdf", "doc3.pdf" };
var results = documents.AsParallel().Select(doc =>
{
    var tesseract = new IronTesseract();
    tesseract.Configuration.ReadBarCodes = true;
    return tesseract.Read(new OcrPdfInput(doc));
}).ToList();
// Process multiple documents in parallel
var documents = new[] { "doc1.pdf", "doc2.pdf", "doc3.pdf" };
var results = documents.AsParallel().Select(doc =>
{
    var tesseract = new IronTesseract();
    tesseract.Configuration.ReadBarCodes = true;
    return tesseract.Read(new OcrPdfInput(doc));
}).ToList();
' Process multiple documents in parallel
Dim documents = {"doc1.pdf", "doc2.pdf", "doc3.pdf"}
Dim results = documents.AsParallel().Select(Function(doc)
    Dim tesseract = New IronTesseract()
    tesseract.Configuration.ReadBarCodes = True
    Return tesseract.Read(New OcrPdfInput(doc))
End Function).ToList()
$vbLabelText   $csharpLabel

2.メモリ管理abort tokens を長時間実行する操作に使用してください:

// Implement cancellation for large batch processing
using var cts = new CancellationTokenSource();
ocrTesseract.Configuration.CancellationToken = cts.Token;

// Cancel if processing takes too long
cts.CancelAfter(TimeSpan.FromMinutes(5));
// Implement cancellation for large batch processing
using var cts = new CancellationTokenSource();
ocrTesseract.Configuration.CancellationToken = cts.Token;

// Cancel if processing takes too long
cts.CancelAfter(TimeSpan.FromMinutes(5));
' Implement cancellation for large batch processing
Using cts As New CancellationTokenSource()
    ocrTesseract.Configuration.CancellationToken = cts.Token

    ' Cancel if processing takes too long
    cts.CancelAfter(TimeSpan.FromMinutes(5))
End Using
$vbLabelText   $csharpLabel

3.結果のエクスポート:結果を検索可能なPDFとして保存し、テキストとBarCodeデータの両方を維持します:

// Export results with embedded barcode values
result.SaveAsSearchablePdf("output-with-barcodes.pdf");
// Export results with embedded barcode values
result.SaveAsSearchablePdf("output-with-barcodes.pdf");
' Export results with embedded barcode values
result.SaveAsSearchablePdf("output-with-barcodes.pdf")
$vbLabelText   $csharpLabel

ビジネス アプリケーションとの統合

IronOCRのバーコード機能は、既存の.NETアプリケーションとシームレスに統合されます。 一般的な統合シナリオは以下のとおりです:

  • 在庫管理:出荷明細から製品コードを抽出する
  • ドキュメントアーカイブ:埋め込まれたバーコード識別子によってスキャンされたドキュメントをインデックス化する。
  • 請求書処理財務ドキュメントで、BarCode SKU を行項目に一致させる。
  • 医療記録:医療フォームと一緒に患者のリストバンドバーコードを処理する。

大量の BarCode や QR コードを処理するプロダクション アプリケーションでは、処理状況の追跡を実装して、処理状況を監視し、実際の測定基準に基づいてパフォーマンスを最適化することを検討してください。

よくある質問

C#アプリケーションでBarCode読み取りを有効にするにはどうすればよいですか?

IronOCRでは、TesseractConfigurationでReadBarCodes = trueを設定することでバーコードの読み取りを有効にします。この設定一つで、通常のテキスト認識と並行してPDFや画像からのバーコード値の自動抽出が有効になり、20以上のバーコードフォーマットをサポートします。

同じ文書からテキストと BarCode の両方を読み取ることはできますか?

そうです、IronOCRは二重抽出を行います - 標準的なOCRによって人間が読めるテキストを取り込み、同時に機械が読めるバーコードをデコードします。OcrResultクラスはこれらの出力を分離し、テキストはTextプロパティから、バーコードデータはBarCodesコレクションからアクセスできるようになっています。

検出できるバーコード形式は?

IronOCRは、1次元バーコード(Code 128, Code 39, Code 93, EAN-13, EAN-8, UPC-A, UPC-E, Codabar, ITF, MSI, Plessey)と2次元バーコード(QR Code, Data Matrix, and more)を含む20以上のバーコードフォーマットをサポートしています。

PDF文書からBarCodeを抽出する方法を教えてください。

IronTesseractオブジェクトを作成し、ReadBarCodesをtrueに設定し、OcrPdfInputコンストラクタを使ってPDFをインポートし、Readメソッドを使用します。IronOcrはOCRを実行し、検出されたすべてのバーコードの値を抽出します。

テキストOCRとバーコード読み取りには、別々のライブラリが必要ですか?

IronOCRの統一されたアプローチは、複数の処理パスや別々のライブラリを必要としません。IronOCRは標準的なOCRテキスト抽出を行い、同時にバーコードのデコードを一度に行います。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

準備はできましたか?
Nuget ダウンロード 5,384,824 | バージョン: 2026.2 リリース