### Install Build Dependencies Source: https://github.com/sicos1977/tesseractocr/wiki/How-to-use-in-Docker-on-Linux Installs Git, CMake, and build tools required for compiling Tesseract and its dependencies from source. ```Dockerfile RUN apt-get update && apt-get install -y --no-install-recommends \ git cmake build-essential \ && rm -rf /var/lib/apt/lists/* ``` -------------------------------- ### Install Core Tools and Dependencies Source: https://github.com/sicos1977/tesseractocr/wiki/How-to-use-in-Docker-on-Linux Installs essential system tools, Tesseract development libraries, and image processing dependencies. Updates the certificate store and cleans up package lists. ```Dockerfile RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates curl gnupg unzip wget libtesseract-dev libc6-dev libjpeg-dev \ && update-ca-certificates \ && rm -rf /var/lib/apt/lists/* ``` -------------------------------- ### Install Leptonica Dependencies via vcpkg Source: https://github.com/sicos1977/tesseractocr/wiki/Compling_tesseract_and_leptonica.md Installs static versions of essential image format libraries for both x86 and x64 architectures using vcpkg. ```bash vcpkg install giflib:x86-windows-static libjpeg-turbo:x86-windows-static liblzma:x86-windows-static libpng:x86-windows-static tiff:x86-windows-static zlib:x86-windows-static vcpkg install giflib:x64-windows-static libjpeg-turbo:x64-windows-static liblzma:x64-windows-static libpng:x64-windows-static tiff:x64-windows-static zlib:x64-windows-static ``` -------------------------------- ### Complete Layout Example Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-layout.md Provides a comprehensive C# code example demonstrating how to iterate through the OCR layout hierarchy, from page to blocks, paragraphs, text lines, words, and symbols, accessing their properties. ```APIDOC ## Complete Layout Example ```csharp using var engine = new Engine(@"./tessdata", Language.English); using var img = Pix.Image.LoadFromFile("document.png"); using var page = engine.Process(img); Console.WriteLine($"Page Mean Confidence: {page.MeanConfidence}"); foreach (var block in page.Layout) { Console.WriteLine($"Block ({block.BlockType}): confidence={block.Confidence}"); if (block.BoundingBox.HasValue) { var bbox = block.BoundingBox.Value; Console.WriteLine($" Position: ({bbox.X1}, {bbox.Y1}) Size: {bbox.Width}x{bbox.Height}"); } foreach (var paragraph in block.Paragraphs) { var info = paragraph.Info; Console.WriteLine($" Paragraph: confidence={paragraph.Confidence}, justification={info.Justification}"); foreach (var textLine in paragraph.TextLines) { Console.WriteLine($" Line: confidence={textLine.Confidence}"); foreach (var word in textLine.Words) { Console.WriteLine($" Word '{word.Text}': confidence={word.Confidence}, dictionary={word.IsFromDictionary}"); foreach (var symbol in word.Symbols) { Console.WriteLine($" Char '{symbol.Text}': confidence={symbol.Confidence}"); } } } } } ``` ``` -------------------------------- ### Build and Install Leptonica Source: https://github.com/sicos1977/tesseractocr/wiki/How-to-use-in-Docker-on-Linux Clones the Leptonica library, configures it with CMake to build shared libraries, compiles it in release mode, and installs it to /usr/local. It also creates a symbolic link for libdl. ```Dockerfile RUN git clone --depth 1 --branch 1.85.0 https://github.com/DanBloomberg/leptonica.git /leptonica WORKDIR /leptonica RUN mkdir build WORKDIR /leptonica/build RUN cmake .. -DBUILD_SHARED_LIBS=ON RUN cmake --build . --config Release RUN cmake --install . --prefix /usr/local RUN ln -s /lib/x86_64-linux-gnu/libdl.so.2 /usr/lib/libdl.so RUN ldconfig ``` -------------------------------- ### Final Docker Image Setup Source: https://github.com/sicos1977/tesseractocr/wiki/How-to-use-in-Docker-on-Linux Sets up the final image, exposes the application port, configures the application URLs, copies external training data, and creates symbolic links for Tesseract and Leptonica shared libraries. ```Dockerfile FROM build AS final EXPOSE 5000 ENV ASPNETCORE_URLS=http://+:5000 ENV HOME=/home # run docker with --build-context ext= COPY --from=ext trainData/ ${HOME}/trainData/ WORKDIR /app # Copy published app COPY --from=build /app . RUN ln -s /usr/local/lib/libleptonica.so ./x64/libleptonica-1.85.0.dll.so RUN ln -s /usr/lib/x86_64-linux-gnu/libtesseract.so ./x64/libtesseract55.dll.so ENTRYPOINT ["dotnet", ""] ``` -------------------------------- ### Complete Document Layout Processing Example Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-layout.md Demonstrates initializing the OCR engine, processing an image, and iterating through the entire layout hierarchy (blocks, paragraphs, text lines, words, symbols) to extract detailed information. ```csharp using var engine = new Engine(@"./tessdata", Language.English); using var img = Pix.Image.LoadFromFile("document.png"); using var page = engine.Process(img); Console.WriteLine($"Page Mean Confidence: {page.MeanConfidence}"); foreach (var block in page.Layout) { Console.WriteLine($"Block ({block.BlockType}): confidence={block.Confidence}"); if (block.BoundingBox.HasValue) { var bbox = block.BoundingBox.Value; Console.WriteLine($" Position: ({bbox.X1}, {bbox.Y1}) Size: {bbox.Width}x{bbox.Height}"); } foreach (var paragraph in block.Paragraphs) { var info = paragraph.Info; Console.WriteLine($" Paragraph: confidence={paragraph.Confidence}, justification={info.Justification}"); foreach (var textLine in paragraph.TextLines) { Console.WriteLine($" Line: confidence={textLine.Confidence}"); foreach (var word in textLine.Words) { Console.WriteLine($" Word '{word.Text}': confidence={word.Confidence}, dictionary={word.IsFromDictionary}"); foreach (var symbol in word.Symbols) { Console.WriteLine($" Char '{symbol.Text}': confidence={symbol.Confidence}"); } } } } } ``` -------------------------------- ### Install TesseractOCR via NuGet Source: https://github.com/sicos1977/tesseractocr/blob/master/TesseractOCR/README.md Command to install the TesseractOCR package using the NuGet Package Manager Console in Visual Studio. ```powershell Install-Package TesseractOCR ``` -------------------------------- ### Integrating NLog with TesseractOCR Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-loggers.md Configure NLog with a logging rule and file target, then obtain a logger instance. Ensure NLog is installed and configured. ```csharp var config = new NLog.Config.LoggingConfiguration(); var fileTarget = new NLog.Targets.FileTarget { FileName = "ocr.log" }; config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, fileTarget); var logger = NLog.LogManager.Setup() .LoadConfiguration(config) .GetCurrentClassLogger(); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` -------------------------------- ### Multi-Language Recognition Setup Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/README.md Configures the OCR engine to recognize text in multiple languages simultaneously. ```csharp var languages = new List { Language.English, Language.Spanish }; using var engine = new Engine(@"./tessdata", languages); ``` -------------------------------- ### Tesseract OCR Entry Points Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-index.md This snippet outlines the primary entry points for interacting with the Tesseract OCR library, including starting the engine, processing images, and accessing results. ```APIDOC ## Entry Points ### Description Provides the main methods and constructors to initiate and perform OCR tasks. ### Methods - **new Engine()** - Purpose: Initializes the main OCR engine. - **engine.Process(image)** - Purpose: Processes an image to perform OCR. - **Pix.Image.LoadFromFile(filePath)** - Purpose: Loads an image from a specified file path. - **page.Text** - Purpose: Retrieves the recognized text from an OCR result page. - **page.Layout** - Purpose: Accesses the layout hierarchy of the OCR result. ``` -------------------------------- ### Integrating Serilog with TesseractOCR Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-loggers.md Use Serilog for logging by creating a LoggerFactory, adding Serilog, and creating an ILogger instance. Ensure Serilog is installed. ```csharp using var logger = new LoggerFactory() .AddSerilog() .CreateLogger("TesseractOCR"); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` -------------------------------- ### Iterating Through Words and Symbols Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-layout.md Example of iterating through words in a text line and then through the symbols within each word to display their properties. ```csharp foreach (var word in textLine.Words) { Console.WriteLine($"Word: {word.Text}"); Console.WriteLine($" Dictionary: {word.IsFromDictionary}"); Console.WriteLine($" Numeric: {word.IsNumeric}"); foreach (var symbol in word.Symbols) { Console.WriteLine($" Char: {symbol.Text}"); } } ``` -------------------------------- ### Handling LoadLibraryException Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/errors.md Example of catching LoadLibraryException, which indicates a failure to load native Tesseract libraries. It suggests checking for the presence of DLLs in the output directory. ```csharp try { var engine = new Engine(@"./tessdata", Language.English); } catch (LoadLibraryException ex) { Console.WriteLine($"Failed to load native library: {ex.Message}"); Console.WriteLine("Ensure Tesseract DLLs are in the output directory"); } ``` -------------------------------- ### Process Image and Get Text Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/README.md Processes an image using the initialized engine and retrieves the recognized text. ```csharp using var page = engine.Process(image); var text = page.Text; var confidence = page.MeanConfidence; ``` -------------------------------- ### Complete OCR Example with Error Handling Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/getting-started.md Implement comprehensive error handling for Tesseract OCR operations, catching specific exceptions like TesseractException, InvalidOperationException, and IOException. Checks for result confidence. ```csharp using var engine = new Engine(@"./tessdata", Language.English); using var img = Pix.Image.LoadFromFile("document.png"); try { using var page = engine.Process(img); if (page.MeanConfidence >= 0.8f) { Console.WriteLine("High confidence result:"); Console.WriteLine(page.Text); } else { Console.WriteLine("Low confidence result. Manual review needed."); } } catch (TesseractException ex) { Console.WriteLine($"OCR Error: {ex.Message}"); } catch (InvalidOperationException ex) { Console.WriteLine($"Invalid operation: {ex.Message}"); } catch (IOException ex) { Console.WriteLine($"File error: {ex.Message}"); } ``` -------------------------------- ### Simple Text Extraction Pattern Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/getting-started.md A straightforward example of performing OCR on an image and printing the extracted text. Ensure language data is correctly configured. ```csharp using var engine = new Engine(@"./tessdata", Language.English); using var img = Pix.Image.LoadFromFile("scan.png"); using var page = engine.Process(img); Console.WriteLine(page.Text); ``` -------------------------------- ### Extract Text from Image Bytes Source: https://github.com/sicos1977/tesseractocr/wiki/examples.md This example demonstrates how to extract text from an image loaded from a byte array. It reads the image file into memory as bytes before processing. ```csharp using (var fs = new FileStream(filename, FileMode.Open, file_access)) ; using (var ms = new MemoryStream()) { fs.CopyTo(ms); bytes[] fileBytes = ms.ToArray(); using (var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default)) { using (var img = TesseractOCR.Pix.Image.LoadFromMemory(fileBytes)) { using (var page = engine.Process(img)) { var txt = page.Text; } } } } ``` -------------------------------- ### Engine Constructor with Configuration Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Demonstrates initializing the Engine with custom options and a logger. Ensure the dataPath points to your 'tessdata' directory. ```csharp public Engine( string dataPath, Language language, EngineMode engineMode = EngineMode.Default, IEnumerable configFiles = null, IDictionary initialOptions = null, bool setOnlyNonDebugVariables = false, ILogger logger = null) ``` ```csharp var options = new Dictionary { { "tessedit_char_whitelist", "0123456789" }, { "classify_bln_numeric_mode", "1" } }; var logger = new TesseractOCR.Loggers.Console(); var engine = new Engine( "./tessdata", Language.English, EngineMode.Default, null, options, false, logger); ``` -------------------------------- ### Iterate Through Page Layout Hierarchy Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-page.md Use the Layout property to get an enumerator for the page's layout hierarchy, starting from Blocks down to Symbols. This is useful for detailed analysis of the recognized text structure. ```csharp foreach (var block in page.Layout) { Console.WriteLine($"Block confidence: {block.Confidence}"); foreach (var paragraph in block.Paragraphs) { Console.WriteLine($" Paragraph: {paragraph.Text}"); foreach (var textLine in paragraph.TextLines) { Console.WriteLine($" Line: {textLine.Text}"); foreach (var word in textLine.Words) { Console.WriteLine($" Word: {word.Text} (confidence: {word.Confidence})"); foreach (var symbol in word.Symbols) { Console.WriteLine($" Symbol: {symbol.Text}"); } } } } } ``` -------------------------------- ### Initialize Logger with File or Console Source: https://github.com/sicos1977/tesseractocr/blob/master/TesseractOCR/README.md Demonstrates how to initialize a logger, either to a file if a log file path is provided, or to the console. ```csharp var logger = !string.IsNullOrWhiteSpace() ? new TesseractOCR.Loggers.Stream(File.OpenWrite()) : new TesseractOCR.Loggers.Console(); ``` -------------------------------- ### TesseractOCR Engine Class Constructors Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-index.md Demonstrates the various ways to instantiate the TesseractOCR Engine, specifying language, mode, and optional configurations. ```csharp public Engine(string, Language, EngineMode, IEnumerable, IDictionary, bool, ILogger); public Engine(string, List, EngineMode, IEnumerable, IDictionary, bool, ILogger); public Engine(string, string, EngineMode, IEnumerable, IDictionary, bool, ILogger); ``` -------------------------------- ### Load Tesseract Configuration Files Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Initializes the Tesseract engine with custom configuration files. Ensure files are UTF-8 encoded with Unix line endings and follow the 'variable_name value' format. ```csharp var configFiles = new[] { @"./tessdata/configs/base", @"./tessdata/configs/digits" }; var engine = new Engine( @"./tessdata", Language.English, configFiles: configFiles); ``` -------------------------------- ### Height Property Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-pix-image.md Gets the height of the image in pixels. ```APIDOC ## Height ### Description Image height in pixels. ### Type int ### Access Read-only ``` -------------------------------- ### Width Property Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-pix-image.md Gets the width of the image in pixels. ```APIDOC ## Width ### Description Image width in pixels. ### Type int ### Access Read-only ``` -------------------------------- ### YRes Property Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-pix-image.md Gets or sets the vertical resolution of the image in DPI. ```APIDOC ## YRes ### Description Vertical resolution in DPI (dots per inch). ### Type int ### Access Read-write ``` -------------------------------- ### Create Engine with Language String Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Instantiate the Engine class using a string to specify languages. Use '+' to separate multiple languages. ```csharp using var engine = new Engine(@"./tessdata", "eng+nld"); ``` -------------------------------- ### TesseractOCR Engine Class Configuration Methods Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-index.md Illustrates how to set and retrieve Tesseract variables, including string, boolean, integer, and double types, and how to print variables to a file. ```csharp public bool SetVariable(string, string); public bool SetVariable(string, bool); public bool SetVariable(string, int); public bool SetVariable(string, double); public bool SetDebugVariable(string, string); public bool TryGetStringVariable(string, out string); public bool TryGetBoolVariable(string, out bool); public bool TryGetIntVariable(string, out int); public bool TryGetDoubleVariable(string, out double); public bool TryPrintVariablesToFile(string); ``` -------------------------------- ### XRes Property Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-pix-image.md Gets or sets the horizontal resolution of the image in DPI. ```APIDOC ## XRes ### Description Horizontal resolution in DPI (dots per inch). ### Type int ### Access Read-write ``` -------------------------------- ### Depth Property Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-pix-image.md Gets the bit depth of the image (bits per pixel). ```APIDOC ## Depth ### Description Image bit depth (1, 2, 4, 8, 16, or 32 bits per pixel). ### Type int ### Access Read-only ``` -------------------------------- ### Initialize Engine Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/README.md Initializes the OCR engine with a specified tessdata path and language. ```csharp using var engine = new Engine(@"./tessdata", Language.English); ``` -------------------------------- ### DataPath Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Gets the data path where the tessdata directory is located, with trailing slashes removed. ```APIDOC ## DataPath ### Description Returns the data path where the tessdata directory is located. ### Returns string - Data path with trailing slashes removed. ``` -------------------------------- ### Prepare Language Data Directory Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/getting-started.md Structure your project to include the 'tessdata' directory with necessary language files and an 'images' directory for input images. ```text YourProject/ ├── tessdata/ │ ├── eng.traineddata │ ├── fra.traineddata │ └── osd.traineddata (for orientation detection) ├── images/ │ └── document.png └── Program.cs ``` -------------------------------- ### InitLanguage Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Gets the Language enum value used in the last valid initialization of the Tesseract engine. ```APIDOC ## InitLanguage ### Description Returns the Language enum value used in the last valid initialization. ### Returns Language - The initialized Language enum value. ``` -------------------------------- ### Initialize Engine with Data Path Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Specifies how to initialize the Tesseract engine by providing the correct data path. The path should point to the parent directory of 'tessdata'. ```csharp using var engine = new Engine(@"C:\Tesseract", Language.English); using var engine = new Engine(@"./tessdata", Language.English); ``` -------------------------------- ### Configuring Engine with a Logger Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-loggers.md Demonstrates how to pass a specific logger instance (Console logger in this case) during Tesseract Engine initialization. This ensures all library operations are logged. ```csharp // Single language with logger var logger = new TesseractOCR.Loggers.Console(); using var engine = new Engine( @"./tessdata", Language.English, EngineMode.Default, logger: logger ); ``` -------------------------------- ### Engine Constructor (Multiple Languages) Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Creates a new Engine instance configured for multiple languages. It takes a list of Language enum values for initialization. ```APIDOC ## Engine(string dataPath, List languages, EngineMode engineMode = EngineMode.Default, IEnumerable configFiles = null, IDictionary initialValues = null, bool setOnlyNonDebugVariables = false, ILogger logger = null) ### Description Creates a new Engine instance configured for multiple languages. ### Parameters #### Path Parameters - **dataPath** (string) - Required - Path to parent directory containing 'tessdata' folder. - **languages** (List) - Required - List of Language enum values to load. #### Query Parameters - **engineMode** (EngineMode) - Optional - Default: EngineMode.Default - OCR engine mode. - **configFiles** (IEnumerable) - Optional - Default: null - Configuration files. - **initialValues** (IDictionary) - Optional - Default: null - Initial engine variables. - **setOnlyNonDebugVariables** (bool) - Optional - Default: false - Sets only non-debug variables if true. - **logger** (ILogger) - Optional - Default: null - Logger implementation. ### Request Example ```csharp var languages = new List { Language.English, Language.Dutch }; using var engine = new Engine(@"./tessdata", languages); ``` ``` -------------------------------- ### Engine Logging Configuration Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-loggers.md Shows how to configure logging when creating the TesseractOCR Engine instance. ```APIDOC ## Logging Configuration ### Description Logging is configured when creating the Engine instance by passing an `ILogger` implementation to the constructor. ### Example with Console Logger ```csharp // Single language with logger var logger = new TesseractOCR.Loggers.Console(); using var engine = new Engine( @"./tessdata", Language.English, EngineMode.Default, logger: logger ); ``` ### Disabling Logging To disable logging, pass `null` or omit the logger parameter (default behavior). ```csharp using var engine = new Engine(@"./tessdata", Language.English); // No logging output ``` ``` -------------------------------- ### Get Initialized Language Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Retrieves the Language enum value used during the last successful initialization of the Tesseract engine. ```csharp public Language InitLanguage { get; } ``` -------------------------------- ### Tesseract OCR Core Operations Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-index.md Demonstrates the basic workflow for initializing the Tesseract engine, loading an image, processing it, extracting text and confidence, iterating through the layout, configuring engine variables, and cleaning up resources. ```csharp // Create engine var engine = new Engine(path, language, mode); // Load image var img = Pix.Image.LoadFromFile(path); // Process var page = engine.Process(img, segMode); // Get text var text = page.Text; var confidence = page.MeanConfidence; // Iterate layout foreach (var block in page.Layout) foreach (var paragraph in block.Paragraphs) foreach (var line in paragraph.TextLines) foreach (var word in line.Words) // Use word.Text, word.Confidence, word.BoundingBox // Configure engine.SetVariable("name", value); engine.DefaultPageSegMode = mode; // Cleanup page.Dispose(); engine.Dispose(); ``` -------------------------------- ### DefaultPageSegMode Property Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Gets or sets the default page segmentation mode for image processing methods. Defaults to PageSegMode.Auto. ```APIDOC ## DefaultPageSegMode ### Description Gets or sets the default page segmentation mode used by Process methods. Defaults to PageSegMode.Auto. ### Parameters - **DefaultPageSegMode** (PageSegMode) - Required - The page segmentation mode. ### Property ```csharp public PageSegMode DefaultPageSegMode { get; set; } ``` ### Type PageSegMode ### Default Value PageSegMode.Auto ``` -------------------------------- ### Colormap Property Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-pix-image.md Gets or sets the colormap for the image. Setting this property to null removes the colormap. The type is Colormap. ```csharp public Colormap Colormap { get; set; } ``` -------------------------------- ### Initialize Engine with Multiple Languages (Enum List) Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Initializes the Tesseract engine to support multiple languages using a list of the Language enum. ```csharp var languages = new List { Language.English, Language.Spanish, Language.French }; using var engine = new Engine(@"./tessdata", languages); ``` -------------------------------- ### Create Engine with Multiple Languages Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Instantiate the Engine class to support multiple languages. Provide a list of Language enum values. ```csharp var languages = new List { Language.English, Language.Dutch }; using var engine = new Engine(@"./tessdata", languages); ``` -------------------------------- ### Get Loaded Languages Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Returns a list of Language enum values that are currently loaded and available within the Tesseract engine. ```csharp public List LoadedLanguages { get; } ``` -------------------------------- ### Saving Thresholded Image Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-page.md Get and save the thresholded (binary) version of the processed image. This can be useful for debugging or further image analysis. ```csharp using var thresholded = page.ThresholdedImage; thresholded.Save("thresholded.png", ImageFormat.Png); ``` -------------------------------- ### Simple Text Extraction Workflow Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/README.md A basic workflow demonstrating how to initialize the engine, load an image, process it, and print the extracted text. ```csharp using var engine = new Engine(@"./tessdata", Language.English); using var img = Pix.Image.LoadFromFile("scan.png"); using var page = engine.Process(img); Console.WriteLine(page.Text); ``` -------------------------------- ### Handle InvalidOperationException Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/errors.md Use this when an operation is invalid in the current state, for example, attempting to process another image while one is already being processed. ```csharp using var engine = new Engine(@"./tessdata", Language.English); using var img = Pix.Image.LoadFromFile("test.png"); using (var page1 = engine.Process(img)) { try { using (var page2 = engine.Process(img)) // Error! { } } catch (InvalidOperationException ex) { Console.WriteLine($"Invalid operation: {ex.Message}"); // Message: "Only one image can be processed at once..." } } ``` -------------------------------- ### Restore and Publish .NET Application Source: https://github.com/sicos1977/tesseractocr/wiki/How-to-use-in-Docker-on-Linux Restores NuGet packages and publishes the .NET application for release, optimizing for cache usage. ```Dockerfile RUN --mount=type=cache,target=/root/.nuget/packages \ dotnet restore RUN --mount=type=cache,target=/root/.nuget/packages \ dotnet publish -c Release \ -o /app --no-restore ``` -------------------------------- ### Get Available Languages Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Returns a list of all Language enum values that are present in the tessdata directory, indicating all languages that can potentially be loaded. ```csharp public List AvailableLanguages { get; } ``` -------------------------------- ### Access Paragraph Information and Text Lines Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-layout.md Retrieve paragraph justification and iterate through its text lines to get individual line content. ```csharp foreach (var paragraph in block.Paragraphs) { var info = paragraph.Info; Console.WriteLine($"Justification: {info.Justification}"); foreach (var textLine in paragraph.TextLines) { Console.WriteLine($" Line: {textLine.Text}"); } } ``` -------------------------------- ### Print Configuration Variables to File Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Saves the current Tesseract configuration variables to a specified file for review or backup. Returns true if successful, false otherwise. ```csharp var configFile = "tesseract_config.txt"; if (engine.TryPrintVariablesToFile(configFile)) { Console.WriteLine($"Configuration saved to {configFile}"); } else { Console.WriteLine("Failed to save configuration"); } ``` -------------------------------- ### Microsoft.Extensions.Logging.Console Integration Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-loggers.md Demonstrates how to use Microsoft.Extensions.Logging.ILogger with Console and Debug providers with TesseractOCR. ```APIDOC ## Microsoft.Extensions.Logging.Console Example ### Description Integrates TesseractOCR with Microsoft.Extensions.Logging, specifically using the Console and Debug providers. ### Code ```csharp var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); services.AddLogging(builder => { builder.AddConsole(); builder.AddDebug(); }); var serviceProvider = services.BuildServiceProvider(); var logger = serviceProvider.GetRequiredService>(); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` ``` -------------------------------- ### Engine Constructor (Language String) Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Creates a new Engine instance using a string specification for languages, allowing for single or multiple languages separated by '+'. ```APIDOC ## Engine(string dataPath, string languages, EngineMode engineMode = EngineMode.Default, IEnumerable configFiles = null, IDictionary initialValues = null, bool setOnlyNonDebugVariables = false, ILogger logger = null) ### Description Creates a new Engine instance using language string specification. ### Parameters #### Path Parameters - **dataPath** (string) - Required - Path to parent directory containing 'tessdata' folder. - **languages** (string) - Required - Languages as string, e.g. "eng" or "eng+nld" for multiple. #### Query Parameters - **engineMode** (EngineMode) - Optional - Default: EngineMode.Default - OCR engine mode. - **configFiles** (IEnumerable) - Optional - Default: null - Configuration files. - **initialValues** (IDictionary) - Optional - Default: null - Initial engine variables. - **setOnlyNonDebugVariables** (bool) - Optional - Default: false - Sets only non-debug variables if true. - **logger** (ILogger) - Optional - Default: null - Logger implementation. ### Request Example ```csharp using var engine = new Engine(@"./tessdata", "eng+nld"); ``` ``` -------------------------------- ### Serilog Integration Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-loggers.md Demonstrates how to use a custom Serilog ILogger implementation with TesseractOCR. ```APIDOC ## Serilog Example ### Description Integrates TesseractOCR with Serilog by providing a Serilog-compatible logger. ### Code ```csharp using var logger = new LoggerFactory() .AddSerilog() .CreateLogger("TesseractOCR"); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` ``` -------------------------------- ### Initialize and Use Engine with 'using' Statement Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md The Engine class implements IDisposable. Always use a 'using' statement for automatic disposal of resources. ```csharp using var engine = new Engine(@"./tessdata", Language.English); // Use engine here // Automatically disposed ``` -------------------------------- ### Engine Constructor (Single Language) Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Creates a new Engine instance configured for a single language. It requires the path to the Tesseract data directory and the desired language. ```APIDOC ## Engine(string dataPath, Language language, EngineMode engineMode = EngineMode.Default, IEnumerable configFiles = null, IDictionary initialOptions = null, bool setOnlyNonDebugVariables = false, ILogger logger = null) ### Description Creates a new Engine instance configured for a single language. ### Parameters #### Path Parameters - **dataPath** (string) - Required - Path to parent directory containing 'tessdata' folder. Ignored if TESSDATA_PREFIX environment variable is set. - **language** (Language) - Required - The OCR language to load. Use Language enum value. #### Query Parameters - **engineMode** (EngineMode) - Optional - Default: EngineMode.Default - OCR engine mode (Legacy, LSTM, or both). - **configFiles** (IEnumerable) - Optional - Default: null - Tesseract configuration files (UTF8 without BOM, Unix line endings). - **initialOptions** (IDictionary) - Optional - Default: null - Initial engine variables as key-value pairs. - **setOnlyNonDebugVariables** (bool) - Optional - Default: false - If true, only sets non-debug variables. - **logger** (ILogger) - Optional - Default: null - Microsoft.Extensions.Logging ILogger implementation for logging output. ### Request Example ```csharp using var engine = new Engine(@"./tessdata", Language.English); ``` ``` -------------------------------- ### Get Data Path Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Retrieves the path to the directory containing Tesseract's language data files (tessdata). The returned path has trailing slashes removed. ```csharp public string DataPath { get; } ``` -------------------------------- ### Initialize Engine with Custom Logger Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Provides a custom ILogger implementation to the Tesseract engine for detailed logging during OCR processes. ```csharp var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory(); loggerFactory.AddProvider(new CustomLoggerProvider()); var logger = loggerFactory.CreateLogger("TesseractOCR"); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` -------------------------------- ### Detect Page Orientation and Confidence Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-page.md Call DetectOrientation to get the page's clockwise rotation in degrees and the confidence level of the detection. This method is typically used with PageSegMode.OsdOnly. ```csharp var page = engine.Process(img, PageSegMode.OsdOnly); page.DetectOrientation(out var orientation, out var confidence); Console.WriteLine($"Orientation: {orientation}° (confidence: {confidence})"); ``` -------------------------------- ### Build Leptonica 1.85.0 (x64) Source: https://github.com/sicos1977/tesseractocr/wiki/Compling_tesseract_and_leptonica.md Clones, checks out, and builds Leptonica version 1.85.0 for x64 using CMake with Visual Studio 2022, enabling shared libraries and specifying vcpkg toolchain. ```bash mkdir vs22-x64 & cd vs22-x64 cmake .. -G "Visual Studio 17 2022" -A x64 -DSW_BUILD=OFF -DBUILD_SHARED_LIBS=ON -DCMAKE_TOOLCHAIN_FILE=%VCPKG_HOME%\scripts\buildsystems\vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static -DCMAKE_INSTALL_PREFIX=..\..\build\x64 cmake --build . --config Release --target install cd .. cd .. ``` -------------------------------- ### Try Get Boolean Configuration Variable Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Attempts to retrieve a configuration variable of type boolean. Returns true if the variable is found and its value is assigned to the output parameter; otherwise, returns false. ```csharp public bool TryGetBoolVariable(string name, out bool value) ``` -------------------------------- ### Perform OCR on an Image Source: https://github.com/sicos1977/tesseractocr/blob/master/TesseractOCR/README.md This C# snippet demonstrates how to initialize the Tesseract OCR engine, load an image file, process it for OCR, and then print the mean confidence and extracted text to the console. Ensure the 'tessdata' directory is correctly placed and the image path is valid. ```csharp using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default); using var img = TesseractOCR.Pix.Image.LoadFromFile(testImagePath); using var page = engine.Process(img); Console.WriteLine("Mean confidence: {0}", page.MeanConfidence); Console.WriteLine("Text: \r\n{0}", page.Text); ``` -------------------------------- ### Try Get String Configuration Variable Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-engine.md Attempts to retrieve a configuration variable of type string. Returns true if the variable is found and its value is assigned to the output parameter; otherwise, returns false. ```csharp public bool TryGetStringVariable(string name, out string value) ``` -------------------------------- ### Initialize Engine with Multiple Languages (String) Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Initializes the Tesseract engine to support multiple languages using a string of 3-letter language codes separated by '+'. ```csharp using var engine = new Engine(@"./tessdata", "eng+spa+fra"); ``` -------------------------------- ### Configure Engine Mode (TesseractOnly) Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Initializes the Tesseract engine to use only the legacy Tesseract engine, suitable for older documents. ```csharp using var engine = new Engine(@"./tessdata", Language.English, EngineMode.TesseractOnly); ``` -------------------------------- ### Image Equality Methods Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-index.md Implements methods for comparing image instances for equality. ```csharp public bool Equals(Image); public override bool Equals(object); public override int GetHashCode(); ``` -------------------------------- ### Multi-language Recognition Configuration Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Initializes the engine to recognize text in multiple languages simultaneously. Ensure all required language data files are present. ```csharp var languages = new List { Language.English, Language.Spanish, Language.French, Language.German }; var engine = new Engine( @"./tessdata", languages, EngineMode.Default); ``` -------------------------------- ### Image Equality Comparison Methods Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-pix-image.md Provides methods for comparing Image instances for equality. Two Image instances are considered equal if they reference the same underlying image data. ```csharp public bool Equals(Image other) public override bool Equals(object obj) public override int GetHashCode() public static bool operator ==(Image lhs, Image rhs) public static bool operator !=(Image lhs, Image rhs) ``` -------------------------------- ### Handling TesseractException Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/errors.md Demonstrates how to catch and handle TesseractException, which is thrown for various library-specific errors like engine initialization or image processing failures. ```csharp try { var engine = new Engine(@"./tessdata", Language.English); } catch (TesseractException ex) { Console.WriteLine($"Tesseract error: {ex.Message}"); } ``` -------------------------------- ### Image Disposal with Using Statement Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-pix-image.md Demonstrates the preferred method for disposing of Image objects to release memory, using a 'using' statement for automatic disposal. ```csharp // Using statement (preferred) using var img = Pix.Image.LoadFromFile("image.png"); // Use image // Automatically disposed ``` -------------------------------- ### Handle Tesseract Initialization Errors Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/errors.md Use a try-catch block to handle potential initialization failures of the Tesseract engine. ```csharp try { var engine = new Engine(@"./tessdata", Language.English); } catch (TesseractException ex) { // Handle initialization failure Console.WriteLine($"Engine init failed: {ex.Message}"); } catch (LoadLibraryException ex) { // Handle missing native libraries Console.WriteLine($"Missing native DLLs: {ex.Message}"); } ``` -------------------------------- ### NLog Integration Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-loggers.md Demonstrates how to use a custom NLog ILogger implementation with TesseractOCR. ```APIDOC ## NLog Example ### Description Integrates TesseractOCR with NLog by providing an NLog-compatible logger. ### Code ```csharp var config = new NLog.Config.LoggingConfiguration(); var fileTarget = new NLog.Targets.FileTarget { FileName = "ocr.log" }; config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, fileTarget); var logger = NLog.LogManager.Setup() .LoadConfiguration(config) .GetCurrentClassLogger(); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` ``` -------------------------------- ### Configure Logger for Console Output Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Initializes the Tesseract engine with a logger that outputs OCR-related messages to the console. ```csharp var logger = new TesseractOCR.Loggers.Console(); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` -------------------------------- ### Engine Class - Configuration Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/README.md Demonstrates how to configure OCR behavior by setting variables on the Engine object. ```APIDOC ## Engine Configuration Methods ### Description Methods for configuring the OCR engine's behavior and retrieving settings. ### Methods - **SetVariable(string name, object value)** → bool - Sets a configuration variable for the OCR engine. - **TryGetVariable(string name, out object value)** → bool - Attempts to retrieve the value of a configuration variable. ### Example Usage ```csharp engine.SetVariable("tessedit_char_whitelist", "0123456789"); ``` ``` -------------------------------- ### Integrating Microsoft.Extensions.Logging.Console with TesseractOCR Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-reference-loggers.md Configure logging using ServiceCollection, adding Console and Debug providers. Build the service provider to retrieve an ILogger instance. ```csharp using var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); services.AddLogging(builder => { builder.AddConsole(); builder.AddDebug(); }); var serviceProvider = services.BuildServiceProvider(); var logger = serviceProvider.GetRequiredService>(); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` -------------------------------- ### Configure Logger for File Output Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Initializes the Tesseract engine with a logger that writes OCR-related messages to a specified log file. ```csharp var logger = new TesseractOCR.Loggers.File(@"C:\logs\ocr.log"); var engine = new Engine(@"./tessdata", Language.English, logger: logger); ``` -------------------------------- ### Build Leptonica 1.85.0 (x86) Source: https://github.com/sicos1977/tesseractocr/wiki/Compling_tesseract_and_leptonica.md Clones, checks out, and builds Leptonica version 1.85.0 for x86 using CMake with Visual Studio 2022, enabling shared libraries and specifying vcpkg toolchain. ```bash git clone https://github.com/DanBloomberg/leptonica.git & cd leptonica git checkout -b 1.85.0 1.85.0 mkdir vs22-x86 & cd vs22-x86 cmake .. -G "Visual Studio 17 2022" -A Win32 -DSW_BUILD=OFF -DBUILD_SHARED_LIBS=ON -DCMAKE_TOOLCHAIN_FILE=%VCPKG_HOME%\scripts\buildsystems\vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x86-windows-static -DCMAKE_INSTALL_PREFIX=..\..\build\x86 cmake --build . --config Release --target install cd .. ``` -------------------------------- ### Image Loading Methods Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/api-index.md Provides static methods to load images from various sources like files and memory streams. ```csharp public static Image LoadFromFile(string); public static Image LoadFromMemory(byte[]); public static Image LoadFromMemory(MemoryStream); public static Image LoadFromMemory(byte[], int, int); public static Image LoadMultiPageTiffFromMemory(byte[], ref int); public static IEnumerable EnumerateInMemTiff(byte[]); ``` -------------------------------- ### Set Colormap on Image Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/types.md Demonstrates how to create and set a Colormap on an image object, typically used for images with 8-bit depth or less. ```csharp // Set colormap on image if (image.Depth <= 8) { var colormap = new Colormap(); image.Colormap = colormap; } ``` -------------------------------- ### Configure Engine Mode (TesseractAndLstm) Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/configuration.md Initializes the Tesseract engine to use both the legacy Tesseract and LSTM engines, providing the highest accuracy at the cost of speed. ```csharp using var engine = new Engine(@"./tessdata", Language.English, EngineMode.TesseractAndLstm); ``` -------------------------------- ### Create Searchable PDF from Image Source: https://github.com/sicos1977/tesseractocr/wiki/examples.md This snippet illustrates how to generate a searchable PDF from an image file. It uses a PDF renderer and requires the 'tessdata' directory for OCR processing. ```csharp using (var renderer = TesseractOCR.Renderers.Result.CreatePdfRenderer(@"test.pdf", @"./tessdata", false)) { // PDF Title using (renderer.BeginDocument("SearchablePdfTest")) { const string configurationFilePath = @"C:\tessdata"; using (var engine = new Engine(configurationFilePath, Language.English, EngineMode.TesseractAndLstm)) { using (var img = TesseractOCR.Pix.Image.LoadFromFile(@"C:\file-page1.jpg")) { using (var page = engine.Process(img, "SearchablePdfTest")) { renderer.AddPage(page); } } } } } ``` -------------------------------- ### Engine Class - Initialization and Processing Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/README.md Demonstrates how to initialize the OCR engine and process an image to extract text. The Engine class is the main entry point for OCR operations. ```APIDOC ## Engine.Process ### Description Processes an image using the OCR engine to extract text and results. ### Method `Process(Image, PageSegMode?)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **Image** (Image) - The image object to process. - **PageSegMode?** (PageSegMode, optional) - The page segmentation mode to use. ### Request Example ```csharp using var engine = new Engine(@"./tessdata", Language.English); using var img = Pix.Image.LoadFromFile("scan.png"); using var page = engine.Process(img); Console.WriteLine(page.Text); ``` ### Response #### Success Response (Page) - **Text** (string) - The extracted text from the image. - **MeanConfidence** (float) - The average confidence score of the OCR results. - **Layout** (Blocks) - The hierarchical layout of the document. #### Response Example ```json { "Text": "Extracted text content.", "MeanConfidence": 0.95, "Layout": { ... } } ``` ``` -------------------------------- ### Rect Structure Initialization Source: https://github.com/sicos1977/tesseractocr/blob/master/_autodocs/types.md Represents a rectangular region using coordinates and dimensions. Use the constructor for x, y, width, height or FromCoords for x1, y1, x2, y2. ```csharp public readonly struct Rect : IEquatable { public int X1 { get; } public int Y1 { get; } public int X2 { get; } public int Y2 { get; } public int Width { get; } public int Height { get; } public Rect(int x, int y, int width, int height) public static Rect FromCoords(int x1, int y1, int x2, int y2) } ``` ```csharp var region = new Rect(10, 10, 100, 50); // x=10, y=10, width=100, height=50 var pageRegion = Rect.FromCoords(0, 0, 1000, 1000); // x1, y1, x2, y2 format ```