IT/SW Dev.

쉬운 AI Coding - EasyOCR(텍스트 추출) 패키지 및 Python 예제

부티형 2025. 2. 19. 21:02
반응형

출처 : 부티형

 
다음은 EasyOCR 패키지를 사용하여 이미지에서 텍스트를 추출하는 Python 코드입니다.

설치

먼저 easyocr 패키지를 설치해야 합니다.

pip install easyocr

코드

반응형
import easyocr
import cv2
import matplotlib.pyplot as plt

# 이미지 경로 설정
image_path = "example.png"  # 여기에 이미지 파일 경로 입력

# EasyOCR 리더 생성 (한국어, 영어 지원)
reader = easyocr.Reader(['en', 'ko'])

# 이미지에서 텍스트 추출
results = reader.readtext(image_path)

# 결과 출력
for (bbox, text, prob) in results:
    print(f"인식된 텍스트: {text} (신뢰도: {prob:.4f})")

# 이미지에 인식된 텍스트 표시
image = cv2.imread(image_path)

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))
    
    # 박스 그리기
    cv2.rectangle(image, top_left, bottom_right, (0, 255, 0), 2)
    
    # 텍스트 표시
    cv2.putText(image, text, (top_left[0], top_left[1] - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)

# 이미지 출력
plt.figure(figsize=(10, 10))
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.show()

설명

  1. easyocr.Reader(['en', 'ko'])를 사용하여 영어('en')와 한국어('ko')를 지원하는 OCR 모델을 로드합니다.
  2. reader.readtext(image_path)를 통해 이미지에서 텍스트를 추출합니다.
  3. 추출된 텍스트와 신뢰도를 출력합니다.
  4. OpenCV를 사용하여 인식된 텍스트 주변에 박스를 그려 시각적으로 표시합니다.
  5. matplotlib을 사용하여 결과 이미지를 출력합니다.

이제 위 코드를 실행하면 이미지에 있는 텍스트를 추출하고, 그 결과를 시각적으로 확인할 수 있습니다!

반응형