如何在C#中使用IronOCR進行進度跟蹤
IronOCR為OCR操作提供了一個基於事件的進度跟蹤系統,允許開發者通過OcrProgress事件監控讀取進度,該事件實時報告完成百分比、處理的頁數和時間指標。
此範例展示了如何使用IronOCR監控OCR進度:訂閱內建的OcrProgress事件,並接收即時反饋,包括百分比、已完成頁數和總頁數,同時閱讀PDF。 只需幾行程式碼即可開始。
-
1Install IronOCR with NuGet Package Manager
-
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"));C# -
3部署以在您的實時環境中測試
今天就開始在您的專案中使用IronOCR,透過免費試用
最小化工作流程 (5 步)
- 下載一個追蹤閱讀進度的C#庫
- 訂閱OcrProgress事件
- 使用事件傳遞的實例來檢索進度資訊
- 獲取百分比進度和總持續時間
- 檢索開始和結束時間以及總頁數
如何在我的OCR應用程式中實現進度跟蹤?
在使用OCR處理大型文件或文件批次時,進度跟蹤是必不可少的。 可以訂閱OcrProgress事件以接收讀取過程的進度更新。 這對於PDF OCR操作以及處理多頁TIFF文件特別有用。
該事件傳遞一個包含OCR工作進度資訊的實例,如開始時間、總頁數、進度百分比、持續時間和結束時間。這一功能與異步操作無縫結合,並可與多執行緒結合以提高性能。
以下範例將使用這份文件作為樣例:"生物多樣性研究經驗:田野課程",作者Thea B. Gessler,愛荷華州立大學。
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)我可以從事件中獲取哪些進度資訊?
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;
}
}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將進度跟蹤整合到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");
}
}
}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處理大型文件和超時
在處理文件龐大的文件時,進度跟蹤變得更加有價值。 將其與超時設置和中止令牌結合,為更好的控制提供助力:
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
Public Async Function ProcessLargeDocumentWithTimeout() As Task
Dim cts = New CancellationTokenSource()
Dim tesseract = 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進度跟蹤的最佳實踐
-
更新頻率:
OcrProgress事件在處理過程中頻繁觸發。 考慮過濾更新以避免令您的UI或日誌不堪重負。 -
性能影響:進度跟蹤的性能負擔只是些許,但過度的日誌記錄或UI更新可能會拖慢OCR過程。
-
記憶體管理:對於大型TIFF文件或PDF,與進度監控一起監控記憶體使用情況以確保最佳性能。
-
錯誤處理:始終在進度事件處理程式中包含錯誤處理,以防止異常中斷OCR過程。
-
執行緒安全:從進度事件中更新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文件特別有價值,允許監控處理狀態、估算完成時間,以及在長時間操作期間提供使用者反饋。
Is there a recommended frequency for OcrProgress updates?
While the OcrProgress event fires frequently, it's recommended to filter updates to avoid overwhelming your UI or logs, which can impact performance.
How can IronOCR's progress tracking improve the processing of large documents?
When dealing with large documents, IronOCR's progress tracking allows for better control with timeout settings and abort tokens, providing a mechanism to handle slow processing efficiently.
Does progress tracking in IronOCR affect performance?
Progress tracking in IronOCR has minimal performance overhead, although excessive logging or UI updates based on progress events may slow down the overall OCR process.
What best practices should I follow for using progress tracking in IronOCR?
Best practices include managing update frequencies, ensuring thread safety when updating UI elements, and incorporating error handling to maintain smooth OCR operations.
Can IronOCR be used for tracking progress in multi-threaded environments?
Yes, IronOCR's progress tracking can be combined with multi-threading to enhance OCR performance, handling multiple documents or large files more efficiently.

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