如何使用IronOCR在C#中读取屏幕截图
IronOCR 的 ReadScreenshot 方法可以高效提取截图中的文本,能处理不同尺寸和带有噪声的截图,支持 PNG、JPG 和 BMP 等常见文件格式。
截图便于快速分享信息和记录重要数据,但截图尺寸各异,图像也可能带有噪声,因此 OCR 提取文本较为困难。
IronOCR 提供 ReadScreenshot 等专用方法,可从常见格式的截图中提取信息。与标准 OCR 方法相比,此方法还针对截图执行自动降噪、增强对比度等预处理。
要使用此功能,请安装 [IronOcr.Extension.AdvancedScan] 包。该扩展提供高级计算机视觉功能,可提高截图的文本识别准确率,尤其适用于现代应用程序中的用户界面元素、系统字体和经过抗锯齿处理的文本。
使用 IronOCR 的 ReadScreenshot 时,将截图加载到 OcrInput 中,再调用 ReadScreenShot,即可从 OcrPhotoResult 获取提取的文本、置信度分数和文本区域。只需少量配置,即可快速将图像转为可用文本。
-
1使用 IronOCR 安装 NuGet Package Manager
-
2复制并运行这段代码。
OcrPhotoResult result = new IronTesseract().ReadScreenShot(new OcrInput().LoadImage("screenshot.png"));Dim result As OcrPhotoResult = New IronTesseract().ReadScreenShot(New OcrInput().LoadImage("screenshot.png"))Dim result As OcrPhotoResult = New IronTesseract().ReadScreenShot(New OcrInput().LoadImage("screenshot.png")) -
3部署到您的生产环境中进行测试
今天就用免费试用在您的项目中开始使用IronOCR
本指南演示了如何使用 IronOCR 进行截图文本识别,并通过示例和结果对象的属性进行了讲解。 我们将探讨高级场景,如处理特定区域、处理多语言内容,以及优化批处理性能。
基本流程(5 步)
- 下载用于读取截图的C#库
- 导入截图图像以进行处理
- 使用
ReadScreenshot方法从图像中提取文本 - 使用OcrPhotoResult属性检索提取的数据以进行进一步处理。
- 根据需要保存或导出提取的文本
如何使用ReadScreenshot从截图中提取文本?
在 IronOCR 中读取截图时,将 OcrInput 作为参数传给 ReadScreenshot。与库中的标准 Read 方法相比,此方法更适合处理截图,可自动检测用户界面元素,更好地处理经过抗锯齿处理的字体,并提高对不同操作系统的系统字体的识别能力。
什么类型的截图效果最好?
下面是代码示例使用的输入图像。图像包含不同字体和字号的文本,用于展示此方法的适用范围。ReadScreenshot 方法擅长识别:
- 系统用户界面字体(Windows、macOS、Linux)
- 现代应用程序中经过抗锯齿处理的文本
- 混用不同字号和样式的文本
- 在复杂背景上叠加文字
- 控制台输出和终端截图
- 使用各种网络字体的浏览器内容
为获得最佳效果,请按原始分辨率截图,避免压缩。此方法支持各种图像格式,其中 PNG 采用无损压缩,最能保持文本清晰度。

如何实现ReadScreenshot方法?
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);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
Dim ocr = New IronTesseract()
Using 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)
End UsingImports IronOcr
Imports System
Imports System.Linq
' Instantiate OCR engine
Dim ocr = New IronTesseract()
Using 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)
End Using对于复杂场景,可以增加预处理步骤来改善截图识别效果:
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");
// 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");
// 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")
' 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 UsingImports 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")
' 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 UsingOcrPhotoResult 提供哪些属性?

