OpenCV Python实现KNN手写数字与英文字母识别

阿澈
阿澈
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍如何使用OpenCV和Python中的KNN算法实现手写数字与英文字母的OCR识别。通过处理digits.png和letter-recognition.data数据集,演示数据预处理、模型训练及准确率评估。手写数字识别准确率达91.76%,英文字母识别准确率为93.06%,并提供了保存训练数据以提升后续效率的方法。

基于KNN的手写数据OCR识别

手写数字的OCR识别

我们的目标是构建一个能够读取手写数字的应用程序。为此,我们需要准备训练数据(train_data)和测试数据(test_data)。OpenCV自带一个名为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识别

在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 相关产品和应用

全部下载

专题列表