-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.py
88 lines (71 loc) · 2.41 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Better samples/python2/opt_flow.py
## reference
# - http://stackoverflow.com/questions/2601194/displaying-a-webcam-feed-using-opencv-and-python
# - http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html
from __future__ import print_function
import cv2
from OpticalFlowShowcase import *
usage_text = '''
Hit followings to switch to:
1 - Dense optical flow by HSV color image (default);
2 - Dense optical flow by lines;
3 - Dense optical flow by warped image;
4 - Lucas-Kanade method.
Hit 's' to save image.
Hit 'f' to flip image horizontally.
Hit ESC to exit.
'''
def main():
## private routines
def change(key, prevFrame):
message, type = {
ord('1'): ('==> Dense_by_hsv', 'dense_hsv'),
ord('2'): ('==> Dense_by_lines', 'dense_lines'),
ord('3'): ('==> Dense_by_warp', 'dense_warp'),
ord('4'): ('==> Lucas-Kanade', 'lucas_kanade')
}.get(key, ('==> Dense_by_hsv', 'dense_hsv'))
print(message)
of = CreateOpticalFlow(type)
of.set1stFrame(prevFrame)
return of
def capture(vc):
rval, frame = vc.read()
if rval and flipImage:
frame = cv2.flip(frame, 1)
return (rval, frame)
## main starts here
flipImage = True
vc = cv2.VideoCapture(0)
if not vc.isOpened():
exit -1
cv2.namedWindow("preview")
### try to get the first frame
rval, frame = capture(vc)
if rval:
of = change('1', frame)
### main work
while rval:
rval, frame = capture(vc)
### do it
img = of.apply(frame)
cv2.imshow("preview", img)
### key operation
key = cv2.waitKey(1)
if key == 27: # exit on ESC
print('Closing...')
break
elif key == ord('s'): # save
cv2.imwrite('img_raw.png',frame)
cv2.imwrite('img_w_flow.png',img)
print("Saved raw frame as 'img_raw.png' and displayed as 'img_w_flow.png'")
elif key == ord('f'): # save
flipImage = not flipImage
print("Flip image: " + {True:"ON", False:"OFF"}.get(flipImage))
elif ord('1') <= key and key <= ord('4'):
of = change(key, frame)
## finish
vc.release()
cv2.destroyWindow("preview")
if __name__ == '__main__':
print(usage_text)
main()