Cómo usar visión por computadora para encontrar texto en C#

How to use Computer Vision to Find Text

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

IronOCR utilizes OpenCV to use Computer Vision to detect areas where text exists in an image. This is useful for images that contain a lot of noise, images with text in many different places, and images where text is warped. The use of computer vision in IronOCR will determine where text regions exist and then use Tesseract to attempt to read those regions.

Quickstart: Detect and OCR the Primary Text Region

This example shows how easily you can get started: just load an image, let IronOCR’s Computer Vision auto-find the main text region with FindTextRegion(), then immediately run .Read(...) to extract the text. It takes only one simple line to go from image to OCR output.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronOCR with NuGet Package Manager

    PM > Install-Package IronOcr

  2. Copy and run this code snippet.

    using var result = new IronTesseract().Read(new OcrInput().LoadImage("image.png").FindTextRegion());
  3. Deploy to test on your live environment

    Start using IronOCR in your project today with a free trial
    arrow pointer

IronOCR.ComputerVision Installation via NuGet Package

OpenCV methods that perform Computer Vision in IronOCR are visible in the regular IronOCR NuGet package.

Use of these methods requires NuGet installation of IronOcr.ComputerVision to the solution. You are prompted to download it if you do not have it installed.

  • Windows: IronOcr.ComputerVision.Windows
  • Linux: IronOcr.ComputerVision.Linux
  • macOS: IronOcr.ComputerVision.MacOS
  • macOS ARM: IronOcr.ComputerVision.MacOS.ARM

Install using the NuGet Package Manager or paste the following in the Package Manager Console:

Install-Package IronOcr.ComputerVision.Windows

This will provide the necessary assemblies to use IronOCR Computer Vision with our model file.

Functionality and API

Code Examples are included further down this tutorial. Here is a general overview of the methods that are currently available:

Method Explanation
FindTextRegion Detect regions which contain text elements and instruct Tesseract to only search for text within the area in which text was detected.
FindMultipleTextRegions Detect areas which contain text elements and divide the page into separate images based on text regions.
GetTextRegions Scans the image and returns a list of text regions as `List`.

FindTextRegion

Usage of FindTextRegion will use computer vision to detect regions which contain text elements on every page of an OcrInput object.

:path=/static-assets/ocr/content-code-examples/how-to/computer-vision-findtextregion-1.cs
using IronOcr;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("/path/file.png");

input.FindTextRegion();
OcrResult result = ocr.Read(input);
string resultText = result.Text;
Imports IronOcr

Private ocr = New IronTesseract()
Private input = New OcrInput()
input.LoadImage("/path/file.png")

input.FindTextRegion()
Dim result As OcrResult = ocr.Read(input)
Dim resultText As String = result.Text
$vbLabelText   $csharpLabel

Precaución This method overload is currently depreciated in IronOcr 2025.6.x and doesn't take custom parameters.

Can optionally be called with custom parameters:

:path=/static-assets/ocr/content-code-examples/how-to/computer-vision-findtextregion-2.cs
using IronOcr;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("/path/file.png");

input.FindTextRegion(Scale: 2.0, DilationAmount: 20, Binarize: true, Invert: true);
OcrResult result = ocr.Read(input);
string resultText = result.Text;
Imports IronOcr

Private ocr = New IronTesseract()
Private input = New OcrInput()
input.LoadImage("/path/file.png")

input.FindTextRegion(Scale:= 2.0, DilationAmount:= 20, Binarize:= True, Invert:= True)
Dim result As OcrResult = ocr.Read(input)
Dim resultText As String = result.Text
$vbLabelText   $csharpLabel

In this example, I will use the following image for a method I am writing which needs to crop to areas containing text but input images may vary in text location. In this case, I can use FindTextRegion to narrow down the scan to an area that Computer Vision has detected text. This is an example image:

Image with Text
:path=/static-assets/ocr/content-code-examples/how-to/computer-vision-findtextregion-3.cs
using IronOcr;
using IronSoftware.Drawing;
using System;
using System.Linq;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("wh-words-sign.jpg");

// Find the text region using Computer Vision
Rectangle textCropArea = input.GetPages().First().FindTextRegion();

