Reconocer texto en una imagen mediante una aplicación .NET para Linux

Categoría del blog: ImgingOCR.NETLinux

23.12.2022

Este artículo explica cómo crear una aplicación .NET de consola y reconocer texto de imágenes en Ubuntu. Para el reconocimiento de texto de imágenes se utilizan el SDK .NET de VintaSoft Imaging y Plug-ins (PDF, OCR, Document Cleanup).

Pasos para completar esta tarea:
  1. Abrir el escritorio de Ubuntu.

  2. Cree una carpeta que almacenará los archivos de la aplicación .NET. Cree la carpeta "Recognize_Text_In_Image" en el escritorio del usuario y acceda a ella.


  3. Abrir la terminal de comandos. Esto se puede hacer seleccionando "Abrir en la terminal" en el menú contextual o presionando la combinación de teclas Ctrl+Alt+T.


  4. Llame al comando en la terminal, que crea un proyecto de una nueva aplicación .NET de consola:
    dotnet new console --framework net6.0
    



    El proyecto creado contiene los archivos "Recognize_Text_In_Image.csproj" y "Program.cs", que contienen el código C# de la aplicación. Cierre la terminal.

  5. Abra el archivo de proyecto "Recognize_Text_In_Image.csproj" en el editor de texto y cambie el texto del archivo al siguiente:
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <RootNamespace>ConsoleApp1</RootNamespace>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="SkiaSharp" Version="2.88.0" />
        <PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.88.0" />
        <PackageReference Include="Vintasoft.Imaging" Version="12.1.5.1" />
        <PackageReference Include="Vintasoft.Imaging.Drawing.SkiaSharp" Version="12.1.5.1" />
        <PackageReference Include="Vintasoft.Imaging.DocCleanup" Version="7.1.5.1" />
        <PackageReference Include="Vintasoft.Imaging.Ocr" Version="7.1.5.1" />
        <PackageReference Include="Vintasoft.Imaging.Ocr.Tesseract" Version="7.1.5.1" />
        <PackageReference Include="Vintasoft.Imaging.Pdf" Version="9.1.5.1" />
        <PackageReference Include="Vintasoft.Imaging.Pdf.Ocr" Version="9.1.5.1" />
        <PackageReference Include="Vintasoft.Shared" Version="3.3.1.1" />
      </ItemGroup>
    
      <ItemGroup>
        <Content Include="OCR.tif">
          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
        </Content>
      </ItemGroup>
    
    </Project>
    



    El proyecto modificado hace referencia a nuget-packages para VintaSoft Imaging .NET SDK (Vintasoft.Shared.dll, Vintasoft.Imaging.dll, Vintasoft.Imaging.Drawing.SkiaSharp.dll), el complemento VintaSoft Document Cleanup .NET (Vintasoft.Imaging.DocCleanup.dll), el complemento VintaSoft OCR .NET (Vintasoft.Imaging.Ocr.dll, Vintasoft.Imaging.Ocr.Tesseract.dll) y el complemento VintaSoft PDF .NET (Vintasoft.Imaging.Pdf, Vintasoft.Imaging.Pdf.Ocr).

  6. Abra el archivo "Program.cs" y cambie su código al siguiente código C#:
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Vintasoft.Imaging.ImagingGlobalSettings.Register("%EVAL_LIC_USER_NAME%", "%EVAL_LIC_USER_EMAIL%", "%EVAL_LIC_DATE%", "%EVAL_LIC_REG_CODE%");
    
                string imageFilePath = "OCR.tif";
    
                string tesseractOcrPath = "TesseractOCR";
                // create the OCR engine
                using (Vintasoft.Imaging.Ocr.Tesseract.TesseractOcr tesseractOcr = new Vintasoft.Imaging.Ocr.Tesseract.TesseractOcr(tesseractOcrPath))
                {
                    // specify that OCR engine will recognize English text
                    Vintasoft.Imaging.Ocr.OcrLanguage language = Vintasoft.Imaging.Ocr.OcrLanguage.English;
                    // create the OCR engine settings
                    Vintasoft.Imaging.Ocr.Tesseract.TesseractOcrSettings settings = new Vintasoft.Imaging.Ocr.Tesseract.TesseractOcrSettings(language);
                    // initialize the OCR engine
                    tesseractOcr.Init(settings);
    
                    // load an image with text
                    using (Vintasoft.Imaging.VintasoftImage image = new Vintasoft.Imaging.VintasoftImage(imageFilePath))
                    {
                        // preprocess image before text recognition
    
                        // remove noise from image
                        Vintasoft.Imaging.ImageProcessing.Document.DespeckleCommand despeckleCommand = new Vintasoft.Imaging.ImageProcessing.Document.DespeckleCommand();
                        despeckleCommand.ExecuteInPlace(image);
                        // remove lines from image
                        Vintasoft.Imaging.ImageProcessing.Document.LineRemovalCommand lineRemovalCommand = new Vintasoft.Imaging.ImageProcessing.Document.LineRemovalCommand();
                        lineRemovalCommand.ExecuteInPlace(image);
    
                        // specify an image with text
                        tesseractOcr.SetImage(image);
    
                        // recognize text in image
                        Vintasoft.Imaging.Ocr.Results.OcrPage ocrResult = tesseractOcr.Recognize();
    
                        // create PDF document
                        using (Vintasoft.Imaging.Pdf.PdfDocument pdfDocument = new Vintasoft.Imaging.Pdf.PdfDocument("OCR.pdf", Vintasoft.Imaging.Pdf.PdfFormat.Pdf_14))
                        {
                            // create PDF document builder
                            Vintasoft.Imaging.Pdf.Ocr.PdfDocumentBuilder documentBuilder = new Vintasoft.Imaging.Pdf.Ocr.PdfDocumentBuilder(pdfDocument);
                            documentBuilder.ImageCompression = Vintasoft.Imaging.Pdf.PdfCompression.Auto;
                            documentBuilder.PageCreationMode = Vintasoft.Imaging.Pdf.Ocr.PdfPageCreationMode.ImageOverText;
    
                            // add OCR result to the PDF document
                            documentBuilder.AddPage(image, ocrResult);
    
                            // save changes in PDF document
                            pdfDocument.SaveChanges();
                        }
    
                        // clear the image
                        tesseractOcr.ClearImage();
                    }
                    // shutdown the OCR engine
                    tesseractOcr.Shutdown();
                }
            }
        }
    }
    



    El código de la aplicación reconocerá el texto de la imagen y guardará el resultado en un documento PDF con capacidad de búsqueda.

  7. Obtenga el código para usar la versión de evaluación en Linux siguiendo el procedimiento descrito en la documentación e inserte el código obtenido en el código C# del archivo "Program.cs".


  8. Copie el archivo "OCR.tif" a la carpeta del proyecto.


    Puede usar cualquier otro archivo que contenga una imagen de documento en lugar del archivo "OCR.tif".

  9. Abra la terminal y compile el proyecto .NET usando el siguiente comando:
    dotnet build Recognize_Text_In_Image.csproj
    



    Cerrar la terminal.

  10. Vaya a la carpeta "bin/Debug/net6.0/".


  11. Abre la terminal y ejecuta la aplicación .NET con el siguiente comando:
    dotnet ./Recognize_Text_In_Image.dll
    



    Cerrar la terminal.

  12. Abra el documento PDF creado y vea los resultados: