Repository navigation
Expand file tree
/
Copy pathsort.py
More file actions
180 lines (155 loc) · 6.46 KB
/
Copy pathsort.py
File metadata and controls
180 lines (155 loc) · 6.46 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# SORT tracker (Simple Online and Realtime Tracking), Bewley et al. 2016
# Every object gets a Kalman filter, and boxes are matched to tracks with the Hungarian algorithm on IoU.
from collections import deque
import numpy as np
from scipy.optimize import linear_sum_assignment
def iou_batch(a, b):
# IoU of every box in a with every box in b, boxes are x1,y1,x2,y2
a = np.expand_dims(a, 1)
b = np.expand_dims(b, 0)
w = np.maximum(0, np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]))
h = np.maximum(0, np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]))
inter = w * h
area_a = (a[..., 2] - a[..., 0]) * (a[..., 3] - a[..., 1])
area_b = (b[..., 2] - b[..., 0]) * (b[..., 3] - b[..., 1])
return inter / (area_a + area_b - inter + 1e-9)
def bbox_to_z(bbox):
# x1,y1,x2,y2 -> centre x, centre y, area, aspect ratio
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
return np.array([bbox[0] + w / 2, bbox[1] + h / 2, w * h, w / (h + 1e-9)], dtype=float).reshape(4, 1)
def x_to_bbox(x):
# back from the Kalman state to x1,y1,x2,y2
s = max(float(x[2, 0]), 1e-6)
r = max(float(x[3, 0]), 1e-6)
w = np.sqrt(s * r)
h = s / w
cx, cy = float(x[0, 0]), float(x[1, 0])
return np.array([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2])
class KalmanBoxTracker:
count = 0
def __init__(self, bbox, cls, conf):
# state = [cx, cy, area, ratio, vx, vy, v_area]
self.F = np.eye(7)
self.F[0, 4] = self.F[1, 5] = self.F[2, 6] = 1.0
self.H = np.zeros((4, 7))
self.H[:4, :4] = np.eye(4)
self.R = np.eye(4)
self.R[2:, 2:] *= 10.0
self.P = np.eye(7)
self.P[4:, 4:] *= 1000.0
self.P *= 10.0
self.Q = np.eye(7)
self.Q[-1, -1] *= 0.01
self.Q[4:, 4:] *= 0.01
self.x = np.zeros((7, 1))
self.x[:4] = bbox_to_z(bbox)
KalmanBoxTracker.count += 1
self.id = KalmanBoxTracker.count
self.cls = cls
self.conf = conf
self.hits = 1
self.hit_streak = 1
self.time_since_update = 0
self.trail = deque(maxlen=40)
self.confirmed = False # was shown at least once
self.shown = False # was shown in the last detection frame
def predict(self):
if self.x[6, 0] + self.x[2, 0] <= 0:
self.x[6, 0] = 0.0
self.x = self.F @ self.x
self.P = self.F @ self.P @ self.F.T + self.Q
if self.time_since_update > 0:
self.hit_streak = 0
self.time_since_update += 1
return x_to_bbox(self.x)
def coast(self):
# same as predict but for frames where we have no detection, so the counters are left alone
if self.x[6, 0] + self.x[2, 0] <= 0:
self.x[6, 0] = 0.0
self.x = self.F @ self.x
self.P = self.F @ self.P @ self.F.T + self.Q
def update(self, bbox, cls, conf):
z = bbox_to_z(bbox)
y = z - self.H @ self.x
S = self.H @ self.P @ self.H.T + self.R
K = self.P @ self.H.T @ np.linalg.inv(S)
self.x = self.x + K @ y
self.P = (np.eye(7) - K @ self.H) @ self.P
self.cls = cls
self.conf = conf
self.time_since_update = 0
self.hits += 1
self.hit_streak += 1
def get_state(self):
return x_to_bbox(self.x)
class Sort:
def __init__(self, max_age=30, min_hits=3, iou_threshold=0.3, show_lost=2):
self.max_age = max_age
self.min_hits = min_hits
self.iou_threshold = iou_threshold
self.show_lost = show_lost # keep showing the predicted box when YOLO misses an object for a moment
self.trackers = []
self.frame_count = 0
KalmanBoxTracker.count = 0
def update(self, boxes, classes, confs):
# returns rows of [x1, y1, x2, y2, id, class, conf]
self.frame_count += 1
boxes = np.asarray(boxes, dtype=float).reshape(-1, 4)
classes = np.asarray(classes).reshape(-1)
confs = np.asarray(confs, dtype=float).reshape(-1)
# predict where the old tracks should be now
preds = []
for t in self.trackers:
p = t.predict()
preds.append(p if not np.isnan(p).any() else np.zeros(4))
preds = np.array(preds).reshape(-1, 4)
# match detections with tracks
matches = []
unmatched = list(range(len(boxes)))
if len(self.trackers) and len(boxes):
iou = iou_batch(preds, boxes)
# a car should never be matched with a person
same_class = np.array([[t.cls == c for c in classes] for t in self.trackers])
iou = np.where(same_class, iou, 0.0)
rows, cols = linear_sum_assignment(-iou)
for r, c in zip(rows, cols):
if iou[r, c] >= self.iou_threshold:
matches.append((r, c))
matched_dets = {m[1] for m in matches}
unmatched = [c for c in range(len(boxes)) if c not in matched_dets]
for r, c in matches:
self.trackers[r].update(boxes[c], classes[c], confs[c])
for c in unmatched:
self.trackers.append(KalmanBoxTracker(boxes[c], classes[c], confs[c]))
results = []
for t in self.trackers:
t.shown = False
if t.time_since_update <= self.show_lost and (t.confirmed or t.hit_streak >= self.min_hits or self.frame_count <= self.min_hits):
t.confirmed = True
t.shown = True
b = t.get_state()
t.trail.append((int((b[0] + b[2]) / 2), int(b[3])))
results.append([*b, t.id, t.cls, t.conf])
# drop tracks that were lost for too long
self.trackers = [t for t in self.trackers if t.time_since_update <= self.max_age]
return np.array(results, dtype=float).reshape(-1, 7)
def coast(self):
# for frames where YOLO was not run: move the visible tracks using their speed
results = []
for t in self.trackers:
if not t.shown:
continue
t.coast()
b = t.get_state()
if np.isnan(b).any():
t.shown = False
continue
t.trail.append((int((b[0] + b[2]) / 2), int(b[3])))
results.append([*b, t.id, t.cls, t.conf])
return np.array(results, dtype=float).reshape(-1, 7)
def get_trail(self, track_id):
for t in self.trackers:
if t.id == track_id:
return list(t.trail)
return []