Cómo entrenar fuentes personalizadas para Tesseract 5 en C#

C# Custom Font Training for Tesseract 5 (for Windows Users)

This article was translated from English: Does it need improvement?
Translated
View the article in English

Utilize custom font training for Tesseract 5 to improve the accuracy and recognition capabilities of the OCR engine when working with specific fonts or font styles that may not be well-supported by default.

The process involves providing Tesseract with training data, such as font samples and corresponding text, so that it can learn the specific characteristics and patterns of the custom fonts.

Quickstart: Use Your .traineddata Font File in C#

Here’s how you can use your custom-trained Tesseract font file in IronOCR in just a couple of lines. Ideal for getting accurate OCR for special or decorative fonts fast.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronOCR with NuGet Package Manager

    PM > Install-Package IronOcr

  2. Copy and run this code snippet.

    var ocr = new IronOcr.IronTesseract();
    ocr.UseCustomTesseractLanguageFile("path/to/YourCustomFont.traineddata");
    string text = ocr.Read(new IronOcr.OcrInput("image-with-special-font.png")).Text;
  3. Deploy to test on your live environment

    Start using IronOCR in your project today with a free trial
    arrow pointer

Step 1: Download the Latest Version of IronOCR

Install via DLL

Download the IronOcr DLL directly to your machine.

Install via NuGet

Alternatively, you can install through NuGet with the following command:

Install-Package IronOcr

Step 2: Install and Set Up WSL2 and Ubuntu

Refer to the tutorial on Setting up WSL2 and Ubuntu.

Por favor notaCustom font training can currently be done only on Linux.

Step 3: Install Tesseract 5 on Ubuntu

Use the following commands to install Tesseract 5:

sudo apt install tesseract-ocr
sudo apt install libtesseract-dev
sudo apt install tesseract-ocr
sudo apt install libtesseract-dev
SHELL

Step 4: Download the Font You Would Like to Train

We are using the AMGDT font for this tutorial. The font file can be either .ttf or .otf. Example of downloaded font file

Step 5: Mount the Disk Drive of Your Working Space for Custom Font Training

Use the commands below to mount Drive D: as your working space.

cd /
cd /mnt/d
cd /
cd /mnt/d
SHELL

Step 6: Copy the Font File to Ubuntu Font Folder

Copy the font file to the following Ubuntu directories: /usr/share/fonts and /usr/local/share/fonts.

Access files in Ubuntu by typing \\wsl$ in the file explorer's address bar.

Ubuntu folder directory

Troubleshooting: Destination Folder Access Denied

If you encounter access denied errors, resolve this by using the command line to copy the files.

cd /
su root
cd /c/Users/Admin/Downloads/'AMGDT Regular'
cp 'AMGDT Regular.ttf' /usr/share/fonts
cp 'AMGDT Regular.ttf' /usr/local/share/fonts
exit
cd /
su root
cd /c/Users/Admin/Downloads/'AMGDT Regular'
cp 'AMGDT Regular.ttf' /usr/share/fonts
cp 'AMGDT Regular.ttf' /usr/local/share/fonts
exit
SHELL

Step 7: Clone tesseract_tutorial from GitHub

Clone the tesseract_tutorial repository using the following command:

git clone https://github.com/astutejoe/tesseract_tutorial.git
git clone https://github.com/astutejoe/tesseract_tutorial.git
SHELL

Step 8: Clone tesstrain and tesseract from GitHub

Navigate to the tesseract_tutorial directory, then clone the tesstrain and tesseract repositories:

git clone https://github.com/tesseract-ocr/tesstrain
git clone https://github.com/tesseract-ocr/tesseract
git clone https://github.com/tesseract-ocr/tesstrain
git clone https://github.com/tesseract-ocr/tesseract
SHELL
  • tesstrain contains the "Makefile" used to create the .traineddata file.
  • tesseract contains the "tessdata" folder, which includes original .traindata files used for reference during custom font training.

Step 9: Create a "data" Folder for Storing Outputs

Create a "data" folder within tesseract_tutorial/tesstrain.

Step 10: Run split_training_text.py

Return to the tesseract_tutorial folder and execute the following command:

python split_training_text.py
python split_training_text.py
SHELL

After running split_training_text.py, it will create .box and .tif files in the "data" folder.

Troubleshooting: Fontconfig Warning

Font Config Warning If you see the warning Fontconfig warning: "/tmp/fonts.conf, line 4: empty font directory name ignored", it is due to missing font directories. Solve this by editing the tesseract_tutorial/fonts.conf file and adding:

<dir>/usr/share/fonts</dir>
<dir>/usr/local/share/fonts</dir>
<dir prefix="xdg">fonts</dir>
<!-- the following element will be removed in the future -->
<dir>~/.fonts</dir>
<dir>/usr/share/fonts</dir>
<dir>/usr/local/share/fonts</dir>
<dir prefix="xdg">fonts</dir>
<!-- the following element will be removed in the future -->
<dir>~/.fonts</dir>
XML

Copy it to /etc/fonts with:

cp fonts.conf /etc/fonts
cp fonts.conf /etc/fonts
SHELL

Additionally, update split_training_text.py:

