2월 1주차_프로젝트 진행상황 - chloe73/openCV GitHub Wiki

💡이번주 목표 : 영어 및 숫자 인식에 대한 레퍼런스 참고 후 관련 기술 혹은 알고리즘, 원리 공부

📝손글씨 OCR 프로젝트

  • 필기체 숫자인식이란?

필기체 숫자인식이란 손으로 쓴 글씨를 컴퓨터가 인식하는 것을 말하며, 이미 스마트폰과 테블릿 PC가 대중화 되면서 함께 해당 기술이 탑재되어 이용 할 수 있는 경우가 많아 우리에게 매우 익숙한 기술이다.

image

⭐️우리의 계획 : 텐서플로우를 이용해서 단층신경망으로 MNIST 필기 숫자를 인식

✅먼저 손글씨를 훈련시키기 위해 txt파일로 이루어진 MNIST데이터를 받아온다.

image

위 사진은 txt파일로 된 MNIST 데이터이다.

이 txt파일의 내용을 보면, 아래 사진과 같이 0과 1로 이루어져 있는 txt파일이 존재한다.

image

✅0과 1로 되어있기 때문에 0은 그대로 냅두고 1을 255로 변경하여 흰색으로 저장을 해준다.

import os
import numpy as np

def preprocessing_txt(path):
    txtPaths = [os.path.join(path,f) for f in os.listdir(path)]
    count = 0
    #파일읽기
    for txtPath in txtPaths :
        count += 1
        filename = os.path.basename(txtPath)
        percent_bar(txtPaths,count)
        f = open(txtPath)
        img = []
        while True :
            tmp=[]
            text = f.readline()
            if not text :
                break
            for i in range(0,len(text)-1) : 
                #라인을 일어올때 text가 1일경우 255로 변경
                if int(text[i]) == 1 :
                    tmp.append(np.uint8(255))
                else :
                    tmp.append(np.uint8(0))
            img.append(tmp)		#img배열에 쌓아줌
        img = np.array(img)
        cv2.imwrite('./kNN/trainingPNGs/'+filename.split('.')[0]+'.png',img) #저장
    print('\n'+str(count)+'files are saved(preprocessing_txt2png)')
preprocessing_txt('./kNN/trainingDigits')

MNIST란?

MNIST 데이터베이스 (Modified National Institute of Standards and Technology database)는 손으로 쓴 숫자들로 이루어진 대형 데이터베이스이며, 다양한 화상 처리 시스템을 트레이닝하기 위해 일반적으로 사용된다[위키백과]

MNIST 사용법

데이터 준비

텐서플로우 라이브러리가 있다면 다음 코드를 다운받을 위치에서 실행한다.

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/", one_hot=False)

이 명령은 실행되는 파이썬 파일의 폴더에 mnist라는 이름의 폴더를 추가하고, 그곳에 mnist 데이터를 인터넷에서 받아오는 역할을 한다.

또는 다음 사이트에서 4가지 파일을 다운받는다

http://yann.lecun.com/exdb/mnist/

train-images-idx3-ubyte.gz: training set images (9912422 bytes)

train-labels-idx1-ubyte.gz: training set labels (28881 bytes)

t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)

t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)

다운받았다면 압축을 푼 뒤, 사용할 위치로 파일을 이동시킨다.

MNIST 데이터 시각화

아래 파이썬 코드는 mnist 데이터를 불러오고 시각화할 수 있는 메소드를 제공한다.

import os
import struct
import numpy as np


def read(dataset = "training", path = "."): # path: 파일경로

    if dataset is "training":
        fname_img = os.path.join(path, 'train-images.idx3-ubyte')
        fname_lbl = os.path.join(path, 'train-labels.idx1-ubyte')
    elif dataset is "testing":
        fname_img = os.path.join(path, 't10k-images.idx3-ubyte')
        fname_lbl = os.path.join(path, 't10k-labels.idx1-ubyte')
    else:
        raise ValueError("dataset must be 'testing' or 'training'")

    # Load everything in some numpy arrays
    with open(fname_lbl, 'rb') as flbl:
        magic, num = struct.unpack(">II", flbl.read(8))
        lbl = np.fromfile(flbl, dtype=np.int8)

    with open(fname_img, 'rb') as fimg:
        magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16))
        img = np.fromfile(fimg, dtype=np.uint8).reshape(len(lbl), rows, cols)

    get_img = lambda idx: (lbl[idx], img[idx])

    mnist_data = []
    for i in range(len(lbl)):
        mnist_data.append(get_img(i))
    return mnist_data


def show(image):
    from matplotlib import pyplot
    import matplotlib as mpl
    fig = pyplot.figure()
    ax = fig.add_subplot(1,1,1)
    imgplot = ax.imshow(image, cmap=mpl.cm.Greys)
    imgplot.set_interpolation('nearest')
    ax.xaxis.set_ticks_position('top')
    ax.yaxis.set_ticks_position('left')
    pyplot.show()

MNIST사용법

압축을 푼 mnist 데이터를 사용할 위치로 이동시킨다.

MNIST 데이터를 보기 위해서는 아래처럼 작성하면 볼 수 있다.

mnist = read("training", path="/mnist")
image = next(mnist)
show(image[1])