// For debugging and demonstration purposes, lets see what region it found:
input.StampCropRectangleAndSaveAs(textCropArea, Color.Red, "image_text_area", AnyBitmap.ImageFormat.Png);

// Looks good, so let us apply this region to hasten the read:
var ocrResult = ocr.Read("wh-words-sign.jpg", textCropArea);
Console.WriteLine(ocrResult.Text);
Imports IronOcr
Imports IronSoftware.Drawing
Imports System
Imports System.Linq

Private ocr = New IronTesseract()
Private input = New OcrInput()
input.LoadImage("wh-words-sign.jpg")

' Find the text region using Computer Vision
Dim textCropArea As Rectangle = input.GetPages().First().FindTextRegion()

' For debugging and demonstration purposes, lets see what region it found:
input.StampCropRectangleAndSaveAs(textCropArea, Color.Red, "image_text_area", AnyBitmap.ImageFormat.Png)

' Looks good, so let us apply this region to hasten the read:
Dim ocrResult = ocr.Read("wh-words-sign.jpg", textCropArea)
Console.WriteLine(ocrResult.Text)
$vbLabelText   $csharpLabel

Now this code has two outputs, the first is a .png file saved by StampCropRectangleAndSaveAs which is used for debugging. We can see where IronCV (Computer Vision) thought the text was:

Image with Text Area Highlighted

Looks pretty good. Now the second output is the Text itself which is:

IRONSOFTWARE

50,000+

Developers in our active community

10,777,061 19,313
NuGet downloads Support tickets resolved
50%+ 80%+
Engineering Team growth Support Team growth
$25,000+

Raised with #TEAMSEAS to clean our beaches & waterways

FindMultipleTextRegions

Usage of FindMultipleTextRegions takes all pages of an OcrInput object and uses computer vision to detect areas which contain text elements and divide the input into separate images based on text regions:

:path=/static-assets/ocr/content-code-examples/how-to/computer-vision-findmultipletextregions-1.cs
using IronOcr;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("/path/file.png");

input.FindMultipleTextRegions();
OcrResult result = ocr.Read(input);
string resultText = result.Text;
Imports IronOcr

Private ocr = New IronTesseract()
Private input = New OcrInput()
input.LoadImage("/path/file.png")

input.FindMultipleTextRegions()
Dim result As OcrResult = ocr.Read(input)
Dim resultText As String = result.Text
$vbLabelText   $csharpLabel

Precaución Starting from IronOcr v2025.6.x, the FindMultipleTextRegions method no longer supports custom parameters.

Can optionally be called with custom parameters:

:path=/static-assets/ocr/content-code-examples/how-to/computer-vision-findmultipletextregions-2.cs
using IronOcr;

var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("/path/file.png");

input.FindMultipleTextRegions(Scale: 2.0, DilationAmount: -1, Binarize: true, Invert: false);
OcrResult result = ocr.Read(input);
string resultText = result.Text;
Imports IronOcr

Private ocr = New IronTesseract()
Private input = New OcrInput()
input.LoadImage("/path/file.png")

input.FindMultipleTextRegions(Scale:= 2.0, DilationAmount:= -1, Binarize:= True, Invert:= False)
Dim result As OcrResult = ocr.Read(input)
Dim resultText As String = result.Text
$vbLabelText   $csharpLabel

Another overload method of FindMultipleTextRegions takes an OCR Page and returns a list of OCR Pages, one for each Text region on it:

:path=/static-assets/ocr/content-code-examples/how-to/computer-vision-findmultipletextregions-3.cs
using IronOcr;
using System.Collections.Generic;
using System.Linq;

int pageIndex = 0;
using var input = new OcrInput();
input.LoadImage("/path/file.png");

var selectedPage = input.GetPages().ElementAt(pageIndex);
List<OcrInputPage> textRegionsOnPage = selectedPage.FindMultipleTextRegions();
Imports IronOcr
Imports System.Collections.Generic
Imports System.Linq

Private pageIndex As Integer = 0
Private input = New OcrInput()
input.LoadImage("/path/file.png")

Dim selectedPage = input.GetPages().ElementAt(pageIndex)
Dim textRegionsOnPage As List(Of OcrInputPage) = selectedPage.FindMultipleTextRegions()
$vbLabelText   $csharpLabel

GetTextRegions

Usage of GetTextRegions returns a list of crop areas where text was detected in a page:

