본문 바로가기
업무자동화 with Python

[업무자동화 with Python] EasyOCR을 활용한 OCR해보기

by CodeCrafter 2025. 3. 1.
반응형

 

1. OCR이란?

 

- OCR(Optical Character Recognition, 광학 문자 인식)은 이미지 속의 문자를 인식하고 이를 디지털 텍스트로 변환하는 기술입니다. 오늘날 OCR 기술은 다양한 산업에서 사용되며, 문서 디지털화, 자동 데이터 입력, 자동차 번호판 인식, 의료 기록 분석 등 많은 분야에서 활용됩니다.

 

2. EasyOCR이란?

- EasyOCR은 Python 기반의 강력한 OCR 라이브러리로, 딥러닝 기반 문자 인식을 지원합니다. PaddleOCR이나 Tesseract와 비교했을 때, 설치가 간단하고 다양한 언어를 지원하며 사용법이 직관적하다는 장점이 있습니다.

2.1 Easy OCR의 주요 특징

  • 80개 이상의 언어 지원
  • 딥러닝을 활용한 강력한 인식 성능
  • 설치 및 사용법이 간단
  • GPU 가속 지원 가능 (PyTorch 기반)

2.2 Easy OCR을 활용한 실제 데이터 OCR

- 이번에는 실제 사진에 대해서 OCR을 진행해보겠습니다.

 

- 이번 구현간에는 코랩 환경에서 진행해보겠습니다.

 

- 먼저 코랩환경에서 한글 폰트가 그림에서 나오도록 한글 폰트를 설치해줍니다.

!apt-get install -y fonts-nanum
!fc-cache -fv
!rm -rf ~/.cache/matplotlib

 

- 한글 폰트가 그림에서 잘 나오는지 확인해봅니다.

import matplotlib.pyplot as plt
from matplotlib import font_manager

# 나눔 폰트 경로 확인
font_path = "/usr/share/fonts/truetype/nanum/NanumGothic.ttf"

# 폰트 설정
font_manager.fontManager.addfont(font_path)
plt.rc('font', family='NanumGothic')  # 나눔고딕 설정
plt.rcParams['axes.unicode_minus'] = False  # 마이너스 기호 깨짐 방지

# 한글 플롯 테스트
plt.figure(figsize=(8, 6))
plt.title("한글 플롯 테스트")
plt.plot([1, 2, 3], [4, 5, 6], label="한글 라벨")
plt.legend()
plt.show()

 

* 이상이 없네요

 

- 이제 easyocr 라이브러리를 설치해줍니다.

!pip install easyocr

 

- 먼저 다음 표지판에 대해서 OCR을 진행해보겠습니다.

 

- 해당 파일에 대해서 OCR 결과를 도출해보겠습니다.

 

* 먼저 OCR 인식 결과를 터미널 환경에서 텍스트로 print해보면 아래와 같습니다.

from PIL import ImageFont, ImageDraw, Image
import numpy as np
import cv2
import easyocr
import matplotlib.pyplot as plt

# OCR 실행
reader = easyocr.Reader(['ko', 'en'])
image_path = '/content/drive/MyDrive/korean.png'  # 이미지 파일 경로
results = reader.readtext(image_path)

# 결과 출력
print("\n=== OCR 인식 결과 ===")
for (bbox, text, prob) in results:
    print(f"Detected Text: {text}, Probability: {prob:.2f}")
 

 

 


* 이를 bounding box와 함께 그림상에서 표시하면 아래와 같습니다.

# 원본 이미지 로드
image = cv2.imread(image_path)
image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

# 한글 폰트 설정 (Colab에서는 Nanum Gothic 폰트 설치 필요)
font_path = "/usr/share/fonts/truetype/nanum/NanumGothic.ttf"
font = ImageFont.truetype(font_path, 40)  # 폰트 크기 지정

# 이미지에 OCR 결과 추가
draw = ImageDraw.Draw(image_pil)
for (bbox, text, prob) in results:
    (top_left, top_right, bottom_right, bottom_left) = bbox
    top_left = tuple(map(int, top_left))
    bottom_right = tuple(map(int, bottom_right))
   
    # 박스 그리기
    draw.rectangle([top_left, bottom_right], outline="green", width=3)
   
    # 한글 텍스트 추가
    draw.text((top_left[0], top_left[1] - 40), text, font=font, fill=(0, 255, 0))

# 결과 출력
image = np.array(image_pil)
plt.figure(figsize=(10, 10))
plt.imshow(image)
plt.axis('off')
plt.show()

 

 

 

꽤나 잘 되는 것 같네요.

 

 

이번에는 좀 더 복잡한 영수증을 바탕으로 진행해보겠습니다.

 

사용할 영수증의 사진은 아래와 같습니다.

 

from PIL import ImageFont, ImageDraw, Image
import numpy as np
import cv2
import easyocr
import matplotlib.pyplot as plt

# OCR 실행
reader = easyocr.Reader(['ko', 'en'])
image_path = '/content/drive/MyDrive/blue receipt.jpg'  # 이미지 파일 경로
results = reader.readtext(image_path)

# 결과 출력
print("\n=== OCR 인식 결과 ===")
for (bbox, text, prob) in results:
    print(f"Detected Text: {text}, Probability: {prob:.2f}")

 

 

* 이를 boundix box와 함께 그림상에서 표시해보겠습니다.

# 원본 이미지 로드
image = cv2.imread(image_path)
image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

# 한글 폰트 설정 (Colab에서는 Nanum Gothic 폰트 설치 필요)
font_path = "/usr/share/fonts/truetype/nanum/NanumGothic.ttf"
font = ImageFont.truetype(font_path, 10)  # 폰트 크기 지정

# 이미지에 OCR 결과 추가
draw = ImageDraw.Draw(image_pil)
for (bbox, text, prob) in results:
    (top_left, top_right, bottom_right, bottom_left) = bbox
    top_left = tuple(map(int, top_left))
    bottom_right = tuple(map(int, bottom_right))
   
    # 박스 그리기
    draw.rectangle([top_left, bottom_right], outline="green", width=3)
   
    # 한글 텍스트 추가
    draw.text((top_left[0], top_left[1] - 40), text, font=font, fill=(0, 255, 0))

# 결과 출력
image = np.array(image_pil)
plt.figure(figsize=(10, 10))
plt.imshow(image)
plt.axis('off')
plt.show()

 

 

 

- 글자가 복잡하다보니 원하는 형태의 bounding box가 나오지는 않았지만, 이를 프레임워크적인 규칙을 적용해 잘 가공하면 좋은 정보가 될 것 같습니다.

반응형

댓글