How to Fix Image Colors for Reading

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

Fixing image colors involves several techniques to improve the legibility and quality of an image. IronOcr offers binarization, grayscale, inversion, and color replacement methods to make text and content within an image more readable and aesthetically pleasing, which is particularly important when working with OCR (Optical Character Recognition) to extract text from images. Reading only the selected text color is also possible.

Quickstart: Isolate Specific Text Colors in One Go

Use IronOCR’s SelectTextColor method to focus OCR on just the text color you care about—no complex image manipulation. In one line, you can load an image, choose the text color and tolerance, and extract only that text for accurate OCR results.

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.

    new IronTesseract().Read(new IronOcr.OcrImageInput("sample.jpg").SelectTextColor(new IronSoftware.Drawing.Color("#DB645C"), 60));
  3. Deploy to test on your live environment

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


Binarize Image Example

This process converts the image into a two-color format, typically black and white. It's useful for separating text from the background and reducing noise, making the text more distinct and easier to read.

To apply the binarization effect to the image, use the Binarize method. Since OCR processes work best with the highest contrast image, featuring black text on a white background, this method proves significant in making the background very distinctive from the characters.

:path=/static-assets/ocr/content-code-examples/how-to/image-color-correction-binarize-image.cs
using IronOcr;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Add image
using var imageInput = new OcrImageInput("sample.jpg");
// Apply binarize affect
imageInput.Binarize();

// Export the modified image
imageInput.SaveAsImages("binarize.jpg");
Imports IronOcr

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Add image
Private imageInput = New OcrImageInput("sample.jpg")
' Apply binarize affect
imageInput.Binarize()

' Export the modified image
imageInput.SaveAsImages("binarize.jpg")
$vbLabelText   $csharpLabel

For convenience, you can export the modified image using the SaveAsImages method. Below is a comparison of the image before and after binarization.

Sample image
Binarized image

Grayscale Image Example

Converting the image into various shades of gray can make it less distracting and more reader-friendly. This is especially helpful when the original colors in the image are causing visual clutter.

To apply the grayscale effect to the image, use the ToGrayScale method. The grayscale process involves taking the average of the R, G, and B values.

:path=/static-assets/ocr/content-code-examples/how-to/image-color-correction-grayscale-image.cs
// Apply grayscale affect
imageInput.ToGrayScale();
' Apply grayscale affect
imageInput.ToGrayScale()
$vbLabelText   $csharpLabel
Sample image
Grayscaled image

Invert Image Example

Inverting the colors can enhance contrast. For example, turning white text on a black background into black text on a white background can improve readability.

Use the Invert method to invert the image color. The method optionally accepts a boolean value, which is used to remove all color channels and return a grayscale image.

:path=/static-assets/ocr/content-code-examples/how-to/image-color-correction-invert-image.cs
// Apply invert affect
imageInput.Invert();
' Apply invert affect
imageInput.Invert()
$vbLabelText   $csharpLabel

The below images show the Invert method with and without the grayscale option.

Inverted image
Inverted and grayscaled image

Replace Color Example

This technique allows you to replace specific colors in the image with other colors, which can help highlight or de-emphasize certain elements. It's often used to make text more prominent or to correct problematic color contrasts.

To use the ReplaceColor method, specify the current color to be replaced as well as the new color. The third parameter of the method, which corresponds to the tolerance value, is also important. A higher tolerance is required in blurry images to achieve the desired result.

:path=/static-assets/ocr/content-code-examples/how-to/image-color-correction-replace-color.cs
using IronOcr;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Add image
using var imageInput = new OcrImageInput("sample.jpg");
IronSoftware.Drawing.Color currentColor = new IronSoftware.Drawing.Color("#DB645C");
IronSoftware.Drawing.Color newColor = IronSoftware.Drawing.Color.DarkCyan;

// Replace color
imageInput.ReplaceColor(currentColor, newColor, 80);

// Export the modified image
imageInput.SaveAsImages("replaceColor");
Imports IronOcr

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Add image
Private imageInput = New OcrImageInput("sample.jpg")
Private currentColor As New IronSoftware.Drawing.Color("#DB645C")
Private newColor As IronSoftware.Drawing.Color = IronSoftware.Drawing.Color.DarkCyan

' Replace color
imageInput.ReplaceColor(currentColor, newColor, 80)

' Export the modified image
imageInput.SaveAsImages("replaceColor")
$vbLabelText   $csharpLabel
Sample image
Replaced color image

Read Specific Text Color Example

This feature aims to read only the specified text color. Use the SelectTextColor method to specify the color for IronOcr to focus on, along with the tolerance value. The tolerance value accepts a range of 0-255, which represents the allowable difference between pixel color and the selected color for each R, G, and B value in the color space.

