development

파이썬으로 이미지에서 텍스트 추출하기

여름싼타 2023. 2. 12. 22:19
반응형

 

파이썬으로 이미지에서 글자 추출하기

 

이미지에서 글자를 추출하는 과정은 여러 가지 단계로 구성된다. 대표적인 글자 추출 과정은 다음과 같다.

 

  1. 이미지 전처리: 이미지에서 노이즈를 제거하고, 글자의 크기와 모양을 개선하는 작업
  2. 이미지 분할: 이미지를 개별 글자로 분할
  3. 글자 인식: 개별 글자 이미지를 인식하여 글자로 변환

 

파이썬에서는 OCR (Optical Character Recognition) 라이브러리를 사용하여 이미지에서 글자를 추출할 수 있다. 가장 인기 있는 OCR 라이브러리인 Tesseract-OCR을 사용한 방법이다.

 

 

설치

pip3 install pytesseract

만약 python3가 아니면 아래처럼 설치한다.

pip install pytesseract

 

다음 예제 코드는 현재 디렉터리의 모든 이미지 파일에서 찾을 수 있는 모든 텍스트를 추출한다.

#!/usr/bin/python3

# mass-ocr-images.py

from PIL import Image
import os
import pytesseract
import sys

# You must specify the full path to the tesseract executable.
# In Linux, you can get this by using the command:
# which tesseract
pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract'

def main(argv):
 for filename in os.listdir("."):
 if str(filename) not in ['.', '..']:
 nameParts = str(filename).split(".")
 if nameParts[-1].lower() in ["gif", "png", "jpg", "jpeg", "tif", "tiff"]:
 # Calls to the API should always be bounded by a timeout, just in case.
 try:
  print ("Found filename [" + str(filename) + "]")
  ocrText = pytesseract.image_to_string(str(filename), timeout=5)
  print (ocrText)
  print ("")
 except Exception as err:
  print ("Processing of [" + str(filename) + "] failed due to error [" + str(err) + "]")

if __name__ == "__main__":
 main(sys.argv[1:])

 

참고 : https://www.developer.com/languages/python/extract-text-images-python/

반응형