Android OCR with Tesseract 5 and ML Kit: Build a Side-by-Side Comparison App

Tesseract 5 and ML Kit can both read a receipt on an Android phone without a network connection, and on the same 1400 × 1420 photo they disagree in ways that matter: ML Kit finished in a median 147 ms and read every line, while Tesseract 5.5.1 took 235 ms and misread the masked card number as VESAREL A021. This tutorial builds a Kotlin app that runs both engines on one image, switches between them with a tap, and shows the timings and text side by side so you can pick the right one for your own documents.

Android OCR app comparing Tesseract 5 and ML Kit on a receipt

What you’ll build: a single-screen Android app with three modes — Tesseract, ML Kit, and Compare. It loads a photo from the system picker, the camera, a shared intent, or a bundled receipt, runs the selected engine(s) sequentially, and renders a result card per engine with elapsed time, character/word/line counts, mean confidence, and copy/share actions. Compare mode adds a speed-ratio card and a “Fastest” badge.

Key Takeaways

  • Tesseract4Android 4.9.0 packages Tesseract 5.5.1 and Leptonica 1.85, so you get a current engine from a single Gradle dependency instead of building tess-two from source.
  • Tesseract still needs a real filesystem path containing a tessdata folder. On Android 10 and later that means app-private storage, so the 4 MB eng.traineddata ships in assets/ and is copied to filesDir on first use.
  • Decode images with ImageDecoder and ALLOCATOR_SOFTWARE. Hardware bitmaps cannot be read by Tesseract’s JNI bridge through AndroidBitmap_lockPixels.
  • ML Kit returns text blocks in detection order, which is not reading order for a receipt. Sorting line boxes by geometry before joining them makes the output comparable with Tesseract’s plain text.
  • Time only the recognition call, and run the engines one after another. Running both in parallel makes each engine fight for the same cores and invalidates the comparison.
  • In this sample, ML Kit was about 1.6× faster at steady state and more accurate on right-aligned prices, while Tesseract reported a higher mean confidence. Confidence scores are not comparable across engines.

Common Developer Questions

Can Tesseract OCR run fully offline on Android?

Yes. Tesseract4Android compiles Tesseract and Leptonica into native libraries, and recognition needs only the traineddata file on disk. The sample app ships tessdata_fast/eng.traineddata (4 MB) inside the APK, copies it to app-private storage, and never opens a socket during recognition.

Is ML Kit text recognition free and on-device?

Yes, for the bundled Latin recognizer: com.google.mlkit:text-recognition:16.0.1 includes the model inside your APK, so recognition runs on the device with no Play Services model download and no per-call cost. The unbundled Play Services variant is smaller but downloads the model on first use, which breaks offline-first apps.

Which engine reads a receipt more accurately?

In this sample, ML Kit. On the bundled receipt photo, ML Kit returned all 14 lines in reading order, including VISA **** 4021 and the right-aligned prices. Tesseract 5.5.1 merged the price column into the item lines and turned the masked card number into VESAREL A021. Treat that as one data point, not a general ranking: Tesseract’s strength is clean, flat scans, while ML Kit’s detector is built for photographed scenes.

How do I switch between Tesseract and ML Kit at runtime?

Keep both engines behind an OcrEngine interface, store an EngineSelection enum in the ViewModel, and map the segmented button to it. Each run asks the selection for its engine list, so Compare mode runs both while the single-engine modes run one. Results are cached per run, so switching modes after a run re-filters the existing cards instead of re-running OCR.

Why is Tesseract slower than ML Kit on the same image?

In five consecutive runs on an OPPO PLG110, the median was 235 ms for Tesseract and 147 ms for ML Kit on the same 1400 × 1420 receipt. Tesseract’s pipeline includes grayscale conversion, Otsu binarization, and layout analysis before recognition, while ML Kit uses a detector-plus-recognizer pipeline tuned for mobile. Timing scales with text density, so measure your own images before choosing.

Prerequisites

  • Android Studio with Android SDK 35 and JDK 17.
  • An Android device or emulator running API 24 or higher (arm64 for a physical phone).
  • Basic familiarity with Kotlin, ViewBinding, and coroutines.
  • A Tesseract English model: the sample uses tessdata_fast/eng.traineddata.

How Tesseract 5 and ML Kit differ on Android

  Tesseract 5.5.1 ML Kit Text Recognition v2
