跳過到頁腳內容
使用 IRONOCR

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

光學字元識別 (OCR) 改變了開發人員在 .NET 專案中處理文件的方式。 無論是處理掃描文件、影像檔案或 TIFF 檔案,實施可靠的 OCR 解決方案都能讓應用程式擷取文字,並將視覺資料轉換為機器可讀取的內容。 在這篇文章中,我們將教您如何使用 IronOCR 在 C# CodeProject 中使用 OCR,IronOCR 是一個功能強大的 OCR 函式庫,可以簡化整個文字辨識的過程。

開始免費試用 IronOCR 以跟隨這些程式碼範例。

如何在我的 .NET 專案中設定 OCR 函式庫?

在 Visual Studio 中設定光學字元識別 (OCR) 只需要幾個步驟。 IronOCR 函式庫可透過 NuGet 取得,可直接整合至任何 Windows 應用程式。

打開 Visual Studio 並創建一個新的控制台應用程序項目。 在 "解决方案资源管理器 "中,右键单击 "引用 "并选择 "管理 NuGet 包"。搜尋"IronOcr"並安裝套件。 NuGet 套件管理程式會下載所有所需的 DLL 檔案,並自動將引用加入您的專案。

// Install via Package Manager Console
Install-Package IronOCR
// Install via Package Manager Console
Install-Package IronOCR
$vbLabelText   $csharpLabel

安裝完成後,請新增 using 語句,將 IronOCR 命名空間匯入您的程式。 本庫支援 .NET Framework 4.6.2+ 和 .NET Core,可確保不同專案類型和 Windows 版本之間的相容性。

如何從影像檔案中萃取文字?

OCR 流程的第一步是載入影像並將其通過 OCR 引擎。IronOCR 提供 IronTesseract 類別作為字元識別作業的主要 OCR API。 此 OCR 範例展示了從任何影像檔案中萃取文字的基本方法。

using System;
using IronOcr;
class Program
{
    static void Main(string[] args)
    {
        // Initialize the new Tesseract engine
        var ocr = new IronTesseract();
        // Load the image file and perform OCR
        using (var input = new OcrInput())
        {
            input.LoadImage(@"sample-document.png");
            // Process the image and extract text
            OcrResult result = ocr.Read(input);
            // Output the recognized text
            var text = result.Text;
            Console.WriteLine(text);
        }
    }
}
using System;
using IronOcr;
class Program
{
    static void Main(string[] args)
    {
        // Initialize the new Tesseract engine
        var ocr = new IronTesseract();
        // Load the image file and perform OCR
        using (var input = new OcrInput())
        {
            input.LoadImage(@"sample-document.png");
            // Process the image and extract text
            OcrResult result = ocr.Read(input);
            // Output the recognized text
            var text = result.Text;
            Console.WriteLine(text);
        }
    }
}
Imports System
Imports IronOcr

Class Program
    Shared Sub Main(args As String())
        ' Initialize the new Tesseract engine
        Dim ocr As New IronTesseract()
        ' Load the image file and perform OCR
        Using input As New OcrInput()
            input.LoadImage("sample-document.png")
            ' Process the image and extract text
            Dim result As OcrResult = ocr.Read(input)
            ' Output the recognized text
            Dim text As String = result.Text
            Console.WriteLine(text)
        End Using
    End Sub
End Class
$vbLabelText   $csharpLabel

光學字元識別輸出

OCR in C# CodeProject Tutorial:使用 IronOCR 從圖片中萃取文字:圖片 1 - OCR 輸出的螢幕截圖

上面的程式碼會建立一個 IronTesseract 物件,作為所有文字辨識作業的 OCR 引擎。 OcrInput 類別接受各種影像格式,包括 PNG、JPEG、BMP、GIF 和 TIFF。 當您呼叫讀取方法時,函式庫會處理輸入的影像,並傳回一個包含辨識文字的 OcrResult 物件。

OcrResult.Text 屬性會以純文字字串的形式提供擷取的內容,以便在您的應用程式中進一步處理。 此 OCR 程式碼會在內部處理複雜的字元識別演算法,在不同的文件類型中提供高準確度的識別結果。

如何處理掃描的文件和 TIFF 檔案?

現實世界的應用程式通常需要處理以 TIFF 檔案儲存的多頁掃描文件。 OCR 函式庫透過允許開發人員載入特定頁面範圍或處理整個文件,有效率地處理這些情境。 此範例程式碼顯示如何處理多格 TIFF 影像。

