mirror of https://github.com/opencv/opencv.git
Open Source Computer Vision Library
https://opencv.org/
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
187 lines
5.3 KiB
187 lines
5.3 KiB
12 years ago
|
#!/usr/bin/env python
|
||
12 years ago
|
|
||
12 years ago
|
'''
|
||
|
SVM and KNearest digit recognition.
|
||
|
|
||
10 years ago
|
Sample loads a dataset of handwritten digits from '../data/digits.png'.
|
||
12 years ago
|
Then it trains a SVM and KNearest classifiers on it and evaluates
|
||
|
their accuracy.
|
||
|
|
||
|
Following preprocessing is applied to the dataset:
|
||
|
- Moment-based image deskew (see deskew())
|
||
|
- Digit images are split into 4 10x10 cells and 16-bin
|
||
|
histogram of oriented gradients is computed for each
|
||
|
cell
|
||
|
- Transform histograms to space with Hellinger metric (see [1] (RootSIFT))
|
||
|
|
||
|
|
||
|
[1] R. Arandjelovic, A. Zisserman
|
||
|
"Three things everyone should know to improve object retrieval"
|
||
|
http://www.robots.ox.ac.uk/~vgg/publications/2012/Arandjelovic12/arandjelovic12.pdf
|
||
|
|
||
|
Usage:
|
||
|
digits.py
|
||
|
'''
|
||
|
|
||
9 years ago
|
|
||
|
# Python 2/3 compatibility
|
||
|
from __future__ import print_function
|
||
|
|
||
12 years ago
|
# built-in modules
|
||
12 years ago
|
from multiprocessing.pool import ThreadPool
|
||
12 years ago
|
|
||
|
import cv2
|
||
|
|
||
|
import numpy as np
|
||
12 years ago
|
from numpy.linalg import norm
|
||
|
|
||
12 years ago
|
# local modules
|
||
|
from common import clock, mosaic
|
||
|
|
||
|
|
||
|
|
||
12 years ago
|
SZ = 20 # size of each digit is SZ x SZ
|
||
|
CLASS_N = 10
|
||
10 years ago
|
DIGITS_FN = '../data/digits.png'
|
||
12 years ago
|
|
||
|
def split2d(img, cell_size, flatten=True):
|
||
|
h, w = img.shape[:2]
|
||
|
sx, sy = cell_size
|
||
|
cells = [np.hsplit(row, w//sx) for row in np.vsplit(img, h//sy)]
|
||
|
cells = np.array(cells)
|
||
|
if flatten:
|
||
|
cells = cells.reshape(-1, sy, sx)
|
||
|
return cells
|
||
|
|
||
|
def load_digits(fn):
|
||
9 years ago
|
print('loading "%s" ...' % fn)
|
||
12 years ago
|
digits_img = cv2.imread(fn, 0)
|
||
|
digits = split2d(digits_img, (SZ, SZ))
|
||
|
labels = np.repeat(np.arange(CLASS_N), len(digits)/CLASS_N)
|
||
|
return digits, labels
|
||
|
|
||
|
def deskew(img):
|
||
|
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
|
||
|
|
||
|
class StatModel(object):
|
||
|
def load(self, fn):
|
||
9 years ago
|
self.model.load(fn) # Known bug: https://github.com/Itseez/opencv/issues/4969
|
||
12 years ago
|
def save(self, fn):
|
||
|
self.model.save(fn)
|
||
|
|
||
|
class KNearest(StatModel):
|
||
|
def __init__(self, k = 3):
|
||
|
self.k = k
|
||
10 years ago
|
self.model = cv2.ml.KNearest_create()
|
||
12 years ago
|
|
||
|
def train(self, samples, responses):
|
||
10 years ago
|
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
|
||
12 years ago
|
|
||
|
def predict(self, samples):
|
||
10 years ago
|
retval, results, neigh_resp, dists = self.model.findNearest(samples, self.k)
|
||
12 years ago
|
return results.ravel()
|
||
|
|
||
|
class SVM(StatModel):
|
||
|
def __init__(self, C = 1, gamma = 0.5):
|
||
10 years ago
|
self.model = cv2.ml.SVM_create()
|
||
10 years ago
|
self.model.setGamma(gamma)
|
||
|
self.model.setC(C)
|
||
|
self.model.setKernel(cv2.ml.SVM_RBF)
|
||
|
self.model.setType(cv2.ml.SVM_C_SVC)
|
||
12 years ago
|
|
||
|
def train(self, samples, responses):
|
||
10 years ago
|
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
|
||
12 years ago
|
|
||
|
def predict(self, samples):
|
||
9 years ago
|
return self.model.predict(samples)[1].ravel()
|
||
12 years ago
|
|
||
|
|
||
|
def evaluate_model(model, digits, samples, labels):
|
||
|
resp = model.predict(samples)
|
||
|
err = (labels != resp).mean()
|
||
9 years ago
|
print('error: %.2f %%' % (err*100))
|
||
12 years ago
|
|
||
|
confusion = np.zeros((10, 10), np.int32)
|
||
|
for i, j in zip(labels, resp):
|
||
|
confusion[i, j] += 1
|
||
9 years ago
|
print('confusion matrix:')
|
||
|
print(confusion)
|
||
|
print()
|
||
12 years ago
|
|
||
|
vis = []
|
||
|
for img, flag in zip(digits, resp == labels):
|
||
|
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
|
||
|
if not flag:
|
||
|
img[...,:2] = 0
|
||
|
vis.append(img)
|
||
|
return mosaic(25, vis)
|
||
|
|
||
|
def preprocess_simple(digits):
|
||
|
return np.float32(digits).reshape(-1, SZ*SZ) / 255.0
|
||
|
|
||
|
def preprocess_hog(digits):
|
||
|
samples = []
|
||
|
for img in digits:
|
||
|
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
|
||
|
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
|
||
|
mag, ang = cv2.cartToPolar(gx, gy)
|
||
|
bin_n = 16
|
||
|
bin = np.int32(bin_n*ang/(2*np.pi))
|
||
|
bin_cells = bin[:10,:10], bin[10:,:10], bin[:10,10:], bin[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)
|
||
|
|
||
|
# transform to Hellinger kernel
|
||
|
eps = 1e-7
|
||
|
hist /= hist.sum() + eps
|
||
|
hist = np.sqrt(hist)
|
||
|
hist /= norm(hist) + eps
|
||
|
|
||
|
samples.append(hist)
|
||
|
return np.float32(samples)
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
9 years ago
|
print(__doc__)
|
||
12 years ago
|
|
||
|
digits, labels = load_digits(DIGITS_FN)
|
||
|
|
||
9 years ago
|
print('preprocessing...')
|
||
12 years ago
|
# shuffle digits
|
||
|
rand = np.random.RandomState(321)
|
||
|
shuffle = rand.permutation(len(digits))
|
||
|
digits, labels = digits[shuffle], labels[shuffle]
|
||
|
|
||
9 years ago
|
digits2 = list(map(deskew, digits))
|
||
12 years ago
|
samples = preprocess_hog(digits2)
|
||
|
|
||
|
train_n = int(0.9*len(samples))
|
||
|
cv2.imshow('test set', mosaic(25, digits[train_n:]))
|
||
|
digits_train, digits_test = np.split(digits2, [train_n])
|
||
|
samples_train, samples_test = np.split(samples, [train_n])
|
||
|
labels_train, labels_test = np.split(labels, [train_n])
|
||
|
|
||
|
|
||
9 years ago
|
print('training KNearest...')
|
||
12 years ago
|
model = KNearest(k=4)
|
||
|
model.train(samples_train, labels_train)
|
||
|
vis = evaluate_model(model, digits_test, samples_test, labels_test)
|
||
|
cv2.imshow('KNearest test', vis)
|
||
|
|
||
9 years ago
|
print('training SVM...')
|
||
12 years ago
|
model = SVM(C=2.67, gamma=5.383)
|
||
|
model.train(samples_train, labels_train)
|
||
|
vis = evaluate_model(model, digits_test, samples_test, labels_test)
|
||
|
cv2.imshow('SVM test', vis)
|
||
9 years ago
|
print('saving SVM as "digits_svm.dat"...')
|
||
12 years ago
|
model.save('digits_svm.dat')
|
||
|
|
||
|
cv2.waitKey(0)
|