인공지능과 기계학습
차량 번호판 인식(1/3)-Tesseract OCR과 OpenCV를 사용하여 이미지에서 번호판을 추출하고 텍스트를 인식하는 과정을 구현
지콩빵
2024. 6. 30. 17:27
# 필요한 라이브러리 설치
!pip install pytesseract
!sudo apt-get install tesseract-ocr
!sudo apt-get install tesseract-ocr-kor
# 필요한 라이브러리 임포트
import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab.patches import cv2_imshow
import pytesseract
# 이미지 전처리 함수
def preprocess_image(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
edged = cv2.Canny(blur, 10, 200)
return edged
# 번호판 영역 찾기 함수
def find_contours(image, edged):
contours, _ = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]
location = None
for contour in contours:
approx = cv2.approxPolyDP(contour, 10, True)
if len(approx) == 4:
location = approx
break
return location
# 번호판 텍스트 추출 함수
def extract_text(image):
config = ('-l kor --oem 1 --psm 7')
text = pytesseract.image_to_string(image, config=config)
return text.strip()
# 메인 함수
def process_image(image_path):
image = cv2.imread(image_path)
edged = preprocess_image(image)
location = find_contours(image, edged)
if location is not None:
mask = np.zeros(image.shape[:2], np.uint8)
new_image = cv2.drawContours(mask, [location], 0, 255, -1)
new_image = cv2.bitwise_and(image, image, mask=mask)
(x, y) = np.where(mask == 255)
(topx, topy) = (np.min(x), np.min(y))
(bottomx, bottomy) = (np.max(x), np.max(y))
cropped = image[topx:bottomx+1, topy:bottomy+1]
text = extract_text(cropped)
print("인식된 번호판:", text)
cv2_imshow(cropped)
else:
print("번호판을 찾을 수 없습니다.")
# 이미지 처리
image_paths = ['00.jpg', '01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg', '06.jpg', '07.jpg', '08.jpg', '09.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg']
for path in image_paths:
print(f"Processing {path}")
process_image(path)
print()
결과- 번호판 인식 자체를 못하거나 텍스트 추출이 정확하지 않음
2편에서는 Tesseract OCR과 OpenCV이 아닌, 번호판 특화 데이터셋으로 학습된 OCR 모델을 사용해보겠다.