Packaging cz.adaptech.tesseract4android:tesseract4android:4.9.0 (JitPack) com.google.mlkit:text-recognition:16.0.1 (Google Maven)
Model delivery *.traineddata in your app, copied to internal storage Bundled in the APK (Latin), or downloaded with the unbundled variant
Languages Any tessdata language, combined with + (eng+deu) One recognizer per script (Latin, Chinese, Devanagari, Japanese, Korean)
Output Plain UTF-8 text, hOCR, TSV, per-word boxes Blocks → lines → elements, with optional element confidence
Layout handling Page segmentation modes Detector finds text regions first
License Apache 2.0 Google ML Kit terms

The practical difference is model ownership. With Tesseract you decide which traineddata files ship and where they live; the engine gives you raw text plus word-level boxes through ResultIterator. With ML Kit you get a model that is already optimized for phone photos, structured blocks with bounding boxes, and no model management, at the cost of a fixed set of scripts.

The 2014 version of this post built tesseract-android-tools from source with the NDK and pushed language files to external storage. That path no longer works: the Google Code repositories are gone, current NDKs reject the old Application.mk, and Android 10+ blocks the external tessdata path. Tesseract4Android plus scoped storage replaces all of it.

Step 1: Create the project and add both engines

Create an Empty Views Activity project with Kotlin and ViewBinding. Then add JitPack, because Tesseract4Android is not on Maven Central:

// settings.gradle.kts
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        // Tesseract4Android is published through JitPack.
        maven("https://jitpack.io")
    }
}

Add the dependencies and keep the traineddata file uncompressed so it can be copied byte for byte:

// app/build.gradle.kts
android {
    compileSdk = 35

    defaultConfig {
        minSdk = 24
        targetSdk = 35
    }

    androidResources {
        noCompress += "traineddata"
    }
}

dependencies {
    // Tesseract 5.5.1 + Leptonica 1.85, built with CMake.
    implementation("cz.adaptech.tesseract4android:tesseract4android:4.9.0")

    // ML Kit text recognition, bundled Latin model.
    implementation("com.google.mlkit:text-recognition:16.0.1")

    // .await() for the ML Kit Task API.
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.8.1")
}

Download eng.traineddata from the tessdata_fast repository and place it at app/src/main/assets/tessdata/eng.traineddata. The fast model is 4 MB and is accurate enough for receipts, labels, and documents; tessdata_best is roughly four times larger and slower.

Step 2: Put both engines behind one interface

The UI should not care which engine produced a string. Define a small contract and a result type that carries everything the cards display:

enum class EngineId(val displayName: String) {
    TESSERACT("Tesseract 5"),
    MLKIT("ML Kit")
}

enum class EngineSelection(val engines: List<EngineId>) {
    TESSERACT(listOf(EngineId.TESSERACT)),
    MLKIT(listOf(EngineId.MLKIT)),
    COMPARE(listOf(EngineId.TESSERACT, EngineId.MLKIT))
}

interface OcrEngine {
    val id: EngineId
    val detail: String
    suspend fun recognize(bitmap: Bitmap): OcrResult
    fun release()
}

data class OcrResult(
    val engineId: EngineId,
    val engineDetail: String,
    val text: String,
    val elapsedMs: Long,
    val meanConfidence: Int?
) {
    val charCount: Int = text.count { !it.isWhitespace() }
    val wordCount: Int = text.split(Regex("\\s+")).count { it.isNotBlank() }
    val lineCount: Int = text.lineSequence().count { it.isNotBlank() }
}

elapsedMs measures only the recognition call. Model loading, engine initialization, and bitmap decoding are excluded so repeated runs stay comparable.

Step 3: Run Tesseract 5 with a bundled model

TessBaseAPI.init() validates that the data path contains a tessdata subdirectory and throws IllegalArgumentException otherwise. On Android 10+ the only reliable location is app-private storage, so copy the asset out before initializing:

private fun ensureApi(): TessBaseAPI {
    api?.let { return it }

    val dataDir = File(context.filesDir, "tesseract")
    val tessdataDir = File(dataDir, "tessdata")
    if (!tessdataDir.exists() && !tessdataDir.mkdirs()) {
        throw IOException("Cannot create ${tessdataDir.absolutePath}")
    }

    val model = File(tessdataDir, "$LANGUAGE.traineddata")
    if (!model.exists() || model.length() == 0L) {
        copyAsset("tessdata/$LANGUAGE.traineddata", model)
    }

    val created = TessBaseAPI()
    if (!created.init(dataDir.absolutePath, LANGUAGE)) {
        created.recycle()
        throw IllegalStateException("Tesseract failed to load the $LANGUAGE model")
    }
    created.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO)
    api = created
    return created
}

