COMPARACIóN CON OTROS COMPONENTES

Comparación entre IronOCR y Dynamsoft OCR

Actualizado 13 de junio, 2022
Compartir:

El reconocimiento óptico de caracteres, o OCR (Optical Character Recognition), es un proceso de introducción de datos que implica el reconocimiento y la digitalización de texto, tanto escrito como impreso. Es un tipo de tecnología informática que emplea el análisis de imágenes para convertir fotografías digitales de texto impreso en letras y números que puedan ser utilizados por otros programas, como los procesadores de texto. El texto se convierte en códigos de caracteres para poder buscarlo y modificarlo en un ordenador.

Mientras que el pasado era un mundo en el que todos los documentos eran físicos, y el futuro puede ser una sociedad en la que todos los documentos sean digitales, el presente es cambiante. Los documentos físicos y digitales coexisten en este estado de transición, por lo que tecnologías como el OCR son fundamentales para la conversión de ida y vuelta.

La recuperación de documentos, la introducción de datos y la accesibilidad son sólo algunas de las aplicaciones del OCR. La mayoría de las aplicaciones de OCR proceden de documentos escaneados, aunque en ocasiones también se emplean fotografías. El OCR supone un valioso ahorro de tiempo, ya que a menudo la única opción es volver a mecanografiar el material. A continuación se ofrecen algunos ejemplos de cómo puede utilizarse el OCR:

  • Se pueden recuperar archivos de texto editables de documentos escaneados, incluidos faxes.
  • Los formularios se clasifican utilizando una aproximación de su contenido manuscrito.
  • Utilización del escaneado de libros para crear libros electrónicos editables y con capacidad de búsqueda.
  • Utilizar fotos de capturas de pantalla para buscar y cambiar texto.
  • La tecnología de texto a voz se utiliza para leer libros a personas con problemas de visión.

    Aunque éstas son sólo algunas de las aplicaciones del OCR, demuestran la versatilidad de la tecnología en una amplia gama de sectores. Casi todos los empleados de todas las empresas dependen sustancialmente de los documentos a diario, de ahí que el uso empresarial sea una consideración clave en el desarrollo de sistemas OCR.

    En este artículo, compararemos los dos lectores de OCR más potentes:

  • IronOCR
  • Dynamsoft OCR

    IronOCR y Dynamsoft OCR son dos bibliotecas OCR .NET que permiten la conversión de imágenes escaneadas y el procesamiento OCR de documentos PDF. Puede transformar imágenes en texto que permita búsquedas con sólo unas líneas de código. También puede recuperar palabras sueltas, letras y párrafos.

IronOCR: las características más destacadas

IronOCR ofrece la capacidad única de detectar, leer e interpretar texto de imágenes y documentos PDF que no se han escaneado con precisión. IronOCR ofrece el enfoque más sencillo para extraer texto de documentos y fotos, aunque no siempre sea el más rápido, porque afina y corrige automáticamente los escaneados de baja calidad, reduciendo la inclinación, la distorsión, el ruido de fondo y los problemas de perspectiva, al tiempo que mejora la resolución y el contraste.

IronOCR permite a los desarrolladores enviarle imágenes escaneadas de una o varias páginas, y devolverá todo el texto, los códigos de barras y la información QR. Un conjunto de clases de la biblioteca OCR añade capacidad de OCR a las aplicaciones basadas en web, de escritorio o de consola. Tesseract OCR C#, así como las aplicaciones de red JPG, PNG, TIFF, PDF, GIF y BMP, son sólo algunos de los formatos que pueden utilizarse como entrada.

Reconocimiento óptico de caracteres IronOCR (OCR) engine puede leer texto preparado utilizando muchos tipos de letra comunes, cursivas, pesos y subrayados. Las clases de recorte permiten al OCR trabajar con rapidez y precisión. Cuando se trabaja con documentos de varias páginas, el motor multihilo de IronOCR acelera el OCR.

Características de IronOCR

Para la gestión de Tesseract, utilizamos IronOCR porque es único en los siguientes aspectos:

  • Funciona directamente en .NET puro
  • No requiere que Tesseract esté instalado en su máquina
  • Funciona con los motores más recientes: Tesseract 5 ( así como Tesseract 4 y 3)
  • Está disponible para cualquier proyecto .NET: .NET Framework 4.5 +, .NET Standard 2 + y .NET Core 2, 3 & .NET 5
  • Mayor precisión y velocidad que el Tesseract tradicional
  • Compatible con Xamarin, Mono, Azure y Docker
  • Gestiona el complejo sistema de diccionarios Tesseract mediante paquetes NuGet
  • Admite PDFS, Tiffs MultiFrame y los principales formatos de imagen sin necesidad de configuración.
  • Puede corregir escaneos de baja calidad y sesgados para obtener los mejores resultados de Tesseract.

Dynamsoft OCR - características