控制台输出会显示从截图中提取的全部文本。以下是 OcrPhotoResult 的属性及其用途:
Text: 从OCR输入提取的文本。 该属性以单个字符串的形式包含所有识别文本,并保留了带换行符和间距的原始布局。Confidence: 双精度属性,表示识别结果的统计置信度,取值为 0 到 1,1 表示置信度最高。可用此属性在应用程序中进行质量控制。TextRegion: 由TextRegion对象组成的数组,用于定位截图中的文本。默认情况下,TextRegion派生自 IronOCR 模型中的Rectangle类,包含矩形的x和y坐标,以及height和width。
通过 TextRegions 可以:
- 从特定截图区域提取文本
- 确定用户界面元素的位置
- 根据文本位置创建可点击的叠加层
- 实施特定区域的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.TextInRegion}");
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.RegionConf:P2}");
Console.WriteLine("---");
}
// Find specific UI elements by text content
var buttonRegion = result.TextRegions
.FirstOrDefault(r => r.TextInRegion.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.TextInRegion}");
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.RegionConf:P2}");
Console.WriteLine("---");
}
// Find specific UI elements by text content
var buttonRegion = result.TextRegions
.FirstOrDefault(r => r.TextInRegion.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 = New IronTesseract()
Using input = 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.TextInRegion}")
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.RegionConf:P2}")
Console.WriteLine("---")
Next
' Find specific UI elements by text content
Dim buttonRegion = result.TextRegions _
.FirstOrDefault(Function(r) r.TextInRegion.Contains("Submit", StringComparison.OrdinalIgnoreCase))
If buttonRegion IsNot Nothing Then
Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}")
End If
End UsingImports IronOcr
Imports System
Imports System.Linq
Dim ocr = New IronTesseract()
Using input = 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.TextInRegion}")
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.RegionConf:P2}")
Console.WriteLine("---")
Next
' Find specific UI elements by text content
Dim buttonRegion = result.TextRegions _
.FirstOrDefault(Function(r) r.TextInRegion.Contains("Submit", StringComparison.OrdinalIgnoreCase))
If buttonRegion IsNot Nothing Then
Console.WriteLine($"Found button at: {buttonRegion.Region.X}, {buttonRegion.Region.Y}")
End If
End Using高级截图处理技术
处理多语言截图
当处理包含多种语言的截图时,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 UsingImports 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批量处理的性能优化
在处理多张截图时,应采用以下优化策略:
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 = New IronTesseract()
' Process screenshots in parallel for better performance
Dim tasks = screenshotPaths.Select(Async Function(path)
Using input = 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 FunctionImports IronOcr
Imports System.Collections.Generic
Imports System.Threading.Tasks
Public Async Function ProcessScreenshotBatchAsync(screenshotPaths As List(Of String)) As Task
Dim ocr = New IronTesseract()
' Process screenshots in parallel for better performance
Dim tasks = screenshotPaths.Select(Async Function(path)
Using input = 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截图OCR的最佳实践
- 捕获质量:在原始分辨率下截图,不进行缩放
- 格式选择:使用PNG格式以保持无损质量
- 预处理:根据截图内容应用合适的滤镜
- 置信度阈值:为关键应用实施基于置信度的验证
- 进度跟踪:为长时间操作实施进度跟踪
常见用例
ReadScreenshot方法非常适合:
- 自动化UI测试和验证
- 数字资产管理系统
- 用于捕捉错误信息的客户支持工具
- 文档自动化
- 用于屏幕阅读器的辅助工具
- 游戏和流媒体应用程序
与IronOCR功能的集成
截图读取功能可与 IronOCR 的其他功能配合使用。可通过处理 OCR 结果将数据导出为各种格式,也可通过高级 Tesseract 配置微调识别效果。
总结
IronOCR 的 ReadScreenshot 方法专为从截图中提取文本而优化。针对截图的预处理、较高的识别准确率和丰富的结果数据,有助于开发人员构建可靠的截图处理应用。无论是自动化工具、无障碍解决方案还是数据提取系统,ReadScreenshot 都能提供生产环境所需的性能和准确性。
常见问题
使用IronOCR的`ReadScreenshot`方法的主要优点是什么?
IronOCR中的ReadScreenshot方法经过优化,可从截图中读取文本,提供自动降噪和UI元素检测等功能,从而提高文本识别的准确性。
IronOCR的`ReadScreenshot`方法支持哪些图像格式?
IronOCR的ReadScreenshot方法支持常见的文件格式,如PNG、JPG和BMP,使其能够处理多种类型的截图。
IronOCR如何处理截图中的不同字体和字号?
IronOCR的ReadScreenshot方法擅长识别系统UI字体、抗锯齿文本和多种字体大小,即使在复杂背景上叠加也能准确提取文本。
IronOCR的`ReadScreenshot`方法可以处理多语言截图吗?
是的,IronOCR提供可靠的多语言文本识别支持,使其对包含多种国际语言的截图有效。
IronOCR使用哪些预处理技术来提高截图文本提取?
IronOCR使用降噪和增强对比度等预处理技术来提高截图文本提取的准确性。
如何安装所需工具以使用IronOCR的`ReadScreenshot`方法?
要使用ReadScreenshot功能,请从NuGet安装IronOcr库以及可选的IronOcr.Extension.AdvancedScan包,以获取高级的截图文本识别功能。
`OcrPhotoResult`在使用`ReadScreenshot`方法时返回哪些属性?
OcrPhotoResult返回提取的文本、置信度评分和文本区域等属性,提供识别文本及其在截图中位置的详细信息。
IronOCR如何确保截图文本提取的高准确性?
IronOCR通过应用多种优化措施确保高准确性,比如抗锯齿和UI字体的自动检测,以及适用于截图特定挑战的高级预处理。
使用IronOCR时PNG是截图的最佳格式吗?
是的,建议使用PNG格式进行截图,因为它具有无损压缩特性,能最好地保留文本清晰度,从而更准确的OCR结果。
IronOCR的`ReadScreenshot`方法的一些常见用例是什么?
ReadScreenshot方法的常见用例包括自动化UI测试、数字资产管理、客户支持工具、文档自动化以及面向屏幕阅读器的辅助工具。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。