본문 바로가기
AI

EasyOCR 간단 리뷰(Recognition)

by Myungbin 2024. 7. 4.

EasyOCR

EasyOCR은 Text Detection + Text Recognition으로 구분이 되어있고 Text Detection에서 텍스트의 위치를 파악하고 Recognition에서 문자 인식 기능을 수행합니다.

현재 Text Detection은 따로 하고 있기 때문에, Text Recognition 위주입니다.

Installation

pip install pytorch (in your env)

pip install easyocr

EasyOCR은 Pytorch 기반으로 실행되기 때문에 자신의 환경에 맞는 Pytorch를 먼저 설치해야 합니다.

Usage

import easyocr

reader = easyocr.Reader(['ko','en']) 
result = reader.readtext('image.jpg')
# 만약 Text detection / recognize를 따로 하고 싶다면, 다음과 같이 사용할 수 있습니다. 
reader.detect('image.jpg')
reader.recognizer('image.jpg')

코드 사용방법 자체는 굉장히 간단한데, Reader로 모델을 메모리에 로드하고 readtext를 통해 Detection + Reconition을 한번에 수행합니다. readtext에는 image path, numpy array등이 들어갈 수 있습니다.

  • ['ko','en']는 easyocr에서 찾아야 하는 언어 목록입니다. 지원하는 언어 목록을 확인할 수 있습니다.

Model Load

Custom Model

Detection Model은 CRAFT를 사용하여 텍스트의 위치를 파악하고 Recognition Model은 CRNN(feature extraction (Resnet and VGG), sequence labeling (LSTM) and decoding (CTC))이 사용됩니다.

  • Recognition 모델에서 한국어는 FeatureExtraction이 Resnet이 아닌 VGG가 사용되고 있습니다. easyocr.py의 131line에 lang_list를 “ko”로 할 때 gen2모델을 불러오게 설정되어 있는데, gen2 모델은 VGG16입니다. 그래서 이 부분을 gen1으로 바꿔주면 FeatureExtraction Model을 Resnet으로 사용할 수 있습니다.
elif 'ko' in lang_list:
    self.setModelLanguage('korean', lang_list, ['ko','en'], '["ko","en"]')
    model = recognition_models['gen2']['korean_g2']
    recog_network = 'generation2'

Resnet & VGG

Recognition 동작 방식

1. reformat input

이미지를 gray scale 이미지로 변환합니다.

2. get image list

  1. if free list: compute the perspective transform matrix and then apply it
  2. compute ratio and resize
  3. sort by vertical position

3. get text

DataLoad & Augmentation

AlignCollate class에서 augmentation 기능 추가하기 numpy array라 albumentation 및 cv2를 사용하여 글자를 잘 인식할 수 있게 Augmentation이 가능합니다. Easyocr에서는 resize & contrast(0.5)를 합니다.

4. recognizer predict

batch_max_length는 이미지의 채널의 수 입니다.

batch_max_length + 1을 하게 되는데, 이 +1은 blank입니다.

batch_max_length = image_batch
length_for_pred = torch.IntTensor([batch_max_length] * batch_size).to(device)
text_for_pred = torch.LongTensor(batch_size, batch_max_length + 1).fill_(0).to(device)
preds = model(image, text_for_pred)

 

5. decoer

decoder는 “greedy”가 사용됩니다.

Greedy Search Decoder: output sequnece에서 생성된 각각의 확률 분포에서 가장 값이 높은 토큰을 선택

a: 연속된 중복 문자 제거 b: ignore 문자 제거 c: 필터링

  texts = []
  index = 0
  for l in length:
      t = text_index[index:index + l]
      a = np.insert(~((t[1:]==t[:-1])),0,True)
      b = ~np.isin(t,np.array(self.ignore_idx))
      c = a & b
      text = ''.join(np.array(self.character)[t[c.nonzero()]])
      texts.append(text)
      index += l

 

'AI' 카테고리의 다른 글

YOLO Custom Dataset  (0) 2024.05.29
ollama baseline  (0) 2024.04.19
LLaMA-Factory Baseline  (1) 2024.04.18