recognition_en.md 17.1 KB
Newer Older
1
# Text Recognition
K
Khanh Tran 已提交
2

3
- [1. Data Preparation](#DATA_PREPARATION)
W
WenmuZhou 已提交
4 5 6 7
    - [1.1 Costom Dataset](#Costom_Dataset)
    - [1.2 Dataset Download](#Dataset_download)
    - [1.3 Dictionary](#Dictionary)  
    - [1.4 Add Space Category](#Add_space_category)
W
WenmuZhou 已提交
8

9
- [2. Training](#TRAINING)
W
WenmuZhou 已提交
10
    - [2.1 Data Augmentation](#Data_Augmentation)
T
tink2123 已提交
11 12
    - [2.2 General Training](#Training)
    - [2.3 Multi-language Training](#Multi_language)
13
    - [2.4 Training with Knowledge Distillation](#kd)
W
WenmuZhou 已提交
14

15
- [3. Evaluation](#EVALUATION)
W
WenmuZhou 已提交
16

17 18
- [4. Prediction](#PREDICTION)
- [5. Convert to Inference Model](#Inference)
W
WenmuZhou 已提交
19 20

<a name="DATA_PREPARATION"></a>
21
## 1. Data Preparation
K
Khanh Tran 已提交
22 23


W
WenmuZhou 已提交
24
PaddleOCR supports two data formats:
T
tink2123 已提交
25 26
- `LMDB` is used to train data sets stored in lmdb format(LMDBDataSet);
- `general data` is used to train data sets stored in text files(SimpleDataSet):
K
Khanh Tran 已提交
27 28 29 30 31 32

Please organize the dataset as follows:

The default storage path for training data is `PaddleOCR/train_data`, if you already have a dataset on your disk, just create a soft link to the dataset directory:

```
W
WenmuZhou 已提交
33
# linux and mac os
34
ln -sf <path/to/dataset> <path/to/paddle_ocr>/train_data/dataset
W
WenmuZhou 已提交
35 36
# windows
mklink /d <path/to/paddle_ocr>/train_data/dataset <path/to/dataset>
K
Khanh Tran 已提交
37 38
```

W
WenmuZhou 已提交
39
<a name="Costom_Dataset"></a>
40
### 1.1 Costom Dataset
K
Khanh Tran 已提交
41 42 43 44 45

If you want to use your own data for training, please refer to the following to organize your data.

- Training set

W
WenmuZhou 已提交
46
It is recommended to put the training images in the same folder, and use a txt file (rec_gt_train.txt) to store the image path and label. The contents of the txt file are as follows:
K
Khanh Tran 已提交
47 48 49 50 51 52

* Note: by default, the image path and image label are split with \t, if you use other methods to split, it will cause training error

```
" Image file name           Image annotation "

W
WenmuZhou 已提交
53 54
train_data/rec/train/word_001.jpg   简单可依赖
train_data/rec/train/word_002.jpg   用科技让复杂的世界更简单
W
WenmuZhou 已提交
55
...
K
Khanh Tran 已提交
56 57 58 59 60 61
```

The final training set should have the following file structure:

```
|-train_data
W
WenmuZhou 已提交
62
  |-rec
W
WenmuZhou 已提交
63 64 65 66 67 68
    |- rec_gt_train.txt
    |- train
        |- word_001.png
        |- word_002.jpg
        |- word_003.jpg
        | ...
K
Khanh Tran 已提交
69 70 71 72 73 74 75 76
```

- Test set

Similar to the training set, the test set also needs to be provided a folder containing all images (test) and a rec_gt_test.txt. The structure of the test set is as follows:

```
|-train_data
W
WenmuZhou 已提交
77
  |-rec
K
Khanh Tran 已提交
78 79 80 81 82 83 84 85
    |-ic15_data
        |- rec_gt_test.txt
        |- test
            |- word_001.jpg
            |- word_002.jpg
            |- word_003.jpg
            | ...
```
W
WenmuZhou 已提交
86 87

<a name="Dataset_download"></a>
88
### 1.2 Dataset Download
W
WenmuZhou 已提交
89

T
tink2123 已提交
90
- ICDAR2015
W
WenmuZhou 已提交
91

T
tink2123 已提交
92 93
If you do not have a dataset locally, you can download it on the official website [icdar2015](http://rrc.cvc.uab.es/?ch=4&com=downloads).
Also refer to [DTRB](https://github.com/clovaai/deep-text-recognition-benchmark#download-lmdb-dataset-for-traininig-and-evaluation-from-here) ,download the lmdb format dataset required for benchmark
W
WenmuZhou 已提交
94 95 96 97 98 99 100 101 102 103

PaddleOCR provides label files for training the icdar2015 dataset, which can be downloaded in the following ways:

```
# Training set label
wget -P ./train_data/ic15_data  https://paddleocr.bj.bcebos.com/dataset/rec_gt_train.txt
# Test Set Label
wget -P ./train_data/ic15_data  https://paddleocr.bj.bcebos.com/dataset/rec_gt_test.txt
```

T
tink2123 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
PaddleOCR also provides a data format conversion script, which can convert ICDAR official website label to a data format
supported by PaddleOCR. The data conversion tool is in `ppocr/utils/gen_label.py`, here is the training set as an example:

```
# convert the official gt to rec_gt_label.txt
python gen_label.py --mode="rec" --input_path="{path/of/origin/label}" --output_label="rec_gt_label.txt"
```

The data format is as follows, (a) is the original picture, (b) is the Ground Truth text file corresponding to each picture:

![](../datasets/icdar_rec.png)


- Multilingual dataset

The multi-language model training method is the same as the Chinese model. The training data set is 100w synthetic data. A small amount of fonts and test data can be downloaded using the following two methods.
* [Baidu Netdisk](https://pan.baidu.com/s/1bS_u207Rm7YbY33wOECKDA) ,Extraction code:frgi.
* [Google drive](https://drive.google.com/file/d/18cSWX7wXSy4G0tbKJ0d9PuIaiwRLHpjA/view)


W
WenmuZhou 已提交
124
<a name="Dictionary"></a>
T
tink2123 已提交
125
### 1.3 Dictionary
K
Khanh Tran 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

Finally, a dictionary ({word_dict_name}.txt) needs to be provided so that when the model is trained, all the characters that appear can be mapped to the dictionary index.

Therefore, the dictionary needs to contain all the characters that you want to be recognized correctly. {word_dict_name}.txt needs to be written in the following format and saved in the `utf-8` encoding format:

```
l
d
a
d
r
n
```

In `word_dict.txt`, there is a single word in each line, which maps characters and numeric indexes together, e.g "and" will be mapped to [2 5 1]

W
WenmuZhou 已提交
142 143
PaddleOCR has built-in dictionaries, which can be used on demand.

K
Khanh Tran 已提交
144 145
`ppocr/utils/ppocr_keys_v1.txt` is a Chinese dictionary with 6623 characters.

W
WenmuZhou 已提交
146 147 148 149
`ppocr/utils/ic15_dict.txt` is an English dictionary with 63 characters

`ppocr/utils/dict/french_dict.txt` is a French dictionary with 118 characters

150
`ppocr/utils/dict/japan_dict.txt` is a Japanese dictionary with 4399 characters
W
WenmuZhou 已提交
151

T
tink2123 已提交
152
`ppocr/utils/dict/korean_dict.txt` is a Korean dictionary with 3636 characters
W
WenmuZhou 已提交
153

T
tink2123 已提交
154 155
`ppocr/utils/dict/german_dict.txt` is a German dictionary with 131 characters

T
tink2123 已提交
156
`ppocr/utils/en_dict.txt` is a English dictionary with 96 characters
W
WenmuZhou 已提交
157

X
xiaoting 已提交
158

W
WenmuZhou 已提交
159
The current multi-language model is still in the demo stage and will continue to optimize the model and add languages. **You are very welcome to provide us with dictionaries and fonts in other languages**,
littletomatodonkey's avatar
fix doc  
littletomatodonkey 已提交
160
If you like, you can submit the dictionary file to [dict](../../ppocr/utils/dict) and we will thank you in the Repo.
K
Khanh Tran 已提交
161 162


T
tink2123 已提交
163
To customize the dict file, please modify the `character_dict_path` field in `configs/rec/rec_icdar15_train.yml` .
K
Khanh Tran 已提交
164

T
tink2123 已提交
165 166 167 168
- Custom dictionary

If you need to customize dic file, please add character_dict_path field in configs/rec/rec_icdar15_train.yml to point to your dictionary path. And set character_type to ch.

W
WenmuZhou 已提交
169
<a name="Add_space_category"></a>
170
### 1.4 Add Space Category
T
tink2123 已提交
171

172
If you want to support the recognition of the `space` category, please set the `use_space_char` field in the yml file to `True`.
T
tink2123 已提交
173

W
WenmuZhou 已提交
174
<a name="TRAINING"></a>
175
## 2.Training
K
Khanh Tran 已提交
176

T
tink2123 已提交
177
<a name="Data_Augmentation"></a>
T
tink2123 已提交
178
### 2.1 Data Augmentation
T
tink2123 已提交
179 180 181 182 183 184 185 186

PaddleOCR provides a variety of data augmentation methods. All the augmentation methods are enabled by default.

The default perturbation methods are: cvtColor, blur, jitter, Gasuss noise, random crop, perspective, color reverse, TIA augmentation.

Each disturbance method is selected with a 40% probability during the training process. For specific code implementation, please refer to: [rec_img_aug.py](../../ppocr/data/imaug/rec_img_aug.py)

<a name="Training"></a>
T
tink2123 已提交
187
### 2.2 General Training
T
tink2123 已提交
188

K
Khanh Tran 已提交
189 190 191 192 193 194
PaddleOCR provides training scripts, evaluation scripts, and prediction scripts. In this section, the CRNN recognition model will be used as an example:

First download the pretrain model, you can download the trained model to finetune on the icdar2015 data:

```
cd PaddleOCR/
T
tink2123 已提交
195 196
# Download the pre-trained model of en_PP-OCRv3
wget -P ./pretrain_models/ https://paddleocr.bj.bcebos.com/PP-OCRv3/english/en_PP-OCRv3_rec_train.tar
K
Khanh Tran 已提交
197 198
# Decompress model parameters
cd pretrain_models
T
tink2123 已提交
199
tar -xf en_PP-OCRv3_rec_train.tar && rm -rf en_PP-OCRv3_rec_train.tar
K
Khanh Tran 已提交
200 201 202 203 204
```

Start training:

```
T
tink2123 已提交
205
# GPU training Support single card and multi-card training
T
tink2123 已提交
206
# Training icdar15 English data and The training log will be automatically saved as train.log under "{save_model_dir}"
T
tink2123 已提交
207 208

#specify the single card training(Long training time, not recommended)
T
tink2123 已提交
209 210
python3 tools/train.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.pretrained_model=en_PP-OCRv3_rec_train/best_accuracy

T
tink2123 已提交
211
#specify the card number through --gpus
T
tink2123 已提交
212
python3 -m paddle.distributed.launch --gpus '0,1,2,3'  tools/train.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.pretrained_model=en_PP-OCRv3_rec_train/best_accuracy
K
Khanh Tran 已提交
213
```
T
tink2123 已提交
214 215


K
Khanh Tran 已提交
216 217 218 219
PaddleOCR supports alternating training and evaluation. You can modify `eval_batch_step` in `configs/rec/rec_icdar15_train.yml` to set the evaluation frequency. By default, it is evaluated every 500 iter and the best acc model is saved under `output/rec_CRNN/best_accuracy` during the evaluation process.

If the evaluation set is large, the test will be time-consuming. It is recommended to reduce the number of evaluations, or evaluate after training.

T
tink2123 已提交
220
* Tip: You can use the `-c` parameter to select multiple model configurations under the `configs/rec/` path for training. The recognition algorithms supported at [rec_algorithm](https://github.com/PaddlePaddle/PaddleOCR/blob/dygraph/doc/doc_en/algorithm_overview.md):
K
Khanh Tran 已提交
221 222


W
WenmuZhou 已提交
223
For training Chinese data, it is recommended to use
T
tink2123 已提交
224 225 226
[ch_PP-OCRv3_rec.yml](../../configs/rec/PP-OCRv3/ch_PP-OCRv3_rec.yml). If you want to try the result of other algorithms on the Chinese data set, please refer to the following instructions to modify the configuration file:

Take `ch_PP-OCRv3_rec.yml` as an example:
K
Khanh Tran 已提交
227 228 229
```
Global:
  ...
230 231
  # Add a custom dictionary, such as modify the dictionary, please point the path to the new dictionary
  character_dict_path: ppocr/utils/ppocr_keys_v1.txt
K
Khanh Tran 已提交
232 233
  # Modify character type
  ...
234
  # Whether to recognize spaces
235
  use_space_char: True
K
Khanh Tran 已提交
236

237 238 239 240

Optimizer:
  ...
  # Add learning rate decay strategy
241 242 243 244 245 246 247 248 249
  lr:
    name: Cosine
    learning_rate: 0.001
  ...

...

Train:
  dataset:
M
MissPenguin 已提交
250
    # Type of dataset,we support LMDBDataSet and SimpleDataSet
251 252 253 254 255 256 257 258 259
    name: SimpleDataSet
    # Path of dataset
    data_dir: ./train_data/
    # Path of train list
    label_file_list: ["./train_data/train_list.txt"]
    transforms:
      ...
      - RecResizeImg:
          # Modify image_shape to fit long text
T
tink2123 已提交
260
          image_shape: [3, 48, 320]
261 262 263 264 265 266 267 268 269
      ...
  loader:
    ...
    # Train batch_size for Single card
    batch_size_per_card: 256
    ...

Eval:
  dataset:
M
MissPenguin 已提交
270
    # Type of dataset,we support LMDBDataSet and SimpleDataSet
271 272 273 274 275 276 277 278 279
    name: SimpleDataSet
    # Path of dataset
    data_dir: ./train_data
    # Path of eval list
    label_file_list: ["./train_data/val_list.txt"]
    transforms:
      ...
      - RecResizeImg:
          # Modify image_shape to fit long text
T
tink2123 已提交
280
          image_shape: [3, 48, 320]
281 282 283 284 285
      ...
  loader:
    # Eval batch_size for Single card
    batch_size_per_card: 256
    ...
K
Khanh Tran 已提交
286 287 288
```
**Note that the configuration file for prediction/evaluation must be consistent with the training.**

W
WenmuZhou 已提交
289
<a name="Multi_language"></a>
T
tink2123 已提交
290
### 2.3 Multi-language Training
T
tink2123 已提交
291 292 293

Currently, the multi-language algorithms supported by PaddleOCR are:

T
tink2123 已提交
294 295 296 297 298 299 300 301 302 303 304 305
| Configuration file |  Algorithm name |   backbone |   trans   |   seq      |     pred     |  language |
| :--------: |  :-------:   | :-------:  |   :-------:   |   :-----:   |  :-----:   | :-----:  |
| rec_chinese_cht_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | chinese traditional  |
| rec_en_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | English(Case sensitive)   |
| rec_french_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | French |  
| rec_ger_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | German   |
| rec_japan_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | Japanese |
| rec_korean_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | Korean  |
| rec_latin_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | Latin  |
| rec_arabic_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | arabic |
| rec_cyrillic_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | cyrillic   |
| rec_devanagari_lite_train.yml |  CRNN |   Mobilenet_v3 small 0.5 |  None   |  BiLSTM |  ctc  | devanagari  |
T
tink2123 已提交
306

T
tink2123 已提交
307
For more supported languages, please refer to : [Multi-language model](https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.1/doc/doc_en/multi_languages_en.md#4-support-languages-and-abbreviations)
W
WenmuZhou 已提交
308 309 310 311 312 313 314 315 316


If you want to finetune on the basis of the existing model effect, please refer to the following instructions to modify the configuration file:

Take `rec_french_lite_train` as an example:

```
Global:
  ...
317
  # Add a custom dictionary, such as modify the dictionary, please point the path to the new dictionary
W
WenmuZhou 已提交
318 319
  character_dict_path: ./ppocr/utils/dict/french_dict.txt
  ...
320
  # Whether to recognize spaces
321
  use_space_char: True
322

W
WenmuZhou 已提交
323
...
324 325 326

Train:
  dataset:
M
MissPenguin 已提交
327
    # Type of dataset,we support LMDBDataSet and SimpleDataSet
328 329 330 331 332 333 334 335 336
    name: SimpleDataSet
    # Path of dataset
    data_dir: ./train_data/
    # Path of train list
    label_file_list: ["./train_data/french_train.txt"]
    ...

Eval:
  dataset:
M
MissPenguin 已提交
337
    # Type of dataset,we support LMDBDataSet and SimpleDataSet
338 339 340 341 342 343
    name: SimpleDataSet
    # Path of dataset
    data_dir: ./train_data
    # Path of eval list
    label_file_list: ["./train_data/french_val.txt"]
    ...
W
WenmuZhou 已提交
344
```
K
Khanh Tran 已提交
345

346 347 348 349 350 351
<a name="kd"></a>

### 2.4 Training with Knowledge Distillation

Knowledge distillation is supported in PaddleOCR for text recognition training process. For more details, please refer to [doc](./knowledge_distillation_en.md).

W
WenmuZhou 已提交
352
<a name="EVALUATION"></a>
353

354
## 3. Evalution
K
Khanh Tran 已提交
355

T
tink2123 已提交
356
The evaluation dataset can be set by modifying the `Eval.dataset.label_file_list` field in the `configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml` file.
K
Khanh Tran 已提交
357 358 359

```
# GPU evaluation, Global.checkpoints is the weight to be tested
T
tink2123 已提交
360
python3 -m paddle.distributed.launch --gpus '0' tools/eval.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.checkpoints={path/to/weights}/best_accuracy
K
Khanh Tran 已提交
361 362
```

W
WenmuZhou 已提交
363
<a name="PREDICTION"></a>
364
## 4. Prediction
K
Khanh Tran 已提交
365 366 367 368


Using the model trained by paddleocr, you can quickly get prediction through the following script.

T
tink2123 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
The default prediction picture is stored in `infer_img`, and the trained weight is specified via `-o Global.checkpoints`:


According to the `save_model_dir` and `save_epoch_step` fields set in the configuration file, the following parameters will be saved:

```
output/rec/
├── best_accuracy.pdopt  
├── best_accuracy.pdparams  
├── best_accuracy.states  
├── config.yml  
├── iter_epoch_3.pdopt  
├── iter_epoch_3.pdparams  
├── iter_epoch_3.states  
├── latest.pdopt  
├── latest.pdparams  
├── latest.states  
└── train.log
```

Among them, best_accuracy.* is the best model on the evaluation set; iter_epoch_x.* is the model saved at intervals of `save_epoch_step`; latest.* is the model of the last epoch.
K
Khanh Tran 已提交
390 391 392

```
# Predict English results
T
tink2123 已提交
393
python3 tools/infer_rec.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.pretrained_model={path/to/weights}/best_accuracy  Global.infer_img=doc/imgs_words/en/word_1.png
K
Khanh Tran 已提交
394 395
```

T
tink2123 已提交
396

K
Khanh Tran 已提交
397 398
Input image:

399
![](../imgs_words/en/word_1.png)
K
Khanh Tran 已提交
400 401 402 403 404

Get the prediction result of the input image:

```
infer_img: doc/imgs_words/en/word_1.png
T
tink2123 已提交
405
        result: ('joint', 0.9998967)
K
Khanh Tran 已提交
406 407
```

408
The configuration file used for prediction must be consistent with the training. For example, you completed the training of the Chinese model with `python3 tools/train.py -c configs/rec/ch_ppocr_v2.0/rec_chinese_lite_train_v2.0.yml`, you can use the following command to predict the Chinese model:
K
Khanh Tran 已提交
409 410 411

```
# Predict Chinese results
W
WenmuZhou 已提交
412
python3 tools/infer_rec.py -c configs/rec/ch_ppocr_v2.0/rec_chinese_lite_train_v2.0.yml -o Global.pretrained_model={path/to/weights}/best_accuracy Global.load_static_weights=false Global.infer_img=doc/imgs_words/ch/word_1.jpg
K
Khanh Tran 已提交
413 414 415 416
```

Input image:

417
![](../imgs_words/ch/word_1.jpg)
K
Khanh Tran 已提交
418 419 420 421 422

Get the prediction result of the input image:

```
infer_img: doc/imgs_words/ch/word_1.jpg
T
tink2123 已提交
423
        result: ('韩国小馆', 0.997218)
K
Khanh Tran 已提交
424
```
425 426 427

<a name="Inference"></a>

428
## 5. Convert to Inference Model
429 430 431 432 433 434 435 436 437

The recognition model is converted to the inference model in the same way as the detection, as follows:

```
# -c Set the training algorithm yml configuration file
# -o Set optional parameters
# Global.pretrained_model parameter Set the training model address to be converted without adding the file suffix .pdmodel, .pdopt or .pdparams.
# Global.save_inference_dir Set the address where the converted model will be saved.

T
tink2123 已提交
438
python3 tools/export_model.py -c configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml -o Global.pretrained_model=en_PP-OCRv3_rec_train/best_accuracy  Global.save_inference_dir=./inference/en_PP-OCRv3_rec/
439 440 441 442 443 444 445
```

If you have a model trained on your own dataset with a different dictionary file, please make sure that you modify the `character_dict_path` in the configuration file to your dictionary file path.

After the conversion is successful, there are three files in the model save directory:

```
T
tink2123 已提交
446
inference/en_PP-OCRv3_rec/
447 448 449 450 451 452 453
    ├── inference.pdiparams         # The parameter file of recognition inference model
    ├── inference.pdiparams.info    # The parameter information of recognition inference model, which can be ignored
    └── inference.pdmodel           # The program file of recognition model
```

- Text recognition model Inference using custom characters dictionary

文幕地方's avatar
文幕地方 已提交
454
  If the text dictionary is modified during training, when using the inference model to predict, you need to specify the dictionary path used by `--rec_char_dict_path`
455 456

  ```
文幕地方's avatar
文幕地方 已提交
457
  python3 tools/infer/predict_rec.py --image_dir="./doc/imgs_words_en/word_336.png" --rec_model_dir="./your inference model" --rec_image_shape="3, 32, 100" --rec_char_dict_path="your text dict path"
458
  ```