我正在尝试通过Python 2.7接口使用OpenCV来实现一个基于机器学习的OCR应用程序,以从图像文件中解析出文本。我使用了这个教程(为方便起见,我在下面重新发布了代码)。我对机器学习完全是新手,对OpenCV也相对较新。
手写数字的OCR:
import numpy as npimport cv2from matplotlib import pyplot as pltimg = cv2.imread('digits.png')gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# Now we split the image to 5000 cells, each 20x20 sizecells = [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 datak = 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=1knn = 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 wrongmatches = result==test_labelscorrect = np.count_nonzero(matches)accuracy = correct*100.0/result.sizeprint accuracy# save the datanp.savez('knn_data.npz',train=train, train_labels=train_labels)# Now load the datawith np.load('knn_data.npz') as data: print data.files train = data['train'] train_labels = data['train_labels']
英文字母的OCR:
第二个代码片段(用于英文字母)从以下格式的.data
文件中获取输入:
T,2,8,3,5,1,8,13,0,6,6,10,8,0,8,0,8I,5,12,3,7,2,10,5,5,4,13,3,9,2,8,4,10D,4,11,6,8,6,10,6,2,6,10,3,7,3,7,3,9N,7,11,6,6,3,5,9,4,6,4,4,10,6,10,2,8G,2,1,3,1,1,8,6,6,6,6,5,9,1,7,5,10S,4,11,5,8,3,8,8,6,9,5,6,6,0,8,9,7B,4,2,5,4,4,8,7,6,6,7,6,6,2,8,7,10
…大约有20,000行这样的数据。这些数据描述了字符的轮廓。
我对其工作原理有基本的了解,但我对如何使用它来对图像进行实际的OCR感到困惑。我如何使用这段代码编写一个函数,该函数以cv2
图像作为参数并返回表示识别文本的字符串?
回答:
一般来说,机器学习的工作原理如下:首先,你必须训练你的程序理解问题的领域。然后你开始提问。
所以如果你在创建一个OCR,第一步是教你的程序字母A看起来是什么样的,然后是B,以此类推。
你使用OpenCV来清除图像中的噪声,并识别可能为字母的像素组并将它们隔离出来。
然后你将这些字母输入到你的OCR程序中。在训练模式下,你会输入图像并解释图像代表哪个字母。在询问模式下,你会输入图像并询问它是哪个字母。训练得越好,你的答案就越准确(程序可能会识别错误字母,总是有这种可能)。