Get Started with OCR in C# and VB.NET

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

IronOCR 是一款 C# 程式庫,讓 .NET 平台軟體開發人員能夠識別並讀取圖片及 PDF 文件中的文字。 這是一個純 .NET OCR 函式庫,採用目前已知最先進的 Tesseract 引擎。

安裝

透過 NuGet 套件管理員安裝

請透過 NuGet 套件管理員,在 Visual Studio 或命令列中安裝 IronOCR。 在 Visual Studio 中,請透過以下方式切換至控制台:

  • 工具 ->
  • NuGet 套件管理員 ->
  • 套件管理主控台
Install-Package IronOcr

至 NuGet 查看 IronOCR,以獲取更多版本更新與安裝資訊。

另有適用於不同平台的 IronOCR NuGet 套件

  • Windows: </https:>
  • Linux: </https:>
  • macOS: </https:>
  • macOS (ARM): </https:>

IronOcr.Extensions.AdvancedScan(適用於 Linux 和 macOS)

此套件適用於使用 Linux 和 Mac 系統,且希望同時享有 IronOCR 進階功能的使用者。

疑難排解

隨著此套件的最新更新,IronOCR 已將 OpenCV 依賴項整合至套件內部以簡化流程,因此,若開發人員目前在導入 OpenCV 依賴項時遇到以下錯誤。

The type of namespace name `OpenCvSharp` could not be found(are you missing a using directive or an assembly reference)

您可以安全地移除 OpenCV 命名空間,問題即可解決。

下載 IronOCR .ZIP 檔案

您亦可選擇透過 ZIP 檔案下載 IronOCR。 點擊此處直接下載 DLL 檔案。 下載 ZIP 檔案後:

.NET Framework 4.0+ 安裝說明:

  • 將 net40 資料夾中的 IronOcr.dll 加入您的專案
  • 接著請新增對以下組件的引用:

    • System.Co/nfiguration
    • System.Drawing
    • System.Web

.NET Standard、.NET Core 2.0+ 及 .NET 5 操作說明

  • 將 netstandard2.0 資料夾中的 IronOcr.dll 加入您的專案
  • 接著請新增 NuGet 套件參考至:

    • System.Drawing.Com/mon 4.7 或更高版本

下載 IronOCR 安裝程式(僅限 Windows)

另一種選擇是下載我們的 IronOCR 安裝程式,該程式將安裝 IronOCR 所需的所有資源,使其開箱即用。 請注意,此選項僅適用於 Windows 系統。 請點擊此處下載安裝程式。 下載 ZIP 檔案後:

.NET Framework 4.0+ 安裝說明:

  • 將 net40 資料夾中的 IronOcr.dll 加入您的專案
  • 接著請新增對以下組件的引用:

    • System.Co/nfiguration
    • System.Drawing
    • System.Web

.NET Standard、.NET Core 2.0+ 及 .NET 5 操作說明

  • 將 netstandard2.0 資料夾中的 IronOcr.dll 加入您的專案
  • 接著請新增 NuGet 套件參考至:

    • System.Drawing.Com/mon 4.7 或更高版本

為何選擇 IronOCR?

IronOCR 是一款安裝簡便、功能完備且文件詳盡的 .NET 程式庫。

選擇 IronOCR,無需使用任何外部網路服務、支付持續性費用,或透過網際網路傳送機密文件,即可實現 99.8% 以上的 OCR 準確度

為何 C# 開發者會選擇 IronOCR 而非原生 Tesseract:

  • 安裝為單一 DLL 或 NuGet 套件
  • 內建 Tesseract 5、4 及 3 引擎。
  • 99.8% 的準確度顯著優於標準版 Tesseract。
  • 極速效能與多執行緒
  • 相容於 MVC、WebApp、桌面、主控台及伺服器應用程式
  • 無需處理任何可執行檔或 C++ 程式碼
  • 完整支援 PDF OCR
  • 對幾乎任何圖像檔案或 PDF 執行 OCR
  • 完整支援 .NET Core、.NET Standard 及 Framework
  • 支援部署於 Windows、Mac、Linux、Azure、Docker、Lambda 及 AWS
  • 讀取 BarCode 與 QR 碼
  • 將 OCR 結果匯出為 XHTML
  • 將 OCR 結果匯出為可搜尋的 PDF 文件
  • 支援多執行緒
  • 125 種國際語言,皆透過 NuGet 或 OcrData 檔案進行管理
  • 擷取圖片、座標、統計資料及字型。 不僅是文字。
  • 可用於在商業及專有應用程式中重新分發 Tesseract OCR。

