如何在 C# 中使用 OcrProgress Tracking

如何在 C# 中使用 IronOCR 進行進度追蹤

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

IronOCR 為 OCR 操作提供基於事件的進度追蹤系統,開發人員可透過 OcrProgress 事件監控讀取進度,該事件會即時回報完成百分比、已處理的頁面數以及時間指標。

快速入門:訂閱 OcrProgress 並閱讀 PDF

此範例展示如何使用 IronOCR 監控 OCR 進度:訂閱其內建的 OcrProgress 事件,即可在讀取 PDF 時即時獲得進度回報,包含完成百分比、已處理頁數及總頁數。 只需幾行程式碼即可開始使用。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronOcr

    PM > Install-Package IronOcr
  2. 請複製並執行此程式碼片段。

    var ocr = new IronOcr.IronTesseract();
    ocr.OcrProgress += (s, e) => Console.WriteLine(e.ProgressPercent + "% (" + e.PagesComplete + "/" + e.TotalPages + ")");
    var result = ocr.Read(new IronOcr.OcrInput().LoadPdf("file.pdf"));
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronOCR

    arrow pointer


如何在我的 OCR 應用程式中實作進度追蹤?

在處理大型文件或使用 OCR 處理批次檔案時,進度追蹤至關重要。 訂閱 OcrProgress 事件,即可接收閱讀進度的更新通知。 這對於 PDF OCR 操作以及處理多頁 TIFF 檔案時特別有用。

該事件會傳遞一個包含 OCR 工作進度資訊的實例,例如開始時間、總頁數、進度百分比、執行時間及結束時間。此功能可與非同步操作無縫整合,並能結合多執行緒技術以提升效能。

The following example uses this document as a sample: "Experiences in Biodiversity Research: A Field Course" by Thea B. 蓋斯勒,愛荷華州立大學。

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

var ocrTesseract = new IronTesseract();

// Subscribe to OcrProgress event
ocrTesseract.OcrProgress += (_, ocrProgressEventsArgs) =>
{
    Console.WriteLine("Start time: " + ocrProgressEventsArgs.StartTimeUTC.ToString());
    Console.WriteLine("Total pages number: " + ocrProgressEventsArgs.TotalPages);
    Console.WriteLine("Progress(%) | Duration");
    Console.WriteLine("    " + ocrProgressEventsArgs.ProgressPercent + "%     | " + ocrProgressEventsArgs.Duration.TotalSeconds + "s");
    Console.WriteLine("End time: " + ocrProgressEventsArgs.EndTimeUTC.ToString());
    Console.WriteLine("----------------------------------------------");
};

using var input = new OcrInput();
input.LoadPdf("Experiences-in-Biodiversity-Research-A-Field-Course.pdf");

// Progress events will fire during the read operation
var result = ocrTesseract.Read(input);
Imports IronOcr
Imports System

Private ocrTesseract = New IronTesseract()

' Subscribe to OcrProgress event
Private ocrTesseract.OcrProgress += Sub(underscore, ocrProgressEventsArgs)
	Console.WriteLine("Start time: " & ocrProgressEventsArgs.StartTimeUTC.ToString())
	Console.WriteLine("Total pages number: " & ocrProgressEventsArgs.TotalPages)
	Console.WriteLine("Progress(%) | Duration")
	Console.WriteLine("    " & ocrProgressEventsArgs.ProgressPercent & "%     | " & ocrProgressEventsArgs.Duration.TotalSeconds & "s")
	Console.WriteLine("End time: " & ocrProgressEventsArgs.EndTimeUTC.ToString())
	Console.WriteLine("----------------------------------------------")
End Sub

Private input = New OcrInput()
input.LoadPdf("Experiences-in-Biodiversity-Research-A-Field-Course.pdf")

' Progress events will fire during the read operation
Dim result = ocrTesseract.Read(input)
$vbLabelText   $csharpLabel
顯示進度追蹤(從 95% 至 100% 完成)的控制台輸出,包含時間戳記與耗時資料

我可從該活動中獲取哪些進度資訊?

