Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/GOTURN/goturnTracker.py
3118 views
1
# Copyright 2018 Satya Mallick (LearnOpenCV.com)
2
3
# Import modules
4
import cv2, sys, os
5
6
if not (os.path.isfile('goturn.caffemodel') and os.path.isfile('goturn.prototxt')):
7
errorMsg = '''
8
Could not find GOTURN model in current directory.
9
Please ensure goturn.caffemodel and goturn.prototxt are in the current directory
10
'''
11
12
print(errorMsg)
13
sys.exit()
14
15
# Create tracker
16
tracker = cv2.TrackerGOTURN_create()
17
18
# Read video
19
video = cv2.VideoCapture("chaplin.mp4")
20
21
# Exit if video not opened
22
if not video.isOpened():
23
print("Could not open video")
24
sys.exit()
25
26
# Read first frame
27
ok,frame = video.read()
28
if not ok:
29
print("Cannot read video file")
30
sys.exit()
31
32
33
# Define a bounding box
34
bbox = (276, 23, 86, 320)
35
36
# Uncomment the line below to select a different bounding box
37
#bbox = cv2.selectROI(frame, False)
38
39
# Initialize tracker with first frame and bounding box
40
ok = tracker.init(frame,bbox)
41
42
while True:
43
# Read a new frame
44
ok, frame = video.read()
45
if not ok:
46
break
47
48
# Start timer
49
timer = cv2.getTickCount()
50
51
# Update tracker
52
ok, bbox = tracker.update(frame)
53
54
# Calculate Frames per second (FPS)
55
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);
56
57
# Draw bounding box
58
if ok:
59
# Tracking success
60
p1 = (int(bbox[0]), int(bbox[1]))
61
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
62
cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
63
else :
64
# Tracking failure
65
cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
66
67
# Display tracker type on frame
68
cv2.putText(frame, "GOTURN Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
69
70
# Display FPS on frame
71
cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);
72
73
# Display result
74
cv2.imshow("Tracking", frame)
75
76
# Exit if ESC pressed
77
k = cv2.waitKey(1) & 0xff
78
if k == 27:
79
break
80
81