using System;
using IronOcr;
class Program
{
    static void Main(string[] args)
    {
        var ocr = new IronTesseract();
        using (var input = new OcrInput())
        {
            // Load specific pages from a multi-page TIFF file
            int[] pageIndices = new int[] { 0, 1, 2 };
            input.LoadImageFrames(@"scanned-documents.tiff", pageIndices);
            // Apply image enhancement for better results
            input.Deskew();
            OcrResult result = ocr.Read(input);
            // Access page-by-page results
            foreach (var page in result.Pages)
            {
                Console.WriteLine($"Page {page.PageNumber}:");
                Console.WriteLine(page.Text);
            }
        }
    }
}
using System;
using IronOcr;
class Program
{
    static void Main(string[] args)
    {
        var ocr = new IronTesseract();
        using (var input = new OcrInput())
        {
            // Load specific pages from a multi-page TIFF file
            int[] pageIndices = new int[] { 0, 1, 2 };
            input.LoadImageFrames(@"scanned-documents.tiff", pageIndices);
            // Apply image enhancement for better results
            input.Deskew();
            OcrResult result = ocr.Read(input);
            // Access page-by-page results
            foreach (var page in result.Pages)
            {
                Console.WriteLine($"Page {page.PageNumber}:");
                Console.WriteLine(page.Text);
            }
        }
    }
}
Imports System
Imports IronOcr

Class Program
    Shared Sub Main(ByVal args As String())
        Dim ocr As New IronTesseract()
        Using input As New OcrInput()
            ' Load specific pages from a multi-page TIFF file
            Dim pageIndices As Integer() = {0, 1, 2}
            input.LoadImageFrames("scanned-documents.tiff", pageIndices)
            ' Apply image enhancement for better results
            input.Deskew()
            Dim result As OcrResult = ocr.Read(input)
            ' Access page-by-page results
            For Each page In result.Pages
                Console.WriteLine($"Page {page.PageNumber}:")
                Console.WriteLine(page.Text)
            Next
        End Using
    End Sub
End Class
$vbLabelText   $csharpLabel

OCR 從多頁 TIFF 檔案輸出

OCR in C# CodeProject Tutorial:使用 IronOCR 從影像中萃取文字:影像 2 - 多頁 TIFF OCR 輸出

LoadImageFrames 方法接受一個檔案路徑和一個整數陣列,指定要處理的頁面。 當您只需要大型文件檔案中的特定頁面時,此方法可優化效能。 Deskew 過濾器可修正掃描影像中的任何旋轉或對齊問題,改善影像品質和 OCR 準確度。

結果中的每頁都會保留版面資訊,包括段落、行和單字。 OCR API 可存取置信度分數和定位資料,讓複雜的文件分析超越簡單的文字擷取。

如何處理 OCR 原始碼錯誤並提昇辨識結果?

生產應用程式需要適當的錯誤處理,以管理各種異常情況。 影像品質問題、不支援的檔案格式或損毀的檔案都可能導致 OCR 程序失敗。 實作異常處理可確保您的應用程式能優雅地回應這些情況。

