digits.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #!/usr/bin/env python
  2. '''
  3. SVM and KNearest digit recognition.
  4. Sample loads a dataset of handwritten digits from '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. import numpy as np
  22. import cv2 as cv
  23. # built-in modules
  24. from multiprocessing.pool import ThreadPool
  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 = '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. fn = cv.samples.findFile(fn)
  41. print('loading "%s" ...' % fn)
  42. digits_img = cv.imread(fn, cv.IMREAD_GRAYSCALE)
  43. digits = split2d(digits_img, (SZ, SZ))
  44. labels = np.repeat(np.arange(CLASS_N), len(digits)/CLASS_N)
  45. return digits, labels
  46. def deskew(img):
  47. m = cv.moments(img)
  48. if abs(m['mu02']) < 1e-2:
  49. return img.copy()
  50. skew = m['mu11']/m['mu02']
  51. M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
  52. img = cv.warpAffine(img, M, (SZ, SZ), flags=cv.WARP_INVERSE_MAP | cv.INTER_LINEAR)
  53. return img
  54. class KNearest(object):
  55. def __init__(self, k = 3):
  56. self.k = k
  57. self.model = cv.ml.KNearest_create()
  58. def train(self, samples, responses):
  59. self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
  60. def predict(self, samples):
  61. _retval, results, _neigh_resp, _dists = self.model.findNearest(samples, self.k)
  62. return results.ravel()
  63. def load(self, fn):
  64. self.model = cv.ml.KNearest_load(fn)
  65. def save(self, fn):
  66. self.model.save(fn)
  67. class SVM(object):
  68. def __init__(self, C = 1, gamma = 0.5):
  69. self.model = cv.ml.SVM_create()
  70. self.model.setGamma(gamma)
  71. self.model.setC(C)
  72. self.model.setKernel(cv.ml.SVM_RBF)
  73. self.model.setType(cv.ml.SVM_C_SVC)
  74. def train(self, samples, responses):
  75. self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
  76. def predict(self, samples):
  77. return self.model.predict(samples)[1].ravel()
  78. def load(self, fn):
  79. self.model = cv.ml.SVM_load(fn)
  80. def save(self, fn):
  81. self.model.save(fn)
  82. def evaluate_model(model, digits, samples, labels):
  83. resp = model.predict(samples)
  84. err = (labels != resp).mean()
  85. print('error: %.2f %%' % (err*100))
  86. confusion = np.zeros((10, 10), np.int32)
  87. for i, j in zip(labels, resp):
  88. confusion[i, int(j)] += 1
  89. print('confusion matrix:')
  90. print(confusion)
  91. print()
  92. vis = []
  93. for img, flag in zip(digits, resp == labels):
  94. img = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
  95. if not flag:
  96. img[...,:2] = 0
  97. vis.append(img)
  98. return mosaic(25, vis)
  99. def preprocess_simple(digits):
  100. return np.float32(digits).reshape(-1, SZ*SZ) / 255.0
  101. def preprocess_hog(digits):
  102. samples = []
  103. for img in digits:
  104. gx = cv.Sobel(img, cv.CV_32F, 1, 0)
  105. gy = cv.Sobel(img, cv.CV_32F, 0, 1)
  106. mag, ang = cv.cartToPolar(gx, gy)
  107. bin_n = 16
  108. bin = np.int32(bin_n*ang/(2*np.pi))
  109. bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[10:,10:]
  110. mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
  111. hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
  112. hist = np.hstack(hists)
  113. # transform to Hellinger kernel
  114. eps = 1e-7
  115. hist /= hist.sum() + eps
  116. hist = np.sqrt(hist)
  117. hist /= norm(hist) + eps
  118. samples.append(hist)
  119. return np.float32(samples)
  120. if __name__ == '__main__':
  121. print(__doc__)
  122. digits, labels = load_digits(DIGITS_FN)
  123. print('preprocessing...')
  124. # shuffle digits
  125. rand = np.random.RandomState(321)
  126. shuffle = rand.permutation(len(digits))
  127. digits, labels = digits[shuffle], labels[shuffle]
  128. digits2 = list(map(deskew, digits))
  129. samples = preprocess_hog(digits2)
  130. train_n = int(0.9*len(samples))
  131. cv.imshow('test set', mosaic(25, digits[train_n:]))
  132. digits_train, digits_test = np.split(digits2, [train_n])
  133. samples_train, samples_test = np.split(samples, [train_n])
  134. labels_train, labels_test = np.split(labels, [train_n])
  135. print('training KNearest...')
  136. model = KNearest(k=4)
  137. model.train(samples_train, labels_train)
  138. vis = evaluate_model(model, digits_test, samples_test, labels_test)
  139. cv.imshow('KNearest test', vis)
  140. print('training SVM...')
  141. model = SVM(C=2.67, gamma=5.383)
  142. model.train(samples_train, labels_train)
  143. vis = evaluate_model(model, digits_test, samples_test, labels_test)
  144. cv.imshow('SVM test', vis)
  145. print('saving SVM as "digits_svm.dat"...')
  146. model.save('digits_svm.dat')
  147. cv.waitKey(0)
  148. cv.destroyAllWindows()