IronOCR 在處理真實世界的圖像及不完美的文件時表現尤為出色,例如照片,或是可能含有數位雜訊或瑕疵的低解析度掃描檔。

其他針對 .NET 平台的免費 OCR 函式庫(例如其他 .NET Tesseract API 和網路服務)在這些實際應用情境中的表現並不如預期。

OCR with Tesseract 5 - Start Coding in C

以下程式碼範例展示了使用 C# 或 VB .NET 從圖片中讀取文字是多麼簡單。

OneLiner

:path=/static-assets/ocr/content-code-examples/get-started/get-started-1.cs
string Text = new IronTesseract().Read(@"img\Screenshot.png").Text;
Dim Text As String = (New IronTesseract()).Read("img\Screenshot.png").Text
$vbLabelText   $csharpLabel

可配置的 Hello World

:path=/static-assets/ocr/content-code-examples/get-started/get-started-2.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();

// Add multiple images
input.LoadImage("images/sample.jpeg");

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

Private ocr As New IronTesseract()
Private OcrInput As using

' Add multiple images
input.LoadImage("images/sample.jpeg")

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

C# PDF OCR

同樣的方法也可用於從任何 PDF 文件中擷取文字。

:path=/static-assets/ocr/content-code-examples/get-started/get-started-3.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();

// We can also select specific PDF page numbers to OCR
input.LoadPdf("example.pdf", Password: "password");

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

// 1 page for every page of the PDF
Console.WriteLine($"{result.Pages.Length} Pages");
Imports IronOcr

Private ocr As New IronTesseract()
Private OcrInput As using

' We can also select specific PDF page numbers to OCR
input.LoadPdf("example.pdf", Password:= "password")

Dim result As OcrResult = ocr.Read(input)
Console.WriteLine(result.Text)

' 1 page for every page of the PDF
Console.WriteLine($"{result.Pages.Length} Pages")
$vbLabelText   $csharpLabel

多頁 TIFF 檔案的 OCR

:path=/static-assets/ocr/content-code-examples/get-started/get-started-4.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();
var pageindices = new int[] { 1, 2 };
input.LoadImageFrames("multi-frame.tiff", pageindices);
OcrResult result = ocr.Read(input);
Console.WriteLine(result.Text);
Imports IronOcr

Private ocr As New IronTesseract()
Private OcrInput As using
Private pageindices = New Integer() { 1, 2 }
input.LoadImageFrames("multi-frame.tiff", pageindices)
Dim result As OcrResult = ocr.Read(input)
Console.WriteLine(result.Text)
$vbLabelText   $csharpLabel

BarCode 與 QR 碼

IronOCR 的獨特功能在於,它能在掃描文字的同時,從文件中讀取 BARCODE 和 QR 碼。 OcrResult.OcrBarcode 類別的實例會向開發人員提供每個掃描BarCode的詳細資訊。

:path=/static-assets/ocr/content-code-examples/get-started/get-started-5.cs
using IronOcr;

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

using OcrInput input = new OcrInput();
input.LoadImage("img/Barcode.png");

OcrResult Result = ocr.Read(input);
foreach (var Barcode in Result.Barcodes)
{
    // type and location properties also exposed
    Console.WriteLine(Barcode.Value);
}
Imports IronOcr

Private ocr As New IronTesseract()
ocr.Configuration.ReadBarCodes = True

Using input As New OcrInput()
	input.LoadImage("img/Barcode.png")
	
	Dim Result As OcrResult = ocr.Read(input)
	For Each Barcode In Result.Barcodes
		' type and location properties also exposed
		Console.WriteLine(Barcode.Value)
	Next Barcode
End Using
$vbLabelText   $csharpLabel

針對圖片特定區域的 OCR

IronOCR 的所有掃描與讀取方法,皆能精確指定我們希望從哪一頁或哪幾頁的哪個部分讀取文字。 這在處理標準化表單時非常實用,能節省大量時間並提升效率。

若要使用裁切區域,我們需要新增對 System.Drawing 的系統參照,以便能使用 System.Drawing.Rectangle 物件。

:path=/static-assets/ocr/content-code-examples/get-started/get-started-6.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();

// Dimensions are in pixel
var contentArea = new System.Drawing.Rectangle() { X = 215, Y = 1250, Height = 280, Width = 1335 };

