如何在 C# 中使用 IronOCR 閱讀螢幕截圖#。

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

IronOCR 的 ReadScreenshot 方法可以高效地從螢幕截圖中提取文字,處理各種尺寸和雜訊挑戰,同時支援常見的檔案格式,包括 PNG、JPG 和 BMP。

螢幕截圖提供了分享資訊和擷取重要資料的快速方式。 然而,由於不同的尺寸和雜訊,從螢幕截圖中抽取文字已被證明是困難的。這使得螢幕截圖成為 OCR 的挑戰媒介。

IronOCR 透過提供 ReadScreenshot 等專門的方法來解決這個問題。 此方法已針對閱讀螢幕截圖並從中擷取資訊進行最佳化,同時接受常見的檔案格式。 與標準 OCR 方法不同的是,此方法應用了專為螢幕截圖內容量身打造的特定預處理最佳化,包括自動降噪和對比強化。

若要使用此功能,請安裝 IronOcr.Extension.AdvancedScan套件。 本擴充套件提供先進的電腦視覺功能,可提升螢幕截圖文字的辨識準確度,特別是針對現代應用程式中的 UI 元件、系統字型和反鋸齒文字。

快速入門:從螢幕截圖中讀取文字

使用 IronOCR 的 ReadScreenshot 可在幾秒鐘內開始使用 - 將您的螢幕截圖載入 OcrInput 中,呼叫 ReadScreenShot 並立即透過 OcrPhotoResult 存取擷取的文字、置信分數和文字區域。 這是將圖像轉換成可用文字的最快方法,只需最少的設定。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronOCR

    PM > Install-Package IronOcr

  2. 複製並運行這段程式碼。

    OcrPhotoResult result = new IronTesseract().ReadScreenShot(new OcrInput().LoadImage("screenshot.png"));
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronOCR,免費試用!
    arrow pointer

本指南示範如何使用 IronOCR 進行螢幕截圖文字識別,透過範例和結果物件的屬性進行說明。 我們將探討一些進階的情境,例如 處理特定區域、處理多語言內容,以及優化批次處理的效能。

如何使用 ReadScreenshot 從螢幕擷取文字?

若要在 IronOCR 中讀取螢幕快照,請使用 ReadScreenshot 方法,該方法會將 OcrInput 視為參數。 與庫的標準Read方法相比,此方法更適合螢幕截圖。 優化包括自動偵測 UI 元件、更好地處理反鋸齒字體,以及改善不同作業系統的系統字體辨識。

請注意@

  • 該方法目前適用於英語、中文、日語、韓語以及拉丁字母等語言。
  • 在 .NET Framework 上使用進階掃描功能需要專案在 x64 架構上運作。

哪些類型的螢幕截圖效果最佳?

以下是我們為程式碼範例提供的輸入; 我們透過混合使用不同的文字字型和大小來展示此方法的多樣性。 ReadScreenshot 方法擅長於辨識:

  • 系統 UI 字型 (Windows, macOS, Linux)
  • 來自現代應用程式的反鋸齒文字
  • 混合字型大小和樣式
  • 複雜背景上覆蓋的文字
  • 控制台輸出和終端截圖
  • 使用各種網頁字型的瀏覽器內容

為達到最佳效果,請以原始解析度擷取螢幕截圖,不要壓縮。 本方法可處理 各種圖片格式,但 PNG 格式因其無損壓縮,最能保留文字的清晰度。

IronOCR C# OCR 函式庫首頁,顯示平台相容性及文字辨識的主要功能

如何實作 ReadScreenshot 方法?

:path=/static-assets/ocr/content-code-examples/how-to/read-screenshot-read-screenshot.cs
using IronOcr;
using System;
using System.Linq;

// Instantiate OCR engine
var ocr = new IronTesseract();

using var inputScreenshot = new OcrInput();
inputScreenshot.LoadImage("screenshotOCR.png");

// Perform OCR
OcrPhotoResult result = ocr.ReadScreenShot(inputScreenshot);

// Output screenshot information
Console.WriteLine(result.Text);
Console.WriteLine(result.TextRegions.First().Region.X);
Console.WriteLine(result.TextRegions.Last().Region.Width);
Console.WriteLine(result.Confidence);
Imports IronOcr
Imports System
Imports System.Linq