Copy through a temporary file and rename, so a process death mid-copy cannot leave a truncated model behind. Then guard the native API with a mutex and measure only the recognition:

override suspend fun recognize(bitmap: Bitmap): OcrResult = mutex.withLock {
    withContext(Dispatchers.Default) {
        val tess = ensureApi()
        val startedAt = SystemClock.elapsedRealtime()
        tess.setImage(bitmap)
        val text = tess.getUTF8Text().orEmpty()
        val elapsedMs = SystemClock.elapsedRealtime() - startedAt

        OcrResult(id, detail, text, elapsedMs, tess.meanConfidence())
    }
}

PSM_AUTO lets Tesseract choose a page segmentation mode. For a single column of text, PSM_SINGLE_BLOCK often produces cleaner lines; for sparse text such as signs, try PSM_SPARSE_TEXT. Changing the mode is a one-line experiment with setPageSegMode.

Step 4: Run ML Kit and restore reading order

ML Kit’s Text object exposes blocks, lines, and elements. The block list is in detection order, not necessarily top-to-bottom: on a receipt with a centered header and right-aligned prices, the naive concatenation returns “Latte, Cappuccino, BLUE BOTTLE COFFEE, Butter Croissant…”. Sort the line boxes by geometry first:

private fun flatten(result: Text): String {
    val lines = result.textBlocks
        .flatMap { it.lines }
        .mapNotNull { line ->
            val box = line.boundingBox ?: return@mapNotNull null
            if (line.text.isBlank()) null else LineBox(box.top, box.bottom, box.left, line.text)
        }
        .sortedWith(compareBy({ it.top }, { it.left }))

    if (lines.isEmpty()) return result.text.orEmpty()

    val rows = mutableListOf<MutableList<LineBox>>()
    for (line in lines) {
        val row = rows.lastOrNull()
        val sameRow = row != null && abs(line.centerY - row.map { it.centerY }.average()) <
            maxOf(line.height, row.maxOf { it.height }) * 0.6f
        if (sameRow) row!!.add(line) else rows.add(mutableListOf(line))
    }

    return rows.joinToString("\n") { row ->
        row.sortedBy { it.left }.joinToString("  ") { it.text }
    }
}

Two lines count as the same visual row when their vertical centers are within 60% of the taller line’s height. Joining a row with two spaces keeps Latte and $4.75 on one line, which is what a person expects to read.

Convert the bitmap to an InputImage, await the Task, and average the element confidences when ML Kit provides them (the Latin model does not always, so the UI falls back to “n/a conf.”):

override suspend fun recognize(bitmap: Bitmap): OcrResult {
    val startedAt = SystemClock.elapsedRealtime()
    val text = recognizer.process(InputImage.fromBitmap(bitmap, 0)).await()
    val elapsedMs = SystemClock.elapsedRealtime() - startedAt
    return OcrResult(id, detail, flatten(text), elapsedMs, meanConfidence(text))
}

Android 13’s photo picker removes the storage permission from the flow entirely:

private val pickImage = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
    if (uri != null) loadImage(uri, getString(R.string.source_gallery))
}

binding.btnGallery.setOnClickListener {
    pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
}

For the camera, write the capture to a cache file exposed through FileProvider, and persist the pending URI in onSaveInstanceState because a heavy camera app can kill your process while it is in front:

val uri = FileProvider.getUriForFile(this, "$packageName.fileprovider", File(captureDir, fileName))
pendingCameraUri = uri
takePicture.launch(uri)

Decoding is where naive samples fail. BitmapFactory.decodeFile ignores EXIF rotation on older APIs, and a 12 MP photo costs about 48 MB as ARGB_8888. Both problems disappear with ImageDecoder on API 28+, plus an EXIF fallback for API 24–27:

@RequiresApi(Build.VERSION_CODES.P)
private fun decodeWithImageDecoder(context: Context, uri: Uri): Bitmap {
    val source = ImageDecoder.createSource(context.contentResolver, uri)
    return ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
        decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
        decoder.isMutableRequired = false
        decoder.setTargetSampleSize(sampleSizeFor(info.size.width, info.size.height))
    }
}