OcrProgress 事件提供全面的進度資料,有助於監控和優化 OCR 效能。 每個屬性在追蹤操作過程中皆有其特定用途:

  • ProgressPercent:OCR 任務的進度,以已完成頁數的百分比表示,範圍為 0 至 100。適用於更新 GUI 應用程式的進度條。
  • TotalPages:OCR 引擎正在處理的總頁數。此數值對於計算預估完成時間至關重要。
  • PagesComplete:OCR 讀取已完全完成的頁面數。 此計數會隨著頁面的處理而逐漸增加。
  • Duration:OCR 任務的總耗時,表示整個流程完成所需的時間。 以 TimeSpan 格式進行測量,並在事件觸發時更新。
  • StartTimeUTC:OCR 工作開始的日期與時間,以協調世界時 (UTC) 格式表示。
  • EndTimeUTC:OCR 工作 100% 完成的日期與時間(UTC 格式)。 此屬性在 OCR 處理期間為 null,並會在處理完成後填入資料。

進階進度追蹤實作

針對生產環境的應用程式,應實作更精細的進度追蹤機制。 此範例包含錯誤處理與詳細記錄功能:

using IronOcr;
using System;
using System.Diagnostics;

public class OcrProgressTracker
{
    private readonly IronTesseract _tesseract;
    private Stopwatch _stopwatch;
    private int _lastReportedPercent = 0;

    public OcrProgressTracker()
    {
        _tesseract = new IronTesseract();

        // Configure for optimal performance
        _tesseract.Language = OcrLanguage.EnglishBest;
        _tesseract.Configuration.ReadBarCodes = false;

        // Subscribe to progress event
        _tesseract.OcrProgress += OnOcrProgress;
    }

    private void OnOcrProgress(object sender, OcrProgressEventsArgs e)
    {
        // Only report significant progress changes (every 10%)
        if (e.ProgressPercent - _lastReportedPercent >= 10 || e.ProgressPercent == 100)
        {
            _lastReportedPercent = e.ProgressPercent;

            Console.WriteLine($"Progress: {e.ProgressPercent}%");
            Console.WriteLine($"Pages: {e.PagesComplete}/{e.TotalPages}");
            Console.WriteLine($"Elapsed: {e.Duration.TotalSeconds:F1}s");

            // Estimate remaining time
            if (e.ProgressPercent > 0 && e.ProgressPercent < 100)
            {
                var estimatedTotal = e.Duration.TotalSeconds / (e.ProgressPercent / 100.0);
                var remaining = estimatedTotal - e.Duration.TotalSeconds;
                Console.WriteLine($"Estimated remaining: {remaining:F1}s");
            }

            Console.WriteLine("---");
        }
    }

    public OcrResult ProcessDocument(string filePath)
    {
        _stopwatch = Stopwatch.StartNew();

        using var input = new OcrInput();
        input.LoadPdf(filePath);

        // Apply image filters for better accuracy
        input.Deskew();
        input.DeNoise();

        var result = _tesseract.Read(input);

        _stopwatch.Stop();
        Console.WriteLine($"Total processing time: {_stopwatch.Elapsed.TotalSeconds:F1}s");

        return result;
    }
}
using IronOcr;
using System;
using System.Diagnostics;

public class OcrProgressTracker
{
    private readonly IronTesseract _tesseract;
    private Stopwatch _stopwatch;
    private int _lastReportedPercent = 0;

    public OcrProgressTracker()
    {
        _tesseract = new IronTesseract();

        // Configure for optimal performance
        _tesseract.Language = OcrLanguage.EnglishBest;
        _tesseract.Configuration.ReadBarCodes = false;

        // Subscribe to progress event
        _tesseract.OcrProgress += OnOcrProgress;
    }

    private void OnOcrProgress(object sender, OcrProgressEventsArgs e)
    {
        // Only report significant progress changes (every 10%)
        if (e.ProgressPercent - _lastReportedPercent >= 10 || e.ProgressPercent == 100)
        {
            _lastReportedPercent = e.ProgressPercent;

            Console.WriteLine($"Progress: {e.ProgressPercent}%");
            Console.WriteLine($"Pages: {e.PagesComplete}/{e.TotalPages}");
            Console.WriteLine($"Elapsed: {e.Duration.TotalSeconds:F1}s");

            // Estimate remaining time
            if (e.ProgressPercent > 0 && e.ProgressPercent < 100)
            {
                var estimatedTotal = e.Duration.TotalSeconds / (e.ProgressPercent / 100.0);
                var remaining = estimatedTotal - e.Duration.TotalSeconds;
                Console.WriteLine($"Estimated remaining: {remaining:F1}s");
            }

            Console.WriteLine("---");
        }
    }

