如何使用 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] 套件。 此擴充功能提供進階的電腦視覺功能,可提升螢幕截圖文字辨識的準確度,特別針對現代應用程式中的使用者介面元件、系統字型及抗鋸齒文字。

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

使用 IronOCR 的 ReadScreenshot 功能,幾秒鐘內即可開始操作——將您的螢幕截圖上傳至 OcrInput,呼叫 ReadScreenShot,並透過 OcrPhotoResult 立即存取擷取的文字、信心分數及文字區域。 這是將圖片轉為可用文字最快捷的方式,且設定步驟極簡。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/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 輸入中擷取的文字。 此屬性將所有識別出的文字作為單一字串儲存,並保留原始的換行與空格格式。
  • Confidence:一個雙精度屬性,表示統計精確度的置信度,範圍為 0 到 1,其中 1 代表最高置信度。 請使用此工具在您的應用程式中實施品質控管。
  • TextRegion:一個由 TextRegion 物件組成的陣列,其屬性會回傳螢幕截圖中文字所在的區域。 預設情況下,所有 TextRegion 皆為 IronOCR 模型所衍生的 Rectangle 類別。 其中包含 xy 座標,以及矩形的 heightwidth

透過 TextRegions,您可以:

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

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 方法非常適合用於:

  • 自動化使用者介面測試與驗證
  • 數位資產管理系統
  • 用於擷取錯誤訊息的客戶支援工具
  • 文件自動化
  • 螢幕閱讀器的輔助功能工具
  • 遊戲與串流應用程式

與 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.Extensions.AdvancedScan 套件,該套件提供進階的電腦視覺功能,可提升螢幕截圖文字辨識的準確度。

我何時能開始從螢幕截圖中擷取文字?

透過 IronOCR,您只需將螢幕截圖載入 OcrInput,呼叫 ReadScreenShot 方法,即可在數秒內從截圖中擷取文字,並透過 OcrPhotoResult 立即取得擷取的文字、信心分數及文字區域。

螢幕截圖 OCR 最適合用於哪類內容?

IronOCR 的螢幕截圖優化功能包含:自動偵測使用者介面元件、提升跨作業系統的系統字型辨識能力,以及更妥善處理現代應用程式中常見的抗鋸齒文字。

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

是的,IronOCR 支援處理螢幕截圖的特定區域,讓您能針對感興趣的特定區域進行處理,而非處理整張圖片,這有助於提升效能與準確度。

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

IronOCR 的 ReadScreenshot 方法可處理截圖中的多語言內容,使其適用於國際化應用程式及多語言使用者介面。

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
執行範例 觀看您的圖片轉為可搜尋文字。