test_digits.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. #!/usr/bin/env python
  2. '''
  3. SVM and KNearest digit recognition.
  4. Sample loads a dataset of handwritten digits from '../data/digits.png'.
  5. Then it trains a SVM and KNearest classifiers on it and evaluates
  6. their accuracy.
  7. Following preprocessing is applied to the dataset:
  8. - Moment-based image deskew (see deskew())
  9. - Digit images are split into 4 10x10 cells and 16-bin
  10. histogram of oriented gradients is computed for each
  11. cell
  12. - Transform histograms to space with Hellinger metric (see [1] (RootSIFT))
  13. [1] R. Arandjelovic, A. Zisserman
  14. "Three things everyone should know to improve object retrieval"
  15. http://www.robots.ox.ac.uk/~vgg/publications/2012/Arandjelovic12/arandjelovic12.pdf
  16. '''
  17. # Python 2/3 compatibility
  18. from __future__ import print_function
  19. # built-in modules
  20. from multiprocessing.pool import ThreadPool
  21. import cv2 as cv
  22. import numpy as np
  23. from numpy.linalg import norm
  24. SZ = 20 # size of each digit is SZ x SZ
  25. CLASS_N = 10
  26. DIGITS_FN = 'samples/data/digits.png'
  27. def split2d(img, cell_size, flatten=True):
  28. h, w = img.shape[:2]
  29. sx, sy = cell_size
  30. cells = [np.hsplit(row, w//sx) for row in np.vsplit(img, h//sy)]
  31. cells = np.array(cells)
  32. if flatten:
  33. cells = cells.reshape(-1, sy, sx)
  34. return cells
  35. def deskew(img):
  36. m = cv.moments(img)
  37. if abs(m['mu02']) < 1e-2:
  38. return img.copy()
  39. skew = m['mu11']/m['mu02']
  40. M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
  41. img = cv.warpAffine(img, M, (SZ, SZ), flags=cv.WARP_INVERSE_MAP | cv.INTER_LINEAR)
  42. return img
  43. class StatModel(object):
  44. def load(self, fn):
  45. self.model.load(fn) # Known bug: https://github.com/opencv/opencv/issues/4969
  46. def save(self, fn):
  47. self.model.save(fn)
  48. class KNearest(StatModel):
  49. def __init__(self, k = 3):
  50. self.k = k
  51. self.model = cv.ml.KNearest_create()
  52. def train(self, samples, responses):
  53. self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
  54. def predict(self, samples):
  55. _retval, results, _neigh_resp, _dists = self.model.findNearest(samples, self.k)
  56. return results.ravel()
  57. class SVM(StatModel):
  58. def __init__(self, C = 1, gamma = 0.5):
  59. self.model = cv.ml.SVM_create()
  60. self.model.setGamma(gamma)
  61. self.model.setC(C)
  62. self.model.setKernel(cv.ml.SVM_RBF)
  63. self.model.setType(cv.ml.SVM_C_SVC)
  64. def train(self, samples, responses):
  65. self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
  66. def predict(self, samples):
  67. return self.model.predict(samples)[1].ravel()
  68. def evaluate_model(model, digits, samples, labels):
  69. resp = model.predict(samples)
  70. err = (labels != resp).mean()
  71. confusion = np.zeros((10, 10), np.int32)
  72. for i, j in zip(labels, resp):
  73. confusion[int(i), int(j)] += 1
  74. return err, confusion
  75. def preprocess_simple(digits):
  76. return np.float32(digits).reshape(-1, SZ*SZ) / 255.0
  77. def preprocess_hog(digits):
  78. samples = []
  79. for img in digits:
  80. gx = cv.Sobel(img, cv.CV_32F, 1, 0)
  81. gy = cv.Sobel(img, cv.CV_32F, 0, 1)
  82. mag, ang = cv.cartToPolar(gx, gy)
  83. bin_n = 16
  84. bin = np.int32(bin_n*ang/(2*np.pi))
  85. bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[10:,10:]
  86. mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
  87. hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
  88. hist = np.hstack(hists)
  89. # transform to Hellinger kernel
  90. eps = 1e-7
  91. hist /= hist.sum() + eps
  92. hist = np.sqrt(hist)
  93. hist /= norm(hist) + eps
  94. samples.append(hist)
  95. return np.float32(samples)
  96. from tests_common import NewOpenCVTests
  97. class digits_test(NewOpenCVTests):
  98. def load_digits(self, fn):
  99. digits_img = self.get_sample(fn, 0)
  100. digits = split2d(digits_img, (SZ, SZ))
  101. labels = np.repeat(np.arange(CLASS_N), len(digits)/CLASS_N)
  102. return digits, labels
  103. def test_digits(self):
  104. digits, labels = self.load_digits(DIGITS_FN)
  105. # shuffle digits
  106. rand = np.random.RandomState(321)
  107. shuffle = rand.permutation(len(digits))
  108. digits, labels = digits[shuffle], labels[shuffle]
  109. digits2 = list(map(deskew, digits))
  110. samples = preprocess_hog(digits2)
  111. train_n = int(0.9*len(samples))
  112. _digits_train, digits_test = np.split(digits2, [train_n])
  113. samples_train, samples_test = np.split(samples, [train_n])
  114. labels_train, labels_test = np.split(labels, [train_n])
  115. errors = list()
  116. confusionMatrixes = list()
  117. model = KNearest(k=4)
  118. model.train(samples_train, labels_train)
  119. error, confusion = evaluate_model(model, digits_test, samples_test, labels_test)
  120. errors.append(error)
  121. confusionMatrixes.append(confusion)
  122. model = SVM(C=2.67, gamma=5.383)
  123. model.train(samples_train, labels_train)
  124. error, confusion = evaluate_model(model, digits_test, samples_test, labels_test)
  125. errors.append(error)
  126. confusionMatrixes.append(confusion)
  127. eps = 0.001
  128. normEps = len(samples_test) * 0.02
  129. confusionKNN = [[45, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  130. [ 0, 57, 0, 0, 0, 0, 0, 0, 0, 0],
  131. [ 0, 0, 59, 1, 0, 0, 0, 0, 1, 0],
  132. [ 0, 0, 0, 43, 0, 0, 0, 1, 0, 0],
  133. [ 0, 0, 0, 0, 38, 0, 2, 0, 0, 0],
  134. [ 0, 0, 0, 2, 0, 48, 0, 0, 1, 0],
  135. [ 0, 1, 0, 0, 0, 0, 51, 0, 0, 0],
  136. [ 0, 0, 1, 0, 0, 0, 0, 54, 0, 0],
  137. [ 0, 0, 0, 0, 0, 1, 0, 0, 46, 0],
  138. [ 1, 1, 0, 1, 1, 0, 0, 0, 2, 42]]
  139. confusionSVM = [[45, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  140. [ 0, 57, 0, 0, 0, 0, 0, 0, 0, 0],
  141. [ 0, 0, 59, 2, 0, 0, 0, 0, 0, 0],
  142. [ 0, 0, 0, 43, 0, 0, 0, 1, 0, 0],
  143. [ 0, 0, 0, 0, 40, 0, 0, 0, 0, 0],
  144. [ 0, 0, 0, 1, 0, 50, 0, 0, 0, 0],
  145. [ 0, 0, 0, 0, 1, 0, 51, 0, 0, 0],
  146. [ 0, 0, 1, 0, 0, 0, 0, 54, 0, 0],
  147. [ 0, 0, 0, 0, 0, 0, 0, 0, 47, 0],
  148. [ 0, 1, 0, 1, 0, 0, 0, 0, 1, 45]]
  149. self.assertLess(cv.norm(confusionMatrixes[0] - confusionKNN, cv.NORM_L1), normEps)
  150. self.assertLess(cv.norm(confusionMatrixes[1] - confusionSVM, cv.NORM_L1), normEps)
  151. self.assertLess(errors[0] - 0.034, eps)
  152. self.assertLess(errors[1] - 0.018, eps)
  153. if __name__ == '__main__':
  154. NewOpenCVTests.bootstrap()