fontconf_dir = '/etc/fonts'
fontconf_dir = '/etc/fonts'
PYTHON

Note: Number of Training (.box and .tif) Files

The current number of training files is set to 100. You can modify this in split_training_text.py.

Set the Number of Training Files

Step 11: Download eng.traineddata

Download eng.traineddata from this repository and place it in tesseract_tutorial/tesseract/tessdata.

Step 12: Create Your Custom Font .traineddata

Navigate to the tesstrain folder and use the command below in WSL2:

TESSDATA_PREFIX=../tesseract/tessdata make training MODEL_NAME=AMGDT START_MODEL=eng TESSDATA=../tesseract/tessdata MAX_ITERATIONS=100
TESSDATA_PREFIX=../tesseract/tessdata make training MODEL_NAME=AMGDT START_MODEL=eng TESSDATA=../tesseract/tessdata MAX_ITERATIONS=100
SHELL
  • MODEL_NAME is your custom font name.
  • START_MODEL is the original .traineddata reference.
  • MAX_ITERATIONS defines the number of iterations (more iterations can improve the accuracy of .traineddata).

Troubleshooting: "Failed to Read Data" in Makefile

To resolve "Failed to read data" issues, modify the Makefile:

WORDLIST_FILE := $(OUTPUT_DIR2)/$(MODEL_NAME).lstm-word-dawg
NUMBERS_FILE := $(OUTPUT_DIR2)/$(MODEL_NAME).lstm-number-dawg
PUNC_FILE := $(OUTPUT_DIR2)/$(MODEL_NAME).lstm-punc-dawg

Troubleshooting: "Failed to Load Script Unicharset"

Insert Latin.unicharset into the tesstrain/data/langdata folder. The Latin.unicharset can be found here.

Step 13: Verify the Accuracy of Created .traineddata

With 1000 .box and .tif files and 3000 iterations of training, the output .traineddata (AMGDT.traineddata) achieves a minimal training error rate (BCER) of around 5.77.

Traineddata Accuracy

For further reading and reference, see the tutorial: YouTube Video

Preguntas Frecuentes

¿Cómo puedo entrenar una fuente personalizada para usar con Tesseract en C#?

Para entrenar una fuente personalizada para Tesseract usando C#, primero debes descargar IronOCR, preparar tu archivo de fuente, y configurar un entorno Linux a través de WSL2 y Ubuntu en Windows, ya que el entrenamiento de fuentes personalizadas de Tesseract sólo es compatible en Linux.

¿Cuáles son los pasos para instalar Tesseract 5 en un sistema Windows usando WSL2?

Para instalar Tesseract 5 en Windows usando WSL2, debes configurar Ubuntu y luego usar los comandos sudo apt install tesseract-ocr y sudo apt install libtesseract-dev para completar la instalación.

¿Qué debo hacer si encuentro errores de 'Acceso Denegado a la Carpeta de Destino' al copiar archivos de fuentes?

Si enfrentas errores de 'Acceso Denegado a la Carpeta de Destino', utiliza la línea de comandos con acceso root para copiar los archivos de fuentes en los directorios necesarios y evitar problemas de permisos.

¿Por qué es necesario un entorno Linux para el entrenamiento de fuentes personalizadas en Tesseract?

Se requiere un entorno Linux para el entrenamiento de fuentes personalizadas en Tesseract porque las herramientas de entrenamiento están diseñadas para ejecutarse en sistemas tipo Unix, y WSL2 puede usarse para emular este entorno en Windows.

¿Cómo soluciono los errores de 'advertencia de Fontconfig' al entrenar fuentes personalizadas?

Para resolver los errores de 'advertencia de Fontconfig', debes añadir las rutas del directorio de fuentes al archivo fonts.conf y asegurar que se copie al directorio /etc/fonts.

¿Cuál es el propósito del repositorio 'tesstrain' en el entrenamiento de fuentes personalizadas?

El repositorio 'tesstrain' se utiliza para crear el archivo .traineddata necesario para el entrenamiento de fuentes personalizadas en Tesseract, proporcionando los scripts y el Makefile necesarios para el proceso.

¿Cómo puedo resolver el error 'Falló al Cargar el Script Unicharset'?

Para solucionar el error 'Falló al Cargar el Script Unicharset', debes insertar el Latin.unicharset en la carpeta tesstrain/data/langdata para asegurar que el conjunto de caracteres necesario esté disponible.

¿Cómo verifico la precisión de mis datos entrenados personalizados en Tesseract?

Puedes verificar la precisión de tus datos entrenados personalizados comprobando la tasa de error de entrenamiento, conocida como BCER, y asegurándote de que sea mínima después de suficientes iteraciones y ajustes de los archivos de entrenamiento.

Kannaopat Udonpant
Ingeniero de Software
Antes de convertirse en Ingeniero de Software, Kannapat completó un doctorado en Recursos Ambientales de la Universidad de Hokkaido en Japón. Mientras perseguía su grado, Kannapat también se convirtió en miembro del Laboratorio de Robótica de Vehículos, que es parte del Departamento de Ingeniería ...
Leer más
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 5,044,537 | Versión: 2025.11 recién lanzado