How to Define a Specific OCR Region of an Image

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

Often, you only need to extract text from a small part of an image, such as a total amount on an invoice or a specific field from a form. Scanning the full document is inefficient and can introduce errors by capturing irrelevant text.

IronOCR allows you to improve precision, performance, and accuracy by specifying the exact rectangular region to scan. This guide provides a step-by-step walkthrough on how to define a specific OCR region, extract text from it, and visually verify that your coordinates are correct for your OCR tasks.

Get Started with IronOCR

Comience a usar IronOCR en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer


Perform OCR on Specific Region

To define a specific OCR region, you create a Rectangle object from the IronSoftware.Drawing namespace. This object requires four values: the x-coordinate, the y-coordinate, the width, and the height, all in pixels. The (x, y) coordinates represent the top-left corner of your desired area.

When you load your image using LoadImage, you pass this Rectangle as the second parameter. IronOCR will then restrict its OCR process to only the pixels within that bounding box.

ConsejosTo find the coordinates for your Rectangle, you can use a simple image editor like MS Paint. Open your input image, hover your mouse over the top-left and bottom-right corners of the specified region, and note the (x, y) pixel coordinates. You can then calculate the rectangle's properties: (x1, y1, width, height), where width = x2-x1 and height = y2-y1.

OCR Input

We'll use a sample image with three paragraphs. Our goal is to extract only the second paragraph and ignore the rest of the text.

OCR Input

Code

:path=/static-assets/ocr/content-code-examples/how-to/ocr-region-of-an-image.cs
using IronOcr;
using IronSoftware.Drawing;
using System;

var ocrTesseract = new IronTesseract();
using var ocrInput = new OcrInput();

// Define the specific region as a Rectangle
// (x, y) is the top-left corner.
var ContentArea = new Rectangle(x: 215, y: 1250, width: 1335, height: 280);

ocrInput.LoadImage("region-input.png", ContentArea);

var ocrResult = ocrTesseract.Read(ocrInput);

// Print the extracted text
Console.WriteLine(ocrResult.Text);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

As you can see from the console output, only the second paragraph is processed by the OCR.

OCR Output

Verifying the OCR region of an Image

To ensure you've selected the correct coordinates for the input image, you can visualize the ContentArea you defined. A simple way to do this is to draw the rectangle on the input image and save it as a new file with StampCropRectangleAndSaveAs. This helps you debug and fine-tune the coordinates for optimal performance.

Here is the output image after drawing the specified bounding box on our example input image from above.

Code

:path=/static-assets/ocr/content-code-examples/how-to/ocr-region-of-an-image-highlighted.cs
using IronOcr;
using IronSoftware.Drawing;

var ocrTesseract = new IronTesseract();
using var ocrInput = new OcrInput();

// Define the specific rectangular area to scan within the image.
// The coordinates are in pixels: (x, y) is the top-left corner of the rectangle.
var ContentArea = new Rectangle(x: 4, y: 59, width: 365, height: 26);

ocrInput.LoadImage("region-input.png", ContentArea);

var ocrResult = ocrTesseract.Read(ocrInput);

// Draws the rectangle from above in a blue bounding box on the image for visualization.
ocrInput.StampCropRectangleAndSaveAs(ContentArea, Color.Aqua, "region-input.png");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

OCR Highlighted Output

The light blue rectangle confirms that we have correctly isolated the second paragraph for processing.

Preguntas Frecuentes

¿Por qué debería definir una región de OCR específica de una imagen?

Definir una región de OCR específica de una imagen es útil para mejorar la precisión y la exactitud al centrarse en el área de interés, como el monto total de una factura, en lugar de escanear todo el documento, lo que puede introducir errores.

¿Cómo puedo especificar una región de OCR usando IronOCR?

Puede especificar una región de OCR en IronOCR creando un objeto `Rectangle` con las coordenadas y dimensiones deseadas. A continuación, pase este rectángulo al método `LoadImage`, restringiendo el procesamiento de OCR a esa región específica.

¿Cuáles son los parámetros necesarios para definir una región de OCR?

Para definir una región de OCR, debe proporcionar cuatro parámetros para el objeto "Rectángulo": coordenada x, coordenada y, ancho y alto. Estos parámetros determinan la esquina superior izquierda y el tamaño de la región.

¿Cómo puedo asegurarme de que se seleccionen las coordenadas correctas para el OCR?

Para garantizar las coordenadas correctas, visualice el ContentArea definido dibujando el rectángulo en la imagen de entrada con `StampCropRectangleAndSaveAs`. Esto facilita la depuración y el ajuste preciso de las coordenadas.

¿Qué herramientas puedo utilizar para encontrar las coordenadas de mi región OCR?

Puede usar un editor de imágenes sencillo como MS Paint para encontrar las coordenadas de su región de OCR. Pase el ratón sobre las esquinas superior izquierda e inferior derecha del área deseada para observar las coordenadas de píxeles (x, y).

¿Cuál es el beneficio de utilizar IronOCR para tareas de OCR específicas de cada región?

IronOCR le permite extraer texto de manera eficiente de regiones específicas de una imagen, reduciendo errores y mejorando el rendimiento al evitar la captura de texto irrelevante.

¿Puedo verificar visualmente la región de OCR antes de procesarla?

Sí, puede verificar visualmente la región de OCR dibujando el rectángulo en la imagen de entrada. Esto confirma que se aísla el área correcta para el procesamiento, lo que garantiza la precisión.

¿Qué tipos de imágenes puedo procesar con IronOCR?

IronOCR puede procesar una variedad de formatos de imagen, lo que le permite extraer texto de regiones específicas de imágenes utilizadas en documentos, formularios y facturas.

¿Cómo gestiona IronOCR el proceso de OCR dentro de una región específica?

IronOCR restringe su proceso de OCR a los píxeles dentro del cuadro delimitador especificado, lo que garantiza que solo se extraiga el texto dentro de la región definida.

¿Cuál es el formato de salida del proceso OCR en IronOCR?

Se puede acceder al formato de salida del proceso OCR en IronOCR a través de la propiedad `OcrResult`, lo que le permite ver y manipular los datos extraídos según sea necesario.

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