La biblioteca Dynamsoft.NET OCR es un componente .NET que proporciona un reconocimiento óptico de caracteres rápido y fiable. Se utiliza para crear aplicaciones de escritorio .NET en C# o VB.NET. Basta con crear un código para convertir el texto inútil de un PDF o unas fotos en texto digital para editarlo, buscarlo, archivarlo, etc., utilizando las API básicas de OCR.

Las imágenes de escáneres y otros dispositivos compatibles con TWAIN pueden adquirirse de las siguientes formas:

  • Se admiten mecanismos nativos, de memoria intermedia y de transferencia de imágenes de archivos de disco.
  • Con el alimentador automático de documentos, es posible escanear por lotes (ADF).
  • Los atributos TWAIN pueden utilizarse para modificar funcionalidades comunes de los dispositivos.
  • IfAutoFeed, IfAutoScan, Resolución, Profundidad de bits, Brillo, Contraste, Unidad, Dúplex y otras características se pueden cambiar.
  • Admite la detección de páginas en blanco.
  • Permite cambiar y guardar perfiles de escáner.

    Captura imágenes de cámaras web compatibles con UVC y WIA:

  • Muestra un vídeo en directo mientras capturas fotos desde la webcam elegida.
  • ustomiza los ajustes de la cámara: Brillo, Contraste, Tono, Saturación, Nitidez, Gamma, Balance de blancos, Compensación de contraluz, Ganancia, Activar color, Zoom, Enfoque, Exposición, Iris, Pan, Tilt, Roll.

    Carga y visualización sólidas de imágenes

  • Se pueden cargar imágenes en formato BMP, JPEG, PNG, TIFF y TIFF multipágina.
  • Es posible acercar y alejar las fotos.
  • Las imágenes pueden recuperarse de una unidad local, un servidor FTP, un servidor HTTP o una base de datos.
  • Descodificación de imágenes para BMP, JPEG, PNG y TIFF mediante uno de los conjuntos más completos de componentes de imágenes .NET.

    Guardar y cargar/descargar

  • Permite leer y escribir fotos en un flujo de archivos.
  • Permite guardar las fotos capturadas como BMP, JPEG, PNG, TIFF o TIFF multipágina en una unidad local, un servidor web o una base de datos.
  • Soporta compresión RLE, G3/G4, LZW, PackBits y TIFF.
  • Se admiten cargas y descargas HTTPS.
  • Uno de los conjuntos más amplios de componentes de imágenes.NET disponibles admite la codificación de imágenes BMP, JPEG, PNG y TIFF.
  • Permite adjuntar fotos recién obtenidas a archivos TIFF existentes.

Leer texto de PDF escaneados u otras imágenes en ASP.NET (Reconocimiento óptico de caracteres)

En el acelerado mundo actual, los clientes quieren que el trabajo se realice con rapidez. Los clientes con proyectos urgentes nos contactan con frecuencia. Nuestra tecnología puede simplemente reconocer el contenido de una imagen y convertirlo en texto si el proyecto implica escanear documentos que contengan imágenes. Reconocimiento óptico de caracteres (OCR) ahorra tiempo y dinero a su empresa, al tiempo que reduce los errores de introducción de datos.

Uso de IronOCR

IronOCR utiliza la clase IronOcr.IronTesseract para realizar sus conversiones OCR.

En este ejemplo básico utilizamos la clase IronOcr.IronTesseract para leer texto de una imagen y devolver automáticamente su resultado como una cadena.

//  PM> Install-Package IronOcr
using IronOcr;
var Result = new IronTesseract().Read(@"img\Screenshot.png");
Console.WriteLine(Result.Text);
//  PM> Install-Package IronOcr
using IronOcr;
var Result = new IronTesseract().Read(@"img\Screenshot.png");
Console.WriteLine(Result.Text);
'  PM> Install-Package IronOcr
Imports IronOcr
Private Result = (New IronTesseract()).Read("img\Screenshot.png")
Console.WriteLine(Result.Text)
VB   C#

En consecuencia, el siguiente párrafo es 100% exacto:


Ejemplo sencillo de IronOCR

En este sencillo ejemplo probaremos la precisión de nuestra librería C# OCR para leer texto de un PNG

Imagen. Esta es una prueba muy básica, pero las cosas se irán complicando a medida que avance el tutorial.

El rápido zorro marrón salta sobre el perro perezoso

Aunque pueda parecer sencillo a primera vista, detrás de la superficie se esconde un comportamiento sofisticado: escanear la imagen para comprobar su alineación, calidad y resolución, examinar sus atributos, optimizar el motor de OCR y, por último, leer el texto como lo haría un ser humano.

El OCR es una tarea difícil para una máquina, y la velocidad de lectura puede ser comparable a la de un ser humano. Dicho de otro modo, el OCR no es un procedimiento rápido. En este caso, sin embargo, es absolutamente correcto.

Precisión de los resultados de la aplicación OCR en C#

En la mayoría de los escenarios del mundo real, los desarrolladores querrán que sus proyectos se ejecuten lo más rápidamente posible. En este caso, le proponemos que utilice las clases OcrInput e IronTesseract del espacio de nombres IronOCR add ons.

