digits.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. Usage:
  17. digits.py
  18. '''
  19. # Python 2/3 compatibility
  20. from __future__ import print_function
  21. # built-in modules
  22. from multiprocessing.pool import ThreadPool
  23. import cv2
  24. import numpy as np
  25. from numpy.linalg import norm
  26. # local modules
  27. from common import clock, mosaic
  28. SZ = 20 # size of each digit is SZ x SZ
  29. CLASS_N = 10
  30. DIGITS_FN = '../data/digits.png'
  31. def split2d(img, cell_size, flatten=True):
  32. h, w = img.shape[:2]
  33. sx, sy = cell_size
  34. cells = [np.hsplit(row, w//sx) for row in np.vsplit(img, h//sy)]
  35. cells = np.array(cells)
  36. if flatten:
  37. cells = cells.reshape(-1, sy, sx)
  38. return cells
  39. def load_digits(fn):
  40. print('loading "%s" ...' % fn)
  41. digits_img = cv2.imread(fn, 0)
  42. digits = split2d(digits_img, (SZ, SZ))
  43. labels = np.repeat(np.arange(CLASS_N), len(digits)/CLASS_N)
  44. return digits, labels
  45. def deskew(img):
  46. m = cv2.moments(img)
  47. if abs(m['mu02']) < 1e-2:
  48. return img.copy()
  49. skew = m['mu11']/m['mu02']
  50. M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
  51. img = cv2.warpAffine(img, M, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
  52. return img
  53. class StatModel(object):
  54. def load(self, fn):
  55. self.model.load(fn) # Known bug: https://github.com/Itseez/opencv/issues/4969
  56. def save(self, fn):
  57. self.model.save(fn)
  58. class KNearest(StatModel):
  59. def __init__(self, k = 3):
  60. self.k = k
  61. self.model = cv2.ml.KNearest_create()
  62. def train(self, samples, responses):
  63. self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
  64. def predict(self, samples):
  65. retval, results, neigh_resp, dists = self.model.findNearest(samples, self.k)
  66. return results.ravel()
  67. class SVM(StatModel):
  68. def __init__(self, C = 1, gamma = 0.5):
  69. self.model = cv2.ml.SVM_create()
  70. self.model.setGamma(gamma)
  71. self.model.setC(C)
  72. self.model.setKernel(cv2.ml.SVM_RBF)
  73. self.model.setType(cv2.ml.SVM_C_SVC)
  74. def train(self, samples, responses):
  75. self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
  76. def predict(self, samples):
  77. return self.model.predict(samples)[1].ravel()
  78. def evaluate_model(model, digits, samples, labels):
  79. resp = model.predict(samples)
  80. err = (labels != resp).mean()
  81. print('error: %.2f %%' % (err*100))
  82. confusion = np.zeros((10, 10), np.int32)
  83. for i, j in zip(labels, resp):
  84. confusion[i, j] += 1
  85. print('confusion matrix:')
  86. print(confusion)
  87. print()
  88. vis = []
  89. for img, flag in zip(digits, resp == labels):
  90. img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  91. if not flag:
  92. img[...,:2] = 0
  93. vis.append(img)
  94. return mosaic(25, vis)
  95. def preprocess_simple(digits):
  96. return np.float32(digits).reshape(-1, SZ*SZ) / 255.0
  97. def preprocess_hog(digits):
  98. samples = []
  99. for img in digits:
  100. gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
  101. gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
  102. mag, ang = cv2.cartToPolar(gx, gy)
  103. bin_n = 16
  104. bin = np.int32(bin_n*ang/(2*np.pi))
  105. bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[10:,10:]
  106. mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
  107. hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
  108. hist = np.hstack(hists)
  109. # transform to Hellinger kernel
  110. eps = 1e-7
  111. hist /= hist.sum() + eps
  112. hist = np.sqrt(hist)
  113. hist /= norm(hist) + eps
  114. samples.append(hist)
  115. return np.float32(samples)
  116. if __name__ == '__main__':
  117. print(__doc__)
  118. digits, labels = load_digits(DIGITS_FN)
  119. print('preprocessing...')
  120. # shuffle digits
  121. rand = np.random.RandomState(321)
  122. shuffle = rand.permutation(len(digits))
  123. digits, labels = digits[shuffle], labels[shuffle]
  124. digits2 = list(map(deskew, digits))
  125. samples = preprocess_hog(digits2)
  126. train_n = int(0.9*len(samples))
  127. cv2.imshow('test set', mosaic(25, digits[train_n:]))
  128. digits_train, digits_test = np.split(digits2, [train_n])
  129. samples_train, samples_test = np.split(samples, [train_n])
  130. labels_train, labels_test = np.split(labels, [train_n])
  131. print('training KNearest...')
  132. model = KNearest(k=4)
  133. model.train(samples_train, labels_train)
  134. vis = evaluate_model(model, digits_test, samples_test, labels_test)
  135. cv2.imshow('KNearest test', vis)
  136. print('training SVM...')
  137. model = SVM(C=2.67, gamma=5.383)
  138. model.train(samples_train, labels_train)
  139. vis = evaluate_model(model, digits_test, samples_test, labels_test)
  140. cv2.imshow('SVM test', vis)
  141. print('saving SVM as "digits_svm.dat"...')
  142. model.save('digits_svm.dat')
  143. cv2.waitKey(0)