' Instantiate OCR engine
Private ocr = New IronTesseract()

Private inputScreenshot = New OcrInput()
inputScreenshot.LoadImage("screenshotOCR.png")

' Perform OCR
Dim result As OcrPhotoResult = ocr.ReadScreenShot(inputScreenshot)

' Output screenshot information
Console.WriteLine(result.Text)
Console.WriteLine(result.TextRegions.First().Region.X)
Console.WriteLine(result.TextRegions.Last().Region.Width)
Console.WriteLine(result.Confidence)
$vbLabelText   $csharpLabel

對於複雜的情境,請使用額外的預處理功能來強化螢幕截圖的閱讀過程:

using IronOcr;
using System;

// Configure OCR engine with specific settings for screenshots
var ocr = new IronTesseract()
{
    // Set language for better accuracy with non-English content
    Language = OcrLanguage.English,
    // Configure for screen-resolution images
    Configuration = new TesseractConfiguration()
    {
        PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd,
        // Enable whitelist for specific characters if needed
        WhiteListCharacters = null
    }
};

using var inputScreenshot = new OcrInput();
// Load screenshot with specific DPI setting for consistency
inputScreenshot.LoadImage("screenshotOCR.png", 96); // Standard screen DPI

// Apply preprocessing for better accuracy
inputScreenshot.DeNoise(); // Remove screenshot artifacts
inputScreenshot.Sharpen(); // Enhance text edges

// Perform OCR with error handling
try
{
    OcrPhotoResult result = ocr.ReadScreenShot(inputScreenshot);

    // Process results with confidence threshold
    if (result.Confidence > 0.8)
    {
        Console.WriteLine($"High confidence text extraction: {result.Text}");
    }
    else
    {
        Console.WriteLine("Low confidence - consider image preprocessing");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"OCR Error: {ex.Message}");
}
using IronOcr;
using System;

// Configure OCR engine with specific settings for screenshots
var ocr = new IronTesseract()
{
    // Set language for better accuracy with non-English content
    Language = OcrLanguage.English,
    // Configure for screen-resolution images
    Configuration = new TesseractConfiguration()
    {
        PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd,
        // Enable whitelist for specific characters if needed
        WhiteListCharacters = null
    }
};

using var inputScreenshot = new OcrInput();
// Load screenshot with specific DPI setting for consistency
inputScreenshot.LoadImage("screenshotOCR.png", 96); // Standard screen DPI

// Apply preprocessing for better accuracy
inputScreenshot.DeNoise(); // Remove screenshot artifacts
inputScreenshot.Sharpen(); // Enhance text edges

// Perform OCR with error handling
try
{
    OcrPhotoResult result = ocr.ReadScreenShot(inputScreenshot);

    // Process results with confidence threshold
    if (result.Confidence > 0.8)
    {
        Console.WriteLine($"High confidence text extraction: {result.Text}");
    }
    else
    {
        Console.WriteLine("Low confidence - consider image preprocessing");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"OCR Error: {ex.Message}");
}
Imports IronOcr
Imports System

' Configure OCR engine with specific settings for screenshots
Dim ocr As New IronTesseract() With {
    ' Set language for better accuracy with non-English content
    .Language = OcrLanguage.English,
    ' Configure for screen-resolution images
    .Configuration = New TesseractConfiguration() With {
        .PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd,
        ' Enable whitelist for specific characters if needed
        .WhiteListCharacters = Nothing
    }
}

Using inputScreenshot As New OcrInput()
    ' Load screenshot with specific DPI setting for consistency
    inputScreenshot.LoadImage("screenshotOCR.png", 96) ' Standard screen DPI

    ' Apply preprocessing for better accuracy
    inputScreenshot.DeNoise() ' Remove screenshot artifacts
    inputScreenshot.Sharpen() ' Enhance text edges

    ' Perform OCR with error handling
    Try
        Dim result As OcrPhotoResult = ocr.ReadScreenShot(inputScreenshot)

        ' Process results with confidence threshold
        If result.Confidence > 0.8 Then
            Console.WriteLine($"High confidence text extraction: {result.Text}")
        Else
            Console.WriteLine("Low confidence - consider image preprocessing")
        End If
    Catch ex As Exception
        Console.WriteLine($"OCR Error: {ex.Message}")
    End Try