input.LoadImage("document.png", contentArea);

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

Private ocr As New IronTesseract()
Private OcrInput As using

' Dimensions are in pixel
Private contentArea = New System.Drawing.Rectangle() With {
	.X = 215,
	.Y = 1250,
	.Height = 280,
	.Width = 1335
}

input.LoadImage("document.png", contentArea)

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

低品質掃描文件的 OCR 處理

IronOCR OcrInput 類別可修復一般 Tesseract 無法讀取的掃描檔。

:path=/static-assets/ocr/content-code-examples/get-started/get-started-7.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();
var pageindices = new int[] { 1, 2 };
input.LoadImageFrames(@"img\Potter.tiff", pageindices);

// fixes digital noise and poor scanning
input.DeNoise();

// fixes rotation and perspective
input.Deskew();

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

Private ocr As New IronTesseract()
Private OcrInput As using
Private pageindices = New Integer() { 1, 2 }
input.LoadImageFrames("img\Potter.tiff", pageindices)

' fixes digital noise and poor scanning
input.DeNoise()

' fixes rotation and perspective
input.Deskew()

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

將 OCR 結果匯出為可搜尋的 PDF

:path=/static-assets/ocr/content-code-examples/get-started/get-started-8.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();
input.Title = "Quarterly Report";
input.LoadImage("image1.jpeg");
input.LoadImage("image2.png");
var pageindices = new int[] { 1, 2 };
input.LoadImageFrames("image3.gif", pageindices);

OcrResult result = ocr.Read(input);
result.SaveAsSearchablePdf("searchable.pdf");
Imports IronOcr

Private ocr As New IronTesseract()
Private OcrInput As using
input.Title = "Quarterly Report"
input.LoadImage("image1.jpeg")
input.LoadImage("image2.png")
Dim pageindices = New Integer() { 1, 2 }
input.LoadImageFrames("image3.gif", pageindices)

Dim result As OcrResult = ocr.Read(input)
result.SaveAsSearchablePdf("searchable.pdf")
$vbLabelText   $csharpLabel

TIFF 轉可搜尋 PDF 轉換

:path=/static-assets/ocr/content-code-examples/get-started/get-started-9.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();
var pageindices = new int[] { 1, 2 };
input.LoadImageFrames("example.tiff", pageindices);
ocr.Read(input).SaveAsSearchablePdf("searchable.pdf");
Imports IronOcr

Private ocr As New IronTesseract()
Private OcrInput As using
Private pageindices = New Integer() { 1, 2 }
input.LoadImageFrames("example.tiff", pageindices)
ocr.Read(input).SaveAsSearchablePdf("searchable.pdf")
$vbLabelText   $csharpLabel

將 OCR 結果匯出為 HTML

:path=/static-assets/ocr/content-code-examples/get-started/get-started-10.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();
input.Title = "Html Title";
input.LoadImage("image1.jpeg");

OcrResult Result = ocr.Read(input);
Result.SaveAsHocrFile("results.html");
Imports IronOcr

Private ocr As New IronTesseract()
Private OcrInput As using
input.Title = "Html Title"
input.LoadImage("image1.jpeg")

Dim Result As OcrResult = ocr.Read(input)
Result.SaveAsHocrFile("results.html")
$vbLabelText   $csharpLabel

OCR 影像增強濾鏡

IronOCR 提供專屬濾鏡來處理 OcrInput 物件,以提升 OCR 效能。

影像增強程式碼範例

:path=/static-assets/ocr/content-code-examples/get-started/get-started-11.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
using OcrInput input = new OcrInput();
input.LoadImage("LowQuality.jpeg");

// fixes digital noise and poor scanning
input.DeNoise();

// fixes rotation and perspective
input.Deskew();

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

Private ocr As New IronTesseract()
Private OcrInput As using
input.LoadImage("LowQuality.jpeg")

' fixes digital noise and poor scanning
input.DeNoise()

' fixes rotation and perspective
input.Deskew()

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

OCR 影像濾鏡清單