Puede establecer las características exactas de un trabajo de OCR con OcrInput, tales como:

  • JPEG, TIFF, GIF, BMP y PNG son sólo algunos de los formatos de imagen que pueden utilizarse.
  • Importar documentos PDF en su totalidad o por partes
  • Mejorar el contraste, la resolución y el tamaño de la imagen
  • Corrección de rotación, ruido de escaneado, ruido digital, inclinación e imagen negativa

    IronTesseract

    Elija entre cientos de idiomas y dialectos preconfigurados

  • Utilice los motores de OCR Tesseract 5, 4 ó 3 de inmediato
  • Si estamos viendo una captura de pantalla, un fragmento o el documento completo, especifica el tipo de documento
  • Reconocer códigos de barras
  • PDF archivables, Hocr HTML, un DOM y Strings son opciones para los resultados del OCR
using IronOcr;
var Ocr = new IronTesseract();
using (var Input = new OcrInput(@"img\Potter.tiff")) {
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
}
using IronOcr;
var Ocr = new IronTesseract();
using (var Input = new OcrInput(@"img\Potter.tiff")) {
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
}
Imports IronOcr
Private Ocr = New IronTesseract()
Using Input = New OcrInput("img\Potter.tiff")
Dim Result = Ocr.Read(Input)
Console.WriteLine(Result.Text)
End Using
VB   C#

Podemos utilizarlo incluso en un escaneado de calidad media con una precisión del 100%.

C# OCR Scan From Tiff Ejemplo

Como puede ver, la lectura de textos (y, si se desea, códigos de barras) a partir de una imagen escaneada como un TIFF era bastante fácil. La precisión de este trabajo de OCR es del 100%.

A continuación, probaremos con un escaneado de calidad muy inferior de la misma página, a un DPI bajo y con mucha distorsión y ruido digital, así como daños en el papel original.

C# OCR Escaneado de baja resolución con ruido digital

Aquí es donde IronOCR realmente brilla en comparación con otras bibliotecas de OCR como Tesseract, y encontraremos que otros proyectos de OCR evitan discutir el uso de OCR en imágenes escaneadas del mundo real en lugar de casos de prueba irrealmente "perfectos" creados digitalmente con el fin de lograr el 100% de precisión de OCR.

using IronOcr;
var Ocr = new IronTesseract();
using (var Input = new OcrInput(@"img\Potter.LowQuality.tiff"))
{
Input.Deskew(); //  elimina la rotación y la perspectiva
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
}
using IronOcr;
var Ocr = new IronTesseract();
using (var Input = new OcrInput(@"img\Potter.LowQuality.tiff"))
{
Input.Deskew(); //  elimina la rotación y la perspectiva
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
}
Imports IronOcr
Private Ocr = New IronTesseract()
Using Input = New OcrInput("img\Potter.LowQuality.tiff")
Input.Deskew() '  elimina la rotación y la perspectiva
Dim Result = Ocr.Read(Input)
Console.WriteLine(Result.Text)
End Using
VB   C#

Sin añadir Input.Deskew() para enderezar la imagen obtenemos una precisión del 52,5%. Esto no es suficiente.

Añadir Input.Deskew() nos lleva al 99,8% de precisión, que es casi tan preciso como el OCR de un escáner de alta calidad.

Uso de Dynamsoft OCR

Presentaremos algunos fragmentos de código para utilizar Dynamic Web TWAIN para realizar escaneado TWAIN y OCR del lado del cliente en JavaScript.

Imágenes escaneadas

Puede cambiar la configuración de escaneado y adquirir fotos de escáneres TWAIN utilizando las sencillas API de Dynamic Web TWAIN.

function acquireImage()
{
DWObject.SelectSourceByIndex(document.getElementById("source").selectedIndex); //seleccionar un escáner TWAIN disponible

    //configurar los ajustes de escaneado, como el tipo de píxel, la resolución, el ADF, etc.
    DWObject.IfShowUI = false; //no muestran la interfaz de usuario del escáner
    DWObject.PixelType = 1; //escanear en gris
    DWObject.Resolution = 300;
    DWObject.IfFeederEnabled = true; //escanear desde el alimentador automático
    DWObject.IfDuplexEnabled = false;
    DWObject.IfDisableSourceAfterAcquire = true;

    //adquirir imágenes de escáneres
    DWObject.AcquireImage();
}
function acquireImage()
{
DWObject.SelectSourceByIndex(document.getElementById("source").selectedIndex); //seleccionar un escáner TWAIN disponible

    //configurar los ajustes de escaneado, como el tipo de píxel, la resolución, el ADF, etc.
    DWObject.IfShowUI = false; //no muestran la interfaz de usuario del escáner
    DWObject.PixelType = 1; //escanear en gris
    DWObject.Resolution = 300;
    DWObject.IfFeederEnabled = true; //escanear desde el alimentador automático
    DWObject.IfDuplexEnabled = false;
    DWObject.IfDisableSourceAfterAcquire = true;

    //adquirir imágenes de escáneres
    DWObject.AcquireImage();
}
Private Function acquireImage() As [function]
DWObject.SelectSourceByIndex(document.getElementById("source").selectedIndex) 'seleccionar un escáner TWAIN disponible

	'configurar los ajustes de escaneado, como el tipo de píxel, la resolución, el ADF, etc.
	DWObject.IfShowUI = False 'no muestran la interfaz de usuario del escáner
	DWObject.PixelType = 1 'escanear en gris
	DWObject.Resolution = 300
	DWObject.IfFeederEnabled = True 'escanear desde el alimentador automático
	DWObject.IfDuplexEnabled = False
	DWObject.IfDisableSourceAfterAcquire = True

	'adquirir imágenes de escáneres
	DWObject.AcquireImage()
