喜欢算法的女青年

opencv2.4.13+python2.7学习笔记--使用 knn对手写数字OCR

阅读对象:熟悉knn、了解opencv和python。

1.knn理论介绍:算法学习笔记:knn理论介绍

2. opencv中knn函数

路径:opencv\sources\modules\ml\include\opencv2\ml\ml.hpp

3.案例

3.1数据集介绍

我们的目的是创建一个可以对手写数字进行识别的程序。为了达到这个目的我们需要训练数据和测试数据。OpenCV 安装包中有一副图片(/samples/python2/data/digits.png), 其中有5000 个手写数字(每个数字重复 500遍)。每个数字是一个20x20 的小图。 所以第一步就是将这个图像分割成 5000个不同的数字。我们在将拆分后的每一个数字的图像重排成一行含有 400 个像素点的新图像。这个就是我们的特征集,所有像素的灰度值。这是我们能创建的最简单的特征集。我们使用每个数字的前 250 个样本做训练数据,剩余的250 个做测试数据。

3.2代码

示例中得到的准确率为91.72%,和官网结果一样,可以结合统计中的抽样重新分配训练集和测试集,也可以尝试用不同的距离度量方法(或者相似度度量方法),取不同的K,重新进行数据实验,时间有限,我并没有去找哪个参数代表的是距离度量方法。[备注,方便查阅]

import numpy as np
import cv2
from matplotlib import pyplot as plt

dir='C:/Users/Thinkpad/Desktop/picture/'
img = cv2.imread(dir+'5.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

4.3中的图片

参考资料:[1]http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_ml/py_knn/py_knn_opencv/py_knn_opencv.html

end!!

 

posted on 2017-03-16 17:33  喜欢算法的女青年  阅读(734)  评论(0编辑  收藏  举报

导航