IronOCR 內建的用於提升 OCR 效能的輸入濾波器包括:

  • OcrInput.Rotate(double degrees) - 將圖片順時針旋轉指定角度。若要逆時針旋轉,請使用負數。
  • OcrInput.Binarize() - 此濾鏡會將每個像素轉換為純黑或純白,不留中間色調,這可能有助於提升對低對比度影像的 OCR 辨識效能。
  • OcrInput.ToGrayScale() - 將每個像素轉換為灰階色調。 這或許無法提升準確性,但可能提高速度。
  • OcrInput.Co/ntrast() - 自動提高對比度,通常能提升低對比度掃描的速度與準確性。
  • OcrInput.DeNoise() - 移除數位雜訊,僅在預期出現雜訊時建議使用。
  • OcrInput.Invert() - 將所有顏色反轉(白色變為黑色,反之亦然)。
  • OcrInput.Dilate() - 進行形態擴展,在物件邊界添加像素,與"侵蝕"功能相反。
  • OcrInput.Erode() - 進行形態學處理,移除物件邊界上的像素,與擴張 (Dilate) 操作相反。
  • OcrInput.Deskew() - 旋轉圖片以調整其正確方向。 此功能相當實用,因為 Tesseract 的傾斜容錯能力有限。
  • OcrInput.EnhanceResolution - 提升低畫質影像的解析度。 此設定通常用於自動管理低 DPI 輸入。
  • EnhanceResolution 可偵測低解析度影像(低於 275 dpi),並將其放大及銳化文字,以獲得更佳的 OCR 結果。 雖然耗時,但這通常能縮短整體 OCR 運作時間。
  • Language - 支援從 22 種國際語言套件中進行選取。
  • Strategy - 根據單字的統計關聯性,允許在"快速但準確度較低"與"進階(運用 AI 提升準確度)"兩種策略間進行選擇。
  • ColorSpace - 選擇以灰階或彩色進行 OCR; 雖然灰階通常是最佳選擇,但在某些對比情境下,彩色呈現可能效果更佳。
  • DetectWhiteTextOnDarkBackgrounds - 針對負片影像進行調整,能自動偵測並讀取深色背景上的白色文字。
  • InputImageType - 用於引導 OCR 函式庫,指定其處理的是完整文件還是片段。
  • RotateAndStraighten - 讓 IronOCR 能正確處理旋轉或受透視變形影響的文件。
  • ReadBarcodes - 可在掃描文字的同時自動讀取 BarCode 與 QR 碼,且不會大幅增加處理時間。
  • ColorDepth - 決定 OCR 處理過程中色彩深度的每像素位元數。 提高深度可提升品質,但也會增加處理時間。

125 種語言套件

IronOCR 透過語言套件支援 125 種國際語言,這些語言套件以 DLL 格式發行,可從本網站NuGet 套件管理員下載

翻譯語言包括德語、法語、英語、中文、日語等。 針對 MRZ、MICR 支票、財務資料、車牌號碼等,已提供專用的語言套件。此外,亦可使用自訂的 Tesseract ".traineddata" 檔案。

語言範例

// Reference to the path of the source file that demonstrates setting language packs for OCR
:path=/static-assets/ocr/content-code-examples/get-started/get-started-12.cs
// Reference to the path of the source file that demonstrates setting language packs for OCR
using IronOcr;

// PM> Install IronOcr.Languages.Arabic
IronTesseract ocr = new IronTesseract();
ocr.Language = OcrLanguage.Arabic;

using OcrInput input = new OcrInput();

var pageindices = new int[] { 1, 2 };
input.LoadImageFrames("img/arabic.gif", pageindices);
// Add image filters if needed
// In this case, even thought input is very low quality
// IronTesseract can read what conventional Tesseract cannot.
OcrResult result = ocr.Read(input);
// Console can't print Arabic on Windows easily.
// Let's save to disk instead.
result.SaveAsTextFile("arabic.txt");
' Reference to the path of the source file that demonstrates setting language packs for OCR
Imports IronOcr

' PM> Install IronOcr.Languages.Arabic
Private ocr As New IronTesseract()
ocr.Language = OcrLanguage.Arabic

Using input As New OcrInput()
	
	Dim pageindices = New Integer() { 1, 2 }
	input.LoadImageFrames("img/arabic.gif", pageindices)
	' Add image filters if needed
	' In this case, even thought input is very low quality
	' IronTesseract can read what conventional Tesseract cannot.
	Dim result As OcrResult = ocr.Read(input)
	' Console can't print Arabic on Windows easily.
	' Let's save to disk instead.
	result.SaveAsTextFile("arabic.txt")
End Using
$vbLabelText   $csharpLabel

多語言範例

亦可同時對多種語言進行 OCR 處理。此功能可提升 Unicode 文件中英文元資料與網址的 OCR 精準度。

