OpenCV  3.1.0-dev
Open Source Computer Vision
OCR of Hand-written Data using SVM

Goal

In this chapter

OCR of Hand-written Digits

In kNN, we directly used pixel intensity as the feature vector. This time we will use Histogram of Oriented Gradients (HOG) as feature vectors.

Here, before finding the HOG, we deskew the image using its second order moments. So we first define a function deskew() which takes a digit image and deskew it. Below is the deskew() function:

1 def deskew(img):
2  m = cv2.moments(img)
3  if abs(m['mu02']) < 1e-2:
4  return img.copy()
5  skew = m['mu11']/m['mu02']
6  M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
7  img = cv2.warpAffine(img,M,(SZ, SZ),flags=affine_flags)
8  return img

Below image shows above deskew function applied to an image of zero. Left image is the original image and right image is the deskewed image.

deskew.jpg
image

Next we have to find the HOG Descriptor of each cell. For that, we find Sobel derivatives of each cell in X and Y direction. Then find their magnitude and direction of gradient at each pixel. This gradient is quantized to 16 integer values. Divide this image to four sub-squares. For each sub-square, calculate the histogram of direction (16 bins) weighted with their magnitude. So each sub-square gives you a vector containing 16 values. Four such vectors (of four sub-squares) together gives us a feature vector containing 64 values. This is the feature vector we use to train our data.

1 def hog(img):
2  gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
3  gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
4  mag, ang = cv2.cartToPolar(gx, gy)
5 
6  # quantizing binvalues in (0...16)
7  bins = np.int32(bin_n*ang/(2*np.pi))
8 
9  # Divide to 4 sub-squares
10  bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:]
11  mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
12  hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
13  hist = np.hstack(hists)
14  return hist

Finally, as in the previous case, we start by splitting our big dataset into individual cells. For every digit, 250 cells are reserved for training data and remaining 250 data is reserved for testing. Full code is given below:

1 import cv2
2 import numpy as np
3 
4 SZ=20
5 bin_n = 16 # Number of bins
6 
7 
8 affine_flags = cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR
9 
10 def deskew(img):
11  m = cv2.moments(img)
12  if abs(m['mu02']) < 1e-2:
13  return img.copy()
14  skew = m['mu11']/m['mu02']
15  M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
16  img = cv2.warpAffine(img,M,(SZ, SZ),flags=affine_flags)
17  return img
18 
19 def hog(img):
20  gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
21  gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
22  mag, ang = cv2.cartToPolar(gx, gy)
23  bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16)
24  bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:]
25  mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
26  hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
27  hist = np.hstack(hists) # hist is a 64 bit vector
28  return hist
29 
30 img = cv2.imread('digits.png',0)
31 
32 cells = [np.hsplit(row,100) for row in np.vsplit(img,50)]
33 
34 # First half is trainData, remaining is testData
35 train_cells = [ i[:50] for i in cells ]
36 test_cells = [ i[50:] for i in cells]
37 
38 ###### Now training ########################
39 
40 deskewed = [map(deskew,row) for row in train_cells]
41 hogdata = [map(hog,row) for row in deskewed]
42 trainData = np.float32(hogdata).reshape(-1,64)
43 responses = np.float32(np.repeat(np.arange(10),250)[:,np.newaxis])
44 
45 svm = cv2.ml.SVM_create()
46 svm.setKernel(cv2.ml.SVM_LINEAR)
47 svm.setType(cv2.ml.SVM_C_SVC)
48 svm.setC(2.67)
49 svm.setGamma(5.383)
50 
51 svm.train(trainData, cv2.ml.ROW_SAMPLE, responses)
52 svm.save('svm_data.dat')
53 
54 ###### Now testing ########################
55 
56 deskewed = [map(deskew,row) for row in test_cells]
57 hogdata = [map(hog,row) for row in deskewed]
58 testData = np.float32(hogdata).reshape(-1,bin_n*4)
59 result = svm.predict(testData)
60 
61 ####### Check Accuracy ########################
62 mask = result==responses
63 correct = np.count_nonzero(mask)
64 print correct*100.0/result.size

This particular technique gave me nearly 94% accuracy. You can try different values for various parameters of SVM to check if higher accuracy is possible. Or you can read technical papers on this area and try to implement them.

Additional Resources

  1. Histograms of Oriented Gradients Video

Exercises

  1. OpenCV samples contain digits.py which applies a slight improvement of the above method to get improved result. It also contains the reference. Check it and understand it.