1+ import cv2
2+ import sys
3+
4+ (major_ver , minor_ver , subminor_ver ) = (cv2 .__version__ ).split ('.' )
5+
6+ if __name__ == '__main__' :
7+
8+ # Set up tracker.
9+ # Instead of MIL, you can also use
10+
11+ tracker_types = ['BOOSTING' , 'MIL' ,'KCF' , 'TLD' , 'MEDIANFLOW' , 'GOTURN' , 'MOSSE' , 'CSRT' ]
12+ tracker_type = tracker_types [2 ]
13+
14+ if int (minor_ver ) < 3 :
15+ tracker = cv2 .Tracker_create (tracker_type )
16+ else :
17+ if tracker_type == 'BOOSTING' :
18+ tracker = cv2 .TrackerBoosting_create ()
19+ if tracker_type == 'MIL' :
20+ tracker = cv2 .TrackerMIL_create ()
21+ if tracker_type == 'KCF' :
22+ tracker = cv2 .TrackerKCF_create ()
23+ if tracker_type == 'TLD' :
24+ tracker = cv2 .TrackerTLD_create ()
25+ if tracker_type == 'MEDIANFLOW' :
26+ tracker = cv2 .TrackerMedianFlow_create ()
27+ if tracker_type == 'GOTURN' :
28+ tracker = cv2 .TrackerGOTURN_create ()
29+ if tracker_type == 'MOSSE' :
30+ tracker = cv2 .TrackerMOSSE_create ()
31+ if tracker_type == "CSRT" :
32+ tracker = cv2 .TrackerCSRT_create ()
33+
34+ # Read video
35+ video = 'videos/traffic.mp4'
36+ cap = cv2 .VideoCapture (video )
37+
38+ # Exit if video not opened.
39+ if not cap .isOpened ():
40+ print ("Could not open video" )
41+ sys .exit ()
42+
43+ # Read first frame.
44+ ok , frame = cap .read ()
45+ if not ok :
46+ print ('Cannot read video file' )
47+ sys .exit ()
48+
49+ # Define an initial bounding box
50+ bbox = (287 , 23 , 86 , 320 )
51+
52+ # Uncomment the line below to select a different bounding box
53+ bbox = cv2 .selectROI (frame , False )
54+
55+ # Initialize tracker with first frame and bounding box
56+ ok = tracker .init (frame , bbox )
57+
58+ while True :
59+ # Read a new frame
60+ ok , frame = cap .read ()
61+ if not ok :
62+ break
63+
64+ # Start timer
65+ timer = cv2 .getTickCount ()
66+
67+ # Update tracker
68+ ok , bbox = tracker .update (frame )
69+
70+ # Calculate Frames per second (FPS)
71+ fps = cv2 .getTickFrequency () / (cv2 .getTickCount () - timer );
72+
73+ # Draw bounding box
74+ if ok :
75+ # Tracking success
76+ p1 = (int (bbox [0 ]), int (bbox [1 ]))
77+ p2 = (int (bbox [0 ] + bbox [2 ]), int (bbox [1 ] + bbox [3 ]))
78+ cv2 .rectangle (frame , p1 , p2 , (255 ,0 ,0 ), 2 , 1 )
79+ else :
80+ # Tracking failure
81+ cv2 .putText (frame , "Tracking failure detected" , (100 ,80 ), cv2 .FONT_HERSHEY_SIMPLEX , 0.75 ,(0 ,0 ,255 ),2 )
82+
83+ # Display tracker type on frame
84+ cv2 .putText (frame , tracker_type + " Tracker" , (100 ,20 ), cv2 .FONT_HERSHEY_SIMPLEX , 0.75 , (50 ,170 ,50 ),2 );
85+
86+ # Display FPS on frame
87+ cv2 .putText (frame , "FPS : " + str (int (fps )), (100 ,50 ), cv2 .FONT_HERSHEY_SIMPLEX , 0.75 , (50 ,170 ,50 ), 2 );
88+
89+ # Display result
90+ cv2 .imshow ("Tracking" , frame )
91+
92+ # Exit if ESC pressed
93+ k = cv2 .waitKey (1 ) & 0xff
94+ if k == 27 : break
0 commit comments