本文共 3298 字,大约阅读时间需要 10 分钟。
在 kNN 中我们直接使用像素的灰度值作为特征向量。这次我们要使用方向梯度直方图Histogram of Oriented Gradients (HOG)作为特征向量。
在计算 HOG 前我们使用图片的二阶矩对其进行抗扭斜(deskew)处理,也就是把歪了的图片摆正。所以我们首先要定义一个函数 deskew(),它可以对一个图像进行抗扭斜处理。下面就是 deskew() 函数:
# 使用方向梯度直方图Histogram of Oriented Gradients (HOG)作为特征向量def deskew(img): #对一个图像进行抗扭斜(deskew)处理,把歪了的图片摆正 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=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR) return img
接下来我们要计算图像的 HOG 描述符,创建一个函数hog()。为此我们计算图像 X 方向和 Y 方向的 Sobel 导数。然后计算得到每个像素的梯度的方向和大小。把这个梯度转换成 16 位的整数。将图像分为 4 个小的方块,对每一个小方块计算它们的朝向直方图(16 个 bin),使用梯度的大小做权重。这样每一个小方块都会得到一个含有 16 个成员的向量。4 个小方块的 4 个向量就组成了这个图像的特征向量(包含 64 个成员)。这就是我们要训练数据的特征向量。
def hog(img): gx = cv.Sobel(img, cv.CV_32F, 1, 0) gy = cv.Sobel(img, cv.CV_32F, 0, 1) mag, ang = cv.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
最后,和前面一样,我们将大图分割成小图。使用每个数字的前 250 个作为训练数据,后 250 个作为测试数据。全部代码如下所示:
import cv2 as cvimport numpy as npSZ=20bin_n = 16 # Number of binsaffine_flags = cv.WARP_INVERSE_MAP|cv.INTER_LINEARdef deskew(img): m = cv.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 = cv.warpAffine(img,M,(SZ, SZ),flags=affine_flags) return imgdef hog(img): gx = cv.Sobel(img, cv.CV_32F, 1, 0) gy = cv.Sobel(img, cv.CV_32F, 0, 1) mag, ang = cv.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 histimg = cv.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)]# First half is trainData, remaining is testDatatrain_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 = cv.ml.SVM_create()svm.setKernel(cv.ml.SVM_LINEAR)svm.setType(cv.ml.SVM_C_SVC)svm.setC(2.67)svm.setGamma(5.383)svm.train(trainData, cv.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==responsescorrect = np.count_nonzero(mask)print(correct*100.0/result.size)
93.8
参考链接:
转载地址:http://gkju.baihongyu.com/