跳至頁尾內容
USING IRONOCR

C# 中的 OCR CodeProject Tutorial:使用 IronOCR 從影像中萃取文字

在C#中進行光學字元識別(OCR)讓您可以從掃描文件、圖像檔案和TIFF文件中提取可機器讀取的文字,並在.NET應用程式中使用。 使用IronOCR,一個.NET原生的OCR程式庫,您只需安裝一個NuGet套件,然後通過幾行程式碼即可從圖像中讀取文字——沒有外部服務,沒有運行時依賴,也沒有按次API費用。

開始您的IronOCR免費試用以便遵循下述程式碼範例。

您如何在.NET項目中安裝IronOCR?

將OCR新增到.NET 10項目的最快方法是通過NuGet套件管理器。 在您的項目目錄中打開終端並運行.NET CLI命令,或使用Visual Studio中的套件管理器控制台:

Install-Package IronOcr

安裝後,NuGet套件管理器會自動下載所有必需的程式集並建立引用。 IronOCR支持.NET Framework 4.6.2+、.NET Core 3.1+和.NET 5至.NET 10,所以它可用於控制臺應用程式、ASP.NET Core服務、WPF應用程式和Azure Functions。

您無需註冊授權碼即可在本地測試——在應用授權之前,輸出上會出現試用水印。 新增using指令,當您準備好生產時,在啟動時傳遞您的授權碼:

using IronOcr;

// Apply license key before any OCR calls (production only)
IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY";
using IronOcr;

// Apply license key before any OCR calls (production only)
IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY";
Imports IronOcr

' Apply license key before any OCR calls (production only)
IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY"
$vbLabelText   $csharpLabel

查看IronOCR授權頁面以了解價格和激活詳情。

您如何從圖像文件中提取文字?

核心OCR工作流程涉及三個物件:OcrResult(輸出)。 下述範例會讀取一個PNG檔案並將識別的文字列印到控制台。

using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
input.LoadImage("sample-document.png");

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
input.LoadImage("sample-document.png");

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    input.LoadImage("sample-document.png")

    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

光學字元識別輸出

C#中的OCR CodeProject教程:使用IronOCR從圖像中提取文字:圖像1 - OCR輸出截圖

IronTesseract將Tesseract 5引擎包裝成.NET友好的預設值,並進行自動模型管理。 OcrInput.LoadImage接受PNG、JPEG、BMP、GIF、TIFF和WebP文件,因此您很少需要在將圖像傳遞給引擎之前進行格式轉換。

OcrResult.Text屬性返回所有識別字元用新行連接起來的普通字串。 要獲得更豐富的存取--單詞邊界框、置信度得分、每段文字--導航result.Characters集合。

一些值得了解的關鍵屬性:

  • result.Pages[0].Text -- 單頁面的文字
  • result.Words[n].Confidence -- 每個單詞的準確度(0.0 -- 1.0)
  • result.Pages[0].Paragraphs -- 進行結構化提取的段落分割

您還可以呼叫ocr.ReadAsync(input)在桌面或網頁應用程式中保持UI執行緒空閒。

您如何處理掃描文件和TIFF文件?

多頁TIFF文件在文件掃描工作流中很常見。 IronOCR使用LoadImageFrames處理它們,允許您選擇具體要處理的幀(頁面)——這在您只需要一個大檔案的子集時非常有用。

using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
int[] pageIndices = { 0, 1, 2 };
input.LoadImageFrames("scanned-documents.tiff", pageIndices);

// Correct skew and remove noise before reading
input.Deskew();
input.DeNoise();

OcrResult result = ocr.Read(input);

foreach (var page in result.Pages)
{
    Console.WriteLine($"Page {page.PageNumber}:");
    Console.WriteLine(page.Text);
}
using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
int[] pageIndices = { 0, 1, 2 };
input.LoadImageFrames("scanned-documents.tiff", pageIndices);

// Correct skew and remove noise before reading
input.Deskew();
input.DeNoise();

OcrResult result = ocr.Read(input);