End Function
VB   C#

Descargar el módulo profesional OCR

Para utilizar el módulo OCR Professional para el OCR del lado del cliente, deberá incluir ocrpro.js en la cabecera y descargar también la DLL OCR Pro.

<script type="text/javascript" src="Resources/addon/dynamsoft.webtwain.addon.ocrpro.js"> </script>

Make edits to the .js file:

var CurrentPathName = unescape(location.pathname);
CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
DWObject.Addon.OCRPro.Download(CurrentPath + "Resources/addon/OCRPro.zip", OnSuccess, OnFailure);
JAVASCRIPT

Recognize text using OCR

Using the JS OCR recognition API to extract text from scanned images is as simple as inserting the code below.

DWObject.Addon.OCRPro.Recognize(0, GetOCRProInfo, GetErrorInfo); // 0 is the index of the image
DWObject.Addon.OCRPro.Recognize(0, GetOCRProInfo, GetErrorInfo); // 0 is the index of the image
DWObject.Addon.OCRPro.Recognize(0, GetOCRProInfo, GetErrorInfo) ' 0 is the index of the image
VB   C#

Reading Cropped Regions of Images

Both sets of software offer solutions for cropping images for OCR.

Reading cropped regions with IronOCR

Iron's branch of Tesseract OCR is adept at reading specific regions of images, as shown in the following code sample.

We can make use of System.Drawing.Rectangle that is used to describe the exact region of an image to be read in pixels.

When dealing with a standardized form that is filled out, and only a portion of the content changes from case to case, this can be really handy.

Scanning a Section of a Page: We can make use of System.Drawing.Rectangle to designate a region in which we shall read a document. Pixels are always the unit of measurement.

We shall find that this improves speed while also avoiding reading needless text. In this example, we will read a student's name from a central region of a standardized paper.

C# OCR Scan From Tiff Example
C# OCR Scan From Tiff Example
using IronOcr;
var Ocr = new IronTesseract();
using (var Input = new OcrInput())
{
// a 41% improvement on speed
var ContentArea = new System.Drawing.Rectangle() { X = 215, Y = 1250, Height = 280, Width = 1335 };
Input.AddImage("img/ComSci.png", ContentArea);
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
}
using IronOcr;
var Ocr = new IronTesseract();
using (var Input = new OcrInput())
{
// a 41% improvement on speed
var ContentArea = new System.Drawing.Rectangle() { X = 215, Y = 1250, Height = 280, Width = 1335 };
Input.AddImage("img/ComSci.png", ContentArea);
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
}
Imports IronOcr
Private Ocr = New IronTesseract()
Using Input = New OcrInput()
' a 41% improvement on speed
Dim ContentArea = New System.Drawing.Rectangle() With {
	.X = 215,
	.Y = 1250,
	.Height = 280,
	.Width = 1335
}
Input.AddImage("img/ComSci.png", ContentArea)
Dim Result = Ocr.Read(Input)
Console.WriteLine(Result.Text)
End Using
VB   C#

This results in a 41 percent boost in speed, while also allowing us to be more specific. This is extremely valuable for .NET OCR applications involving documents that are comparable and consistent, including invoices, receipts, checks, forms, expense claims, and so on.

When reading PDFs, ContentAreas (OCR cropping) is also supported.

Reading cropped regions with Dynamsoft OCR

To begin, launch Visual Studio and build a new C# Windows Forms Application, or open an existing one.

We will need to include DynamicDotNetTWAIN.dll, DynamicOCR.dll, and the appropriate language package. To do so, navigate to Tools -> Choose Toolbox Items, then to the.NET Framework Components tab, click the Browse... button, and locate DynamicDotNetTWAIN.dll in "..Program Files (x86)DynamsoftDynamic.NET TWAIN 4.3 TrialBinv4.0" or v2.0 (depends on the .NET Framework version you are using). Click the OK button. The DynamicDotNetTwain component will then appear in the Toolbox dialog (under the View menu), as illustrated in the accompanying image.

Add Dynamic .NET TWAIN .NET Component

Right-click the project file in Solution Explorer and select Add-> Existing Item... Then, in the file type filter's drop-down list, select All Files. Navigate to  “..\Program Files (x86)\Dynamsoft\Dynamic .NET TWAIN 4.3 Trial\Bin\OCRResources” to add items to the project folder. The .NET TWAIN component can then be dragged and dropped onto the form.

