Sub topic 7
Selecting Languages and Trained Data
Tesseract's recognizer is a trained model, and the language setting decides which model it loads. This chapter covers what a "language" is in Tesseract, how to install and select models, how to combine them, and which errors to expect. It assumes you can already run pytesseract.image_to_string on an image (earlier chapters in this tutorial) and know what a page segmentation mode is.
What a language setting selects
Tesseract does not detect the language of the text. You tell it which model to use, and it recognizes characters with that model. The model lives in a .traineddata file named after a language code, such as eng.traineddata or deu.traineddata.
A .traineddata file is a bundle of data. In current Tesseract versions (4 and later) the main part is a neural network, an LSTM (long short-term memory network), that reads a line of text image and outputs characters. The file also holds the character set the network can output (its "unicharset"), and it can hold dictionaries and word lists used to bias results toward real words.
The character set matters most. A model can only output characters it was trained on. If you run the English model on a German invoice, it has no ü or ß to output. It will pick the closest English characters, so Straße may come back as StraBe. The model does not report an error, because it cannot tell that anything is missing.
The same applies to scripts. The English model cannot read Cyrillic, Arabic, or Chinese text at all. It returns garbage or an empty string.
Language codes and script models
Tesseract uses three-letter codes, mostly ISO 639-2 style codes. Some examples:
| Code | Content |
|---|---|
| `eng` | English |
| `deu` | German |
| `fra` | French |
| `spa` | Spanish |
| `rus` | Russian (Cyrillic) |
| `chi_sim` | Simplified Chinese |
| `chi_tra` | Traditional Chinese |
| `jpn` | Japanese |
| `ara` | Arabic |
Some files do not name a language. Script models such as Latin, Cyrillic, Arabic, and Greek cover a whole writing system. Latin handles text in many Latin-alphabet languages, though without language-specific dictionaries. A script model suits mixed or unknown languages that share one alphabet. A language model usually does better when you know the language.
A special file, osd.traineddata, is used for orientation and script detection (OSD). It does not recognize text. It estimates page rotation and the dominant script, and it is used with --psm 0.
Where the files live
Tesseract looks for .traineddata files in a directory commonly called tessdata. The location depends on how you installed it:
- Debian and Ubuntu packages usually use
/usr/share/tesseract-ocr/<version>/tessdata. - Homebrew on macOS uses a path under the Homebrew prefix, such as
/opt/homebrew/share/tessdata. - Windows installers use a
tessdatafolder inside the install directory.
You can override the location with the TESSDATA_PREFIX environment variable. Its meaning changed between versions. In Tesseract 4 and later it should point to the tessdata directory itself. In 3.x it pointed to the parent directory. A wrong value is a common cause of load errors.
You can also pass the directory per call with --tessdata-dir. This is useful when you keep models in your project instead of installing them system-wide.
Listing what is installed
Before you choose a language, check what Tesseract can see. pytesseract.get_languages runs tesseract --list-langs for you.
import pytesseract
print(pytesseract.get_languages(config=""))The result is a list of codes such as ['eng', 'osd']. If the language you need is missing, install it. On Debian or Ubuntu, packages are named tesseract-ocr-<code>, for example tesseract-ocr-deu. On other systems, download the file from the official tessdata repositories and place it in the tessdata directory.
Selecting one or several languages
Pass the code with the lang argument:
import pytesseract
from PIL import Image
image = Image.open("german_letter.png")
text = pytesseract.image_to_string(image, lang="deu")
print(text)To read text that mixes languages, join codes with +:
import pytesseract
from PIL import Image
image = Image.open("bilingual_menu.png")
text = pytesseract.image_to_string(image, lang="eng+fra")
print(text)The order matters a little. The first language is the primary one, and it is the one whose settings take precedence where models disagree. Put the dominant language first.
Combining models is not free. Each extra model costs these things:
- Load time and memory. Every model is loaded for each engine start.
- Speed. Recognition runs with a larger set of possible outputs, so it is slower.
- Accuracy. With more candidate characters and words, the engine has more ways to be wrong. Two languages that share similar letters can pull results toward the wrong dictionary.
Use the smallest set of languages that covers your documents. If you can route documents by language before OCR, for example by user setting or by file source, do that instead of loading many models for every image.
Choosing between model variants
The official repositories publish three sets of trained data, and they differ in size, speed, and accuracy.
| Set | Contents | Trade-off |
|---|---|---|
| `tessdata` | Standard models with the LSTM and the legacy engine data | Default for many packages, supports `--oem 0` |
| `tessdata_fast` | Smaller integer-quantized LSTM models | Faster and smaller, slightly less accurate |
| `tessdata_best` | Float LSTM models | Most accurate, slowest, LSTM only |
Distribution packages often ship the fast variant or a mix, so two machines with "English installed" can give different results. If accuracy matters and you can afford the time, try tessdata_best on a sample of your documents and measure the difference with the character error rate you will see later in this tutorial. Do not assume the best set is worth its cost for your data.
Models from tessdata_best do not include the legacy engine. If you request --oem 0 (legacy) with them, Tesseract fails. Use --oem 1 (LSTM only) or leave the default.
Loading models from a custom directory
To use a project-local set of models, point Tesseract at the directory:
from pathlib import Path
import pytesseract
from PIL import Image
model_dir = Path("models/tessdata_best").resolve()
config = f'--tessdata-dir "{model_dir}" --oem 1 --psm 6'
image = Image.open("german_letter.png")
text = pytesseract.image_to_string(image, lang="deu", config=config)
print(text)The quotes around the path matter on systems where it may contain spaces. pytesseract splits the config string the way a shell would, so the quoted path stays in one piece.
Comparing languages on your own images
When you are unsure which setting works best, measure it. Mean word confidence is a quick signal, although it is not accuracy. A model can be confidently wrong, so confirm with a ground-truth comparison when you can.
import cv2
import pytesseract
from pytesseract import Output
def mean_confidence(image, lang):
data = pytesseract.image_to_data(image, lang=lang, output_type=Output.DICT)
scores = []
for word, conf in zip(data["text"], data["conf"]):
conf = float(conf)
if word.strip() and conf >= 0:
scores.append(conf)
return sum(scores) / len(scores) if scores else 0.0
image = cv2.imread("german_letter.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
for lang in ["eng", "deu", "eng+deu"]:
print(lang, round(mean_confidence(gray, lang), 1))Run this on a handful of representative images. If deu clearly beats eng on German pages, the language setting is doing real work. If eng+deu is only marginally better than deu, the extra model is probably not worth its cost.
Decision flow
The diagram shows one way to pick a configuration.
Narrowing the character set
Sometimes you know more than the language. If a field only holds digits, such as an invoice number or a postcode, you can restrict the characters the engine may output:
import pytesseract
text = pytesseract.image_to_string(
"invoice_number.png",
lang="eng",
config="--psm 7 -c tessedit_char_whitelist=0123456789",
)
print(text.strip())This turns O into 0 and l into 1 automatically, because letters are not allowed. Whitelisting works reliably with the LSTM engine in Tesseract 4.1 and later, but it was broken in some 4.0 releases, so check your version with tesseract --version. Use it only on crops that you know contain only the allowed characters. On free text it deletes legitimate characters.
Common errors
Error opening data file ... eng.traineddata or Failed loading language 'xyz'. The file is not in the directory Tesseract is searching. Check TESSDATA_PREFIX, run get_languages, and confirm the file name matches the code exactly, including case (chi_sim, not chi-sim).
Garbled output on a non-Latin page. You used a Latin model on another script. Select the correct language or script model.
Missing accents and special letters. The model's character set lacks them. For example, eng on French text drops é or ç in many cases. Use fra or eng+fra.
Results differ between machines. The installed model sets differ (fast versus best) or the Tesseract versions differ. Pin the model files in your project and pass --tessdata-dir.
Warning about a failed OEM. You requested the legacy engine with LSTM-only data. Switch to --oem 1.
Slow runs after adding languages. You are loading several models per call. Reduce the list or split documents by language before OCR.
When Tesseract's language models are not enough
If your text is in a language with no good trained data, or it uses an unusual font such as a dot-matrix print or a stylized logo, accuracy can stay low even with the correct language. Tesseract supports fine-tuning a model on your own images and text, but this needs many labeled lines and some training tooling. Often a cheaper fix comes first: better preprocessing, a tighter page segmentation mode, or a whitelist for fields with a known format. If those fail, a deep-learning OCR engine, covered later in this tutorial, may handle your fonts and scripts better.
Exercise
A scanned form has English labels and handwritten-looking German names printed in Latin letters. You run lang="eng" and the names lose every ä, ö, and ü. What change do you try first, and what cost should you expect?
Show answer
Use lang="eng+deu" with eng first because the labels are English. The model for German adds the umlaut characters to the possible output. The cost is more memory, slower recognition, and some risk that English words are pulled toward German dictionary entries, so compare results on sample images before keeping it.
Exercise
Your code works on your laptop but raises Failed loading language 'deu' on a server. Name two checks you would make.
Show answer
Run pytesseract.get_languages(config="") (or tesseract --list-langs) on the server to see whether deu is installed, and check that TESSDATA_PREFIX points to the tessdata directory that contains deu.traineddata. Alternatively, install the deu file or pass --tessdata-dir to a project folder that includes it.
Exercise
Why might tessdata_best fail when you pass --oem 0?
Show answer
The best models contain only the LSTM network and not the legacy engine data. Legacy mode needs that data, so Tesseract cannot start. Use --oem 1 instead.