foreach (var page in result.Pages)
{
    Console.WriteLine($"Page {page.PageNumber}:");
    Console.WriteLine(page.Text);
}
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    Dim pageIndices As Integer() = {0, 1, 2}
    input.LoadImageFrames("scanned-documents.tiff", pageIndices)

    ' Correct skew and remove noise before reading
    input.Deskew()
    input.DeNoise()

    Dim result As OcrResult = ocr.Read(input)

    For Each page In result.Pages
        Console.WriteLine($"Page {page.PageNumber}:")
        Console.WriteLine(page.Text)
    Next
End Using
$vbLabelText   $csharpLabel

多頁TIFF文件的OCR輸出

C#中的OCR CodeProject教程:使用IronOCR從圖像中提取文字:圖像2 - 多頁TIFF的OCR輸出

Deskew將圖像旋轉以校正平板掃描儀引入的任何傾斜。 DeNoise去除對Tesseract引擎造成困惑的斑點和JPEG影像。這兩個預處理濾鏡共同顯著提高了低質量掃描件的識別準確性。

對於困難的來源材料,提供了額外的OcrInput濾鏡:

  • input.Sharpen() -- 增強模糊圖像的邊緣對比度
  • input.Binarize() -- 將文件轉為黑白以適用於傳真品質文件
  • input.Scale(200) -- 將小圖像放大以獲得更好的字元分離
  • input.Rotate(90) -- 校正旋轉的文件方向

查看IronOCR圖像濾鏡指南,了解完整的預處理選項列表以及何時應用它們。

您如何配置OCR的語言支持?

預設情況下,IronOCR會讀取英文文字。 若要處理其他語言的文件,請安裝匹配的語言NuGet套件並在Language屬性。

dotnet add package IronOcr.Languages.German, IronOcr.Languages.French, IronOcr.Languages.Japanese

然後配置引擎,對於雙語文件,新增次要語言:

using IronOcr;
using IronOcr.Languages;

var ocr = new IronTesseract();
ocr.Language = OcrLanguage.German;

// For bilingual documents (e.g. Canadian forms, EU directives)
ocr.AddSecondaryLanguage(OcrLanguage.French);

using var input = new OcrInput();
input.LoadImage("german-invoice.png");

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
using IronOcr;
using IronOcr.Languages;

var ocr = new IronTesseract();
ocr.Language = OcrLanguage.German;

// For bilingual documents (e.g. Canadian forms, EU directives)
ocr.AddSecondaryLanguage(OcrLanguage.French);

using var input = new OcrInput();
input.LoadImage("german-invoice.png");

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
Imports IronOcr
Imports IronOcr.Languages

Dim ocr As New IronTesseract()
ocr.Language = OcrLanguage.German

' For bilingual documents (e.g. Canadian forms, EU directives)
ocr.AddSecondaryLanguage(OcrLanguage.French)

Using input As New OcrInput()
    input.LoadImage("german-invoice.png")

    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

IronOCR支持超過125種語言,每種語言作為單獨的輕量級NuGet套件提供。 這保持了您的生產二進位文件的精簡化--僅包括應用程式實際需要的語言資料。 當您呼叫AddSecondaryLanguage時,引擎在識別過程中混合主語言和輔助語言模型。

您如何處理OCR錯誤並改善識別結果?

生產應用程式需要對OCR管道進行錯誤處理。圖像質量問題、文件遺失或不支持的格式可能會導致例外情況。 將呼叫包裹在try/catch 塊中可提供潔淨的恢復路徑。

using IronOcr;

var ocr = new IronTesseract();
ocr.Language = OcrLanguage.English;