:path=/static-assets/ocr/content-code-examples/how-to/computer-vision-gettextregions.cs
using IronOcr;
using IronSoftware.Drawing;
using System.Collections.Generic;
using System.Linq;

int pageIndex = 0;
using var input = new OcrInput();
input.LoadImage("/path/file.png");

var selectedPage = input.GetPages().ElementAt(pageIndex);
// List<Rectangle> regions = selectedPage.GetTextRegions();
Imports IronOcr
Imports IronSoftware.Drawing
Imports System.Collections.Generic
Imports System.Linq

Private pageIndex As Integer = 0
Private input = New OcrInput()
input.LoadImage("/path/file.png")

Dim selectedPage = input.GetPages().ElementAt(pageIndex)
' List<Rectangle> regions = selectedPage.GetTextRegions();
$vbLabelText   $csharpLabel

Specific Use Case Guides

With the right settings and input files, OCR can be a very powerful tool. It can almost perfectly imitate the reading capability of a human.

Preguntas Frecuentes

¿Cómo puedo aprovechar la visión por computadora para la detección de texto en imágenes?

IronOCR se puede usar para mejorar la detección de texto en imágenes utilizando su integración con OpenCV. Métodos como FindTextRegion y FindMultipleTextRegions le permiten localizar y manipular efectivamente áreas de texto.

¿Qué pasos se requieren para instalar IronOCR para visión por computadora en diferentes sistemas operativos?

Para usar IronOCR en diferentes sistemas operativos, puede instalar el paquete IronOCR.ComputerVision a través de NuGet. Use el comando Install-Package IronOcr.ComputerVision.Windows para Windows, con paquetes similares disponibles para Linux y macOS.

¿Qué funcionalidad proporciona el método FindTextRegion?

El método FindTextRegion en IronOCR identifica áreas en una imagen donde hay texto presente, permitiendo que Tesseract busque texto solo dentro de esas regiones especificadas, mejorando la precisión del OCR.

¿Cómo mejoran los parámetros personalizados la detección de regiones de texto?

Puede refinar la detección de regiones de texto en IronOCR utilizando parámetros personalizados con el método FindTextRegion, como establecer la altura mínima del texto y permitir subregiones, para identificar más precisamente áreas de texto en imágenes.

¿Por qué es beneficioso detectar múltiples regiones de texto en una imagen?

Detectar múltiples regiones de texto usando el método FindMultipleTextRegions en IronOCR ayuda a dividir una imagen en secciones separadas basadas en texto, lo cual es particularmente útil para procesar documentos con múltiples bloques de texto como facturas y subtítulos.

¿Cómo se pueden recuperar las áreas de texto detectadas de una imagen?

El método GetTextRegions en IronOCR le permite recuperar una lista de áreas de CropRectangle donde se detectó texto dentro de una imagen, permitiendo un mayor procesamiento o manipulación de esas regiones de texto.

¿Cuáles son las características clave de las capacidades de visión por computadora de IronOCR?

Las características de visión por computadora de IronOCR incluyen detección de regiones de texto a través de métodos como FindTextRegion y FindMultipleTextRegions, configuraciones personalizables de OCR y compatibilidad con múltiples sistemas operativos para mejorar la precisión de la detección de texto.

¿Cómo procesa IronOCR imágenes con múltiples regiones de texto?

IronOCR utiliza el método FindMultipleTextRegions para procesar imágenes dividiéndolas en imágenes separadas basadas en regiones de texto detectadas, permitiendo un análisis detallado y manipulación de cada área de texto.

¿Dónde puedo encontrar ejemplos de código para usar métodos de visión por computadora en IronOCR?

El tutorial proporciona ejemplos de código que demuestran el uso de métodos como FindTextRegion y FindMultipleTextRegions con IronOCR, ilustrando aplicaciones prácticas como la lectura de matrículas o el procesamiento de facturas.

¿Qué se necesita para utilizar las características de visión por computadora de IronOCR en C#?

Para usar las características de visión por computadora de IronOCR en C#, debe instalar el paquete IronOcr.ComputerVision a través de NuGet e incluir los espacios de nombres necesarios en su proyecto para acceder a los métodos de detección de texto.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 5,044,537 | Versión: 2025.11 recién lanzado