rusty-tesseract

repository·main·Indexed 41 days ago

https://github.com/thomasgruebl/rusty-tesseract

A Rust wrapper for Google Tesseract OCR version 1.1.10, providing access to text extraction, bounding box detection, and structured data output. It allows configuring the OCR engine via the Args struct (including language, DPI, PSM, and OEM) and supports various image formats such as JPEG, PNG, TIFF, and WEBP. The library provides functions to retrieve system information, including the installed Tesseract version and available language models.

Tokens
5.1K
Snippets
24
Records
26
Agent score
49%

What's inside rusty-tesseract

  1. Configure Tesseract OCR parameters via Args

    main

    When calling image_to_string, you can control the OCR behavior using the Args object. The following parameters can be configured:

    • lang: The language code to use (e.g., "eng").
    • dpi: Optional DPI setting (passed via --dpi).
    • psm: Page Segmentation Mode (passed via --psm).
    • oem: OCR Engine Mode (passed via --oem).
    • Config Variables: Additional Tesseract configuration variables can be passed using the -c flag via the get_config_variable_args() method on the Args object.
  2. Read an image for OCR

    main

    You can prepare an image for processing using the Image struct in two ways:

    1. From a file path: Use Image::from_path("path/to/image.png").
    2. From a DynamicImage: If you are using the image crate, use Image::from_dynamic_image(&dynamic_image).
    // using from_path
    let img = Image::from_path("img/string.png").unwrap();
    
    // using a DynamicImage from the image crate
    let dynamic_image = ImageReader::open("img/string.png")
        .unwrap()
        .decode()
        .unwrap();
    let img = Image::from_dynamic_image(&dynamic_image).unwrap();
  3. Configure Tesseract parameters with Args

    main

    Use the Args struct to customize the OCR engine behavior. If an optional field is set to None, the default value is used.

    Default values:

    • lang: "eng"
    • dpi: Some(150)
    • psm: Some(3)
    • oem: Some(3)

    Available Fields:

    • lang: The model language (e.g., "eng"). Use rusty_tesseract::get_tesseract_langs() to see available options.
    • config_variables: A HashMap of configuration variables (e.g., "tessedit_char_whitelist"). Use rusty_tesseract::get_tesseract_config_parameters() to see available keys.
    • dpi: The DPI for the input image.
    • psm: Page Segmentation Mode.
    • oem: Optical Character Recognition Engine Mode.
    let mut my_args = Args {
        lang: "eng",
        config_variables: HashMap::from([(
                "tessedit_char_whitelist".into(),
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".into(),
            ]),
        ]),
        dpi: Some(150),
        psm: Some(6),
        oem: Some(3),
    };
  4. Extract text, boxes, or data from an image

    main

    Depending on your needs, you can extract OCR results in three different formats:

    1. String output: Use image_to_string(&img, &args) to get the raw text.
    2. Bounding boxes: Use image_to_boxes(&img, &args) to get a BoxOutput. This requires the "makebox" parameter. It provides access to individual symbols and the full boxfile output.
    3. Structured data: Use image_to_data(&img, &args) to get a DataOutput. This requires the "TSV" parameter. It provides a list of data entries containing text and confidence scores (conf).
    // 1. String output
    let output = rusty_tesseract::image_to_string(&img, &my_args).unwrap();
    
    // 2. Box output (requires "makebox" parameter)
    let box_output = rusty_tesseract::image_to_boxes(&img, &my_args).unwrap();
    println!("Symbol: {}", box_output.boxes[0].symbol);
    
    // 3. Data output (requires "TSV" parameter)
    let data_output = rusty_tesseract::image_to_data(&img, &my_args).unwrap();
    let first_text_line = &data_output.data[4];
    println!("Text: {}, Confidence: {}", first_text_line.text, first_text_line.conf);
  5. Get Tesseract system information

    main

    Use these functions to inspect the underlying Tesseract installation:

    • get_tesseract_version(): Returns the installed Tesseract version.
    • get_tesseract_langs(): Returns a list of available language models.
    • get_tesseract_config_parameters(): Returns a list of available configuration parameters.
    let tesseract_version = rusty_tesseract::get_tesseract_version().unwrap();
    let tesseract_langs = rusty_tesseract::get_tesseract_langs().unwrap();
    let parameters = rusty_tesseract::get_tesseract_config_parameters().unwrap();
  6. Create an `Image` from a file path

    main

    Use Image::from_path to load an image from the filesystem. The method validates that the file extension is a supported format. Supported formats include:

    • JPEG / JPG
    • PNG
    • PBM
    • PGM
    • PPM
    • TIFF
    • BMP
    • GIF
    • WEBP

    If the format is unsupported or the path is invalid, it returns TessError::ImageFormatError or TessError::ImageNotFoundError.

    let image = Image::from_path("path/to/image.png")?;
  7. Retrieve Tesseract configuration parameters

    main

    You can programmatically retrieve the list of available Tesseract configuration parameters, their default values, and descriptions by calling get_tesseract_config_parameters(). This function executes the Tesseract binary with the --print-parameters flag and parses the output.

    It returns a ConfigParameterOutput struct containing:

    • output: The raw string output from the Tesseract command.
    • config_parameters: A vector of ConfigParameter objects representing each available setting.
    let config_output = get_tesseract_config_parameters()?;
    
    for param in config_output.config_parameters {
        println!("Parameter: {}, Default: {}", param.name, param.default_value);
    }
  8. Convert an image to bounding boxes with `image_to_boxes`

    main

    Use the image_to_boxes function to perform OCR and retrieve the bounding box coordinates for every detected symbol in an image. This function invokes Tesseract with the makebox argument. It returns a BoxOutput containing both the raw string output from Tesseract and a structured vector of Box objects.

    let img = Image::from_path("path/to/image.png")?;
    let mut args = Args::default();
    args.psm = Some(6); // Example: Set Page Segmentation Mode
    
    let result = image_to_boxes(&img, &args)?;
    
    for box_info in result.boxes {
        println!("Symbol: {}, Position: ({}, {}, {}, {})", 
            box_info.symbol, box_info.left, box_info.top, box_info.right, box_info.bottom);
    }
  9. Extract structured OCR data with image_to_data

    main

    Use the image_to_data function to perform OCR on an image and receive structured data containing text, confidence scores, and bounding box coordinates. This function returns a DataOutput object which contains both the raw string output and a vector of parsed Data objects.

    Arguments:

    • image: A reference to an Image object.
    • args: A reference to Args containing Tesseract configuration parameters (like psm).
    let img = Image::from_path("path/to/image.png").unwrap();
    let mut args = Args::default();
    args.psm = Some(6); // Example: Assume a single uniform block of text
    
    let result = image_to_data(&img, &args).unwrap();
    
    for entry in result.data {
        println!("Text: {}, Confidence: {}", entry.text, entry.conf);
        println!("Location: [{}, {}, {}, {}]", entry.left, entry.top, entry.width, entry.height);
    }
  10. Create an `Image` from a `DynamicImage`

    main

    If you are working with in-memory image data using the image crate, use Image::from_dynamic_image. This method saves the DynamicImage to a temporary .png file to make it accessible to the Tesseract process.

    Errors returned may include TessError::TempfileError or TessError::DynamicImageError.

    use image::DynamicImage;
    
    let dynamic_img: DynamicImage = // ... your image logic
    let image = Image::from_dynamic_image(&dynamic_img)?;