This is the code for clicking the LoadImage button:

private void button1_Click(object sender, EventArgs e) { OpenFileDialog filedlg = new OpenFileDialog(); if (filedlg.ShowDialog() == DialogResult.OK) { dynamicDotNetTwain1.LoadImage(filedlg.FileName);
// choose an image from your local disk and load it into Dynamic .NET TWAIN
} }

We can now attempt to OCR the loaded image and turn it into a searchable text file.

private void dynamicDotNetTwain1_OnImageAreaSelected(short sImageIndex, int left, int top, int right, int bottom) { dynamicDotNetTwain1.OCRTessDataPath = "../../"; // the path of the language package (tessdata)
dynamicDotNetTwain1.OCRLanguage = "eng";
// the language type
dynamicDotNetTwain1.OCRDllPath = "../../";
//the relative path of the OCR DLL file
dynamicDotNetTwain1.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.Text; byte [] sbytes = dynamicDotNetTwain1.OCR(dynamicDotNetTwain1.CurrentImageIndexInBuffer, left, top, right, bottom);
// OCR the selected area of the image
if (sbytes != null) { SaveFileDialog filedlg = new SaveFileDialog(); filedlg.Filter = "Text File(*.txt) *.txt"; if (filedlg.ShowDialog() == DialogResult.OK) { FileStream fs = File.OpenWrite(filedlg.FileName); fs.Write(sbytes, 0, sbytes.Length);
//save the OCR result as a text file
fs.Close(); } MessageBox.Show("OCR successful"); } else { MessageBox.Show(dynamicDotNetTwain1.ErrorString); } }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog filedlg = new OpenFileDialog(); if (filedlg.ShowDialog() == DialogResult.OK) { dynamicDotNetTwain1.LoadImage(filedlg.FileName);
// choose an image from your local disk and load it into Dynamic .NET TWAIN
} }

We can now attempt to OCR the loaded image and turn it into a searchable text file.

private void dynamicDotNetTwain1_OnImageAreaSelected(short sImageIndex, int left, int top, int right, int bottom) { dynamicDotNetTwain1.OCRTessDataPath = "../../"; // the path of the language package (tessdata)
dynamicDotNetTwain1.OCRLanguage = "eng";
// the language type
dynamicDotNetTwain1.OCRDllPath = "../../";
//the relative path of the OCR DLL file
dynamicDotNetTwain1.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.Text; byte [] sbytes = dynamicDotNetTwain1.OCR(dynamicDotNetTwain1.CurrentImageIndexInBuffer, left, top, right, bottom);
// OCR the selected area of the image
if (sbytes != null) { SaveFileDialog filedlg = new SaveFileDialog(); filedlg.Filter = "Text File(*.txt) *.txt"; if (filedlg.ShowDialog() == DialogResult.OK) { FileStream fs = File.OpenWrite(filedlg.FileName); fs.Write(sbytes, 0, sbytes.Length);
//save the OCR result as a text file
fs.Close(); } MessageBox.Show("OCR successful"); } else { MessageBox.Show(dynamicDotNetTwain1.ErrorString); } }
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
	Dim filedlg As New OpenFileDialog()
	If filedlg.ShowDialog() = DialogResult.OK Then
		dynamicDotNetTwain1.LoadImage(filedlg.FileName)
' choose an image from your local disk and load it into Dynamic .NET TWAIN
	End If
End Sub

We can now attempt [to] OCR the loaded image [and] turn it into a searchable text file.private Sub dynamicDotNetTwain1_OnImageAreaSelected(ByVal sImageIndex As Short, ByVal left As Integer, ByVal top As Integer, ByVal right As Integer, ByVal bottom As Integer)
	dynamicDotNetTwain1.OCRTessDataPath = "../../" ' the path of the language package (tessdata)
dynamicDotNetTwain1.OCRLanguage = "eng"
' the language type
dynamicDotNetTwain1.OCRDllPath = "../../"
'the relative path of the OCR DLL file
dynamicDotNetTwain1.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.Text
Dim sbytes() As Byte = dynamicDotNetTwain1.OCR(dynamicDotNetTwain1.CurrentImageIndexInBuffer, left, top, right, bottom)
' OCR the selected area of the image
If sbytes IsNot Nothing Then
	Dim filedlg As New SaveFileDialog()
	filedlg.Filter = "Text File(*.txt) *.txt"
	If filedlg.ShowDialog() = DialogResult.OK Then
		Dim fs As FileStream = File.OpenWrite(filedlg.FileName)
		fs.Write(sbytes, 0, sbytes.Length)
'save the OCR result as a text file
fs.Close()
	End If
	MessageBox.Show("OCR successful")
Else
	MessageBox.Show(dynamicDotNetTwain1.ErrorString)
End If
End Sub
VB   C#

This is how the application looks.

Demo App of Zone OCR using Dynamic .NET TWAIN OCR SDK

Image Performance Tuning

The quality of the input image is the most crucial determinant in the speed of an OCR task. The lower the background noise and the higher the dpi, with a great goal value of around 200 dpi, the faster and more accurate the OCR output.