try
{
    using var input = new OcrInput();
    input.LoadImage("document.png");
    input.DeNoise();
    input.Deskew();

    OcrResult result = ocr.Read(input);

    if (result.Text.Length > 0)
    {
        Console.WriteLine("Recognised text:");
        Console.WriteLine(result.Text);
    }
    else
    {
        Console.WriteLine("No text was detected in the image.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"OCR error: {ex.Message}");
}
using IronOcr;

var ocr = new IronTesseract();
ocr.Language = OcrLanguage.English;

try
{
    using var input = new OcrInput();
    input.LoadImage("document.png");
    input.DeNoise();
    input.Deskew();

    OcrResult result = ocr.Read(input);

    if (result.Text.Length > 0)
    {
        Console.WriteLine("Recognised text:");
        Console.WriteLine(result.Text);
    }
    else
    {
        Console.WriteLine("No text was detected in the image.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"OCR error: {ex.Message}");
}
Imports IronOcr

Dim ocr As New IronTesseract()
ocr.Language = OcrLanguage.English

Try
    Using input As New OcrInput()
        input.LoadImage("document.png")
        input.DeNoise()
        input.Deskew()

        Dim result As OcrResult = ocr.Read(input)

        If result.Text.Length > 0 Then
            Console.WriteLine("Recognised text:")
            Console.WriteLine(result.Text)
        Else
            Console.WriteLine("No text was detected in the image.")
        End If
    End Using
Catch ex As Exception
    Console.WriteLine($"OCR error: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

一些在預期準確性較低時有助於提高準確性的重要設置:

  • ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto -- 讓Tesseract自動選擇單列、多列和單詞佈局
  • ocr.Configuration.ReadBarCodes = false -- 若您處理的僅是文字文件且希望更快的處理速度,可禁用條形碼檢測
  • ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5 -- 確保使用最快的可用引擎

對於欄位出現在可預測位置的結構化表單,請使用基於區域的OCR僅讀取重要區域:

using IronOcr;
using IronSoftware.Drawing;

var ocr = new IronTesseract();

using var input = new OcrInput();
var region = new CropRectangle(x: 50, y: 200, width: 600, height: 100);
input.LoadImage("form.png", region);

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
using IronOcr;
using IronSoftware.Drawing;

var ocr = new IronTesseract();

using var input = new OcrInput();
var region = new CropRectangle(x: 50, y: 200, width: 600, height: 100);
input.LoadImage("form.png", region);

OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
Imports IronOcr
Imports IronSoftware.Drawing

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    Dim region As New CropRectangle(x:=50, y:=200, width:=600, height:=100)
    input.LoadImage("form.png", region)

    Dim result As OcrResult = ocr.Read(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

限制識別到裁剪矩形可將大型圖像的處理時間減少最多90%。 這一技術特別適合提取發票號碼、表單欄位讀取和身份文件掃描。 更多詳情請參見區域OCR使用指南

您如何建立可搜尋的PDF文件?

將掃描圖像檔案轉換為可搜尋的PDF文件是最有價值的OCR用例之一。 生成的文件保留了原始視覺外觀,並嵌入了不可見的文字層,PDF查看器、搜索引擎和螢幕閱讀器可以對其進行索引。

using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
input.Title = "Quarterly Report Q1 2026";
input.LoadImage("page1.png");
input.LoadImage("page2.png");
input.LoadImage("page3.png");

OcrResult result = ocr.Read(input);
result.SaveAsSearchablePdf("searchable-output.pdf");

Console.WriteLine("Searchable PDF created.");
Console.WriteLine($"Pages processed: {result.Pages.Count}");
using IronOcr;

var ocr = new IronTesseract();

using var input = new OcrInput();
input.Title = "Quarterly Report Q1 2026";
input.LoadImage("page1.png");
input.LoadImage("page2.png");
input.LoadImage("page3.png");

OcrResult result = ocr.Read(input);
result.SaveAsSearchablePdf("searchable-output.pdf");

Console.WriteLine("Searchable PDF created.");
Console.WriteLine($"Pages processed: {result.Pages.Count}");
Imports IronOcr

Dim ocr As New IronTesseract()

Using input As New OcrInput()
    input.Title = "Quarterly Report Q1 2026"
    input.LoadImage("page1.png")
    input.LoadImage("page2.png")
    input.LoadImage("page3.png")

    Dim result As OcrResult = ocr.Read(input)
    result.SaveAsSearchablePdf("searchable-output.pdf")

    Console.WriteLine("Searchable PDF created.")
    Console.WriteLine($"Pages processed: {result.Pages.Count}")
End Using
$vbLabelText   $csharpLabel

輸出可搜尋PDF文件

C#中的OCR CodeProject教程:使用IronOCR從圖像中提取文字:圖像3 - 從輸入圖像建立的可搜尋PDF

SaveAsSearchablePdf寫入一個PDF/A相容文件,其中每個識別的字在原始圖像的準確像素坐標上。 Adobe Acrobat、macOS上的Preview和Foxit Reader都支持在這些文件中全文字搜索,並可在生成後立即使用。

對於基於Web的文件查看器或下游NLP管道,請改用result.SaveAsHocrFile("output.hocr")hOCR格式是一個開放的XML標準,將每個單詞的邊界框與文字一起編碼,能夠進行使用者端搜尋時突出顯示和單詞級別的可存取性註釋。

OcrResult可獲得的其他輸出格式:

  • result.SaveAsHocrFile("output.hocr") -- 帶有位置資料的hOCR XML
  • result.ToXDocument() -- 用於程式處理的LINQ-查詢XDocument
  • result.Pages[0].Text -- 適用於流式管線的逐頁純文字

對於已經使用IronPDF的應用程式,您可以將OcrResult直接驅動到PDF生成工作流中,結合OCR提取和PDF編輯於單一.NET過程中。

您如何同時讀取條碼和文字?

IronOCR可以讀取嵌入在列印文字中的條碼和QR碼,而不需要運行單獨的條碼程式庫。 只需一個配置屬性即可啟用此功能:

using IronOcr;

var ocr = new IronTesseract();
ocr.Configuration.ReadBarCodes = true;

using var input = new OcrInput();
input.LoadImage("shipping-label.png");

OcrResult result = ocr.Read(input);

Console.WriteLine("Text:");
Console.WriteLine(result.Text);

Console.WriteLine("Barcodes:");
foreach (var barcode in result.Barcodes)
{
    Console.WriteLine($"  {barcode.Format}: {barcode.Value}");
}
using IronOcr;

var ocr = new IronTesseract();
ocr.Configuration.ReadBarCodes = true;

using var input = new OcrInput();
input.LoadImage("shipping-label.png");

OcrResult result = ocr.Read(input);

Console.WriteLine("Text:");
Console.WriteLine(result.Text);

Console.WriteLine("Barcodes:");
foreach (var barcode in result.Barcodes)
{
    Console.WriteLine($"  {barcode.Format}: {barcode.Value}");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

支持的條碼格式包括Code 128、Code 39、EAN-13、EAN-8、UPC-A、UPC-E、PDF417、Data Matrix和QR碼。 請參見IronOCR條碼讀取指南以獲取詳細資訊。

此功能在物流、醫療保健和零售應用中特別有用,這些應用中的運單標籤、病人腕帶和產品標籤同時包含可人工閱讀的文字和可機器讀取的條碼。

您如何比較IronOCR與其他.NET OCR選項?

評估.NET OCR程式庫的開發人員通常會考慮IronOCR、Tesseract.NET和雲服務,例如Google Cloud Vision或Azure Computer Vision。 下表總結了主要區別:

根據開發者重點標準比較.NET OCR選項
標準 IronOCR Tesseract.NET Azure Computer Vision
部署 本地或雲端,無需外部調用 本地 僅雲端,需要網路連接
安裝 單個NuGet套件 多個套件+原生二進位文件 SDK+Azure訂閱
語言包 125+通過NuGet套件提供 手動下載tessdata 由Azure管理
可搜尋的PDF輸出 內建一個方法調用 未包含 未包含
圖像預處理 12+內建濾鏡 需要手動預處理 自動(伺服器端)
價格模式 一次性永久授權 開源(Apache 2.0) 按次計費

Tesseract由Google作為開源項目維護,在內部為IronOCR和Tesseract.NET提供動力。 IronOCR增加了.NET符合習慣的打包、自動模型管理和生產輸出功能(可搜尋的PDF、hOCR輸出),而這些功能是原始Tesseract綁定所缺乏的。 Azure Computer Vision提供了最先進的雲端準確性,但引入了網路延遲和按次成本,不適合高容量或離線工作流。

在資料隱私法規禁止將文件發送至外部服務的情況下——例如醫療記錄、法律文件、財務報表——像IronOCR這樣的本地程式庫是合適的選擇。

您的下一步是什麼?

您現在擁有了向任何.NET 10應用程式新增OCR的基礎:通過NuGet安裝、基本圖像到文字的提取、多頁TIFF處理、語言配置、錯誤處理、基於區域的讀取、條碼檢測和可搜尋的PDF生成。

若要進一步了解,請探索這些IronOCR資源:

如有關授權問題或需要在生產環境中部署IronOCR,請存取IronOCR授權頁面。 在您的評估期間,免費試用授權可去除輸出水印,而Iron Software的支持團隊在任何層次上都可為技術問題提供幫助。

現在開始使用IronOCR。
green arrow pointer

常見問題

什麼是OCR,它對C#開發者有什麼好處?

OCR,或光學文字識別,將掃描文件、PDF或影像轉換成可編輯和可搜尋的資料。對於C#開發者來說,OCR簡化了文件處理,使應用程式能夠從影像和掃描文件中擷取文字,增強資料的可存取性和可用性。

如何在C#專案中實作OCR?

您可以通過安裝IronOCR NuGet套件、建立IronTesseract實例、將影像載入至OcrInput並呼叫Read方法來在C#專案中實作OCR。返回的OcrResult包含擷取的文字和每字定位資料。

IronOCR支援哪些影像格式?

IronOCR支援PNG、JPEG、BMP、GIF、TIFF和WebP影像格式。這使您可以處理大多數常見影像型別,而無需在處理前轉換文件。

IronOCR能處理多頁TIFF文件嗎?

是的,IronOCR能處理多頁TIFF文件。使用LoadImageFrames和頁碼索引陣列來處理特定頁面,並迭代result.Pages以存取每頁文字。

使用IronOCR能夠從影像的特定區域擷取文字嗎?

是的,通過將CropRectangle傳遞給LoadImage來限制OCR到定義的區域。這大大減少了處理時間,對於從表單、發票和身份證文件中提取特定字段特別有用。

IronOCR是否支援不同語言的文字擷取?

IronOCR支援超過125種語言,每種語言都作為單獨的NuGet套件發佈。設置IronTesseract的Language屬性並呼叫AddSecondaryLanguage來處理雙語文件。

IronOCR與原生Tesseract.NET相比有什麼優勢?

IronOCR基於Tesseract引擎新增了遵循.NET慣例的包裝、自動化語言模型管理、內建影像預處理過濾器、可搜尋的PDF輸出、以及hOCR匯出,所有這些都整合在一個NuGet套件中,無需手動管理本機二進製檔案。

IronOCR如何提高文字辨識的準確性?

IronOCR提供預處理過濾器 -- 傾斜校正、消除噪聲、銳化、二值化、縮放和旋轉 -- 這些過濾器會在Tesseract引擎處理影像前校正常見掃描缺陷,從而提高對低品質源材料的辨識準確性。

IronOCR能夠讀取條碼和QR碼嗎?

是的,將ocr.Configuration.ReadBarCodes設置為true以在同一影像中偵測條碼和QR碼。結果可在OcrResult.Barcodes中獲得,包含格式型別和解碼值。

IronOCR在C#應用程式中的常見用例有哪些?

IronOCR用於文件管理系統、發票和收據資料擷取、從掃描存檔中生成可搜尋的PDF、表單欄位讀取、運輸標籤處理、醫療記錄數位化以及無障礙工具。

Kannaopat Udonpant
軟體工程師
在成為軟體工程師之前,Kannapat在日本北海道大學完成了環境資源博士學位。在攻讀學位期間,Kannapat還成為車輛機器人實驗室的一員,該實驗室隸屬於生產工程系。在2022年,他憑藉C#技能加入了Iron Software的工程團隊,專注於IronPDF。Kannapat珍視他的工作,因為他能直接向撰寫大部分IronPDF程式碼的開發者學習。除了同儕學習,Kannapat還喜歡在Iron Software工作的社交方面。不寫程式碼或文件時,Kannapat通常在他的PS5上玩遊戲或重看The Last of Us。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話