// Reference to the path of the source file that demonstrates multi-language OCR
:path=/static-assets/ocr/content-code-examples/get-started/get-started-13.cs
// Reference to the path of the source file that demonstrates multi-language OCR
using IronOcr;

// PM> Install IronOcr.Languages.ChineseSimplified
IronTesseract ocr = new IronTesseract();
ocr.Language = OcrLanguage.ChineseSimplified;

// We can add any number of languages
ocr.AddSecondaryLanguage(OcrLanguage.English);

using OcrInput input = new OcrInput();
input.LoadPdf("multi-language.pdf");
OcrResult result = ocr.Read(input);
result.SaveAsTextFile("results.txt");
' Reference to the path of the source file that demonstrates multi-language OCR
Imports IronOcr

' PM> Install IronOcr.Languages.ChineseSimplified
Private ocr As New IronTesseract()
ocr.Language = OcrLanguage.ChineseSimplified

' We can add any number of languages
ocr.AddSecondaryLanguage(OcrLanguage.English)

Using input As New OcrInput()
	input.LoadPdf("multi-language.pdf")
	Dim result As OcrResult = ocr.Read(input)
	result.SaveAsTextFile("results.txt")
End Using
$vbLabelText   $csharpLabel

詳細 OCR 結果物件

IronOCR 會針對每項操作返回一個 OCR 結果物件。 一般而言,開發人員會透過 Text 屬性來取得掃描文字。 然而,結果物件中包含更詳盡的資訊。

// Reference to the path of the source file demonstrating detailed OCR result object usage
:path=/static-assets/ocr/content-code-examples/get-started/get-started-14.cs
// Reference to the path of the source file demonstrating detailed OCR result object usage
using IronOcr;

IronTesseract ocr = new IronTesseract();

// Must be set to true to read barcode
ocr.Configuration.ReadBarCodes = true;
using OcrInput input = new OcrInput();
var pageindices = new int[] { 1, 2 };
input.LoadImageFrames(@"img\sample.tiff", pageindices);

OcrResult result = ocr.Read(input);
var pages = result.Pages;
var words = pages[0].Words;
var barcodes = result.Barcodes;
// Explore here to find a massive, detailed API:
// - Pages, Blocks, Paraphaphs, Lines, Words, Chars
// - Image Export, Fonts Coordinates, Statistical Data, Tables
' Reference to the path of the source file demonstrating detailed OCR result object usage
Imports IronOcr

Private ocr As New IronTesseract()

' Must be set to true to read barcode
ocr.Configuration.ReadBarCodes = True
Using input As New OcrInput()
	Dim pageindices = New Integer() { 1, 2 }
	input.LoadImageFrames("img\sample.tiff", pageindices)
	
	Dim result As OcrResult = ocr.Read(input)
	Dim pages = result.Pages
	Dim words = pages(0).Words
	Dim barcodes = result.Barcodes
	' Explore here to find a massive, detailed API:
	' - Pages, Blocks, Paraphaphs, Lines, Words, Chars
	' - Image Export, Fonts Coordinates, Statistical Data, Tables
End Using
$vbLabelText   $csharpLabel

效能

IronOCR 開箱即用,無需進行效能調校或圖片修改。

速度極快:IronOCR.2020+ 的處理速度最高可達前一版本的 10 倍,且錯誤率降低超過 250%。

了解更多

若想進一步了解 C#、VB、F# 或任何其他 .NET 語言中的 OCR 功能,請參閱我們的社群教學文章,其中提供 IronOCR 的實際應用範例,並展示如何針對該程式庫進行最佳化的細節。

此外,亦提供供 .NET 開發者使用的完整 API 參考文件。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

審閱者:
Jeff Fritz
Jeffrey T. Fritz
首席程式經理 - .NET 社群團隊
Jeff 同時也是 .NET 與 Visual Studio 團隊的首席程式經理。他是 .NET Conf 虛擬會議系列的執行製作人,並主持每週播出兩次的開發者直播節目《Fritz and Friends》,在節目中他會與觀眾一起探討技術話題並共同編寫程式碼。Jeff 負責撰寫工作坊內容、準備簡報,並為 Microsoft Build、Microsoft Ignite、.NET Conf 以及 Microsoft MVP Summit 等微軟最大規模的開發者活動規劃內容。
準備開始了嗎?
Nuget 下載 5,896,332 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronOcr
執行範例 觀看您的圖片轉為可搜尋文字。