tesseract-rs

repository·master·Indexed 41 days ago

https://github.com/antimatter15/tesseract-rs

High-level Rust bindings for the Tesseract OCR engine, version 0.15.2. It enables optical character recognition within Rust applications, providing functionality to initialize the engine, load images from files or memory, configure page segmentation modes via PageSegMode, and extract text in String, HOCR, or TSV formats.

Tokens
1.8K
Snippets
8
Records
10
Agent score
52%

What's inside tesseract-rs

  1. Set the OCR Engine Mode (OEM)

    master

    The OcrEngineMode enum allows you to control which Tesseract engine is used:

    • Default: Run Tesseract only (fastest, but deprecated).
    • LstmOnly: Run just the LSTM line recognizer.
    • TesseractLstmCombined: Run the LSTM recognizer with fallback to Tesseract (deprecated).
    • TesseractOnly: Automatically infer mode from config or default to OEM_TESSERACT_ONLY.
    ```rust
    use tesseract::{Tesseract, OcrEngineMode};
    
    let mut tess = Tesseract::new_with_oem(
        None,
        Some("eng"),
        OcrEngineMode::LstmOnly
    )?;
  2. Initialize the Tesseract engine

    master

    Use Tesseract::new or Tesseract::new_with_oem to create a new OCR engine instance. You can optionally specify a datapath (the path to training data) and a language (e.g., "eng").

    If you need to specify the OCR Engine Mode (OEM), use new_with_oem with an OcrEngineMode value.

    ```rust
    // Basic initialization
    let mut tess = Tesseract::new(Some("/path/to/data"), Some("eng"))?;
    
    // Initialization with specific OCR Engine Mode
    let mut tess = Tesseract::new_with_oem(
        None,
        Some("eng"),
        OcrEngineMode::LstmOnly
    )?;
  3. Convert `PageSegMode` to Tesseract internal type

    master

    If you are working with low-level bindings or need the raw Tesseract value, use the as_tess_page_seg_mode() method on a PageSegMode instance. This returns the underlying TessPageSegMode type used by the Tesseract C API.

    let mode = PageSegMode::PsmSingleBlock;
    let tess_mode = mode.as_tess_page_seg_mode();
  4. Load images for OCR

    master

    The Tesseract struct provides several methods to provide image data to the engine:

    • set_image(filename: &str): Loads an image from a file path.
    • set_image_from_mem(img: &[u8]): Loads an image from a byte slice in memory.
    • set_frame(frame_data: &[u8], width: i32, height: i32, bytes_per_pixel: i32, bytes_per_line: i32): Sets an image from raw frame data (useful for video frames).

    Note that these methods consume and return self, allowing for a builder-like pattern.

    ```rust
    // From file
    tess.set_image("path/to/image.png")?;
    
    // From memory
    tess.set_image_from_mem(&buffer)?;
    
    // From raw frame
    tess.set_frame(data, 1920, 1080, 4, 1920 * 4)?;
  5. Use high-level OCR helper functions

    master

    For simple tasks, use the convenience functions that wrap the entire lifecycle (init -> set image -> recognize -> get text):

    • ocr(filename: &str, language: &str): Performs OCR on a file.
    • ocr_from_frame(frame_data, width, height, bytes_per_pixel, bytes_per_line, language): Performs OCR on raw frame data.
    // Simple file OCR
    let text = ocr("image.png", "eng")?;
    
    // Frame OCR
    let text = ocr_from_frame(&data, 800, 600, 3, 2400, "eng")?;
  6. Perform OCR and extract text

    master

    To extract text from an image, you must first call .recognize() to process the image, then call a getter method to retrieve the results.

    Available extraction methods:

    • get_text(): Returns the recognized text as a String.
    • get_hocr_text(page: i32): Returns text encoded as HTML with bounding box tags.
    • get_tsv_text(page: i32): Returns text encoded as TSV, including bounding boxes and confidence scores.

    You can also check the overall confidence using mean_text_conf().

    let text = Tesseract::new(None, Some("eng"))?
        .set_image("image.png")?
        .recognize()?
        .get_text()?;
    
    println!("Recognized text: {}", text);
  7. Configure Tesseract settings

    master

    You can fine-tune the OCR process using the following methods:

    • set_variable(name: &str, value: &str): Sets a Tesseract configuration variable (e.g., tessedit_char_blacklist).
    • set_page_seg_mode(mode: PageSegMode): Sets the page segmentation mode.
    • set_rectangle(left, top, width, height): Limits OCR to a specific rectangular area of the image.
    • set_source_resolution(ppi: i32): Sets the source image resolution in PPI.
    tess.set_variable("tessedit_char_blacklist", "0123456789")?;
    tess.set_page_seg_mode(PageSegMode::SingleColumn);
    tess.set_rectangle(0, 0, 100, 100);
    tess.set_source_resolution(72);
  8. Reference: TesseractError types

    master

    The TesseractError enum captures all possible failures during the OCR process. Common error variants include:

    • InitializeError: Failed to set language or initialize the API.
    • SetImageError: Failed to read an image file.
    • RecognizeError: Error during the recognition phase.
    • GetTextError: Error retrieving UTF-8 text.
    • GetHOCRTextError: Error retrieving HOCR text.
    • GetTsvTextError: Error retrieving TSV text.
    • SetVariableError: Error setting a configuration variable.
  9. Configure Page Segmentation Modes with `PageSegMode`

    master

    The PageSegMode enum allows you to configure how the Tesseract OCR engine analyzes the layout of an image. Choosing the correct mode is critical for accurate text recognition depending on whether your image contains a single word, a single line, a full page, or sparse text.

    Available modes include:

    VariantDescription
    PsmOsdOnlyOrientation and script detection only.
    PsmAutoOsdAutomatic page segmentation with orientation and script detection (OSD).
    PsmAutoOnlyAutomatic page segmentation, but no OSD or OCR.
    PsmAutoFully automatic page segmentation, but no OSD.
    PsmSingleColumnAssume a single column of text of variable sizes.
    PsmSingleBlockVertTextAssume a single uniform block of vertically aligned text.
    PsmSingleBlockAssume a single uniform block of text (Default).
    PsmSingleLineTreat the image as a single text line.
    PsmSingleWordTreat the image as a single word.
    PsmCircleWordTreat the image as a single word in a circle.
    PsmSingleCharTreat the image as a single character.
    PsmSparseTextFind as much text as possible in no particular order.
    PsmSparseTextOsdSparse text with orientation and script detection.
    PsmRawLineTreat the image as a single text line, bypassing Tesseract-specific hacks.
    use tesseract_rs::PageSegMode;
    
    // Example of selecting a mode
    let mode = PageSegMode::PsmSingleWord;