OpenCV-Python教程:51.使用kNN做手寫數(shù)據(jù)OCR

手寫數(shù)字OCR

我們的目標是建立一個應(yīng)用可以讀手寫數(shù)字。為了這個我們需要一些訓(xùn)練數(shù)據(jù)和測試數(shù)據(jù)。OpenCV帶了一個圖像digits.png有5000個手寫數(shù)字(每個數(shù)字500個),每個數(shù)字是一個20x20的圖像,所以我們的第一步是把圖像分成5000個不同的數(shù)字。對于每個數(shù)字,我們把它放到一個400個像素的行上,這是我們的特征集,所有像素的強度值。這是我們創(chuàng)建的最簡單的特征集。我們使用每個數(shù)字的頭250個樣本作為訓(xùn)練數(shù)據(jù),后250個作為測試數(shù)據(jù)。所以讓我們先準備他們。

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

所以我們基本的OCR應(yīng)用準備好了,這個例子給我們91%的準確率。一個提高準確率的選項是加更多的訓(xùn)練數(shù)據(jù),特別是錯誤的。所以我最好是保存訓(xùn)練數(shù)據(jù),下次直接從文件讀取這些數(shù)據(jù)并開始分類。你可以用Numpy的函數(shù)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']

在我們系統(tǒng)里,它要用4.4MB的內(nèi)存,由于我們用強度值(uint8數(shù)據(jù))作為特征,最好是首先把數(shù)據(jù)轉(zhuǎn)換成np.uint8的并保存,在這種情況下它只占1.1MB。然后在加載的時候你可以把它轉(zhuǎn)換會float32.

英語字母表的OCR

下面我們隊英語字母表做同樣處理,但是在數(shù)據(jù)和特征集上做一些小的修改。這里OpenCV提供了數(shù)據(jù)文件。opencv/samples/cpp/letter-recognition.data。如果你打開,你會看到20000根線,像垃圾一樣,實際上,在每行,第一列是一個字母作為標簽,跟著的16個數(shù)字是它的不同特征,這些特征是從UCI機器學(xué)習(xí)庫里得到的。

有20000個樣本,所以我們?nèi)デ?0000個數(shù)據(jù)作為訓(xùn)練樣本,剩下的10000作為測試樣本。我們應(yīng)該把字母表變成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%,如果要增加準確率,你可以增加誤差數(shù)據(jù)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容