Reconhecer texto em imagem usando um aplicativo .NET para Linux

Categoria do blog: ImagensOCR.NETLinux

23.12.2022

Este artigo explica como criar um aplicativo .NET de console e reconhecer texto em imagens no Ubuntu. Para o reconhecimento de texto em imagens, são utilizados o VintaSoft Imaging .NET SDK e seus plug-ins de PDF, OCR e Limpeza de Documentos.

Aqui estão os passos para concluir essa tarefa:
  1. Abra a área de trabalho do Ubuntu.

  2. Crie uma pasta que armazenará os arquivos do aplicativo .NET. Vamos criar a pasta "Recognize_Text_In_Image" na área de trabalho do usuário atual e acessar a pasta.


  3. Abra o terminal de comandos do console. Isso pode ser feito selecionando a opção "Abrir no Terminal" no menu de contexto ou pressionando a combinação de teclas Ctrl+Alt+T.


  4. Execute o comando no terminal, que cria um projeto de um novo aplicativo .NET de console:
    dotnet new console --framework net6.0
    



    O projeto criado contém o arquivo de projeto "Recognize_Text_In_Image.csproj" e o arquivo "Program.cs", que contém o código C# do aplicativo. Feche o terminal.

  5. Abra o arquivo de projeto "Recognize_Text_In_Image.csproj" em um editor de texto e altere o texto do arquivo para o seguinte texto:
    <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>
    



    O projeto alterado faz referência aos pacotes NuGet para VintaSoft Imaging .NET SDK (Vintasoft.Shared.dll, Vintasoft.Imaging.dll, Vintasoft.Imaging.Drawing.SkiaSharp.dll), VintaSoft Document Cleanup .NET Plug-in (Vintasoft.Imaging.DocCleanup.dll), VintaSoft OCR .NET Plug-in (Vintasoft.Imaging.Ocr.dll, Vintasoft.Imaging.Ocr.Tesseract.dll) e VintaSoft PDF .NET Plug-in (Vintasoft.Imaging.Pdf, Vintasoft.Imaging.Pdf.Ocr).

  6. Abra o arquivo "Program.cs" e altere seu código para o seguinte 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();
                }
            }
        }
    }
    



    O código do aplicativo reconhecerá o texto da imagem e salvará o resultado em um documento PDF pesquisável.

  7. Obtenha o código para usar a versão de avaliação no Linux usando o método descrito na documentação e insira o código obtido no código C# do arquivo "Program.cs".


  8. Copie o arquivo "OCR.tif" para a pasta do projeto.


    Você pode usar qualquer outro arquivo contendo uma imagem de documento em vez do arquivo "OCR.tif".

  9. Abra o terminal e compile o projeto .NET usando o seguinte comando:
    dotnet build Recognize_Text_In_Image.csproj
    



    Feche o terminal.

  10. Acesse a pasta "bin/Debug/net6.0/".


  11. Abra o terminal e execute o aplicativo .NET usando o seguinte comando:
    dotnet ./Recognize_Text_In_Image.dll
    



    Feche o terminal.

  12. Abra o documento PDF criado e veja os resultados: