如何在C#中使用OcrProgress追蹤

如何在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. 使用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工作進度資訊的實例,如開始時間、總頁數、進度百分比、持續時間和結束時間。這一功能與異步操作無縫結合,並可與多執行緒結合以提高性能。

以下範例將使用這份文件作為樣例:"生物多樣性研究經驗:田野課程",作者Thea B. Gessler,愛荷華州立大學。

: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進行過程中為空值,並在該過程完成後填入。

高級進度跟蹤實施

對於生產應用程式,實施更複雜的進度跟蹤。 此範例包含錯誤處理和詳細的日誌記錄:

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事件在處理過程中頻繁觸發。 考慮過濾更新以避免令您的UI或日誌不堪重負。

  2. 性能影響:進度跟蹤的性能負擔只是些許,但過度的日誌記錄或UI更新可能會拖慢OCR過程。

  3. 記憶體管理:對於大型TIFF文件或PDF,與進度監控一起監控記憶體使用情況以確保最佳性能。

  4. 錯誤處理:始終在進度事件處理程式中包含錯誤處理,以防止異常中斷OCR過程。

  5. 執行緒安全:從進度事件中更新UI元素時,使用BeginInvoke方法確保正確的執行緒同步。

結論

IronOCR中的進度跟蹤提供了OCR運行的必要可見性,使開發者能夠建立響應式應用程式,讓使用者了解處理狀態。 通過有效地利用OcrProgress事件,您可以自信地構建從單頁文件到大型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方法。該事件將定期觸發,提供完成百分比和已處理的頁面資訊。

進度追蹤對大文件處理有用嗎?

在使用IronOCR處理大型文件或批量文件時,進度追蹤是必不可少的。對於PDF OCR操作和多頁TIFF文件特別有價值,允許監控處理狀態、估算完成時間,以及在長時間操作期間提供使用者反饋。

IronOCR支援多種語言嗎?

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

IronOCR能整合到現有的應用程式中嗎?

IronOCR被設計成可以輕鬆地整合到現有應用程式中,使用C#允許開發人員以最小的努力為其軟體新增OCR功能。

使用IronOCR進行文件管理的好處是什麼?

使用IronOCR進行文件管理通過將掃描的文件轉換為可搜索和可編輯的文字來簡化工作流程,減少手動資料輸入的需求並提高文件的可存取性。

IronOCR如何提高資料精確性?

IronOCR通過其先進的識別算法和影像校正功能提高資料精確性,確保文字提取過程既可靠又精確。

IronOCR有免費試用版嗎?

有的,Iron Software提供IronOCR的免費試用版,允許使用者在做出購買決定前測試其功能和能力。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 6,136,090 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動?

想要快速證明? PM > Install-Package IronOcr
執行範例 觀看您的圖像轉變為可搜尋文字。