Repository navigation
Expand file tree
/
Copy pathobject_tracking.py
More file actions
164 lines (141 loc) · 5.31 KB
/
Copy pathobject_tracking.py
File metadata and controls
164 lines (141 loc) · 5.31 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""YOLOv4 detection plus a small centroid tracker.
This is an educational tracker: detections are associated to existing tracks with a
greedy nearest-centroid match. It is deliberately simpler than a Kalman/ReID tracker.
"""
import argparse
import math
from pathlib import Path
import cv2
from object_detection import ObjectDetection
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--video", default="los_angeles.mp4", help="input video path")
parser.add_argument("--weights", default="dnn_model/yolov4.weights")
parser.add_argument("--cfg", default="dnn_model/yolov4.cfg")
parser.add_argument("--classes", default="dnn_model/classes.txt")
parser.add_argument("--output", help="optional output video path")
parser.add_argument("--display", action="store_true", help="show frames in a window")
parser.add_argument("--cpu", action="store_true", help="disable the CUDA preference")
parser.add_argument("--max-distance", type=float, default=50.0)
return parser.parse_args()
def draw_detection(frame, detection, class_names, color):
center, box, class_id, score = detection
x1, y1, x2, y2 = box
label = f"{class_names[class_id]} {score:.2f}"
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
cv2.circle(frame, center, 4, color, -1)
cv2.putText(
frame,
label,
(x1, max(18, y1 - 7)),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
color,
1,
cv2.LINE_AA,
)
def main():
args = parse_args()
video = Path(args.video)
if not video.is_file():
raise SystemExit(f"Video not found: {video}")
detector = ObjectDetection(
weights_path=args.weights,
cfg_path=args.cfg,
classes_path=args.classes,
use_cuda=not args.cpu,
)
print(f"YOLOv4 loaded on {detector.device}")
capture = cv2.VideoCapture(str(video))
if not capture.isOpened():
raise SystemExit(f"Could not open video: {video}")
writer = None
if args.output:
fps = capture.get(cv2.CAP_PROP_FPS) or 25.0
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
writer = cv2.VideoWriter(
args.output,
cv2.VideoWriter_fourcc(*"mp4v"),
fps,
(width, height),
)
if not writer.isOpened():
raise SystemExit(f"Could not create output video: {args.output}")
tracks = {}
next_track_id = 0
frame_count = 0
show = args.display or args.output is None
try:
while True:
ok, frame = capture.read()
if not ok:
break
frame_count += 1
class_ids, scores, boxes = detector.detect(frame)
detections = []
for class_id, score, box in zip(
class_ids.flatten(),
scores.flatten(),
boxes.reshape(-1, 4),
):
x, y, width, height = (int(value) for value in box)
center = (x + width // 2, y + height // 2)
detections.append(
(
center,
(x, y, x + width, y + height),
int(class_id),
float(score),
)
)
used = set()
updated_tracks = {}
for track_id, previous in tracks.items():
best_index = None
best_distance = args.max_distance
for index, detection in enumerate(detections):
if index in used:
continue
distance = math.dist(previous[0], detection[0])
if distance < best_distance:
best_index = index
best_distance = distance
if best_index is not None:
used.add(best_index)
updated_tracks[track_id] = detections[best_index]
for index, detection in enumerate(detections):
if index not in used:
updated_tracks[next_track_id] = detection
next_track_id += 1
tracks = updated_tracks
for track_id, detection in tracks.items():
color = tuple(
int(value) for value in detector.colors[detection[2] % len(detector.colors)]
)
draw_detection(frame, detection, detector.classes, color)
cv2.putText(
frame,
f"ID {track_id}",
(detection[0][0] + 6, detection[0][1] - 6),
cv2.FONT_HERSHEY_SIMPLEX,
0.45,
color,
1,
cv2.LINE_AA,
)
if writer is not None:
writer.write(frame)
if show:
cv2.imshow("YOLOv4 centroid tracker", frame)
if cv2.waitKey(1) & 0xFF == 27:
break
finally:
capture.release()
if writer is not None:
writer.release()
if show:
cv2.destroyAllWindows()
print(f"Processed {frame_count} frames; {next_track_id} track ids created")
if __name__ == "__main__":
main()