using System;
using IronOcr;
class Program
{
    static void Main(string[] args)
    {
        var ocr = new IronTesseract();
        // Configure the OCR engine for your language
        ocr.Language = OcrLanguage.English;
        try
        {
            using (var input = new OcrInput())
            {
                input.LoadImage(@"document.png");
                // Enhance low-quality images
                input.DeNoise();
                input.Deskew();
                OcrResult result = ocr.Read(input);
                if (result.Text.Length > 0)
                {
                    Console.WriteLine("Recognized text:");
                    Console.WriteLine(result.Text);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"OCR Error: {ex.Message}");
        }
    }
}
using System;
using IronOcr;
class Program
{
    static void Main(string[] args)
    {
        var ocr = new IronTesseract();
        // Configure the OCR engine for your language
        ocr.Language = OcrLanguage.English;
        try
        {
            using (var input = new OcrInput())
            {
                input.LoadImage(@"document.png");
                // Enhance low-quality images
                input.DeNoise();
                input.Deskew();
                OcrResult result = ocr.Read(input);
                if (result.Text.Length > 0)
                {
                    Console.WriteLine("Recognized text:");
                    Console.WriteLine(result.Text);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"OCR Error: {ex.Message}");
        }
    }
}
Imports System
Imports IronOcr

Class Program
    Shared Sub Main(ByVal args As String())
        Dim ocr As New IronTesseract()
        ' Configure the OCR engine for your language
        ocr.Language = OcrLanguage.English
        Try
            Using input As New OcrInput()
                input.LoadImage("document.png")
                ' Enhance low-quality images
                input.DeNoise()
                input.Deskew()
                Dim result As OcrResult = ocr.Read(input)
                If result.Text.Length > 0 Then
                    Console.WriteLine("Recognized text:")
                    Console.WriteLine(result.Text)
                End If
            End Using
        Catch ex As Exception
            Console.WriteLine($"OCR Error: {ex.Message}")
        End Try
    End Sub
End Class
$vbLabelText   $csharpLabel

語言屬性可設定 OCR 引擎使用哪一種語言套件來識別文字。 IronOCR 支援超過 125 種語言,每種語言均以獨立的 NuGet 套件提供。 DeNoise 過濾器可去除掃描文件中的數位雜訊,而 Deskew 則可校正對齊方式 - 這兩項功能對於從不完美的來源影像中取得最佳辨識結果都至關重要。

如何從識別的文字建立可搜尋的 PDF?

將掃描的文件轉換成可搜尋的 PDF 檔案是最有價值的 OCR 應用之一。 使用者可以從之前只有影像的文件中搜尋、選擇和複製文字。 此轉換可讓文件管理系統對內容進行索引,並改善可存取性。

using System;
using IronOcr;
class Program
{
    static void Main(string[] args)
    {
        var ocr = new IronTesseract();
        using (var input = new OcrInput())
        {
            // Set document metadata
            input.Title = "Converted Document";
            // Load source images or existing PDF
            input.LoadImage(@"page1.png");
            input.LoadImage(@"page2.png");
            OcrResult result = ocr.Read(input);
            // Save as searchable PDF with embedded text layer
            result.SaveAsSearchablePdf(@"searchable-output.pdf");
            Console.WriteLine("Searchable PDF created successfully.");
            Console.WriteLine($"Total pages processed: {result.Pages.Count}");
        }
    }
}
using System;
using IronOcr;
class Program
{
    static void Main(string[] args)
    {
        var ocr = new IronTesseract();
        using (var input = new OcrInput())
        {
            // Set document metadata
            input.Title = "Converted Document";
            // Load source images or existing PDF
            input.LoadImage(@"page1.png");
            input.LoadImage(@"page2.png");
            OcrResult result = ocr.Read(input);
            // Save as searchable PDF with embedded text layer
            result.SaveAsSearchablePdf(@"searchable-output.pdf");
            Console.WriteLine("Searchable PDF created successfully.");
            Console.WriteLine($"Total pages processed: {result.Pages.Count}");
        }
    }
}
Imports System
Imports IronOcr

Class Program
    Shared Sub Main(ByVal args As String())
        Dim ocr = New IronTesseract()
        Using input = New OcrInput()
            ' Set document metadata
            input.Title = "Converted Document"
            ' Load source images or existing PDF
            input.LoadImage("page1.png")
            input.LoadImage("page2.png")
            Dim result As OcrResult = ocr.Read(input)
            ' Save as searchable PDF with embedded text layer
            result.SaveAsSearchablePdf("searchable-output.pdf")
            Console.WriteLine("Searchable PDF created successfully.")
            Console.WriteLine($"Total pages processed: {result.Pages.Count}")
        End Using
    End Sub
End Class
$vbLabelText   $csharpLabel

輸出可搜尋的 PDF 文件

OCR in C# CodeProject Tutorial:使用 IronOCR 從影像中萃取文字:影像 3 - 從輸入的影像建立可搜尋的 PDF

SaveAsSearchablePdf 方法會產生 PDF 檔案,保留原始影像的外觀,同時嵌入隱形文字層。 此方法可確保視覺輸出與原始碼完全相符,從而保持文件的真實性,同時還能進行全文檢索。 Microsoft Office 應用程式、Adobe Reader 及其他 PDF 檢視器便可搜尋並索引已辨識的文字。

對於需要 HTML 輸出的應用程式,IronOCR 也提供 SaveAsHocrFile 方法,可以 hOCR 格式匯出結果。 這個以 XML 為基礎的標準包含每個字的定位資料,可支援網頁型的文件檢視器和進階的文字分析工作流程。

結論

使用 IronOCR,在 C# 專案中實現光學字元識別變得簡單直接。 該函式庫可處理複雜的影像處理,支援多種影像格式和語言,並提供靈活的輸出選項,包括可搜尋的 PDF 生成。 從簡單的文字抽取到處理多頁 TIFF 文件,本教學中的範例展示了開發人員所需的核心工作流程。

IronOCR文件進階影像篩選器條碼讀取特定區域的OCR處理提供額外的程式碼範例。 應用程式介面參考詳述所有可用的類別和方法,以建立全面的文件處理解決方案。

!{--01001100010010010100001001010010010000010101001001011001010111110100011101000101010101 01000101111101010011010101000100000101010010010101000100010101000100010111110101011101001000110 1010101000100100001011111010100000101001001001111010001000101010101010000110101010100101010101011 10101010001010010010010010010000010100110001011111010000100100110001001111101000011010010111111010000110100101110--

準備好在您的下一個專案中實作 OCR 嗎? 購買授權,即可在生產環境中部署 IronOCR,並獲得完整的支援與更新。

常見問題解答

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

OCR 或「光學字元辨識」(Optical Character Recognition)是一種技術,可將不同類型的文件(例如掃描的紙本文件、PDF 或數位相機擷取的影像)轉換成可編輯和搜尋的資料。對 C# 開發人員而言,OCR 可讓應用程式從影像和掃描的文件中擷取文字,進而簡化文件處理程序,提升資料的存取性和可用性。

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

您可以使用 IronOCR 函式庫在 C# 專案中實作 OCR。這個函式庫提供了一個易於使用的介面,可在 .NET 應用程式中從影像和掃描的文件中擷取文字,讓您輕鬆地將 OCR 功能整合到專案中。

IronOCR 支援哪些影像格式?

IronOCR 支援多種影像格式,包括 JPEG、PNG、BMP、GIF 和 TIFF。這種靈活性讓您可以處理各種類型的影像檔案,有效率地擷取文字。

IronOCR 可以處理多頁 TIFF 檔案嗎?

是的,IronOCR 可以處理多頁 TIFF 檔案。它提供處理和擷取多頁 TIFF 內每頁文字的功能,使其成為處理複雜文件的理想解決方案。

是否可以使用 IronOCR 從圖片的特定區域提取文字?

是的,IronOCR 允許您指定影像的特定區域,從中抽取文字。當您需要專注於文件的特定區段(例如表單或表格)時,此功能非常有用。

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

IronOCR 支援多種語言的文字擷取,讓您可以無縫處理各種語言的文件。此功能可增強您應用程式的多樣性,迎合全球受眾的需求。

與其他 OCR 函式庫相比,使用 IronOCR 有哪些優點?

IronOCR 具備多項優勢,包括易於使用、可靠的文字辨識、支援多種語言,以及相容於各種影像格式。其強大的功能和效能使其成為希望在 C# 專案中實作 OCR 的開發人員的首選。

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

IronOCR 透過先進的演算法和機器學習技術提高文字辨識的準確度。它可以處理具有不同字型、大小和佈局的高難度文件,確保文字擷取的高精準度。

是否可以將 IronOCR 整合到現有的 .NET 應用程式中?

是的,IronOCR 可以輕鬆地整合到現有的 .NET 應用程式中。其簡單直接的 API 可讓開發人員不費吹灰之力就能在應用程式中加入 OCR 功能,不需大量修改就能增強應用程式的功能。

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

IronOCR 可用於各種 C# 應用程式,包括文件管理系統、資料輸入自動化、歸檔、從發票和收據中抽取文字,以及視障人士的無障礙工具。其多功能性使其適用於各行各業的應用程式。

Kannaopat Udonpant
軟體工程師
在成為軟體工程師之前,Kannapat 完成了日本北海道大學的環境資源博士學位。在攻讀學位期間,Kannapat 也成為生物製造工程系車輛機器人實驗室的成員。2022 年,他利用自己的 C# 技能加入 Iron Software 的工程團隊,主要負責 IronPDF 的開發。Kannapat 非常重視他的工作,因為他可以直接向撰寫 IronPDF 使用的大部分程式碼的開發者學習。除了同儕學習之外,Kannapat 也很享受在 Iron Software 工作的社交生活。不寫程式碼或文件時,Kannapat 通常會用 PS5 玩遊戲或重看《最後的我們》。