leptess

repository·master·Indexed 43 days ago

https://github.com/houqp/leptess

Productive and safe Rust bindings for the Tesseract OCR engine and the Leptonica image processing library. Version 0.14.0 provides APIs for image loading via Pix, text extraction in multiple formats (UTF-8, hOCR, ALTO, TSV), and fine-grained OCR configuration using the Variable enum.

Tokens
11.3K
Snippets
21
Records
28
Agent score
49%

What's inside leptess

  1. Install build dependencies on Windows via vcpkg

    master

    On Windows, Leptess uses vcpkg to provide Tesseract. You must install vcpkg and set up user wide integration so the vcpkg crate can locate the libraries.

    To install Tesseract via vcpkg:

    REM 32 bit
    .\vcpkg install tesseract:x86-windows
    
    REM 64 bit
    .\vcpkg install tesseract:x64-windows

    To run tests on Windows, configure vcpkg-crate to find the dynamic library:

    SET VCPKGRS_DYNAMIC=true
    cargo test
    .
    vcpkg install tesseract:x64-windows
  2. Install build dependencies for Leptess

    master

    Leptess requires clang, Leptonica, and Tesseract (version 4.0.0 or above) to be installed on your system. The installation method depends on your operating system.

    ### Ubuntu
    ```bash
    sudo apt-get install libleptonica-dev libtesseract-dev clang
    sudo apt-get install tesseract-ocr-eng

    Mac

    brew install tesseract leptonica pkg-config
  3. Use the high-level LepTess wrapper for OCR

    master

    The LepTess struct provides a productive and memory-safe high-level wrapper for performing OCR tasks. It manages the underlying Tesseract and Leptonica interactions.

    Full page OCR

    To perform OCR on an entire image file:

    let mut lt = leptess::LepTess::new(Some("./tests/tessdata"), "eng").unwrap();
    lt.set_image("./tests/di.png");
    println!("{}", lt.get_utf8_text().unwrap());

    OCR on a specific region

    To restrict OCR to a specific rectangular area of the image, use set_rectangle before extracting text:

    let mut lt = leptess::LepTess::new(Some("./tests/tessdata"), "eng").unwrap();
    lt.set_image("./tests/di.png");
    lt.set_rectangle(10, 10, 200, 60); // left, top, width, height
    println!("{}", lt.get_utf8_text().unwrap());
    let mut lt = leptess::LepTess::new(Some("./tests/tessdata"), "eng").unwrap();
    lt.set_image("./tests/di.png");
    println!("{}", lt.get_utf8_text().unwrap());
  4. Perform OCR using TessApi

    master

    The standard workflow for Optical Character Recognition (OCR) involves three steps:

    1. Load an image using set_image with a leptonica::Pix object.
    2. (Optional) Set a specific region of interest using set_rectangle or set_rectangle_from_box.
    3. Extract text using one of the get_*_text methods.

    Note: set_image clears previous results and resets the recognition rectangle to the full image size.

    let path = std::path::Path::new("image.png");
    let img = leptess::leptonica::pix_read(&path).unwrap();
    
    let mut tes = leptess::tesseract::TessApi::new(Some("tests/tessdata"), "eng").unwrap();
    
    // 1. Provide the image
    tes.set_image(&img);
    
    // 2. Extract UTF-8 text
    let text = tes.get_utf8_text().unwrap();
  5. Extract bounding boxes for components

    master

    You can retrieve bounding boxes for different levels of components (such as blocks, textlines, or words) using get_component_boxes. This returns a leptonica::Boxa object containing the boxes in reading order.

    let mut lt = leptess::LepTess::new(None, "eng").unwrap();
    lt.set_image("./tests/di.png");
    let boxes = lt.get_component_boxes(
        leptess::capi::TessPageIteratorLevel_RIL_WORD,
        true,
    ).unwrap();
    
    for b in &boxes {
        println!("{:?}", b);
    }
    let mut lt = leptess::LepTess::new(None, "eng").unwrap();
    lt.set_image("./tests/di.png");
    let boxes = lt.get_component_boxes(
        leptess::capi::TessPageIteratorLevel_RIL_WORD,
        true,
    ).unwrap();
    
    for b in &boxes {
        println!("{:?}", b);
    }
  6. Basic OCR usage with LepTess

    master

    To perform OCR, initialize a LepTess instance with an optional configuration and a language code (e.g., "eng"), load an image using set_image, and retrieve the text using get_utf8_text.

    let mut lt = leptess::LepTess::new(None, "eng").unwrap();
    lt.set_image("path/to/page.bmp");
    println!("{}", lt.get_utf8_text().unwrap());
  7. Configure Tesseract variables with set_variable

    master

    Use set_variable to modify internal Tesseract parameters. This allows you to control behavior like character blacklists.

    let mut lt = leptess::LepTess::new(None, "eng").unwrap();
    lt.set_variable(leptess::Variable::TesseditCharBlacklist, "xyz").unwrap();
    let mut lt = leptess::LepTess::new(None, "eng").unwrap();
    lt.set_variable(leptess::Variable::TesseditCharBlacklist, "xyz").unwrap();
  8. Extract component regions with get_component_images

    master

    To identify specific layout components (like blocks, text lines, or words), use get_component_images. This returns a leptonica::Boxa containing the bounding boxes in reading order.

    • level: A TessPageIteratorLevel indicating the granularity (e.g., TessPageIteratorLevel_RIL_BLOCK).
    • text_only: A boolean. If true, only components containing text are returned.

    get_regions() is a convenience method that returns blocks (TessPageIteratorLevel_RIL_BLOCK) regardless of whether they contain text.

  9. Extract different text formats with TessApi

    master

    Depending on your needs, TessApi provides several methods to retrieve recognized text in different formats. All these methods return a Result<String, std::str::Utf8Error> and require a page index (as a c_int).

    • get_utf8_text(): Standard UTF-8 plain text.
    • get_hocr_text(page): Text in hOCR format.
    • get_alto_text(page): Text in ALTO format.
    • get_tsv_text(page): Text in TSV format.
    • get_lstm_box_text(page): LSTM box text.
    • get_word_str_box_text(page): Word string box text.
  10. Get bounding box dimensions with `Box::get_geometry`

    master

    The Box struct represents a single bounding box. You can retrieve its spatial properties using get_geometry(), which returns a BoxGeometry struct containing:

    • x: The x-coordinate (i32).
    • y: The y-coordinate (i32).
    • w: The width (i32).
    • h: The height (i32).
    let geometry = b.get_geometry();
    println!("X: {}, Y: {}, W: {}, H: {}", geometry.x, geometry.y, geometry.w, geometry.h);
  11. Get image dimensions and resolution

    master

    You can query metadata about the currently loaded image via TessApi:

    • get_image_dimensions(): Returns Option<(u32, u32)> representing the width and height. Returns None if no image is loaded.
    • get_source_y_resolution(): Returns the current Y resolution as an i32.
    • set_source_resolution(res): Overrides the image resolution. This is useful for suppressing "Warning: Invalid resolution 0 dpi" messages.