File size: 13,223 Bytes
06d6b9f
6bdcad8
1f6d97d
06d6b9f
7704bc6
 
1f6d97d
7704bc6
1f6d97d
7704bc6
b9b66e6
ec87247
1f6d97d
6bdcad8
1f6d97d
 
 
 
 
 
 
6bdcad8
1f6d97d
 
 
 
 
 
6bdcad8
1f6d97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bdcad8
7704bc6
 
1f6d97d
 
 
 
 
 
 
 
 
7704bc6
1f6d97d
 
 
7704bc6
 
b9b66e6
7704bc6
6bdcad8
1f6d97d
 
e96f282
7704bc6
 
 
ec87247
1f6d97d
 
7704bc6
 
e96f282
1f6d97d
 
 
6bdcad8
e96f282
7704bc6
 
 
ec87247
1f6d97d
e96f282
7704bc6
1f6d97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e96f282
7704bc6
1f6d97d
 
ec87247
 
1f6d97d
ec87247
1f6d97d
 
 
 
 
 
 
 
06d6b9f
1f6d97d
6bdcad8
06d6b9f
1f6d97d
 
 
 
 
 
 
 
 
06d6b9f
7704bc6
1f6d97d
7704bc6
 
6bdcad8
 
e96f282
1f6d97d
 
 
ec87247
1f6d97d
 
 
e96f282
1f6d97d
 
e96f282
1f6d97d
 
 
 
 
e96f282
1f6d97d
 
 
e96f282
1f6d97d
 
 
e96f282
1f6d97d
 
e96f282
1f6d97d
 
e96f282
1f6d97d
 
b9b66e6
1f6d97d
 
e96f282
1f6d97d
 
e96f282
1f6d97d
 
e96f282
1f6d97d
ec87247
1f6d97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec87247
6bdcad8
 
 
 
1f6d97d
 
 
 
6bdcad8
 
1f6d97d
6bdcad8
1f6d97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e96f282
1f6d97d
 
06d6b9f
1f6d97d
 
 
 
ec87247
6bdcad8
1f6d97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e96f282
1f6d97d
 
 
 
 
 
 
 
 
 
 
 
 
7704bc6
1f6d97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9b66e6
7704bc6
ec87247
 
 
 
 
06d6b9f
ec87247
 
 
e96f282
1f6d97d
 
ec87247
 
1f6d97d
 
