【OpenCV-Python】教程:7-6 SVM识别手写字符

OpenCV Python SVM 识别手写字符

【目标】

  • 用 SVM 识别手写字符

【代码】

在kNN中,直接用的是像素亮度值,这次,我们将使用 Histogram of Oriented Gradients (HOG) 作为特征向量

import cv2
import numpy as np

SZ = 20
bin_n = 16  # Number of bins
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

# HOG 特征
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(cv2.samples.findFile('assets/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)]
# First half is trainData, remaining is testData
train_cells = [i[:50] for i in cells]
test_cells = [i[50:] for i in cells]

# 图像校正
deskewed = [list(map(deskew, row)) for row in train_cells]

# 提取特征
hogdata = [list(map(hog, row)) for row in deskewed]

# 训练数据
trainData = np.float32(hogdata).reshape(-1, 64)
responses = np.repeat(np.arange(10), 250)[:, np.newaxis]

# 创建分类器和设置参数
svm = cv2.ml.SVM_create()
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.setType(cv2.ml.SVM_C_SVC)
svm.setC(2.67)
svm.setGamma(5.383)

# 训练
svm.train(trainData, cv2.ml.ROW_SAMPLE, responses)

# 保存参数
svm.save('svm_data.dat')

# 测试
deskewed = [list(map(deskew, row)) for row in test_cells]
hogdata = [list(map(hog, row)) for row in deskewed]
testData = np.float32(hogdata).reshape(-1, bin_n*4)

result = svm.predict(testData)[1]
mask = result == responses
correct = np.count_nonzero(mask)
print(correct*100.0/result.size)

【接口】

  • SVM_create
cv.ml.SVM_create() ->	retval

创建一个空的模型,使用StatModel::train 训练模型,由于SVM有很多参数,并且需要寻找最好的参数,可以使用SVM::trainAuto 自动训练使用最好的参数。

其他见:cv::ml::SVM Class Reference

【参考】

  1. OCR of Hand-written Data using SVM
  2. Histograms of Oriented Gradients Video
  3. Histogram of Oriented Gradients (HOG)
  4. cv::ml::SVM Class Reference

你可能感兴趣的:(#,OpenCV-Python,教程,opencv,python)