    public OcrResult ProcessDocument(string filePath)
    {
        _stopwatch = Stopwatch.StartNew();

        using var input = new OcrInput();
        input.LoadPdf(filePath);

        // Apply image filters for better accuracy
        input.Deskew();
        input.DeNoise();

        var result = _tesseract.Read(input);

        _stopwatch.Stop();
        Console.WriteLine($"Total processing time: {_stopwatch.Elapsed.TotalSeconds:F1}s");

        return result;
    }
}
Imports IronOcr
Imports System
Imports System.Diagnostics

Public Class OcrProgressTracker
    Private ReadOnly _tesseract As IronTesseract
    Private _stopwatch As Stopwatch
    Private _lastReportedPercent As Integer = 0

    Public Sub New()
        _tesseract = New IronTesseract()

        ' Configure for optimal performance
        _tesseract.Language = OcrLanguage.EnglishBest
        _tesseract.Configuration.ReadBarCodes = False

        ' Subscribe to progress event
        AddHandler _tesseract.OcrProgress, AddressOf OnOcrProgress
    End Sub

    Private Sub OnOcrProgress(sender As Object, e As OcrProgressEventsArgs)
        ' Only report significant progress changes (every 10%)
        If e.ProgressPercent - _lastReportedPercent >= 10 OrElse e.ProgressPercent = 100 Then
            _lastReportedPercent = e.ProgressPercent

            Console.WriteLine($"Progress: {e.ProgressPercent}%")
            Console.WriteLine($"Pages: {e.PagesComplete}/{e.TotalPages}")
            Console.WriteLine($"Elapsed: {e.Duration.TotalSeconds:F1}s")

            ' Estimate remaining time
            If e.ProgressPercent > 0 AndAlso e.ProgressPercent < 100 Then
                Dim estimatedTotal = e.Duration.TotalSeconds / (e.ProgressPercent / 100.0)
                Dim remaining = estimatedTotal - e.Duration.TotalSeconds
                Console.WriteLine($"Estimated remaining: {remaining:F1}s")
            End If

            Console.WriteLine("---")
        End If
    End Sub

    Public Function ProcessDocument(filePath As String) As OcrResult
        _stopwatch = Stopwatch.StartNew()

        Using input As New OcrInput()
            input.LoadPdf(filePath)

            ' Apply image filters for better accuracy
            input.Deskew()
            input.DeNoise()

            Dim result = _tesseract.Read(input)

            _stopwatch.Stop()
            Console.WriteLine($"Total processing time: {_stopwatch.Elapsed.TotalSeconds:F1}s")

            Return result
        End Using
    End Function
End Class
$vbLabelText   $csharpLabel

將進度追蹤整合至 UI 應用程式

在使用 Windows Forms 或 WPF 開發桌面應用程式時,進度追蹤對於使用者體驗至關重要。 進度事件可安全地更新 UI 元件:

using System;
using System.Windows.Forms;
using IronOcr;

public partial class OcrForm : Form
{
    private IronTesseract _tesseract;
    private ProgressBar progressBar;
    private Label statusLabel;

    public OcrForm()
    {
        InitializeComponent();
        _tesseract = new IronTesseract();
        _tesseract.OcrProgress += UpdateProgress;
    }

    private void UpdateProgress(object sender, OcrProgressEventsArgs e)
    {
        // Ensure UI updates happen on the main thread
        if (InvokeRequired)
        {
            BeginInvoke(new Action(() => UpdateProgress(sender, e)));
            return;
        }

        progressBar.Value = e.ProgressPercent;
        statusLabel.Text = $"Processing page {e.PagesComplete} of {e.TotalPages}";

        // Show completion message
        if (e.ProgressPercent == 100)
        {
            MessageBox.Show($"OCR completed in {e.Duration.TotalSeconds:F1} seconds");
        }
    }
}
using System;
using System.Windows.Forms;
using IronOcr;

public partial class OcrForm : Form
{
    private IronTesseract _tesseract;
    private ProgressBar progressBar;
    private Label statusLabel;

    public OcrForm()
    {
        InitializeComponent();
        _tesseract = new IronTesseract();
        _tesseract.OcrProgress += UpdateProgress;
    }

    private void UpdateProgress(object sender, OcrProgressEventsArgs e)
    {
        // Ensure UI updates happen on the main thread
        if (InvokeRequired)
        {
            BeginInvoke(new Action(() => UpdateProgress(sender, e)));
            return;
        }

        progressBar.Value = e.ProgressPercent;
        statusLabel.Text = $"Processing page {e.PagesComplete} of {e.TotalPages}";

        // Show completion message
        if (e.ProgressPercent == 100)
        {
            MessageBox.Show($"OCR completed in {e.Duration.TotalSeconds:F1} seconds");
        }
    }
}
Imports System
Imports System.Windows.Forms
Imports IronOcr

