Skip to content

Instantly share code, notes, and snippets.

@billowdood
Created October 30, 2012 02:41
Show Gist options
  • Save billowdood/3977993 to your computer and use it in GitHub Desktop.
Save billowdood/3977993 to your computer and use it in GitHub Desktop.
import numpy as np
import cv2
#Training!
def training(contoursObj):
samples = np.empty((0,100))
#Empty array for the corresponding value
valueDigit = []
#Loop over all the images,in this case we have 9 images per digit,so in total we have 90 images(we included 0 as a digit)
for digit in range(0,10):
for image in range(1,10):
#Get the image and find the contours of the number(rectangle)
image_digit = cv2.imread("Samples\\"+str(digit)+"_"+str(image)+".jpg")
gray = cv2.cvtColor(image_digit,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
#Coordinates of the rectangle (x,y)->starting points, (w,h)-> width and height
x,y,w,h = contours(image_digit)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
key = cv2.waitKey(0)
valueDigit.append(int(chr(key)))
sample = roismall.reshape((1,100))
samples = np.append(samples,sample,0)
valueDigit = np.array(valueDigit,np.float32)
valueDigit = valueDigit.reshape((valueDigit.size,1))
print "training complete"
print samples.size
print valueDigit.size
np.savetxt('generalsamples.data',samples)
np.savetxt('generalvaluedigits.data',valueDigit)
def contours(imageToDraw):
imgray = cv2.cvtColor(imageToDraw,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
x,y,w,h = cv2.boundingRect(contours[0])
return x,y,w,h
def main():
training(contours)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment