OCR of Hand-written Data using kNN

来源:互联网 发布:云计算板块龙头股 编辑:程序博客网 时间:2024/05/16 06:41



我们的目标是创建一个可以识别手写数字的应用。为此我们需要一些训练数据和测试数据。openCV带有数字图片digits.pngopencv/samples/python2/data/带有5000个手写数字(每个数字是500个)。每张图片都是20*20大小。所以首先要将图片切割成5000个不同图片。每个数字 ,把它变成一个单行400像素。这就是我们的特征集,既定义了所有像素的值,也是我们创建的特征采样。前面的250个数字作为训练数据,后250个作为测试数据。

这就是所有准备。


import numpy as npimport cv2from matplotlib import pyplot as pltimg = cv2.imread('digits.png')gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# Now we split the image to 5000 cells, each 20x20 sizecells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]# Make it into a Numpy array. It size will be (50,100,20,20)x = np.array(cells)# Now we prepare train_data and test_data.train = x[:,:50].reshape(-1,400).astype(np.float32) # Size = (2500,400)test = x[:,50:100].reshape(-1,400).astype(np.float32) # Size = (2500,400)# Create labels for train and test datak = np.arange(10)train_labels = np.repeat(k,250)[:,np.newaxis]test_labels = train_labels.copy()# Initiate kNN, train the data, then test it with test data for k=1knn = cv2.KNearest()knn.train(train,train_labels)ret,result,neighbours,dist = knn.find_nearest(test,k=5)# Now we check the accuracy of classification# For that, compare the result with test_labels and check which are wrongmatches = result==test_labelscorrect = np.count_nonzero(matches)accuracy = correct*100.0/result.sizeprint accuracy

ORC app 准备就绪,在例子中可以得到91%的准确率。

进一步提高准确率的方法是增加训练数据,特别是错误的那个。开始开发应用之前,是收集训练数据,保存好,下次直接读取数据,并分类。

可以使用nump有函数,np.savetxt, np.savez, np.load 等等。

# save the datanp.savez('knn_data.npz',train=train, train_labels=train_labels)# Now load the datawith np.load('knn_data.npz') as data:    print data.files    train = data['train']    train_labels = data['train_labels']

在我的系统里将近4.4MB,所以定义特征数值时,转换为unit8再保存,只要1.1MB。当load进来时,转换为uint32。


OCR of English Alphabets


接下来,对英文字做相应的操作,只有轻微改变的特征集。在opencv自带的数据文件里opencv/samples/cpp/letter-recognition.data 打开它会发现有20000行,第一眼就像是一堆垃圾。事实上每行每列的第一个字符是标签,接下来的16个是不同的特征。UCI Machine Learning Repository.可以在主页查看更多细节。this page。


这有20000个有效的样本,10000个作为训练数据,10000作为测试数据,我们把字母转换为ascii,这样才能工作。


import cv2import numpy as npimport matplotlib.pyplot as plt# Load the data, converters convert the letter to a numberdata= np.loadtxt('letter-recognition.data', dtype= 'float32', delimiter = ',',                    converters= {0: lambda ch: ord(ch)-ord('A')})# split the data to two, 10000 each for train and testtrain, test = np.vsplit(data,2)# split trainData and testData to features and responsesresponses, trainData = np.hsplit(train,[1])labels, testData = np.hsplit(test,[1])# Initiate the kNN, classify, measure accuracy.knn = cv2.KNearest()knn.train(trainData, responses)ret, result, neighbours, dist = knn.find_nearest(testData, k=5)correct = np.count_nonzero(result == labels)accuracy = correct*100.0/10000print accuracy



准确率在93。22%



0 0