End Using
$vbLabelText   $csharpLabel

OcrPhotoResult 會傳回哪些屬性?

Visual Studio 除錯器顯示 IronOCR 函式庫的詳細資訊,版本為 2024.9,精確度為 0.937

控制台輸出顯示從截圖中擷取的所有文字實例。 讓我們來探索 OcrPhotoResult 的屬性,以及如何有效利用這些屬性:

  • Text :從 OCR 輸入中提取的文字。 此屬性包含以單一字串形式呈現的所有辨識文字,並保留原始版面的換行與間距。
  • 置信度:雙重屬性,表示統計準確度的置信度,範圍從 0 到 1,其中 1 代表最高置信度。 利用這一點在您的應用程式中實施品質控制。
  • TextRegion:一個 TextRegion 物件的陣列,此陣列持有返回截圖上文字所在區域的屬性。 預設情況下,所有 TextRegion 都是 IronOCR 模型的派生 Rectangle 類別。 它包括 x 和 y 坐標加上矩形的高度和寬度。

使用 TextRegions 可以讓您

  • 從特定的螢幕截圖區域擷取文字
  • 識別 UI 元素位置
  • 根據文字位置建立可點選的覆蓋圖
  • 實施特定區域的 OCR 處理

以下是處理個別文字區域的範例:

using IronOcr;
using System;
using System.Linq;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("screenshot.png");

OcrPhotoResult result = ocr.ReadScreenShot(input);

// Process each text region individually
foreach (var region in result.TextRegions)
{
    Console.WriteLine($"Text: {region.Text}");
    Console.WriteLine($"Location: X={region.Region.X}, Y={region.Region.Y}");
    Console.WriteLine($"Size: {region.Region.Width}x{region.Region.Height}");
    Console.WriteLine($"Confidence: {region.Confidence:P2}");
    Console.WriteLine("---");
}

// Find specific UI elements by text content
var buttonRegion = result.TextRegions
    .FirstOrDefault(r => r.Text.Contains("Submit", StringComparison.OrdinalIgnoreCase));

if (buttonRegion != null)
{
    Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}");
}
using IronOcr;
using System;
using System.Linq;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("screenshot.png");

OcrPhotoResult result = ocr.ReadScreenShot(input);

// Process each text region individually
foreach (var region in result.TextRegions)
{
    Console.WriteLine($"Text: {region.Text}");
    Console.WriteLine($"Location: X={region.Region.X}, Y={region.Region.Y}");
    Console.WriteLine($"Size: {region.Region.Width}x{region.Region.Height}");
    Console.WriteLine($"Confidence: {region.Confidence:P2}");
    Console.WriteLine("---");
}

// Find specific UI elements by text content
var buttonRegion = result.TextRegions
    .FirstOrDefault(r => r.Text.Contains("Submit", StringComparison.OrdinalIgnoreCase));

if (buttonRegion != null)
{
    Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}");
}
Imports IronOcr
Imports System
Imports System.Linq

Dim ocr As New IronTesseract()
Using input As New OcrInput()
    input.LoadImage("screenshot.png")

    Dim result As OcrPhotoResult = ocr.ReadScreenShot(input)

    ' Process each text region individually
    For Each region In result.TextRegions
        Console.WriteLine($"Text: {region.Text}")
        Console.WriteLine($"Location: X={region.Region.X}, Y={region.Region.Y}")
        Console.WriteLine($"Size: {region.Region.Width}x{region.Region.Height}")
        Console.WriteLine($"Confidence: {region.Confidence:P2}")
        Console.WriteLine("---")
    Next

    ' Find specific UI elements by text content
    Dim buttonRegion = result.TextRegions _
        .FirstOrDefault(Function(r) r.Text.Contains("Submit", StringComparison.OrdinalIgnoreCase))

    If buttonRegion IsNot Nothing Then
        Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}")
    End If
End Using
$vbLabelText   $csharpLabel

進階螢幕截圖處理技巧

處理多國語言螢幕截圖

在處理包含多國語言的螢幕截圖時,IronOCR 提供強大的 多國語言支援。 這對國際應用程式或多語言使用者介面的截圖非常有用:

using IronOcr;

// Configure for multiple languages
var ocr = new IronTesseract();
ocr.AddSecondaryLanguage(OcrLanguage.ChineseSimplified);
ocr.AddSecondaryLanguage(OcrLanguage.Japanese);

using var input = new OcrInput();
input.LoadImage("multilingual-screenshot.png");

// Process with language detection
OcrPhotoResult result = ocr.ReadScreenShot(input);
Console.WriteLine($"Extracted multilingual text: {result.Text}");
using IronOcr;

// Configure for multiple languages
var ocr = new IronTesseract();
ocr.AddSecondaryLanguage(OcrLanguage.ChineseSimplified);
ocr.AddSecondaryLanguage(OcrLanguage.Japanese);

using var input = new OcrInput();
input.LoadImage("multilingual-screenshot.png");

// Process with language detection
OcrPhotoResult result = ocr.ReadScreenShot(input);
Console.WriteLine($"Extracted multilingual text: {result.Text}");
Imports IronOcr

' Configure for multiple languages
Dim ocr As New IronTesseract()
ocr.AddSecondaryLanguage(OcrLanguage.ChineseSimplified)
ocr.AddSecondaryLanguage(OcrLanguage.Japanese)

Using input As New OcrInput()
    input.LoadImage("multilingual-screenshot.png")

    ' Process with language detection
    Dim result As OcrPhotoResult = ocr.ReadScreenShot(input)
    Console.WriteLine($"Extracted multilingual text: {result.Text}")
End Using
$vbLabelText   $csharpLabel

批次處理的效能最佳化

在處理多個螢幕截圖時,請執行這些最佳化策略:

using IronOcr;
using System.Collections.Generic;
using System.Threading.Tasks;

public async Task ProcessScreenshotBatchAsync(List<string> screenshotPaths)
{
    var ocr = new IronTesseract();

    // Process screenshots in parallel for better performance
    var tasks = screenshotPaths.Select(async path =>
    {
        using var input = new OcrInput();
        input.LoadImage(path);

        // Apply consistent preprocessing
        input.DeNoise();

        var result = await Task.Run(() => ocr.ReadScreenShot(input));
        return new { Path = path, Result = result };
    });

    var results = await Task.WhenAll(tasks);

    // Process results
    foreach (var item in results)
    {
        Console.WriteLine($"File: {item.Path}");
        Console.WriteLine($"Text: {item.Result.Text}");
        Console.WriteLine($"Confidence: {item.Result.Confidence:P2}");
    }
}
using IronOcr;
using System.Collections.Generic;
using System.Threading.Tasks;

public async Task ProcessScreenshotBatchAsync(List<string> screenshotPaths)
{
    var ocr = new IronTesseract();

    // Process screenshots in parallel for better performance
    var tasks = screenshotPaths.Select(async path =>
    {
        using var input = new OcrInput();
        input.LoadImage(path);

        // Apply consistent preprocessing
        input.DeNoise();

        var result = await Task.Run(() => ocr.ReadScreenShot(input));
        return new { Path = path, Result = result };
    });

    var results = await Task.WhenAll(tasks);

    // Process results
    foreach (var item in results)
    {
        Console.WriteLine($"File: {item.Path}");
        Console.WriteLine($"Text: {item.Result.Text}");
        Console.WriteLine($"Confidence: {item.Result.Confidence:P2}");
    }
}
Imports IronOcr
Imports System.Collections.Generic
Imports System.Threading.Tasks

Public Async Function ProcessScreenshotBatchAsync(screenshotPaths As List(Of String)) As Task
    Dim ocr As New IronTesseract()

    ' Process screenshots in parallel for better performance
    Dim tasks = screenshotPaths.Select(Async Function(path)
                                           Using input As New OcrInput()
                                               input.LoadImage(path)

                                               ' Apply consistent preprocessing
                                               input.DeNoise()

                                               Dim result = Await Task.Run(Function() ocr.ReadScreenShot(input))
                                               Return New With {Key .Path = path, Key .Result = result}
                                           End Using
                                       End Function)

    Dim results = Await Task.WhenAll(tasks)

    ' Process results
    For Each item In results
        Console.WriteLine($"File: {item.Path}")
        Console.WriteLine($"Text: {item.Result.Text}")
        Console.WriteLine($"Confidence: {item.Result.Confidence:P2}")
    Next
