如何在 Python 中使用 SVM 实现 .dat 文件进行手写识别

Posted

技术标签:

【中文标题】如何在 Python 中使用 SVM 实现 .dat 文件进行手写识别【英文标题】:How to implement .dat file for handwritten recognition using SVM in Python 【发布时间】:2018-01-30 03:11:38 【问题描述】:

我一直在尝试根据 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')

这里是digits.png enter image description here

结果,我得到了 svm_data.dat 文件。但现在我不知道如何实现该模型。可以说我想在这里读到这个数字 enter image description here

谁能帮帮我?

【问题讨论】:

【参考方案1】:

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

首先,请注意这与保存的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

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

【讨论】:

以上是关于如何在 Python 中使用 SVM 实现 .dat 文件进行手写识别的主要内容,如果未能解决你的问题,请参考以下文章

sklearn中SVM的实现

如何使用 SIFT 和 SVM 实现通用图像分类器

SVM python小样例

svm+python实现

如何在python中打印SVM集群

如何在 Python 中使用 OpenCV 3.0 中的 HOG 功能训练 SVM 分类器?