Last updated: February 5, 2025

<span aria-hidden="true" id="recognize-text-in-images-ocr-in-rust"></span>

# Recognize text in images (OCR) in Rust

![Tim Koschützki](/assets/images/teammates/avatar-tim-kos-1.jpg?dpl=dpl_B2d4XACVUtA1h8m6kRxZhWsda77Q)

#### Tim Koschützki

Co-founder · Berlin, Germany · Show bio

[](https://x.com/tim%5Fkos)[](https://github.com/tim-kos)

Optical Character Recognition (OCR) is a powerful technology that enables computers to extract text from images. In this DevTip, we explore implementing OCR in Rust using the Tesseract library and effective image processing techniques for accurate text extraction.

<span aria-hidden="true" id="introduction"></span>

## Introduction

Rust's performance and safety guarantees make it an excellent choice for implementing OCR solutions. Whether you are building a document processing system or adding text extraction capabilities to your application, Rust provides a robust ecosystem for handling these tasks efficiently.

<span aria-hidden="true" id="prerequisites"></span>

## Prerequisites

* Rust 1.70 or later
* Tesseract 5.0 or later
* pkg-config (for building)
* Basic knowledge of Rust and Cargo

<span aria-hidden="true" id="setting-up-the-project"></span>

## Setting up the project

First, create a new Rust project and add the required dependencies to your `Cargo.toml`:

```toml
[dependencies]
tesseract = "0.15"
image = "0.25"
anyhow = "1.0"

```

Ensure that you are using the latest versions of these crates for compatibility and performance.

<span aria-hidden="true" id="installing-tesseract"></span>

## Installing Tesseract

Before using the Rust bindings, install Tesseract on your system.

<span aria-hidden="true" id="on-ubuntudebian"></span>

### On Ubuntu/Debian

```bash
sudo apt-get install tesseract-ocr libtesseract-dev

```

<span aria-hidden="true" id="on-macos"></span>

### On macOS

```bash
brew install tesseract  # installs latest version 5.x

```

<span aria-hidden="true" id="basic-ocr-implementation"></span>

## Basic OCR implementation

This example demonstrates how to extract text from an image using Tesseract in Rust.

```rust
use anyhow::Result;
use tesseract::Tesseract;

fn main() -> Result<()> {
    // Initialize Tesseract for English language
    let mut ocr = Tesseract::new(None, Some("eng"))?;
    ocr.set_image("input.png")?;

    // Retrieve the extracted text
    let text = ocr.get_text()?;
    println!("{}", text);

    Ok(())
}

```

<span aria-hidden="true" id="handling-different-image-formats"></span>

## Handling different image formats

Preprocessing images can enhance OCR accuracy. The following function converts an image to grayscale, saves it temporarily, performs OCR, and then cleans up the temporary file.

```rust
use anyhow::Result;
use tesseract::Tesseract;
use image::DynamicImage;

fn prepare_image_for_ocr(image_path: &str) -> Result<String> {
    // Load the image and convert it to grayscale
    let img = image::open(image_path)?.grayscale();

    // Save the preprocessed image to a temporary file
    let temp_path = "temp_processed.png";
    img.save(temp_path)?;

    // Perform OCR on the processed image
    let mut ocr = Tesseract::new(None, Some("eng"))?;
    ocr.set_image(temp_path)?;
    let text = ocr.get_text()?;

    // Clean up the temporary file
    std::fs::remove_file(temp_path)?;
    Ok(text)
}

```

<span aria-hidden="true" id="advanced-ocr-configuration"></span>

## Advanced OCR configuration

Tesseract can be fine-tuned by specifying configuration options such as character whitelists or page segmentation modes.

```rust
use anyhow::Result;
use tesseract::Tesseract;

fn configure_ocr() -> Result<String> {
    let mut ocr = Tesseract::new(None, Some("eng"))?;
    ocr.set_variable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")?;
    ocr.set_variable("tessedit_pageseg_mode", "1")?;
    ocr.set_image("input.png")?;
    let text = ocr.get_text()?;
    Ok(text)
}

```

* The setting `tessedit_char_whitelist` restricts recognition to specified characters, reducing potential errors.
* Adjusting `tessedit_pageseg_mode` can optimize how Tesseract segments the image for various layouts.

<span aria-hidden="true" id="best-practices-for-ocr-in-rust"></span>

## Best practices for OCR in Rust

1. **Image Preprocessing**
   * Convert images to grayscale to enhance text visibility.
   * Ensure a resolution of at least 300 DPI for clear text.
   * Remove noise by applying image filters.
2. **Performance Optimization**
   * Use Rust's concurrency features to process multiple images in parallel.
   * Implement caching for frequently processed documents.
   * Consider batch processing when handling large volumes of images.
3. **Error Handling**

Proper error handling ensures your application gracefully handles issues during OCR operations.

```rust
use anyhow::{Context, Result};
use tesseract::Tesseract;

fn robust_ocr(image_path: &str) -> Result<String> {
    let mut ocr = Tesseract::new(None, Some("eng"))
        .context("Failed to initialize Tesseract")?;
    ocr.set_image(image_path)
        .context("Failed to load image")?;
    let text = ocr.get_text()
        .context("Failed to perform OCR")?;
    Ok(text)
}

```

<span aria-hidden="true" id="handling-multiple-languages"></span>

## Handling multiple languages

Tesseract supports multiple languages. This example demonstrates recognizing text in English, French, and German.

```rust
use anyhow::Result;
use tesseract::Tesseract;

fn multilingual_ocr(image_path: &str) -> Result<String> {
    // Initialize Tesseract with multiple languages: English, French, and German
    let mut ocr = Tesseract::new(None, Some("eng+fra+deu"))?;
    ocr.set_image(image_path)?;
    let text = ocr.get_text()?;
    Ok(text)
}

```

<span aria-hidden="true" id="conclusion"></span>

## Conclusion

Implementing OCR in Rust with Tesseract presents a robust solution for extracting text from images. Rust's safety and performance, combined with Tesseract's mature OCR capabilities, empower you to build efficient text extraction systems.

For added functionality, you can complement your OCR solution using Transloadit's[Document Processing Service](/services/document-processing.md).

<span aria-hidden="true" id="resources"></span>

## Resources

* [Tesseract Documentation⁠](https://tesseract-ocr.github.io/)
* [Rust image Crate Documentation⁠](https://docs.rs/image)
* [Tesseract Rust Bindings Documentation⁠](https://docs.rs/tesseract)

\#ocr#rust#tesseract#image-processing#document-processing-service

### 👩‍💻 Join 20k+ developers

Sign up for our [monthly newsletter](/newsletters.md) to receive direct links to 3 exclusive tech — and 2 product updates. No less, no more.

Your email:

Get access

## File uploading and encoding. Made simple.

Transloadit streamlines file handling for developers, trusted by brands like Coursera and The New York Times. We’re known for a reliable API, top-notch support, and a strong commitment to open source, with projects like [Uppy⁠](https://uppy.io) and [Tus⁠](https://tus.io) setting standards in file processing.

[Sign up](/c/)[Book a Demo](https://survey.typeform.com/to/kRg47Xi5)

No credit card needed · 5 GB included in the free plan

Cancel anytime
