-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopticalflow.py
More file actions
50 lines (38 loc) · 1.19 KB
/
opticalflow.py
File metadata and controls
50 lines (38 loc) · 1.19 KB
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
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
# Create old frame
_, frame = cap.read()
old_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Lucas kanade params
lk_params = dict(winSize = (15, 15),
maxLevel = 4,
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
# Mouse function
def select_point(event, x, y, flags, params):
global point, point_selected, old_points
if event == cv2.EVENT_LBUTTONDOWN:
point = (x, y)
point_selected = True
old_points = np.array([[x, y]], dtype=np.float32)
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", select_point)
point_selected = False
point = ()
old_points = np.array([[]],dtype=np.float32)
while True:
_, frame = cap.read()
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if point_selected is True:
cv2.circle(frame, point, 5, (0, 0, 255), 2)
new_points, status, error = cv2.calcOpticalFlowPyrLK(old_gray, gray_frame, old_points, None, **lk_params)
old_gray = gray_frame.copy()
old_points = new_points
x, y = new_points.ravel()
cv2.circle(frame, (x, y), 5, (0, 255, 0), -1)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()