关于使用OpenCV实现,手写体的OCR应用程序。参考OpenCV官方文档。
比较坑的是一个是OpenCV版本使用接口不一样,我装的opencv3.4,查的确实3.0的指南,以为没什么差别。结果一个是数据’digits.png’,这张图是缺失,应该是装轮子时每装这个,一个是函数KNearest()变了,3.0的和3.4的不一样。另外说一句,官方使用2.x的语法,我用的3.6的编译器。
后来我找到自己以前下的OpenCV,从其解压后的文件夹opencv/samples/data/里找到了这张图。另外说一句,学OpenCV下这么一个包还是不错的,里面还有不少官方例子,放在examples里。OpenCV3.2链接:https://pan.baidu.com/s/1_UdGjrwFUITCy6JcScMjwA 密码:v0td。
digits.png有5000个手写数字(每个数字500)。每个数字都是20x20的图像。所以我们的第一步是将这个图像分成5000个不同的数字。对于每个数字,先将其拼合成400像素的单行。然后使用每个数字的前250个样本作为train_data,使用250个样本作为test_data。
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.ml.KNearest_create()
knn.train(train, cv2.ml.ROW_SAMPLE, train_labels)
ret,result,neighbours,dist = knn.findNearest(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)
然而准确率只有91.76%。
OpenCV官方链接