Public Partial Class OcrForm
    Inherits Form

    Private _tesseract As IronTesseract
    Private progressBar As ProgressBar
    Private statusLabel As Label

    Public Sub New()
        InitializeComponent()
        _tesseract = New IronTesseract()
        AddHandler _tesseract.OcrProgress, AddressOf UpdateProgress
    End Sub

    Private Sub UpdateProgress(sender As Object, e As OcrProgressEventsArgs)
        ' Ensure UI updates happen on the main thread
        If InvokeRequired Then
            BeginInvoke(New Action(Sub() UpdateProgress(sender, e)))
            Return
        End If

        progressBar.Value = e.ProgressPercent
        statusLabel.Text = $"Processing page {e.PagesComplete} of {e.TotalPages}"

        ' Show completion message
        If e.ProgressPercent = 100 Then
            MessageBox.Show($"OCR completed in {e.Duration.TotalSeconds:F1} seconds")
        End If
    End Sub
End Class
$vbLabelText   $csharpLabel

處理大型文件與超時問題

在處理大量文件時,進度追蹤的功能便顯得更加重要。 結合超時設定中止標記,以獲得更佳的控制:

using IronOcr;
using System;
using System.Threading;

public async Task ProcessLargeDocumentWithTimeout()
{
    var cts = new CancellationTokenSource();
    var tesseract = new IronTesseract();

    // Set a timeout of 5 minutes
    cts.CancelAfter(TimeSpan.FromMinutes(5));

    tesseract.OcrProgress += (s, e) =>
    {
        Console.WriteLine($"Progress: {e.ProgressPercent}% - Page {e.PagesComplete}/{e.TotalPages}");

        // Check if we should cancel based on progress
        if (e.Duration.TotalMinutes > 4 && e.ProgressPercent < 50)
        {
            Console.WriteLine("Processing too slow, cancelling...");
            cts.Cancel();
        }
    };

    try
    {
        using var input = new OcrInput();
        input.LoadPdf("large-document.pdf");

        var result = await Task.Run(() => 
            tesseract.Read(input, cts.Token), cts.Token);

        Console.WriteLine("OCR completed successfully");
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine("OCR operation was cancelled");
    }
}
using IronOcr;
using System;
using System.Threading;

public async Task ProcessLargeDocumentWithTimeout()
{
    var cts = new CancellationTokenSource();
    var tesseract = new IronTesseract();

    // Set a timeout of 5 minutes
    cts.CancelAfter(TimeSpan.FromMinutes(5));

    tesseract.OcrProgress += (s, e) =>
    {
        Console.WriteLine($"Progress: {e.ProgressPercent}% - Page {e.PagesComplete}/{e.TotalPages}");

        // Check if we should cancel based on progress
        if (e.Duration.TotalMinutes > 4 && e.ProgressPercent < 50)
        {
            Console.WriteLine("Processing too slow, cancelling...");
            cts.Cancel();
        }
    };

    try
    {
        using var input = new OcrInput();
        input.LoadPdf("large-document.pdf");

        var result = await Task.Run(() => 
            tesseract.Read(input, cts.Token), cts.Token);

        Console.WriteLine("OCR completed successfully");
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine("OCR operation was cancelled");
    }
}
Imports IronOcr
Imports System
Imports System.Threading
Imports System.Threading.Tasks

Public Async Function ProcessLargeDocumentWithTimeout() As Task
    Dim cts As New CancellationTokenSource()
    Dim tesseract As New IronTesseract()

    ' Set a timeout of 5 minutes
    cts.CancelAfter(TimeSpan.FromMinutes(5))

    AddHandler tesseract.OcrProgress, Sub(s, e)
                                          Console.WriteLine($"Progress: {e.ProgressPercent}% - Page {e.PagesComplete}/{e.TotalPages}")

                                          ' Check if we should cancel based on progress
                                          If e.Duration.TotalMinutes > 4 AndAlso e.ProgressPercent < 50 Then
                                              Console.WriteLine("Processing too slow, cancelling...")
                                              cts.Cancel()
                                          End If
                                      End Sub

    Try
        Using input As New OcrInput()
            input.LoadPdf("large-document.pdf")

            Dim result = Await Task.Run(Function() tesseract.Read(input, cts.Token), cts.Token)

            Console.WriteLine("OCR completed successfully")
        End Using
    Catch ex As OperationCanceledException
        Console.WriteLine("OCR operation was cancelled")
    End Try
