Python 2.7 如何在Python中使用SVM实现用于手写识别的.dat文件

Python 2.7 如何在Python中使用SVM实现用于手写识别的.dat文件,python-2.7,opencv,svm,digital-handwritting,Python 2.7,Opencv,Svm,Digital Handwritting,我一直在尝试基于OpenCV库上的代码,使用SVM训练手写数字。我的培训内容如下: 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_INVE

我一直在尝试基于OpenCV库上的代码,使用SVM训练手写数字。我的培训内容如下:

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')
导入cv2
将numpy作为np导入
SZ=20
bin_n=16
svm_参数=dict(内核类型=cv2.svm_线性,
svm_类型=cv2.svm_C_SVC,
C=2.67,γ=5.383)
仿射标志=cv2.扭曲逆映射| cv2.内部线性
def deskew(img):
m=cv2.力矩(img)
如果abs(m['mu02'])小于1e-2:
返回img.copy()
歪斜=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)
返回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.卡特波尔(gx,gy)
bin=np.int32(bin_n*ang/(2*np.pi))#量化(0…16)中的bin值
bin_单元格=存储箱[:10,:10]、存储箱[10:,:10]、存储箱[:10,10:],存储箱[10:,10:]
mag_单元=mag[:10,:10],mag[10:,:10],mag[:10,10:],mag[10:,10:]
hists=[np.bincount(b.ravel(),m.ravel(),bin_n)表示zip中的b,m(bin_单元格,mag_单元格)]
hist=np.hstack(hists)#hist是一个64位向量
返回历史记录
img=cv2.imread('digits.png',0)
如果img为无:
引发异常(“我们需要此处示例/数据中的digits.png图像!”)
cells=[np.hsplit(行,100)表示np.vsplit(img,50)中的行]
列单元=[i[:50]表示单元中的i]
test_cells=[i[50:]表示单元中的i]
deskewed=[列单元中行的映射(deskew,行)]
hogdata=[Deskweed中行的映射(hog,row]
trainData=np.float32(hogdata)。重塑(-1,64)
responses=np.float32(np.repeat(np.arange(10),250)[:,np.newaxis])
svm=cv2.svm()
训练(训练数据、响应、参数=svm_参数)
save('svm_data.dat'))
这里是digits.png

结果,我得到了svm_data.dat文件。但是现在我不知道如何实现这个模型。假设我想在这里读这个数字


有人能帮我吗?

我假设“如何实现模型”是指“如何预测新图像的标签”

首先,请注意,这与保存的
svm_data.dat
本身无关,除非您希望在不同的脚本/会话中执行此操作,在这种情况下,您可以从文件中重新加载经过训练的
svm
对象

因此,预测新数据需要三个步骤:

  • 如果新数据与训练数据存在差异,请对其进行预处理,使其与训练数据相匹配(请参见下面的反转和调整大小)

  • 提取特征的方法与提取训练数据的方法相同

  • 使用经过训练的分类器预测标签

  • 对于您上载的示例图像,可以按如下方式执行:

    # 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


    此外,仔细观察图像会发现它与训练数据(更多的背景,不同的平均值)仍然有点不同,因此,如果分类器在这样的图像上的表现比所使用的测试数据(仅为训练数据的一半)差一点,我也不会感到惊讶。但是,这取决于特征提取对训练图像和预测图像之间的差异的敏感程度。

    我假设“如何实现模型”是指“如何预测新图像的标签”

    首先,请注意,这与保存的
    svm_data.dat
    本身无关,除非您希望在不同的脚本/会话中执行此操作,在这种情况下,您可以从文件中重新加载经过训练的
    svm
    对象

    因此,预测新数据需要三个步骤:

  • 如果新数据与训练数据存在差异,请对其进行预处理,使其与训练数据相匹配(请参见下面的反转和调整大小)

  • 提取特征的方法与提取训练数据的方法相同

  • 使用经过训练的分类器预测标签

  • 对于您上载的示例图像,可以按如下方式执行:

    # 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

    此外,仔细观察图像会发现它与训练数据(更多的背景,不同的平均值)仍然有点不同,因此,如果分类器在这样的图像上的表现比所使用的测试数据(仅为训练数据的一半)差一点,我也不会感到惊讶。但是,这取决于特征提取对训练图像和预测图像之间的差异的敏感程度