[전력계량기OCR인식] 2021/9/20 훈련데이터셋 생성방법에 대해 알아보기

September 20 2021

OCR문자인식모델을 사용하기 전에 한글 이미지 데이터셋을 만들어야 하는데 아래 사이트를 참고하여 어떻게 만드는지에 대해 알아보았습니다.

참고사이트 : TextRecognitionDataGenerator

TextRecognitionDataGenerator

A synthetic data generator for text recognition

  • 직역하자면 텍스트인식을 위한 인조데이터 생성기

what is synthetic data generator?

https://research.aimultiple.com/synthetic-data-generation/

_Synthetic data is artificial data generated with the purpose of preserving privacy, testing systems or creating training data for machine learning algorithms. _

Synthetic data is artificial data that is created by using different algorithms that mirror the statistical properties of the original data but does not reveal any information regarding real people.

Synthetic data is important for businesses due to three reasons: privacy, product testing and training machine learning algorithms.

  • Synthetic data 는 테스트 시스템 또는 머신러닝 알고리즘을 위해 생성된 훈련데이터의 보안을 위해 훈련된 인위적인 데이터이다.

  • Synthetic data 는 원본데이터의 통계적 속성을 반영하는 다른 알고리즘을 사용하여 만들어진 인위적인 데이터이지만, 어떠한 정보도 드러내지 않는다.
  • Synthetic data 는 보안, 제품테스트와 머신러닝 알고리즘 훈련에 있어서 비지니스에서 중요하다.

What is it for?

Generating text image samples to train an OCR software. Now supporting non-latin text! For a more thorough tutorial see the official documentation

OCR 소프트웨어 훈련을 위한 텍스트 이미지 샘플을 생성하기 위해 필요하다. 이제는 라틴이외의 텍스트도 지원한다. 공식 문서를 보며 튜토리얼대로 따라 해라

What do I need to make it work?

Install the pypi package

pip install trdg

Afterwards, you can use trdg from the CLI. I recommend using a virtualenv instead of installing with sudo.

If you want to add another language, you can clone the repository instead. Simply run pip install -r requirements.txt

  • pypi 패키지를 설치한 후에 command 창에서 trdg를 사용할 수 있다. sudo 대신에 가상환경을 사용하는 걸 추천한다.
  • 만약 다른 언어를 추가하고 싶다면, 대신에 repository를 clone할 수도 있다. 간단히 pip install -r requirements.txt를 실행하라

Docker image

If you would rather not have to install anything to use TextRecognitionDataGenerator, you can pull the docker image.

docker pull belval/trdg:latest

docker run -v /output/path/:/app/out/ -t belval/trdg:latest trdg [args]

The path (/output/path/) must be absolute.

  • 만약 TextRecognitionDataGenerator를 사용하기 위해 어떤 것도 설치하고 싶지 않다면, 도커 이미지를 pull 하면 된다.

  • 이미지 저장 경로는 반드시 절대 경로 /output/path/여야한다.

How does it work?

Words will be randomly chosen from a dictionary of a specific language. Then an image of those words will be generated by using font, background, and modifications (skewing, blurring, etc.) as specified.

  • 단어는 특정 언어의 dictionary 로부터 랜덤하게 선택될 것이다. 그러면 지정된 폰트, 배경, 수정(비대칭, 블러 등)에 의해 그 단어들의 이미지가 생성될 것이다.

Basic (Python module)

The usage as a Python module is very similar to the CLI, but it is more flexible if you want to include it directly in your training pipeline, and will consume less space and memory. There are 4 generators that can be used.

  • 파이썬 모듈로 사용하는 것은 command 창과 매우 유사하지만 직접 훈련 파이프라인을 포함시키는게 더 유연하고 공간과 메모리를 더 적게 사용할 것이다. 이 모델에는 4개의 생성기를 사용할 수 있다.
from trdg.generators import (
    GeneratorFromDict,
    GeneratorFromRandom,
    GeneratorFromStrings,
    GeneratorFromWikipedia,
)

# The generators use the same arguments as the CLI, only as parameters
generator = GeneratorFromStrings(
    ['Test1', 'Test2', 'Test3'],
    blur=2,
    random_blur=True
)

for img, lbl in generator:
    # Do something with the pillow images here.
  • pillow images : openCV처럼 이미지 분석 및 처리를 쉽게 할 수 있는 라이브러리. 이미지 처리를 한다는 것은 openCV와 같지만, 차이점이 존재하며, 차이점이 존재합니다. 그 차이점은 https://chacha95.github.io/2019-08-01-PIL-vs-OpenCV/에서 참고합니다.

Basic (CLI)

trdg -c 1000 -w 5 -f 64

You get 1,000 randomly generated images with random text on them like:

