OpenCV-Python教程:51.使用kNN做手写数据OCR

手写数字OCR
我们的目标是建立一个应用可以读手写数字。为了这个我们需要一些训练数据和测试数据。OpenCV带了一个图像digits.png有5000个手写数字(每个数字500个),每个数字是一个20x20的图像,所以我们的第一步是把图像分成5000个不同的数字。对于每个数字,我们把它放到一个400个像素的行上,这是我们的特征集,所有像素的强度值。这是我们创建的最简单的特征集。我们使用每个数字的头250个样本作为训练数据,后250个作为测试数据。所以让我们先准备他们。

import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('digits.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Now we split the image to 5000 cells, each 20x20 size
cells = [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)
【OpenCV-Python教程:51.使用kNN做手写数据OCR】# Create labels for train and test data
k = 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=1
knn = 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 wrong
matches = result==test_labels
correct = np.count_nonzero(matches)
accuracy = correct*100.0/result.size
print accuracy
所以我们基本的OCR应用准备好了,这个例子给我们91%的准确率。一个提高准确率的选项是加更多的训练数据,特别是错误的。所以我最好是保存训练数据,下次直接从文件读取这些数据并开始分类。你可以用Numpy的函数np.savetxt,np.savez, np.load等来做这个。
# save the data
np.savez('knn_data.npz',train=train, train_labels=train_labels)
# Now load the data
with np.load('knn_data.npz') as data:
print data.files
train = data['train']
train_labels = data['train_labels']
在我们系统里,它要用4.4MB的内存,由于我们用强度值(uint8数据)作为特征,最好是首先把数据转换成np.uint8的并保存,在这种情况下它只占1.1MB。然后在加载的时候你可以把它转换会float32.
英语字母表的OCR
下面我们队英语字母表做同样处理,但是在数据和特征集上做一些小的修改。这里OpenCV提供了数据文件。opencv/samples/cpp/letter-recognition.data。如果你打开,你会看到20000根线,像垃圾一样,实际上,在每行,第一列是一个字母作为标签,跟着的16个数字是它的不同特征,这些特征是从UCI机器学习库里得到的。
有20000个样本,所以我们去前10000个数据作为训练样本,剩下的10000作为测试样本。我们应该把字母表变成ascii字符因为我们没法直接处理字母。
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the data, converters convert the letter to a number
data= https://www.it610.com/article/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 test
train, test = np.vsplit(data,2)
# split trainData and testData to features and responses
responses, trainData = https://www.it610.com/article/np.hsplit(train,[1])
labels, testData = https://www.it610.com/article/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/10000
print accuracy
这个的准确率是93.22%,如果要增加准确率,你可以增加误差数据。

    推荐阅读