opencv python 基于KNN的手写体识别的实例

yipeiwu_com5年前Python基础

OCR of Hand-written Data using kNN

OCR of Hand-written Digits

我们的目标是构建一个可以读取手写数字的应用程序, 为此,我们需要一些train_data和test_data. OpenCV附带一个images digits.png(在文件夹opencv\sources\samples\data\中),它有5000个手写数字(每个数字500个,每个数字是20x20图像).所以首先要将图片切割成5000个不同图片,每个数字变成一个单行400像素.前面的250个数字作为训练数据,后250个作为测试数据.

import numpy as np
import cv2
import matplotlib.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

进一步提高准确率的方法是增加训练数据,特别是错误的数据.每次训练时最好是保存训练数据,以便下次使用.

# 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']

OCR of English Alphabets

在opencv / samples / data /文件夹中附带一个数据文件letter-recognition.data.在每一行中,第一列是一个字母表,它是我们的标签. 接下来的16个数字是它的不同特征.

import numpy as np
import cv2
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.ml.KNearest_create()
knn.train(trainData, cv2.ml.ROW_SAMPLE, responses)
ret, result, neighbours, dist = knn.findNearest(testData, k=5)

correct = np.count_nonzero(result == labels)
accuracy = correct*100.0/10000
print( accuracy )

输出:93.06

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python2.7安装图文教程

python2.7安装图文教程

Python安装过程,供大家参考,具体内容如下 1.下载安装程序 我们安装Python的一个重要目的是为了用IAR编译CC2640 OAD文件时执行合并文件的脚本,所以我们一起来看看Py...

python实现微信小程序用户登录、模板推送

Python 实现微信小程序的用户登录 小程序可以通过官方提供的登录邓丽来获取用户身份的标示, 具体文档可以参考 官方文档, 通过流程时序可以看到, 对于需要和前端配合的服务端开发, 主...

Python 条件判断的缩写方法

return (1==1) ? "is easy" : "my god" //C...

使用Python制作简单的小程序IP查看器功能

使用Python制作简单的小程序IP查看器功能

前言 说实话,查看电脑的IP,也挺无聊的,但是够简单,所以就从这里开始吧。IP地址在操作系统里就可以直接查看。但是除了IP地址,我们也想通过IP获取地理地址和网络运营商情况。IP地址和地...

举例详解Python中循环语句的嵌套使用

 Python编程语言允许在一个循环内嵌套另一个循环。下面将介绍几个例子来说明这一概念。 语法 在Python中嵌套循环语句的语法如下: for iterating_var...