Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/digits_video.py
16337 views
1
#!/usr/bin/env python
2
3
# Python 2/3 compatibility
4
from __future__ import print_function
5
6
import numpy as np
7
import cv2 as cv
8
9
# built-in modules
10
import os
11
import sys
12
13
# local modules
14
import video
15
from common import mosaic
16
17
from digits import *
18
19
def main():
20
try:
21
src = sys.argv[1]
22
except:
23
src = 0
24
cap = video.create_capture(src)
25
26
classifier_fn = 'digits_svm.dat'
27
if not os.path.exists(classifier_fn):
28
print('"%s" not found, run digits.py first' % classifier_fn)
29
return
30
31
if True:
32
model = cv.ml.SVM_load(classifier_fn)
33
else:
34
model = cv.ml.SVM_create()
35
model.load_(classifier_fn) #Known bug: https://github.com/opencv/opencv/issues/4969
36
37
while True:
38
_ret, frame = cap.read()
39
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
40
41
42
bin = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 31, 10)
43
bin = cv.medianBlur(bin, 3)
44
contours, heirs = cv.findContours( bin.copy(), cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)
45
try:
46
heirs = heirs[0]
47
except:
48
heirs = []
49
50
for cnt, heir in zip(contours, heirs):
51
_, _, _, outer_i = heir
52
if outer_i >= 0:
53
continue
54
x, y, w, h = cv.boundingRect(cnt)
55
if not (16 <= h <= 64 and w <= 1.2*h):
56
continue
57
pad = max(h-w, 0)
58
x, w = x - (pad // 2), w + pad
59
cv.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0))
60
61
bin_roi = bin[y:,x:][:h,:w]
62
63
m = bin_roi != 0
64
if not 0.1 < m.mean() < 0.4:
65
continue
66
'''
67
gray_roi = gray[y:,x:][:h,:w]
68
v_in, v_out = gray_roi[m], gray_roi[~m]
69
if v_out.std() > 10.0:
70
continue
71
s = "%f, %f" % (abs(v_in.mean() - v_out.mean()), v_out.std())
72
cv.putText(frame, s, (x, y), cv.FONT_HERSHEY_PLAIN, 1.0, (200, 0, 0), thickness = 1)
73
'''
74
75
s = 1.5*float(h)/SZ
76
m = cv.moments(bin_roi)
77
c1 = np.float32([m['m10'], m['m01']]) / m['m00']
78
c0 = np.float32([SZ/2, SZ/2])
79
t = c1 - s*c0
80
A = np.zeros((2, 3), np.float32)
81
A[:,:2] = np.eye(2)*s
82
A[:,2] = t
83
bin_norm = cv.warpAffine(bin_roi, A, (SZ, SZ), flags=cv.WARP_INVERSE_MAP | cv.INTER_LINEAR)
84
bin_norm = deskew(bin_norm)
85
if x+w+SZ < frame.shape[1] and y+SZ < frame.shape[0]:
86
frame[y:,x+w:][:SZ, :SZ] = bin_norm[...,np.newaxis]
87
88
sample = preprocess_hog([bin_norm])
89
digit = model.predict(sample)[0]
90
cv.putText(frame, '%d'%digit, (x, y), cv.FONT_HERSHEY_PLAIN, 1.0, (200, 0, 0), thickness = 1)
91
92
93
cv.imshow('frame', frame)
94
cv.imshow('bin', bin)
95
ch = cv.waitKey(1)
96
if ch == 27:
97
break
98
99
if __name__ == '__main__':
100
main()
101
cv.destroyAllWindows()
102
103