Image Processing Techniques for Dynamsoft OCR

We need to use OCR in a variety of situations, such as scanning a credit card number with our phone or extracting text from paper documents. OCR capabilities are included in Dynamsoft Label Recognition (DLR) and Dynamic Web TWAIN (DWT).

Although they can do an excellent job in general, we can improve the results by using various image processing techniques.

Lighten/remove shadows

Poor illumination may have an impact on the OCR result. To improve the outcome, we can whiten photos or eliminate shadows from images.

Invert

Because the OCR engine is often trained on text in dark colors, text in light colors can be harder to discover and recognize.

Light text

It will be easier to recognize if we invert its color

Light text inverted

To perform the inversion, we can use the GrayscaleTransformationModes parameter in DLR.

Here are the JSON settings:

"GrayscaleTransformationModes": [
    {
        "Mode": "DLR_GTM_INVERTED"
    }
]
"GrayscaleTransformationModes": [
    {
        "Mode": "DLR_GTM_INVERTED"
    }
]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"GrayscaleTransformationModes": [{ "Mode": "DLR_GTM_INVERTED" }]
VB   C#

DLR .net’s reading result:

Light text result

Rescale

If the letter height is too low, the OCR engine may not produce a good result. In general, the image should have a DPI of at least 300.

There is a ScaleUpModes parameter in DLR 1.1 that allows you to scale up letters. We may, of course, scale the image ourselves.

Reading the image directly yields the incorrect result:

1x image

After scaling up the image x2, the result is correct:

2x image

Deskew

It is fine if the text is a little distorted. However, if it is overly skewed, the outcome will be adversely altered. To improve the outcome, we need to crop the image.

To accomplish this, we can use the Hough Line Transform in OpenCV.

Skewed image

Here is the code to deskew the image above.

#coding=utf-8
import numpy as np
import cv2
import math
from PIL import Image

def deskew():
src = cv2.imread("neg.jpg",cv2.IMREAD_COLOR)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
kernel = np.ones((5,5),np.uint8)
erode_Img = cv2.erode(gray,kernel)
eroDil = cv2.dilate(erode_Img,kernel) # erode and dilate
showAndWaitKey("eroDil",eroDil)

    canny = cv2.Canny(eroDil,50,150) # edge detection
    showAndWaitKey("canny",canny)

    lines = cv2.HoughLinesP(canny, 0.8, np.pi / 180, 90,minLineLength=100,maxLineGap=10) # Hough Lines Transform
    drawing = np.zeros(src.shape [:], dtype=np.uint8)

    maxY=0
    degree_of_bottomline=0
    index=0
    for line in lines:        
        x1, y1, x2, y2 = line [0]            
        cv2.line(drawing, (x1, y1), (x2, y2), (0, 255, 0), 1, lineType=cv2.LINE_AA)
        k = float(y1-y2)/(x1-x2)
        degree = np.degrees(math.atan(k))
        if index==0:
            maxY=y1
            degree_of_bottomline=degree # take the degree of the line at the bottom
        else:        
            if y1>maxY:
                maxY=y1
                degree_of_bottomline=degree
        index=index+1
    showAndWaitKey("houghP",drawing)

    img=Image.fromarray(src)
    rotateImg = img.rotate(degree_of_bottomline)
    rotateImg_cv = np.array(rotateImg) 
    cv2.imshow("rotateImg",rotateImg_cv)
    cv2.imwrite("deskewed.jpg",rotateImg_cv)
    cv2.waitKey()

def showAndWaitKey(winName,img):
cv2.imshow(winName,img)
cv2.waitKey()

if __name__ == "__main__":              
deskew()
#coding=utf-8
import numpy as np
import cv2
import math
from PIL import Image

def deskew():
src = cv2.imread("neg.jpg",cv2.IMREAD_COLOR)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
kernel = np.ones((5,5),np.uint8)
erode_Img = cv2.erode(gray,kernel)
eroDil = cv2.dilate(erode_Img,kernel) # erode and dilate
showAndWaitKey("eroDil",eroDil)

    canny = cv2.Canny(eroDil,50,150) # edge detection
    showAndWaitKey("canny",canny)

    lines = cv2.HoughLinesP(canny, 0.8, np.pi / 180, 90,minLineLength=100,maxLineGap=10) # Hough Lines Transform
    drawing = np.zeros(src.shape [:], dtype=np.uint8)

    maxY=0
    degree_of_bottomline=0
    index=0
    for line in lines:        
        x1, y1, x2, y2 = line [0]            
        cv2.line(drawing, (x1, y1), (x2, y2), (0, 255, 0), 1, lineType=cv2.LINE_AA)
        k = float(y1-y2)/(x1-x2)
        degree = np.degrees(math.atan(k))
        if index==0:
            maxY=y1
            degree_of_bottomline=degree # take the degree of the line at the bottom
        else:        
            if y1>maxY:
                maxY=y1
                degree_of_bottomline=degree
        index=index+1
    showAndWaitKey("houghP",drawing)

    img=Image.fromarray(src)
    rotateImg = img.rotate(degree_of_bottomline)
    rotateImg_cv = np.array(rotateImg) 
    cv2.imshow("rotateImg",rotateImg_cv)
    cv2.imwrite("deskewed.jpg",rotateImg_cv)
    cv2.waitKey()