By default, they will be generated to out/ in the current working directory.

  • 다음과 같은 1000개의 랜덤한 생성 이미지를 얻을 수 있습니다

  • 기본적으로 현재 working directory의 out/ 밑에 생성이미지가 저장됩니다.

Text skewing

What if you want random skewing? Add -k and -rk (trdg -c 1000 -w 5 -f 64 -k 5 -rk)

  • 램덤한 비대칭 텍스트 이미지를 얻고 싶으면 -k-rk 명령어를 추가하여 실행시키세요

Text distortion

You can also add distorsion to the generated text with -d and -do

  • 왜곡된 텍스트 이미지를 얻고 싶으면 마찬가지로-d-do를 명령어에 추가하여 실행하면 됩니다.

Text blurring

But scanned document usually aren’t that clear are they? Add -bl and -rbl to get gaussian blur on the generated image with user-defined radius (here 0, 1, 2, 4):

  • 스캔 문서가 깨끗하지 않다면 -bl-rbl를 명령어에 추가하고 radius를 0부터 4까지 지정하여 가우시안 블러처리를 한 이미지를 생성할 수도 있습니다.

Background

Maybe you want another background? Add -b to define one of the three available backgrounds: gaussian noise (0), plain white (1), quasicrystal (2) or image (3).

When using image background (3). A image from the images/ folder will be randomly selected and the text will be written on it.

  • 배경이 포함된 이미지는 -b를 명령어에 추가하고 3가지 타입의 배경을 지정하여 생성할 수 있습니다.
    • 가우시안 노이즈는 0, 아무것도 없는 흰 배경은 1, 준결정모양은 2, 또는 이미지 배경은 3
  • 이미지 배경 3을 사용할 경우, image/밑의 이미지를 랜덤하게 선택하여 텍스트 배경으로 사용될 것입니다.

Handwritten

Or maybe you are working on an OCR for handwritten text? Add -hw! (Experimental)

It uses a Tensorflow model trained using this excellent project by Grzego.

The project does not require TensorFlow to run if you aren’t using this feature

  • 손글씨체를 인식하고 싶다면 -hw를 추가하세요
  • 이는 Grzego를 이용하여 Tensorflow 모델을 훈련했습니다.
  • 손글씨 이미지를 사용하지 않는다면 TensorFlow를 요구하지 않습니다.

Dictionary

The text is chosen at random in a dictionary file (that can be found in the dicts folder) and drawn on a white background made with Gaussian noise. The resulting image is saved as [text]_[index].jpg

There are a lot of parameters that you can tune to get the results you want, therefore I recommend checking out trdg -h for more information.

  • 텍스트는 dictionary의 랜덤 파일과 흰색 배경위에 가우시안 노이즈로 그려집니다. 결과 이미지는 [text]_[index].jpg의 형태로 저장됩니다.

  • trdg -h로 조정할 수 있는 파라미터 정보들을 확인하세요

Add new fonts

The script picks a font at random from the *fonts* directory.

Simply add/remove fonts until you get the desired output.

If you want to add a new non-latin language, the amount of work is minimal.

  1. Create a new folder with your language two-letters code
  2. Add a .ttf font in it
  3. Edit run.py to add an if statement in load_fonts()
  4. Add a text file in dicts with the same two-letters code
  5. Run the tool as you normally would but add -l with your two-letters code

It only supports .ttf for now_

한국어 dictionary는 font/ko밑에 있습니다. 원하는 결과물을 만들때까지 폰트를 추가/ 제거하면 됩니다. 라틴어가 아닌 새로운 언어를 추가하고 싶으면 아래 작업수행하세요

  1. 2글자 코드의 새로운 폴더를 생성하세요
  2. 1에서 생성한 폴더에 .ttf 폰트 파일을 추가하세요
  3. run.py 파일의 load_fonts()메소드에 if문을 추가하세요
  4. 1의 2글자 코드와 같은 dicts 의 텍스트 파일을 추가하세요
  5. -l2글자 코드를 추가하여 명령문을 실행하세요

현재 .ttf 폰트파일만 지원합니다.

Benchmarks

Number of images generated per second.

  • 시간당 생성되는 이미지 수

  • Intel Core i7-4710HQ @ 2.50Ghz + SSD (-c 1000 -w 1)
    • -t 1 : 363 img/s
    • -t 2 : 694 img/s
    • -t 4 : 1300 img/s
    • -t 8 : 1500 img/s
  • AMD Ryzen 7 1700 @ 4.0Ghz + SSD (-c 1000 -w 1)
    • -t 1 : 558 img/s
    • -t 2 : 1045 img/s
    • -t 4 : 2107 img/s
    • -t 8 : 3297 img/s

Leave a comment