End Function
$vbLabelText   $csharpLabel

螢幕快照 OCR 的最佳作法

1.擷取品質:以原始解析度擷取螢幕截圖,無須縮放 2.格式選擇:使用 PNG 格式以保存無損的品質 3.預處理:根據截圖內容套用適當的篩選條件 4.置信度閾值:針對關鍵應用實施基於置信度的驗證 5.進度追蹤:對於長時間的作業,請執行 進度追蹤

常見用例

ReadScreenshot 方法非常適用於:

  • 自動化 UI 測試與驗證
  • 數位資產管理系統
  • 擷取錯誤訊息的客戶支援工具
  • 文件自動化
  • 適用於螢幕閱讀器的無障礙工具
  • 遊戲與串流應用程式

與 IronOCR 功能整合。

螢幕截圖閱讀功能可與其他 IronOCR 功能無縫整合。 探索全面的 OCR 結果處理,以各種格式匯出資料,或深入進階的 Tesseract 配置,以微調識別精確度。

摘要

IronOCR 的 ReadScreenshot 方法為從螢幕截圖中擷取文字提供了強大且最佳化的解決方案。 透過專門的預處理、高準確度以及全面的結果資料,讓開發人員能夠建立穩健的應用程式,可靠地處理螢幕截圖內容。 無論是建立自動化工具、無障礙解決方案或資料擷取系統,ReadScreenshot 方法都能提供生產環境所需的效能與精確度。

常見問題解答

從螢幕截圖中進行 OCR 擷取有何挑戰性?

由於尺寸和雜訊程度各異,螢幕截圖對 OCR 來說是獨特的挑戰。IronOcr 使用其專門的 ReadScreenshot 方法來解決這些問題,該方法可應用專門針對螢幕快照內容最佳化的自動降噪和對比強化功能。

螢幕截圖 OCR 支援哪些檔案格式?

IronOCR 的 ReadScreenshot 方法支援常見的影像檔案格式,包括 PNG、JPG 和 BMP,因此與大多數的螢幕截圖工具和應用程式相容。

ReadScreenshot 方法與標準 OCR 方法有何不同?

與 IronOCR 中的標準 OCR 方法不同,ReadScreenshot 方法應用了專為螢幕截圖內容量身打造的特定預處理最佳化,包括自動降噪、對比強化,以及更好地處理反鋸齒字型和 UI 元素。

螢幕截圖 OCR 功能需要哪些額外套件?

要使用 IronOCR 中的 ReadScreenshot 功能,您需要安裝 IronOcr.Extension.AdvancedScan 套件,該套件提供先進的電腦視覺功能,可提高螢幕截圖文字辨識的準確度。

如何快速開始從螢幕截圖中擷取文字?

使用 IronOCR,您可以在幾秒鐘內從螢幕截圖中擷取文字,只要將螢幕截圖載入 OcrInput、呼叫 ReadScreenShot,並立即透過 OcrPhotoResult 存取擷取的文字、置信分數和文字區域即可。

螢幕截圖 OCR 可針對哪些類型的內容進行最佳化?

IronOCR 的螢幕截圖最佳化功能包括自動偵測 UI 元件、改善不同作業系統的系統字型辨識,以及更好地處理現代應用程式中常見的反鋸齒文字。

我可以處理截圖的特定區域嗎?

是的,IronOCR 支援處理螢幕截圖的特定區域,讓您可以針對特定區域進行處理,而不是處理整張圖片,這樣可以提高效能和精確度。

螢幕截圖 OCR 是否支援多語言內容?

IronOCR 的 ReadScreenshot 方法可以處理螢幕截圖中的多國語言內容,因此適用於國際應用程式和多國語言使用者介面。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 5,384,824 | 版本: 2026.2 剛剛發布