def showAndWaitKey(winName,img):
cv2.imshow(winName,img)
cv2.waitKey()

if __name__ == "__main__":              
deskew()
#coding=utf-8
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import TryCast(numpy, np) import cv2 import math from PIL import Image def deskew(): src = cv2.imread("neg.jpg",cv2.IMREAD_COLOR) gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) kernel = np.ones((5,5),np.uint8) erode_Img = cv2.erode(gray,kernel) eroDil = cv2.dilate(erode_Img,kernel) # erode @and dilate showAndWaitKey("eroDil",eroDil) canny = cv2.Canny(eroDil,50,150) # edge detection showAndWaitKey("canny",canny) lines = cv2.HoughLinesP(canny, 0.8, np.pi / 180, 90,minLineLength=100,maxLineGap=10) # Hough Lines Transform drawing = np.zeros(src.shape [:], dtype=np.uint8) maxY=0 degree_of_bottomline=0 index=0 for line in lines: x1, y1, x2, y2 = line [0] cv2.line(drawing, (x1, y1), (x2, y2), (0, 255, 0), 1, lineType=cv2.LINE_AA) k = float(y1-y2)/(x1-x2) degree = np.degrees(math.atan(k)) if index==0: maxY=y1 degree_of_bottomline=degree # take the degree @of the line at the bottom else: if y1> maxY: maxY=y1 degree_of_bottomline=degree index=index+1 showAndWaitKey("houghP",drawing) img=Image.fromarray(src) rotateImg = img.rotate(degree_of_bottomline) rotateImg_cv = np.array(rotateImg) cv2.imshow("rotateImg",rotateImg_cv) cv2.imwrite("deskewed.jpg",rotateImg_cv) cv2.waitKey() def showAndWaitKey(winName,img): cv2.imshow(winName,img) cv2.waitKey() if __name__ == "__main__": deskew()
VB   C#

Lines detected:

Lines detected

Deskewed:

Deskewed image

Image Processing Techniques for IronOCR

The quality of the input image is not important here because IronOCR excels at repairing defective documents (though this is time-consuming and will cause your OCR jobs to use more CPU cycles).

Choosing input image formats with less digital noise, such as TIFF or PNG, can also result in speedier outcomes than lossy image formats, such as JPEG.

The image filters listed below can significantly enhance performance:

OcrInput.Rotate (double degrees) — Rotates images clockwise by a specified number of degrees. Negative integers are used for anti-clockwise rotation.

OcrInput.Binarize() — This image filter makes every pixel either black or white, with no in-between. It may improve OCR performance in circumstances where the text-to-background contrast is very low.

OcrInput.ToGrayScale() — This image filter converts every pixel to a grayscale shade. It is unlikely to improve OCR accuracy, but it may increase speed.

OcrInput.Contrast() — Automatically increases contrast. In low-contrast scans, this filter frequently improves OCR speed and accuracy.

OcrInput.DeNoise() — This filter should be used only when noise is expected.

OcrInput.Invert() — Reverses all colors. For example, white becomes black: black becomes white.

