tesseract-rs
repository·master·Indexed 41 days ago
https://github.com/antimatter15/tesseract-rsHigh-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.
What's inside tesseract-rs
- tesseract-rs provides Rust bindings for the Tesseract OCR engine. It allows Rust developers to integrate Tesseract's optical character recognition capabilities into their applications.
Set the OCR Engine Mode (OEM)
masterThe
OcrEngineModeenum 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 toOEM_TESSERACT_ONLY.
```rust use tesseract::{Tesseract, OcrEngineMode}; let mut tess = Tesseract::new_with_oem( None, Some("eng"), OcrEngineMode::LstmOnly )?;Initialize the Tesseract engine
masterUse
Tesseract::neworTesseract::new_with_oemto create a new OCR engine instance. You can optionally specify adatapath(the path to training data) and alanguage(e.g., "eng").If you need to specify the OCR Engine Mode (OEM), use
new_with_oemwith anOcrEngineModevalue.```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 )?;Convert `PageSegMode` to Tesseract internal type
masterIf you are working with low-level bindings or need the raw Tesseract value, use the
as_tess_page_seg_mode()method on aPageSegModeinstance. This returns the underlyingTessPageSegModetype used by the Tesseract C API.let mode = PageSegMode::PsmSingleBlock; let tess_mode = mode.as_tess_page_seg_mode();Load images for OCR
masterThe
Tesseractstruct 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)?;Use high-level OCR helper functions
masterFor 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")?;Perform OCR and extract text
masterTo 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 aString.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);Configure Tesseract settings
masterYou 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);Reference: TesseractError types
masterThe
TesseractErrorenum 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.
Configure Page Segmentation Modes with `PageSegMode`
masterThe
PageSegModeenum 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:
Variant Description 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;