ALLOCATOR_SOFTWARE is not optional. ImageDecoder returns hardware bitmaps by default, and Tesseract reads pixels through JNI with AndroidBitmap_lockPixels, which fails on hardware-backed memory. The sample caps the long edge at 2000 px, which is plenty for OCR and keeps peak memory predictable.

The sample receipt is loaded from assets on first launch, so the app has something to recognize before the user grants anything:

object SampleImages {
    private const val RECEIPT_ASSET = "samples/receipt_sample.jpg"

    fun loadReceipt(context: Context): Bitmap =
        context.assets.open(RECEIPT_ASSET).use { BitmapFactory.decodeStream(it) }
}

Step 6: Time the engines and show the comparison

The ViewModel owns both engines and runs them one after another. Sequential execution is deliberate: parallel runs would make the two timings compete for the same cores and produce a misleading ratio.

for (engineId in _uiState.value.selection.engines) {
    _uiState.update { it.copy(activeEngine = engineId) }
    try {
        val result = engines.getValue(engineId).recognize(bitmap)
        collected += result
        _uiState.update { it.copy(results = collected.toList()) }
    } catch (cancellation: CancellationException) {
        throw cancellation
    } catch (error: Throwable) {
        _uiState.update { it.copy(error = "${engineId.displayName} failed: ${error.message ?: error.javaClass.simpleName}") }
    }
}

Results stream into the state as each engine finishes, so the first card appears while the second engine is still working. A coroutine ticks every 80 ms to update the elapsed label, and the result cards are rebuilt only when the payload changes, not on every tick.

The UI is a pinned gradient header with a MaterialButtonToggleGroup, an image card, the three source buttons, and a filled action button:

Android OCR app main screen with the bundled receipt

Switching the toggle changes EngineSelection, and the existing cards are filtered instead of re-running OCR. Compare mode adds the speed card:

Tesseract and ML Kit comparison with timings

Tesseract 5 vs ML Kit: measured results

The input is a photo of a receipt placed on a desk, 1400 × 1420 px, with right-aligned prices, a dashed separator, and a masked card number — the kind of layout that exposes differences in page analysis:

Sample receipt used for the comparison

Test device: OPPO PLG110 (MediaTek MT6993), Android 17, five consecutive runs after warm-up. The first run after install is excluded because ML Kit pays a one-time interpreter warm-up (about 290 ms).

Engine Median Range Characters Mean confidence Accuracy on this image
Tesseract 5.5.1 235 ms 232–242 ms 237 88% Merged prices into item lines; read VISA **** 4021 as VESAREL A021
ML Kit 16.0.1 147 ms 119–151 ms 238 86% Exact text, reading order preserved

The screenshots in this post show single runs; the table reports the medians.

Two things stand out. First, ML Kit’s advantage is not just speed: it preserves the two-column layout that Tesseract collapses, which is why its character count is one higher despite the same 14 lines. Second, confidence is not comparable across engines — Tesseract’s 88% is the mean per-word confidence from its own model, while ML Kit’s 86% averages element-level confidences that the Latin model does not always provide. Use confidence to compare runs of the same engine, not engines against each other.

Tesseract’s output is still usable for search or indexing. It found every item and every price; it merged the two columns and misread one masked number:

Tesseract 5 result with a misread card number

ML Kit keeps the receipt structure intact, including the card line and the prices on the right:

ML Kit result with accurate text

Supporting languages other than English

The sample bundles one English model to keep the APK small, but both engines handle many more languages. The work is different for each: Tesseract loads a language file you ship, while ML Kit needs a separate artifact and client per script.

Tesseract: ship additional traineddata files

Tesseract chooses its language in init() and accepts several models joined with +:

// English plus Simplified Chinese.
private const val LANGUAGE = "eng+chi_sim"

Copy every model you need into app/src/main/assets/tessdata/, then extract all of them on first use:

private val BUNDLED_MODELS = listOf("eng", "chi_sim")

private fun ensureModels(tessdataDir: File) {
    BUNDLED_MODELS.forEach { language ->
        val model = File(tessdataDir, "$language.traineddata")
        if (!model.exists() || model.length() == 0L) {
            copyAsset("tessdata/$language.traineddata", model)
        }
    }
}

The noCompress += "traineddata" rule from Step 1 keeps the files byte-identical, so copying stays fast. Call ensureModels(tessdataDir) from ensureApi() before init(). Sizes from tessdata_fast:

