我们的目标是创建一个可以识别手写数字的应用。为此我们需要一些训练数据和测试数据。openCV带有数字图片digits.png (
opencv/samples/python2/data/
)带有5000个手写数字(每个数字是500个)。每张图片都是20*20大小。所以首先要将图片切割成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)
# 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
ORC app 准备就绪,在例子中可以得到91%的准确率。
进一步提高准确率的方法是增加训练数据,特别是错误的那个。开始开发应用之前,是收集训练数据,保存好,下次直接读取数据,并分类。
可以使用nump有函数,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,所以定义特征数值时,转换为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 cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the data, converters convert the letter to a number
data= 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 = 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/10000
print accuracy
准确率在93。22%