2017-08-22 2 views
1

私はOpenCVライブラリのコードに基づいてSVMを使用して手書き数字を訓練しようとしています。私のトレーニング部分は以下の通りである:PythonでSVMを使用して手書き認識のための.datファイルを実装する方法

import cv2 
import numpy as np 

SZ=20 
bin_n = 16 
svm_params = dict(kernel_type = cv2.SVM_LINEAR, 
        svm_type = cv2.SVM_C_SVC, 
       C=2.67, gamma=5.383) 
affine_flags = cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR 

def deskew(img): 
    m = cv2.moments(img) 
    if abs(m['mu02']) < 1e-2: 
     return img.copy() 
    skew = m['mu11']/m['mu02'] 
    M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]]) 
    img = cv2.warpAffine(img,M,(SZ, SZ),flags=affine_flags) 
    return img 
def hog(img): 
    gx = cv2.Sobel(img, cv2.CV_32F, 1, 0) 
    gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) 
    mag, ang = cv2.cartToPolar(gx, gy) 
    bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16) 
    bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:] 
    mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:] 
    hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)] 
    hist = np.hstack(hists)  # hist is a 64 bit vector 
    return hist 

img = cv2.imread('digits.png',0) 
if img is None: 
    raise Exception("we need the digits.png image from samples/data here !") 


cells = [np.hsplit(row,100) for row in np.vsplit(img,50)] 

train_cells = [ i[:50] for i in cells ] 
test_cells = [ i[50:] for i in cells] 

deskewed = [map(deskew,row) for row in train_cells] 
hogdata = [map(hog,row) for row in deskewed] 
trainData = np.float32(hogdata).reshape(-1,64) 
responses = np.float32(np.repeat(np.arange(10),250)[:,np.newaxis]) 

svm = cv2.SVM() 
svm.train(trainData,responses, params=svm_params) 
svm.save('svm_data.dat') 

相続人digits.png enter image description here

その結果、私はsvm_data.datファイルを得ました。しかし、今はモデルの実装方法がわかりません。ここでこの番号を読もうとしています。 enter image description here

誰かが私を助けてくれますか?

答えて

0

「モデルの実装方法」とは、「新しいイメージのラベルを予測する方法」を意味します。

まず第一に、あなたからあなたの訓練を受けたsvmオブジェクトをリロードすることができ、その場合には、あなたが別のスクリプト/セッションでこれを行うにはしたくない限り、これは、保存されたsvm_data.dat自体とは何の関係もありませんのでご注意ファイル。新しいデータの予測を行う方法のうちそれと

は、三つのステップが必要です。あなたの新しいデータがトレーニングデータから何とか異なる場合、それはそれは、トレーニングデータと一致して前処理し、

  1. を(参照反転およびサイズ変更)。

  2. 抽出機能は、トレーニングデータの場合と同じように機能します。

  3. 訓練された分類器を使用してラベルを予測します。アップロードした例の画像については

次のように、これは行うことができます。

# Load the image 
img_predict = cv2.imread('predict.png', 0) 

# Preprocessing: this image is inverted compared to the training data 
# Here it is inverted back 
img_predict = np.invert(img_predict) 

# Preprocessing: it also has a completely different size 
# This resizes it to the same size as the training data 
img_predict = cv2.resize(img_predict, (20, 20), interpolation=cv2.INTER_CUBIC) 

# Extract the features 
img_predict_ready = np.float32(hog(deskew(img_predict))) 

# Reload the trained svm 
# Not necessary if predicting is done in the same session as training 
svm = cv2.SVM() 
svm.load("svm_data.dat") 

# Run the prediction 
prediction = svm.predict(img_predict_ready) 
print int(prediction) 

期待通りの出力が、0あります。

分類するデータをトレーニングに使用したデータと照合することは非常に重要です。この場合、サイズ変更のステップをスキップすると、画像の分類が誤って2になります。

さらに、画像を見てみると、トレーニングデータとは少し違っています(バックグラウンドが異なる、平均が異なる)ことが分かります。分類器で画像が少し悪化しても驚くことはありませんこれは、使用されたテストデータin the original tutorial(これはトレーニングデータのほんの半分)と比較されます。ただし、これは、フィーチャ抽出がトレーニング画像と予測画像の違いにどれだけ敏感であるかによって異なります。

関連する問題