End Function
$vbLabelText   $csharpLabel

進度追蹤的最佳實踐

  1. 更新頻率:在處理過程中,OcrProgress 事件會頻繁觸發。 請考慮過濾更新內容,以免使用介面或日誌過於繁雜。

  2. 效能影響:進度追蹤對效能的影響極小,但過度的記錄或 UI 更新可能會拖慢 OCR 處理流程。

  3. 記憶體管理:對於大型 TIFF 檔案或 PDF 檔案,請在監控進度的同時關注記憶體使用狀況,以確保最佳效能。

  4. 錯誤處理:請務必在進度事件處理程序中加入錯誤處理機制,以防止例外狀況中斷 OCR 流程。

  5. 執行緒安全性:當從進度事件更新 UI 元素時,請務必使用 InvokeBeginInvoke 方法來確保適當的執行緒同步。

結論

IronOCR 的進度追蹤功能為 OCR 操作提供了關鍵的可視性,讓開發人員能夠建立反應靈敏的應用程式,隨時向使用者通報處理狀態。 透過有效運用 OcrProgress 事件,您將能自信地建置 Professional 應用程式,從單頁文件到龐大的 PDF 檔案,皆能游刃有餘地處理。

若需更進階的 OCR 技術,請參閱我們關於影像濾鏡結果物件的指南,以進一步提升您的 OCR 實作效能。

常見問題

如何即時追蹤 OCR 的進度?

IronOCR 透過 OcrProgress 事件提供基於事件的進度追蹤系統。您只需在 IronTesseract 實例上訂閱此事件,即可在 OCR 運作期間接收包含完成百分比、已處理頁面數及時間指標等即時更新。

OcrProgress 事件提供哪些資訊?

IronOCR 中的 OcrProgress 事件提供全面資料,包括 ProgressPercent(0-100%)、TotalPages 頁數、PagesComplete 已完成頁數、開始與結束時間,以及總耗時。這些資訊對於更新 GUI 應用程式的進度條以及監控 OCR 效能特別有用。

我可以在非同步 OCR 操作中使用進度追蹤功能嗎?

是的,IronOCR 的進度追蹤功能可與非同步操作無縫整合。您可以將其與非同步處理甚至多執行緒技術結合,在提升效能的同時,仍能透過 OcrProgress 事件接收即時進度更新。

如何實作一個簡單的 PDF OCR 進度追蹤器?

若要使用 IronOCR 實現基本的進度追蹤,請建立一個 IronTesseract 實例,透過 lambda 表達式或事件處理常式訂閱 OcrProgress 事件,然後傳入您的 PDF 檔案來呼叫 Read 方法。該事件將定期觸發,提供完成百分比及已處理頁數的資訊。

進度追蹤對於大型文件處理是否有幫助?

using IronOCR 處理大型文件或批次檔案時,進度追蹤至關重要。此功能對於 PDF OCR 操作及多頁 TIFF 檔案尤為實用,讓您能夠監控處理狀態、預估完成時間,並在長時間運作期間向使用者提供回饋。

IronOCR 是否支援多種語言?

IronOCR 支援多種語言,使其成為適用於需要識別不同語言文字的全球應用程式的多功能工具。

IronOCR 能否整合至現有應用程式中?

IronOCR 設計上可輕鬆透過 C# 整合至現有應用程式中,讓開發人員能以最少的努力,為其軟體增添 OCR 功能。

使用 IronOCR 進行文件管理有哪些好處?

使用 IronOCR 進行文件管理,可將掃描文件轉換為可搜尋且可編輯的文字,從而簡化工作流程,減少人工資料輸入的需求,並提升文件的可存取性。

IronOCR 如何提升資料準確性?

IronOCR 透過其先進的辨識演算法與影像校正功能來提升資料準確性,確保文字擷取過程既可靠又精確。

IronOCR 是否有提供免費試用版?

是的,Iron Software 提供 IronOCR 的免費試用版,讓使用者能在決定購買前測試其功能與效能。

Curtis Chau
技術撰稿人

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

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

準備開始了嗎?
Nuget 下載 5,896,332 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

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