training.py (1397B)
1 ############## Code from: http://stackoverflow.com/questions/9413216/simple-digit-recognition-ocr-in-opencv-python ################# 2 import sys 3 4 import numpy as np 5 import cv2 6 7 im = cv2.imread('images/NumberLearning.png') 8 im3 = im.copy() 9 10 gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) 11 blur = cv2.GaussianBlur(gray,(5,5),0) 12 thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2) 13 14 ################# Now finding Contours ################### 15 16 contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) 17 18 samples = np.empty((0,100)) 19 responses = [] 20 keys = [i for i in range(48,58)] 21 22 for cnt in contours: 23 if cv2.contourArea(cnt)>50: 24 [x,y,w,h] = cv2.boundingRect(cnt) 25 26 if h>28: 27 cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2) 28 roi = thresh[y:y+h,x:x+w] 29 roismall = cv2.resize(roi,(10,10)) 30 cv2.imshow('norm',im) 31 key = cv2.waitKey(0) 32 33 if key == 27: # (escape to quit) 34 sys.exit() 35 elif key in keys: 36 responses.append(int(chr(key))) 37 sample = roismall.reshape((1,100)) 38 samples = np.append(samples,sample,0) 39 40 responses = np.array(responses,np.float32) 41 responses = responses.reshape((responses.size,1)) 42 print "training complete" 43 44 np.savetxt('generalsamples.data',samples) 45 np.savetxt('generalresponses.data',responses)