Model Language Size
eng English 4.1 MB
chi_sim Simplified Chinese 2.5 MB
jpn Japanese 2.5 MB
kor Korean 1.7 MB
deu German 1.5 MB
osd Orientation and script detection 10.6 MB

init() can be called again on an existing TessBaseAPI to switch languages at runtime; the next setImage() uses the new model. Two caveats: every model is loaded into memory, so eng+chi_sim+jpn costs more memory and initialization time than a single model, and a multi-language classifier is slightly less accurate than a dedicated one because it has to choose between scripts. If accuracy matters more than size, the tessdata_best models are roughly 3–5× larger and slower.

For phone photos that may be upside down, bundle osd.traineddata and switch to PSM_AUTO_OSD; Tesseract then detects orientation before recognition.

ML Kit: one recognizer per script

The default TextRecognizerOptions.DEFAULT_OPTIONS is the Latin model. It already reads English, German, French, Spanish, Portuguese, Italian, and other Latin-script languages, so most European apps need no extra dependency. Other scripts ship as separate artifacts:

implementation("com.google.mlkit:text-recognition-chinese:16.0.1")
implementation("com.google.mlkit:text-recognition-japanese:16.0.1")
implementation("com.google.mlkit:text-recognition-korean:16.0.1")
implementation("com.google.mlkit:text-recognition-devanagari:16.0.1")

Create the client that matches the script:

val recognizer = TextRecognition.getClient(ChineseTextRecognizerOptions.Builder().build())

JapaneseTextRecognizerOptions, KoreanTextRecognizerOptions, and DevanagariTextRecognizerOptions follow the same pattern. The returned Text object keeps the same blocks → lines → elements structure, so flatten() and the result card work without changes. You cannot mix scripts in one client: keep one recognizer per script, route by the user’s selection, and close the ones you no longer use.

Wire a language picker

Keep the choice in the ViewModel next to EngineSelection:

enum class MlKitScript { LATIN, CHINESE, JAPANESE, KOREAN, DEVANAGARI }

enum class OcrLanguage(val label: String, val tesseract: String, val script: MlKitScript) {
    ENGLISH("English", "eng", MlKitScript.LATIN),
    CHINESE_SIMPLIFIED("简体中文", "chi_sim", MlKitScript.CHINESE),
    GERMAN("Deutsch", "deu", MlKitScript.LATIN),
    JAPANESE("日本語", "jpn", MlKitScript.JAPANESE)
}

When the selection changes, re-initialize Tesseract with language.tesseract and call process() on the client for language.script. Show the active language in the result card subtitle; otherwise two screenshots taken in different languages look identical.

Common Issues & Edge Cases

init() throws “Data path must contain subfolder tessdata”. Pass the parent directory, not the tessdata folder itself: init(filesDir/tesseract, "eng") expects filesDir/tesseract/tessdata/eng.traineddata. Create the directory before the call, and verify the copy finished.

Tesseract returns empty text or crashes on a photo. Check the bitmap config first. Hardware bitmaps from ImageDecoder, Glide, or Coil cannot be locked by the native layer; decode with ALLOCATOR_SOFTWARE or call bitmap.copy(Bitmap.Config.ARGB_8888, false). Empty results on valid bitmaps usually mean the wrong PSM or a missing language file.

ML Kit returns lines in a strange order. The block list follows detection order. Sort lines by boundingBox.top and left, then group them into rows, as in Step 4. Do not assume result.text is reading order either.

The first ML Kit run is much slower. The first inference loads and warms the model. If you show a benchmark in your app, either warm up once at startup or label the first run separately.

The camera result never arrives. If the system kills your activity while the camera is open, the pending URI must survive in onSaveInstanceState; otherwise the TakePicture callback receives saved = true but no target to load.

The APK is huge. Tesseract4Android ships four ABIs (armeabi-v7a, arm64-v8a, x86, x86_64) and ML Kit’s bundled Latin model adds several megabytes. The debug build of this sample is about 79 MB. For release, use an App Bundle or splits { abi { ... } } to ship only arm64 to phones.

You removed INTERNET to guarantee offline behavior and now see SecurityException. ML Kit’s telemetry transport still schedules a job with a connectivity constraint. Keep ACCESS_NETWORK_STATE if you strip INTERNET, or leave both permissions in place; recognition itself never uses the network.

Only English is recognized. Add models to assets/tessdata and initialize with a + list such as eng+chi_sim; ML Kit needs a different artifact and client per script. See Supporting languages other than English.

Source Code

Get the complete sample project source code on GitHub