AI 그게 뭔데
끄적끄적 개발일지
AI 그게 뭔데
전체 방문자
오늘
어제
  • 분류 전체보기 (342)
    • 논문 (5)
    • DL(Deep-Learning) (34)
      • 개념 (14)
      • Python 기초 (14)
      • Tensorflow (6)
      • Pytorch (0)
    • NLP (10)
    • OpenCV (53)
    • DevOps (10)
      • AWS (2)
      • Docker & Kubernetes (4)
      • Spark (3)
      • SQL (1)
    • MacOS (1)
    • React-Native (2)
    • BI (3)
      • GA(Google Analytics) (3)
      • Tableau (0)
    • 알고리즘 (221)
      • 백준 (76)
      • 프로그래머스 (108)
      • 기타 알고리즘 (37)

인기 글

태그

  • 이코테
  • 백준
  • 프로그래머스
  • level1
  • 파이썬
  • LEVEL2
  • Python
  • OpenCV
  • 알고리즘
  • 연습문제

최근 글

hELLO · Designed By 정상우.
AI 그게 뭔데

끄적끄적 개발일지

[OpenCV with Python] 영상 분할과 객체 검출 : 템플릿 매칭2 - 인쇄체 숫자 인식
OpenCV

[OpenCV with Python] 영상 분할과 객체 검출 : 템플릿 매칭2 - 인쇄체 숫자 인식

2022. 2. 4. 23:23

인식(Recognition) 이란?

  • Classifying a detected object into different categories
  • 여러 개의 클래스 중 가장 유사한 클래스 선택

 

 

숫자 템플릿 영상 생성

  • Consolas 폰트로 쓰여진 숫자 영상을 digit0.bmp~digit9.bmp로 저장
  • 숫자 영상의 크기는 100 x 150 크기로 정규화

 

 

인쇄체 숫자 인식 방법

 

💬  인쇄체 숫자 인식 예제

import sys
import numpy as np
import cv2


def load_digits():
    img_digits = []

    for i in range(10):
        filename = './digits/digit{}.bmp'.format(i)
        img_digits.append(cv2.imread(filename, cv2.IMREAD_GRAYSCALE))

        if img_digits[i] is None:
            return None

    return img_digits


def find_digit(img, img_digits):
    max_idx = -1
    max_ccoeff = -1

    # 최대 NCC 찾기
    for i in range(10):
        img = cv2.resize(img, (100, 150))
        res = cv2.matchTemplate(img, img_digits[i], cv2.TM_CCOEFF_NORMED)

        if res[0, 0] > max_ccoeff:
            max_idx = i
            max_ccoeff = res[0, 0]

    return max_idx


def main():
    # 입력 영상 불러오기
    src = cv2.imread('digits_print.bmp')

    if src is None:
        print('Image load failed!')
        return

    # 100x150 숫자 영상 불러오기
    img_digits = load_digits()  # list of ndarray

    if img_digits is None:
        print('Digit image load failed!')
        return

    # 입력 영상 이진화 & 레이블링
    src_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    _, src_bin = cv2.threshold(src_gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
    cnt, _, stats, _ = cv2.connectedComponentsWithStats(src_bin)

    # 숫자 인식 결과 영상 생성
    dst = src.copy()
    for i in range(1, cnt):
        (x, y, w, h, s) = stats[i]

        if s < 1000:
            continue

        # 가장 유사한 숫자 이미지를 선택
        digit = find_digit(src_gray[y:y+h, x:x+w], img_digits)
        cv2.rectangle(dst, (x, y, w, h), (0, 255, 255))
        cv2.putText(dst, str(digit), (x, y - 4), cv2.FONT_HERSHEY_SIMPLEX,
                    1, (0, 255, 255), 2, cv2.LINE_AA)

    cv2.imshow('dst', dst)
    cv2.waitKey()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    main()

 

 

윗줄은 consolas체로 인식률이 높지만, 아래는 arial체로 약간의 오차가 있다.

 

'OpenCV' 카테고리의 다른 글

[OpenCV with Python] 영상 분할과 객체 검출 : HOG 알고리즘 - 보행자 검출  (0) 2022.02.05
[OpenCV with Python] 영상 분할과 객체 검출 : 캐스케이드 분류기 - 얼굴 검출  (0) 2022.02.05
[OpenCV with Python] 영상 분할과 객체 검출 : 템플릿 매칭 1  (0) 2022.02.04
[OpenCV with Python] 영상 분할과 객체 검출 : 모멘트 기반 객체 검출  (0) 2022.02.04
[OpenCV with Python] 영상 분할과 객체 검출 : 그랩컷 - cv2.grabCut  (0) 2022.02.04
    AI 그게 뭔데
    AI 그게 뭔데
    공부와 개발 그리고 AI가 약간 첨가된 흔적 남기기

    티스토리툴바