:path=/static-assets/ocr/content-code-examples/how-to/image-color-correction-select-text-color.cs
using IronOcr;
using System;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Add image
using var imageInput = new OcrImageInput("sample.jpg");
// Text color to focus on
IronSoftware.Drawing.Color focusColor = new IronSoftware.Drawing.Color("#DB645C");

// Specify which text color to read
imageInput.SelectTextColor(focusColor, 60);

// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Output result to console
Console.WriteLine(ocrResult.Text);
Imports IronOcr
Imports System

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Add image
Private imageInput = New OcrImageInput("sample.jpg")
' Text color to focus on
Private focusColor As New IronSoftware.Drawing.Color("#DB645C")

' Specify which text color to read
imageInput.SelectTextColor(focusColor, 60)

' Perform OCR
Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Output result to console
Console.WriteLine(ocrResult.Text)
$vbLabelText   $csharpLabel

Below, you will find the OCR result, which is intended to read only the text in an orange-ish color.

OCR result

Searchable Pdfs

In addition to providing image filtering options, IronOcr enables developers to save modified PDFs either with or without these filters applied. The SaveAsSearchablePdf method includes a boolean flag as its second parameter, which allows users to specify whether to save the PDF with the filters activated or deactivated.

:path=/static-assets/ocr/content-code-examples/how-to/image-quality-correction-searchable-pdf.cs
using IronOcr;

var ocr = new IronTesseract();
var ocrInput = new OcrInput();

// Load a PDF file
ocrInput.LoadPdf("invoice.pdf");

// Apply gray scale filter
ocrInput.ToGrayScale();
OcrResult result = ocr.Read(ocrInput);

// Save the result as a searchable PDF with filters applied
result.SaveAsSearchablePdf("outputGrayscale.pdf", true);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Preguntas Frecuentes

¿Cómo puedo mejorar los colores de las imágenes para OCR en .NET C#?

Puede mejorar los colores de las imágenes para OCR en .NET C# utilizando IronOCR. Comience descargando la biblioteca IronOCR desde NuGet, importe la imagen y aplique técnicas de corrección de color como binarización, escala de grises e inversión para mejorar la legibilidad del texto.

¿Cuál es el papel de la binarización en la corrección de color de imágenes?

La binarización en la corrección de color de imágenes convierte una imagen en formato blanco y negro, lo que ayuda a separar el texto del fondo, reduciendo el ruido y haciendo el texto más distinguible para obtener mejores resultados de OCR usando IronOCR.

¿Cómo beneficia la aplicación de efectos de escala de grises a los procesos de OCR?

La aplicación de efectos de escala de grises reduce las distracciones de color convirtiendo la imagen en tonos de gris. Esta simplificación hace que la imagen esté menos desordenada y mejora la legibilidad del texto, lo que es beneficioso para los procesos de OCR con IronOCR.

¿Cuáles son las ventajas de invertir los colores de las imágenes para la extracción de texto?

Invertir los colores de las imágenes aumenta el contraste al alterar los esquemas de color, como cambiar el texto blanco sobre un fondo negro a texto negro sobre un fondo blanco. Esta mejora del contraste puede mejorar la precisión de la extracción de texto en OCR al usar IronOCR.

¿Cómo se pueden cambiar colores específicos en una imagen para obtener mejores resultados de OCR?

Para cambiar colores específicos en una imagen para obtener mejores resultados de OCR, utilice el método ReplaceColor en IronOCR. Especifique el color original, el nuevo color y ajuste el valor de tolerancia para afinar el reemplazo de color.

¿Es posible enfocarse en texto de un color específico durante OCR?

Sí, puede enfocarse en texto de un color específico durante OCR utilizando el método SelectTextColor en IronOCR. Esto le permite especificar el color del texto objetivo y un valor de tolerancia, mejorando la precisión de OCR para texto en color.

¿Cómo se exportan las imágenes modificadas después de la corrección de color?

Después de aplicar la corrección de color a las imágenes, puede exportarlas utilizando el método SaveAsImages en IronOCR. Esto le permite guardar las imágenes modificadas para su procesamiento o visualización posterior.

¿Por qué es importante ajustar el contraste de las imágenes para la precisión de OCR?

Ajustar el contraste de las imágenes es crucial para la precisión de OCR porque ayuda a distinguir el texto del fondo, haciendo que los caracteres sean más prominentes y fáciles de extraer para los algoritmos de OCR, especialmente cuando se usa IronOCR.

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
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 5,044,537 | Versión: 2025.11 recién lanzado