OcrInput.Dilate() — Advanced morphology. Dilation is the process of adding pixels to the edges of objects in an image. (Erode's inverse)

OcrInput. Erode() — an advanced morphology function. Erosion is the process of removing pixels from the edges of objects. (Dilate's inverse)

OcrInput. Deskew() — Rotates an image so that it is orthogonal and the right way up. Because Tesseract tolerance for skewed scans can be as low as 5 degrees, this is quite useful for OCR.

DeepCleanBackgroundNoise() — Removes a lot of background noise. Only use this filter if you know there is a lot of background noise in the document because it can reduce OCR accuracy on clear documents and is quite CPU intensive.

OcrInput.EnhanceResolution — Improves the resolution of low-resolution photos. Because of OcrInput, this filter is rarely used. OcrInput and will detect and resolve low resolution automatically.

We may want to use Iron Tesseract to speed up OCR on higher-quality scans.

If we're looking for speed, we might start here and subsequently turn features back on until the proper balance is struck.

using IronOcr;
var Ocr = new IronTesseract();
// Configure for speed
Ocr.Configuration.BlackListCharacters = "~`$#^*_}{][\\";
Ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto;
Ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
Ocr.Configuration.EngineMode = TesseractEngineMode.LstmOnly;
Ocr.Language = OcrLanguage.EnglishFast;
using (var Input = new OcrInput(@"img\Potter.tiff"))
{
    var Result = Ocr.Read(Input);
    Console.WriteLine(Result.Text);
}
using IronOcr;
var Ocr = new IronTesseract();
// Configure for speed
Ocr.Configuration.BlackListCharacters = "~`$#^*_}{][\\";
Ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto;
Ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
Ocr.Configuration.EngineMode = TesseractEngineMode.LstmOnly;
Ocr.Language = OcrLanguage.EnglishFast;
using (var Input = new OcrInput(@"img\Potter.tiff"))
{
    var Result = Ocr.Read(Input);
    Console.WriteLine(Result.Text);
}
Imports IronOcr
Private Ocr = New IronTesseract()
' Configure for speed
Ocr.Configuration.BlackListCharacters = "~`$#^*_}{][\"
Ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto
Ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5
Ocr.Configuration.EngineMode = TesseractEngineMode.LstmOnly
Ocr.Language = OcrLanguage.EnglishFast
Using Input = New OcrInput("img\Potter.tiff")
	Dim Result = Ocr.Read(Input)
	Console.WriteLine(Result.Text)
End Using
VB   C#

This result is 99.8% accurate compared to the baseline of 100% — but 35% faster.

Licensing and Pricing

Dynamsoft Licensing and Pricing

Per year license. All rates include one year of maintenance, which includes free software upgrades and premium support.

Dynamsoft offers two types of licenses:

Per client device license

The "One Client Device License" provides access to a same-origin Application (same protocol, same host, and same port) to use the software's features from a single client device. An inactive client device is one that has not accessed any software capability for 90 days in a row. An inactive client device's license seat will be instantly freed and made available for usage by any other active client device. When you reach the maximum number of license seats allowed, Dynamsoft will give you an extra 10% of your client device allowance for emergency use. Once the additional client device allowance has been depleted, no new client devices can access and use the software until there are available license seats again. Please keep in mind that exceeding your client device allowance has no effect on any client devices that have already been licensed.

Per-server license

To deploy the application to a single server, a "One Server License" is required. Servers refer to both physical and virtual servers and include, but are not limited to, production servers, failover servers, development servers that are also used for testing, quality assurance servers, testing servers, and staging servers, all of which require a license. Additional licenses are not required for continuous integration servers (build servers) or localhost development servers. The per-server license is only valid for on-premises server installations, and not for cloud deployments.

Pricing for Dynamsoft OCR starts at USD 1,249/year.

IronOCR Licensing and Pricing

As developers, we all want to accomplish our projects with the least amount of money and resources possible — budgeting is critical. Examine the chart to determine which license is best suited to your requirements and budget.

IronOCR provides licenses with a customizable number of developers, projects, and locations, allowing you to fulfill the needs of your project while only paying for the coverage you require.

IronOCR licensing keys enable you to publish your product without a watermark.

Licenses start from $599 and include one year of support and upgrades.

You can also use a trial license key to try IronOCR for free.

Conclusion

Tesseract OCR on Mac, Windows, Linux, Azure OCR, and Docker are all available with IronOCR for C#. .NET Framework 4.0 or above is required,  .NET Standard 2.0+, .NET Core 2.0+, .NET 5, Mono for macOS and Linux, and Xamarin for macOS are all examples of cross-platform development. IronOCR also uses the latest Tesseract 5 engine to read text, barcodes, and QR codes from all major image and PDF formats. In minutes, this library adds OCR functionality to your desktop, console, or web apps! The OCR can also read PDFs and multi-page TIFFs, and it can be saved as a searchable PDF document or XHTML in any OCR Scan. Plain text, barcode data, and an OCR result class encompassing paragraphs, lines, words, and characters are among its data output choices. It is available in 125 languages, including Arabic, Chinese, English, Finnish, French, German, Hebrew, Italian, Japanese, Korean, Portuguese, Russian, and Spanish, but keep in mind that bespoke language packs can also be generated.

The Dynamic .NET TWAIN OCR add-on is a quick and reliable .NET component for Optical Character Recognition that you can use in WinForms and WPF applications written in C# or VB .NET. You can scan documents or capture photos from webcams using Dynamic .NET TWAIN's image capture module, and then conduct OCR on the images to convert the text in the images to text, searchable PDF files, or strings. Multiple Asian languages, as well as Arabic, are offered in addition to English.

IronOCR offers better licensing than Dynamsoft OCR; IronOcr starts at $599 with one year free, while Dynamsoft starts at $1249 with a free trial. IronOCR also offers licenses for multiple users, while with Dynamsoft, you only get one license per user.

While both sets of software aim at offering the best performance in terms of OCR readings of barcodes, image to text, and image to text, IronOCR stands out in that it shines its light even on images that are in pretty bad shape. It automatically puts in place its sophisticated tuning methods to give you the best OCR results. IronOCR also makes use of Tesseract to give you optimal results with little or no errors.

Iron Software is also offering its customers and users the option to grab its entire suite of software in just two clicks. This means that for the price of two of the components in the Iron Software suite, you can currently get all five components and uninterrupted support.

< ANTERIOR
Comparación entre IronOCR y Tesseract.NET
SIGUIENTE >
Comparación entre IronOCR y Abbyy Finereader

¿Listo para empezar? Versión: 2024.7 recién publicada

Descarga gratuita de NuGet Descargas totales: 2,012,139 Ver licencias >
123