ec87247
7704bc6
ec87247
 
 
1f6d97d
06d6b9f
1f6d97d
 
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""
DeepSORT Tracker Implementation - Complete Fixed Version
Uses Kalman filter for motion prediction + appearance features
"""
import numpy as np
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import cosine
from collections import deque
from typing import List, Optional, Tuple
import uuid
from detection import Detection

class KalmanFilter:
    """Kalman Filter for tracking with constant velocity model"""
    def __init__(self):
        self.F = np.eye(8)
        for i in range(4):
            self.F[i, i+4] = 1
        
        self.H = np.eye(4, 8)
        self.Q = np.eye(8)
        self.Q[4:, 4:] *= 0.01
        self.R = np.eye(4) * 10
        self.P = np.eye(8) * 1000
        self.x = np.zeros(8)
        
    def initiate(self, measurement: np.ndarray):
        self.x[:4] = measurement
        self.x[4:] = 0
        
    def predict(self):
        self.x = self.F @ self.x
        self.P = self.F @ self.P @ self.F.T + self.Q
        return self.x[:4]
    
    def update(self, measurement: np.ndarray):
        y = measurement - 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(8) - K @ self.H) @ self.P
        return self.x[:4]
    
    def get_state(self) -> np.ndarray:
        return self.x[:4]

class DeepSORTTrack:
    """DeepSORT Track with Kalman filter and appearance features"""
    def __init__(self, detection: Detection, track_id: Optional[int] = None):
        self.track_id = track_id if track_id else self._generate_id()
        
        x1, y1, x2, y2 = detection.bbox
        cx = (x1 + x2) / 2
        cy = (y1 + y2) / 2
        w = x2 - x1
        h = y2 - y1
        
        self.kf = KalmanFilter()
        self.kf.initiate(np.array([cx, cy, w, h]))
        
        self.detections = [detection]
        self.confidence = detection.confidence
        self.hits = 1
        self.age = 1
        self.time_since_update = 0
        self.state = 'tentative'
        
        self.features = deque(maxlen=100)
        if hasattr(detection, 'features') and detection.features is not None:
            self.features.append(detection.features)
        
        self.trajectory = deque(maxlen=30)
        self.trajectory.append((cx, cy))
        
        self.avg_confidence = self.confidence
        self.consecutive_misses = 0
        
    def _generate_id(self) -> int:
        return int(uuid.uuid4().int % 100000)
    
    @property
    def bbox(self) -> List[float]:
        cx, cy, w, h = self.kf.get_state()
        return [cx - w/2, cy - h/2, cx + w/2, cy + h/2]
    
    def predict(self):
        self.age += 1
        self.time_since_update += 1
        self.consecutive_misses += 1
        self.kf.predict()
    
    def update(self, detection: Detection):
        x1, y1, x2, y2 = detection.bbox
        cx = (x1 + x2) / 2
        cy = (y1 + y2) / 2
        w = x2 - x1
        h = y2 - y1
        
        self.kf.update(np.array([cx, cy, w, h]))
        
        self.detections.append(detection)
        self.confidence = detection.confidence
        self.avg_confidence = 0.9 * self.avg_confidence + 0.1 * self.confidence
        
        self.hits += 1
        self.time_since_update = 0
        self.consecutive_misses = 0
        
        if hasattr(detection, 'features') and detection.features is not None:
            self.features.append(detection.features)
        
        self.trajectory.append((cx, cy))
        
        if self.state == 'tentative' and self.hits >= 3:
            self.state = 'confirmed'
        
        if len(self.detections) > 5:
            for old_det in self.detections[:-5]:
                if hasattr(old_det, 'image_crop'):
                    old_det.image_crop = None
            self.detections = self.detections[-5:]
    
    def mark_missed(self):
        if self.state == 'confirmed':
            if self.consecutive_misses > 30 or self.time_since_update > 60:
                self.state = 'deleted'
        elif self.state == 'tentative':
            if self.consecutive_misses > 5:
                self.state = 'deleted'
    
    def get_feature(self) -> Optional[np.ndarray]:
        if not self.features:
            return None
        features_array = np.array(list(self.features))
        weights = np.exp(np.linspace(-1, 0, len(features_array)))
        weights /= weights.sum()
        return np.average(features_array, axis=0, weights=weights)

class DeepSORTTracker:
    """DeepSORT Tracker combining Kalman filter with appearance features"""
    def __init__(self,
                 max_iou_distance: float = 0.7,
                 max_age: int = 30,
                 n_init: int = 3,
                 nn_budget: int = 100,
                 use_appearance: bool = True):
        self.max_iou_distance = max_iou_distance
        self.max_age = max_age
        self.n_init = n_init
        self.nn_budget = nn_budget
        self.use_appearance = use_appearance
        
        self.tracks: List[DeepSORTTrack] = []
        self.track_id_count = 1
        
        self.gating_threshold_iou = 0.3
        self.gating_threshold_appearance = 0.5
        
    def update(self, detections: List[Detection]) -> List[DeepSORTTrack]:
        for track in self.tracks:
            track.predict()
        
        matches, unmatched_tracks, unmatched_detections = self._match(
            detections, self.tracks
        )
        
        for track_idx, det_idx in matches:
            self.tracks[track_idx].update(detections[det_idx])
        
        for track_idx in unmatched_tracks:
            self.tracks[track_idx].mark_missed()
        
        for det_idx in unmatched_detections:
            self._initiate_track(detections[det_idx])
        
        self.tracks = [t for t in self.tracks if t.state != 'deleted']
        
        return [t for t in self.tracks if t.state == 'confirmed']
    
    def _match(self, detections: List[Detection], tracks: List[DeepSORTTrack]) -> Tuple:
        if not tracks or not detections:
            return [], list(range(len(tracks))), list(range(len(detections)))
        
        confirmed_tracks = [i for i, t in enumerate(tracks) if t.state == 'confirmed']
        unconfirmed_tracks = [i for i, t in enumerate(tracks) if t.state == 'tentative']
        
        matches_a, unmatched_tracks_a, unmatched_detections = \
            self._matching_cascade(detections, tracks, confirmed_tracks)
        
        iou_track_candidates = unconfirmed_tracks + unmatched_tracks_a
        remaining_detections = [detections[i] for i in unmatched_detections]
        
        matches_b, unmatched_tracks_b, unmatched_detections_b = \
            self._match_iou(remaining_detections, tracks, iou_track_candidates)
        
        matches_b = [(t, unmatched_detections[d]) for t, d in matches_b]
        unmatched_detections = [unmatched_detections[i] for i in unmatched_detections_b]
        
        matches = matches_a + matches_b
        unmatched_tracks = unmatched_tracks_b
        
        return matches, unmatched_tracks, unmatched_detections
    
    def _matching_cascade(self, detections: List[Detection], 
                          tracks: List[DeepSORTTrack],
                          track_indices: List[int]) -> Tuple:
        matches = []
        unmatched_detections = list(range(len(detections)))
        
        for level in range(self.max_age):
            if len(unmatched_detections) == 0:
                break
            
            track_indices_l = [
                k for k in track_indices
                if tracks[k].time_since_update == level
            ]
            
            if len(track_indices_l) == 0:
                continue
            
            detection_subset = [detections[i] for i in unmatched_detections]
            
            matches_l, _, unmatched_subset_indices = self._match_features_and_iou(
                detection_subset,
                tracks,
                track_indices_l
            )
            
            matches_l_remapped = [(t, unmatched_detections[d]) for t, d in matches_l]
            matches.extend(matches_l_remapped)
            
            unmatched_detections = [unmatched_detections[i] for i in unmatched_subset_indices]
        
        unmatched_tracks = [
            k for k in track_indices
            if k not in [t for t, _ in matches]
        ]
        
        return matches, unmatched_tracks, unmatched_detections
    
    def _match_features_and_iou(self, detections: List[Detection],
                                 tracks: List[DeepSORTTrack],
                                 track_indices: List[int]) -> Tuple:
        if not track_indices or not detections:
            return [], track_indices, list(range(len(detections)))
        
        cost_matrix = np.zeros((len(track_indices), len(detections)))
        
        for i, track_idx in enumerate(track_indices):
            track = tracks[track_idx]
            track_bbox = track.bbox
            track_feature = track.get_feature()
            
            for j, detection in enumerate(detections):
                det_bbox = detection.bbox
                
                iou = self._iou(track_bbox, det_bbox)
                iou_cost = 1 - iou
                
                if self.use_appearance and track_feature is not None:
                    if hasattr(detection, 'features') and detection.features is not None:
                        cosine_dist = cosine(track_feature, detection.features)
                        appearance_cost = cosine_dist
                    else:
                        appearance_cost = 0.5
                else:
                    appearance_cost = 0.0
                
                if self.use_appearance and track_feature is not None:
                    cost = 0.5 * iou_cost + 0.5 * appearance_cost
                else:
                    cost = iou_cost
                
                if iou < self.gating_threshold_iou:
                    cost = 1e6
                if self.use_appearance and appearance_cost > self.gating_threshold_appearance:
                    cost = 1e6
                
                cost_matrix[i, j] = cost
        
        row_indices, col_indices = linear_sum_assignment(cost_matrix)
        
        matches = []
        unmatched_tracks = list(range(len(track_indices)))
        unmatched_detections = list(range(len(detections)))
        
        for row, col in zip(row_indices, col_indices):
            if cost_matrix[row, col] < 1e5:
                matches.append((track_indices[row], col))
                unmatched_tracks.remove(row)
                unmatched_detections.remove(col)
        
        unmatched_tracks = [track_indices[i] for i in unmatched_tracks]
        
        return matches, unmatched_tracks, unmatched_detections
    
    def _match_iou(self, detections: List[Detection],
                   tracks: List[DeepSORTTrack],
                   track_indices: List[int]) -> Tuple:
        if not track_indices or not detections:
            return [], track_indices, list(range(len(detections)))
        
        iou_matrix = np.zeros((len(track_indices), len(detections)))
        
        for i, track_idx in enumerate(track_indices):
            track = tracks[track_idx]
            for j, detection in enumerate(detections):
                iou = self._iou(track.bbox, detection.bbox)
                iou_matrix[i, j] = 1 - iou
        
        row_indices, col_indices = linear_sum_assignment(iou_matrix)
        
        matches = []
        unmatched_tracks = list(range(len(track_indices)))
        unmatched_detections = list(range(len(detections)))
        
        for row, col in zip(row_indices, col_indices):
            if iou_matrix[row, col] < self.max_iou_distance:
                matches.append((track_indices[row], col))
                unmatched_tracks.remove(row)
                unmatched_detections.remove(col)
        
        unmatched_tracks = [track_indices[i] for i in unmatched_tracks]
        
        return matches, unmatched_tracks, unmatched_detections
    
    def _initiate_track(self, detection: Detection):
        new_track = DeepSORTTrack(detection, self.track_id_count)
        self.track_id_count += 1
        self.tracks.append(new_track)
    
    def _iou(self, bbox1: List[float], bbox2: List[float]) -> float:
        try:
            x1 = max(bbox1[0], bbox2[0])
            y1 = max(bbox1[1], bbox2[1])
            x2 = min(bbox1[2], bbox2[2])
            y2 = min(bbox1[3], bbox2[3])
            
            if x2 < x1 or y2 < y1:
                return 0.0
            
            intersection = (x2 - x1) * (y2 - y1)
            area1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
            area2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
            union = area1 + area2 - intersection
            
            return intersection / (union + 1e-6)
        except:
            return 0.0
    
    def reset(self):
        self.tracks.clear()
        self.track_id_count = 1
        print("DeepSORT tracker reset")

SimpleTracker = DeepSORTTracker
RobustTracker = DeepSORTTracker