trackflow-python-cuda 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- trackflow/__init__.py +62 -0
- trackflow/benchmark.py +266 -0
- trackflow/boosttrack.py +440 -0
- trackflow/cli.py +631 -0
- trackflow/detector.py +850 -0
- trackflow/homography.py +240 -0
- trackflow/inspector.py +479 -0
- trackflow/inspector_ui.html +538 -0
- trackflow/lines.py +120 -0
- trackflow/models.py +421 -0
- trackflow/ocsort.py +368 -0
- trackflow/pipeline.py +910 -0
- trackflow/privacy.py +167 -0
- trackflow/py.typed +1 -0
- trackflow/reid.py +819 -0
- trackflow/sinks.py +440 -0
- trackflow/tracker.py +1219 -0
- trackflow/types.py +235 -0
- trackflow_python_cuda-0.6.1.dist-info/METADATA +366 -0
- trackflow_python_cuda-0.6.1.dist-info/RECORD +23 -0
- trackflow_python_cuda-0.6.1.dist-info/WHEEL +4 -0
- trackflow_python_cuda-0.6.1.dist-info/entry_points.txt +3 -0
- trackflow_python_cuda-0.6.1.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<title>Trackflow Inspector</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root {
|
|
9
|
+
--bg: #090d1a; --panel: #11182c; --panel-2: #16203a; --border: #253358;
|
|
10
|
+
--text: #e8effc; --muted: #8ea1c4; --accent: #34d399; --sky: #38bdf8;
|
|
11
|
+
--warn: #fbbf24; --danger: #f87171;
|
|
12
|
+
}
|
|
13
|
+
* { box-sizing: border-box; }
|
|
14
|
+
body { margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
|
15
|
+
header { display: flex; align-items: center; justify-content: space-between; padding: 14px 22px; background: var(--panel); border-bottom: 1px solid var(--border); }
|
|
16
|
+
.brand { font-weight: 700; font-size: 17px; display: flex; align-items: center; gap: 10px; }
|
|
17
|
+
.brand span.pill { font-size: 11px; background: #0d3b2e; color: var(--accent); padding: 2px 8px; border-radius: 999px; font-weight: 600; }
|
|
18
|
+
nav { display: flex; gap: 8px; }
|
|
19
|
+
nav button { background: transparent; border: 1px solid var(--border); color: var(--muted); padding: 7px 14px; border-radius: 8px; cursor: pointer; font-weight: 600; }
|
|
20
|
+
nav button.active { background: var(--panel-2); color: var(--text); border-color: var(--sky); }
|
|
21
|
+
main { max-width: 1280px; margin: 0 auto; padding: 18px 22px 40px; }
|
|
22
|
+
.kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-bottom: 18px; }
|
|
23
|
+
.kpi { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 12px 14px; }
|
|
24
|
+
.kpi .lbl { font-size: 11px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }
|
|
25
|
+
.kpi .val { font-size: 22px; font-weight: 700; margin-top: 3px; color: var(--accent); }
|
|
26
|
+
.grid-2 { display: grid; grid-template-columns: 1.45fr 1fr; gap: 16px; }
|
|
27
|
+
@media (max-width: 960px) { .grid-2 { grid-template-columns: 1fr; } }
|
|
28
|
+
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 16px; margin-bottom: 16px; }
|
|
29
|
+
.panel h2 { margin: 0 0 12px; font-size: 15px; display: flex; justify-content: space-between; align-items: center; }
|
|
30
|
+
canvas { width: 100%; background: #060912; border-radius: 8px; border: 1px solid var(--border); display: block; }
|
|
31
|
+
.controls { display: flex; align-items: center; gap: 10px; margin-top: 10px; flex-wrap: wrap; }
|
|
32
|
+
.controls input[type=range] { flex: 1; min-width: 180px; }
|
|
33
|
+
button.btn { background: #1c2c52; border: 1px solid #30477d; color: var(--text); padding: 7px 12px; border-radius: 8px; cursor: pointer; font-size: 13px; font-weight: 600; }
|
|
34
|
+
button.btn.primary { background: #059669; border-color: #10b981; color: #fff; }
|
|
35
|
+
input[type=text], input[type=number] { background: #0c1222; border: 1px solid var(--border); color: var(--text); padding: 8px 10px; border-radius: 8px; font-size: 13px; }
|
|
36
|
+
.markers { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 8px; max-height: 70px; overflow-y: auto; }
|
|
37
|
+
.marker { font-size: 11px; padding: 2px 7px; border-radius: 6px; cursor: pointer; border: 1px solid transparent; }
|
|
38
|
+
.marker.switch { background: rgba(248,113,113,.15); color: var(--danger); border-color: rgba(248,113,113,.4); }
|
|
39
|
+
.marker.merge { background: rgba(52,211,153,.15); color: var(--accent); border-color: rgba(52,211,153,.4); }
|
|
40
|
+
.marker.rec { background: rgba(251,191,36,.15); color: var(--warn); border-color: rgba(251,191,36,.4); }
|
|
41
|
+
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(195px, 1fr)); gap: 10px; max-height: 540px; overflow-y: auto; }
|
|
42
|
+
.card { background: #0c1324; border: 1px solid var(--border); border-radius: 9px; padding: 8px; display: flex; gap: 9px; cursor: pointer; transition: border-color .15s; }
|
|
43
|
+
.card:hover, .card.selected { border-color: var(--sky); }
|
|
44
|
+
.card img { width: 52px; height: 68px; object-fit: cover; border-radius: 6px; background: #17223d; flex-shrink: 0; }
|
|
45
|
+
.card .meta { font-size: 11px; color: var(--muted); line-height: 1.4; }
|
|
46
|
+
.tab { display: none; }
|
|
47
|
+
.tab.active { display: block; }
|
|
48
|
+
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
|
49
|
+
th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); }
|
|
50
|
+
th { color: var(--muted); }
|
|
51
|
+
.hint { font-size: 12px; color: var(--muted); }
|
|
52
|
+
</style>
|
|
53
|
+
</head>
|
|
54
|
+
<body>
|
|
55
|
+
<header>
|
|
56
|
+
<div class="brand">
|
|
57
|
+
Trackflow Inspector
|
|
58
|
+
<span class="pill" id="metaPill">Loading…</span>
|
|
59
|
+
</div>
|
|
60
|
+
<nav>
|
|
61
|
+
<button class="active" data-tab="debugger">Track Debugger</button>
|
|
62
|
+
<button data-tab="floorplan">4-Point Floorplan</button>
|
|
63
|
+
<button data-tab="compare">Tracker Compare</button>
|
|
64
|
+
</nav>
|
|
65
|
+
</header>
|
|
66
|
+
|
|
67
|
+
<main>
|
|
68
|
+
<div class="kpis" id="kpis"></div>
|
|
69
|
+
|
|
70
|
+
<!-- TAB 1: VISUAL TRACK DEBUGGER -->
|
|
71
|
+
<section id="tab-debugger" class="tab active">
|
|
72
|
+
<div class="grid-2">
|
|
73
|
+
<div class="panel">
|
|
74
|
+
<h2>
|
|
75
|
+
<span>Frame Canvas & Timeline Scrubber</span>
|
|
76
|
+
<span class="hint" id="frameInfo">Frame 0</span>
|
|
77
|
+
</h2>
|
|
78
|
+
<canvas id="trackCanvas" width="800" height="450"></canvas>
|
|
79
|
+
<div class="controls">
|
|
80
|
+
<button class="btn primary" id="playBtn">Play</button>
|
|
81
|
+
<input type="range" id="scrubber" min="0" max="0" value="0" />
|
|
82
|
+
<label class="hint"><input type="checkbox" id="showVideo" checked /> Video</label>
|
|
83
|
+
<label class="hint"><input type="checkbox" id="showTrails" checked /> Trails</label>
|
|
84
|
+
</div>
|
|
85
|
+
<div class="hint" style="margin-top:10px;">Diagnostic Event Markers (click to jump):</div>
|
|
86
|
+
<div class="markers" id="eventMarkers"></div>
|
|
87
|
+
</div>
|
|
88
|
+
|
|
89
|
+
<div class="panel">
|
|
90
|
+
<h2>
|
|
91
|
+
<span>Track Cards & Natural-Language Search</span>
|
|
92
|
+
<span class="hint" id="cardCount"></span>
|
|
93
|
+
</h2>
|
|
94
|
+
<div class="controls" style="margin-top:0; margin-bottom:12px;">
|
|
95
|
+
<input type="text" id="nlQuery" placeholder='e.g. "person in red jacket"' style="flex:1;" />
|
|
96
|
+
<button class="btn primary" id="nlSearchBtn">Search</button>
|
|
97
|
+
<button class="btn" id="nlResetBtn">Reset</button>
|
|
98
|
+
</div>
|
|
99
|
+
<div id="searchStatus" class="hint" style="margin-bottom:8px;"></div>
|
|
100
|
+
<div class="cards" id="cardGrid"></div>
|
|
101
|
+
</div>
|
|
102
|
+
</div>
|
|
103
|
+
</section>
|
|
104
|
+
|
|
105
|
+
<!-- TAB 2: 4-POINT FLOORPLAN HOMOGRAPHY -->
|
|
106
|
+
<section id="tab-floorplan" class="tab">
|
|
107
|
+
<div class="grid-2">
|
|
108
|
+
<div class="panel">
|
|
109
|
+
<h2>
|
|
110
|
+
<span>1. Click 4 Ground Corners (TL → TR → BR → BL)</span>
|
|
111
|
+
<button class="btn" id="resetPtsBtn">Clear Points</button>
|
|
112
|
+
</h2>
|
|
113
|
+
<canvas id="calibCanvas" width="760" height="430" style="cursor:crosshair;"></canvas>
|
|
114
|
+
<div class="controls">
|
|
115
|
+
<label class="hint">Width (m): <input type="number" id="worldW" value="10" step="0.5" style="width:74px;" /></label>
|
|
116
|
+
<label class="hint">Height (m): <input type="number" id="worldH" value="8" step="0.5" style="width:74px;" /></label>
|
|
117
|
+
<button class="btn primary" id="projectBtn">Project to Bird's-Eye</button>
|
|
118
|
+
</div>
|
|
119
|
+
<div id="calibStatus" class="hint" style="margin-top:8px;">Click 4 ground corners to compute the homography.</div>
|
|
120
|
+
</div>
|
|
121
|
+
<div class="panel">
|
|
122
|
+
<h2><span>2. Bird's-Eye Trajectories & Heatmap</span></h2>
|
|
123
|
+
<canvas id="floorCanvas" width="600" height="480"></canvas>
|
|
124
|
+
<div id="zoneSummary" class="hint" style="margin-top:10px;"></div>
|
|
125
|
+
</div>
|
|
126
|
+
</div>
|
|
127
|
+
</section>
|
|
128
|
+
|
|
129
|
+
<!-- TAB 3: SIDE-BY-SIDE TRACKER COMPARISON -->
|
|
130
|
+
<section id="tab-compare" class="tab">
|
|
131
|
+
<div class="panel">
|
|
132
|
+
<h2>Side-by-Side Tracker Comparison</h2>
|
|
133
|
+
<div id="compareContent" class="hint">Launch with <code>trackflow inspect run_a --compare run_b</code> to compare trackers side-by-side.</div>
|
|
134
|
+
</div>
|
|
135
|
+
</section>
|
|
136
|
+
</main>
|
|
137
|
+
|
|
138
|
+
<script>
|
|
139
|
+
const PALETTE = ['#34d399','#38bdf8','#a78bfa','#fbbf24','#f472b6','#60a5fa','#4ade80','#fb7185'];
|
|
140
|
+
let DATA = null;
|
|
141
|
+
let frameIdxPos = 0;
|
|
142
|
+
let playing = false;
|
|
143
|
+
let playTimer = null;
|
|
144
|
+
let selectedTrackId = null;
|
|
145
|
+
let calibPoints = [];
|
|
146
|
+
const FRAME_IMG_CACHE = new Map();
|
|
147
|
+
const FRAME_IMG_LIMIT = 120;
|
|
148
|
+
let lastLoadedFrameImg = null;
|
|
149
|
+
|
|
150
|
+
function colorFor(id) { return PALETTE[id % PALETTE.length]; }
|
|
151
|
+
|
|
152
|
+
function getFrameImage(frameIdx, onReady) {
|
|
153
|
+
if (!DATA || !DATA.has_frames) return null;
|
|
154
|
+
const cached = FRAME_IMG_CACHE.get(frameIdx);
|
|
155
|
+
if (cached) {
|
|
156
|
+
if (cached.complete && cached.naturalWidth > 0) return cached;
|
|
157
|
+
if (onReady && !cached._failed) cached._callbacks.push(onReady);
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
const img = new Image();
|
|
161
|
+
img._callbacks = onReady ? [onReady] : [];
|
|
162
|
+
img._failed = false;
|
|
163
|
+
img.onload = () => {
|
|
164
|
+
lastLoadedFrameImg = img;
|
|
165
|
+
const cbs = img._callbacks.splice(0);
|
|
166
|
+
cbs.forEach(fn => fn());
|
|
167
|
+
};
|
|
168
|
+
img.onerror = () => { img._failed = true; img._callbacks.length = 0; };
|
|
169
|
+
img.src = `/api/frame/${frameIdx}`;
|
|
170
|
+
FRAME_IMG_CACHE.set(frameIdx, img);
|
|
171
|
+
if (FRAME_IMG_CACHE.size > FRAME_IMG_LIMIT) {
|
|
172
|
+
FRAME_IMG_CACHE.delete(FRAME_IMG_CACHE.keys().next().value);
|
|
173
|
+
}
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function prefetchFrames(pos) {
|
|
178
|
+
if (!DATA || !DATA.has_frames || !DATA.frames.length) return;
|
|
179
|
+
for (let offset = 1; offset <= 3; offset++) {
|
|
180
|
+
const nextPos = (pos + offset) % DATA.frames.length;
|
|
181
|
+
getFrameImage(DATA.frames[nextPos].frame_idx, null);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
document.querySelectorAll('nav button').forEach(btn => {
|
|
186
|
+
btn.addEventListener('click', () => {
|
|
187
|
+
document.querySelectorAll('nav button').forEach(b => b.classList.remove('active'));
|
|
188
|
+
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
|
189
|
+
btn.classList.add('active');
|
|
190
|
+
document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
|
|
191
|
+
if (btn.dataset.tab === 'floorplan') drawCalibCanvas();
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
async function init() {
|
|
196
|
+
const res = await fetch('/api/run');
|
|
197
|
+
DATA = await res.json();
|
|
198
|
+
const s = DATA.summary;
|
|
199
|
+
document.getElementById('metaPill').textContent = `${s.model || 'model'} · ${s.tracker || 'tracker'} · ${s.device || 'cpu'}`;
|
|
200
|
+
renderKpis();
|
|
201
|
+
renderMarkers();
|
|
202
|
+
renderCards(DATA.cards);
|
|
203
|
+
renderCompare();
|
|
204
|
+
|
|
205
|
+
const scrubber = document.getElementById('scrubber');
|
|
206
|
+
scrubber.max = Math.max(0, DATA.frames.length - 1);
|
|
207
|
+
scrubber.addEventListener('input', e => { frameIdxPos = Number(e.target.value); drawFrame(); });
|
|
208
|
+
document.getElementById('showTrails').addEventListener('change', drawFrame);
|
|
209
|
+
const showVideoEl = document.getElementById('showVideo');
|
|
210
|
+
if (!DATA.has_frames) {
|
|
211
|
+
showVideoEl.checked = false;
|
|
212
|
+
showVideoEl.disabled = true;
|
|
213
|
+
}
|
|
214
|
+
showVideoEl.addEventListener('change', drawFrame);
|
|
215
|
+
|
|
216
|
+
const fw = s.frame_width || 800;
|
|
217
|
+
const fh = s.frame_height || 450;
|
|
218
|
+
const trackCanvas = document.getElementById('trackCanvas');
|
|
219
|
+
trackCanvas.height = Math.max(240, Math.round(trackCanvas.width * (fh / fw)));
|
|
220
|
+
calibCanvas.height = Math.max(240, Math.round(calibCanvas.width * (fh / fw)));
|
|
221
|
+
|
|
222
|
+
if (DATA.homography && DATA.homography.image_points) {
|
|
223
|
+
calibPoints = DATA.homography.image_points.map(p => [...p]);
|
|
224
|
+
document.getElementById('worldW').value = DATA.homography.width_m || 10;
|
|
225
|
+
document.getElementById('worldH').value = DATA.homography.height_m || 8;
|
|
226
|
+
}
|
|
227
|
+
drawFrame();
|
|
228
|
+
drawCalibCanvas();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function escapeText(value) {
|
|
232
|
+
return String(value ?? '').replace(/[&<>"']/g, ch => ({
|
|
233
|
+
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
|
234
|
+
})[ch]);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function renderKpis() {
|
|
238
|
+
const s = DATA.summary, d = DATA.diagnostics;
|
|
239
|
+
const items = [
|
|
240
|
+
['Unique Tracks', s.unique_tracks ?? DATA.cards.length],
|
|
241
|
+
['Avg FPS', (s.avg_fps ?? 0).toFixed(1)],
|
|
242
|
+
['Frames', s.processed_frames ?? DATA.frames.length],
|
|
243
|
+
['Possible ID Switches', d.possible_id_switches],
|
|
244
|
+
['Recoveries / Re-ID', `${d.recoveries} / ${d.reid_merges}`],
|
|
245
|
+
['Re-ID Backend', DATA.reid_backend || 'none'],
|
|
246
|
+
];
|
|
247
|
+
document.getElementById('kpis').innerHTML = items.map(([l,v]) =>
|
|
248
|
+
`<div class="kpi"><div class="lbl">${l}</div><div class="val">${escapeText(v)}</div></div>`
|
|
249
|
+
).join('');
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function renderMarkers() {
|
|
253
|
+
const wrap = document.getElementById('eventMarkers');
|
|
254
|
+
const interesting = DATA.events.filter(e =>
|
|
255
|
+
['possible_id_switch','reid_cross_exit_merge','track_recovered'].includes(e.type)
|
|
256
|
+
);
|
|
257
|
+
if (!interesting.length) { wrap.innerHTML = '<span class="hint">No ID switches or merges flagged.</span>'; return; }
|
|
258
|
+
wrap.innerHTML = interesting.slice(0, 80).map(e => {
|
|
259
|
+
const cls = e.type === 'possible_id_switch' ? 'switch' : (e.type === 'reid_cross_exit_merge' ? 'merge' : 'rec');
|
|
260
|
+
const lbl = e.type === 'possible_id_switch'
|
|
261
|
+
? `F${e.frame_idx} Switch #${e.previous_track_id}→#${e.new_track_id}`
|
|
262
|
+
: e.type === 'reid_cross_exit_merge'
|
|
263
|
+
? `F${e.frame_idx} Re-ID #${e.raw_track_id}→#${e.canonical_track_id}`
|
|
264
|
+
: `F${e.frame_idx} Recovered #${e.track_id}`;
|
|
265
|
+
return `<span class="marker ${cls}" onclick="jumpToFrame(${Number(e.frame_idx)})">${escapeText(lbl)}</span>`;
|
|
266
|
+
}).join('');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function jumpToFrame(targetFrameIdx) {
|
|
270
|
+
const pos = DATA.frames.findIndex(f => f.frame_idx >= targetFrameIdx);
|
|
271
|
+
if (pos >= 0) {
|
|
272
|
+
frameIdxPos = pos;
|
|
273
|
+
document.getElementById('scrubber').value = pos;
|
|
274
|
+
drawFrame();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function renderCards(cards) {
|
|
279
|
+
document.getElementById('cardCount').textContent = `${cards.length} cards`;
|
|
280
|
+
const grid = document.getElementById('cardGrid');
|
|
281
|
+
grid.innerHTML = cards.map(c => {
|
|
282
|
+
const score = c.search_score !== undefined ? `<div>Match: <b>${c.search_score.toFixed(3)}</b></div>`
|
|
283
|
+
: (c.query_score !== null && c.query_score !== undefined ? `<div>Query: <b>${c.query_score.toFixed(3)}</b></div>` : '');
|
|
284
|
+
const thumb = /^crops\/track_\d+\.jpg$/.test(c.thumbnail) ? `<img src="/${c.thumbnail}" alt="Track #${Number(c.track_id)}" />` : '';
|
|
285
|
+
return `<div class="card ${selectedTrackId === c.track_id ? 'selected' : ''}" onclick="selectTrack(${Number(c.track_id)}, ${Number(c.best_frame)})">
|
|
286
|
+
${thumb}
|
|
287
|
+
<div class="meta">
|
|
288
|
+
<div style="color:#fff;font-weight:700;">#${Number(c.track_id)} · ${escapeText(c.class_name)}</div>
|
|
289
|
+
<div>F${Number(c.first_frame)}–F${Number(c.last_frame)} (${Number(c.duration_s)}s)</div>
|
|
290
|
+
<div>Conf ${Number(c.best_confidence)}</div>
|
|
291
|
+
${score}
|
|
292
|
+
</div>
|
|
293
|
+
</div>`;
|
|
294
|
+
}).join('');
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function selectTrack(tid, bestFrame) {
|
|
298
|
+
selectedTrackId = selectedTrackId === tid ? null : tid;
|
|
299
|
+
jumpToFrame(bestFrame);
|
|
300
|
+
renderCards(DATA.cards);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function drawGrid(ctx, width, height) {
|
|
304
|
+
ctx.strokeStyle = '#141d36';
|
|
305
|
+
ctx.lineWidth = 1;
|
|
306
|
+
for (let x = 0; x < width; x += 64) { ctx.beginPath(); ctx.moveTo(x,0); ctx.lineTo(x,height); ctx.stroke(); }
|
|
307
|
+
for (let y = 0; y < height; y += 64) { ctx.beginPath(); ctx.moveTo(0,y); ctx.lineTo(width,y); ctx.stroke(); }
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function drawFrame() {
|
|
311
|
+
const canvas = document.getElementById('trackCanvas');
|
|
312
|
+
const ctx = canvas.getContext('2d');
|
|
313
|
+
const fw = DATA.summary.frame_width || 800;
|
|
314
|
+
const fh = DATA.summary.frame_height || 450;
|
|
315
|
+
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
316
|
+
|
|
317
|
+
if (!DATA.frames.length) {
|
|
318
|
+
drawGrid(ctx, canvas.width, canvas.height);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
const frame = DATA.frames[frameIdxPos];
|
|
322
|
+
document.getElementById('frameInfo').textContent = `Frame ${frame.frame_idx} · ${frame.tracks.length} tracks`;
|
|
323
|
+
|
|
324
|
+
const wantVideo = DATA.has_frames && document.getElementById('showVideo').checked;
|
|
325
|
+
if (wantVideo) {
|
|
326
|
+
const img = getFrameImage(frame.frame_idx, () => {
|
|
327
|
+
if (DATA.frames[frameIdxPos]?.frame_idx === frame.frame_idx) drawFrame();
|
|
328
|
+
});
|
|
329
|
+
const bg = img || lastLoadedFrameImg;
|
|
330
|
+
if (bg) {
|
|
331
|
+
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
|
|
332
|
+
ctx.fillStyle = 'rgba(9, 13, 26, 0.14)';
|
|
333
|
+
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
334
|
+
} else {
|
|
335
|
+
drawGrid(ctx, canvas.width, canvas.height);
|
|
336
|
+
}
|
|
337
|
+
if (playing) prefetchFrames(frameIdxPos);
|
|
338
|
+
} else {
|
|
339
|
+
drawGrid(ctx, canvas.width, canvas.height);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const sx = canvas.width / fw;
|
|
343
|
+
const sy = canvas.height / fh;
|
|
344
|
+
|
|
345
|
+
if (document.getElementById('showTrails').checked) {
|
|
346
|
+
const start = Math.max(0, frameIdxPos - 30);
|
|
347
|
+
const paths = {};
|
|
348
|
+
for (let i = start; i <= frameIdxPos; i++) {
|
|
349
|
+
for (const tr of DATA.frames[i].tracks) {
|
|
350
|
+
(paths[tr.track_id] ||= []).push([(tr.x1 + tr.x2) * 0.5 * sx, tr.y2 * sy]);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
for (const [tid, pts] of Object.entries(paths)) {
|
|
354
|
+
if (pts.length < 2) continue;
|
|
355
|
+
ctx.strokeStyle = colorFor(Number(tid));
|
|
356
|
+
ctx.globalAlpha = selectedTrackId && Number(tid) !== selectedTrackId ? 0.2 : 0.75;
|
|
357
|
+
ctx.lineWidth = 2;
|
|
358
|
+
ctx.beginPath();
|
|
359
|
+
pts.forEach(([x,y], idx) => idx ? ctx.lineTo(x,y) : ctx.moveTo(x,y));
|
|
360
|
+
ctx.stroke();
|
|
361
|
+
}
|
|
362
|
+
ctx.globalAlpha = 1;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
for (const tr of frame.tracks) {
|
|
366
|
+
const dim = selectedTrackId && tr.track_id !== selectedTrackId;
|
|
367
|
+
const col = colorFor(tr.track_id);
|
|
368
|
+
ctx.globalAlpha = dim ? 0.22 : 1;
|
|
369
|
+
ctx.strokeStyle = col;
|
|
370
|
+
ctx.lineWidth = tr.track_id === selectedTrackId ? 3.5 : 2;
|
|
371
|
+
const x = tr.x1 * sx, y = tr.y1 * sy, w = tr.width * sx, h = tr.height * sy;
|
|
372
|
+
ctx.strokeRect(x, y, w, h);
|
|
373
|
+
ctx.fillStyle = col;
|
|
374
|
+
const lbl = `#${tr.track_id} ${tr.class_name} ${(tr.confidence).toFixed(2)}`;
|
|
375
|
+
ctx.font = '12px ui-monospace, monospace';
|
|
376
|
+
const tw = ctx.measureText(lbl).width + 8;
|
|
377
|
+
ctx.fillRect(x, Math.max(0, y - 18), tw, 18);
|
|
378
|
+
ctx.fillStyle = '#090d1a';
|
|
379
|
+
ctx.fillText(lbl, x + 4, Math.max(13, y - 5));
|
|
380
|
+
}
|
|
381
|
+
ctx.globalAlpha = 1;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
document.getElementById('playBtn').addEventListener('click', () => {
|
|
385
|
+
playing = !playing;
|
|
386
|
+
document.getElementById('playBtn').textContent = playing ? 'Pause' : 'Play';
|
|
387
|
+
if (playing) {
|
|
388
|
+
playTimer = setInterval(() => {
|
|
389
|
+
frameIdxPos = (frameIdxPos + 1) % Math.max(1, DATA.frames.length);
|
|
390
|
+
document.getElementById('scrubber').value = frameIdxPos;
|
|
391
|
+
drawFrame();
|
|
392
|
+
}, 66);
|
|
393
|
+
} else {
|
|
394
|
+
clearInterval(playTimer);
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
document.getElementById('nlSearchBtn').addEventListener('click', async () => {
|
|
399
|
+
const q = document.getElementById('nlQuery').value.trim();
|
|
400
|
+
if (!q) return;
|
|
401
|
+
const st = document.getElementById('searchStatus');
|
|
402
|
+
st.textContent = `Searching Track Cards for "${q}"…`;
|
|
403
|
+
const res = await fetch('/api/search', {
|
|
404
|
+
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
405
|
+
body: JSON.stringify({ query: q, top_k: 20 })
|
|
406
|
+
});
|
|
407
|
+
const body = await res.json();
|
|
408
|
+
if (!res.ok) { st.textContent = `Error: ${body.error}`; return; }
|
|
409
|
+
st.textContent = `Ranked ${body.results.length} Track Cards for "${q}".`;
|
|
410
|
+
renderCards(body.results);
|
|
411
|
+
});
|
|
412
|
+
document.getElementById('nlResetBtn').addEventListener('click', () => {
|
|
413
|
+
document.getElementById('nlQuery').value = '';
|
|
414
|
+
document.getElementById('searchStatus').textContent = '';
|
|
415
|
+
renderCards(DATA.cards);
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
// 4-Point Homography Calibration Studio
|
|
419
|
+
const calibCanvas = document.getElementById('calibCanvas');
|
|
420
|
+
calibCanvas.addEventListener('click', e => {
|
|
421
|
+
if (!DATA || calibPoints.length >= 4) return;
|
|
422
|
+
const rect = calibCanvas.getBoundingClientRect();
|
|
423
|
+
const fw = DATA.summary.frame_width || 800;
|
|
424
|
+
const fh = DATA.summary.frame_height || 450;
|
|
425
|
+
const x = ((e.clientX - rect.left) / rect.width) * fw;
|
|
426
|
+
const y = ((e.clientY - rect.top) / rect.height) * fh;
|
|
427
|
+
calibPoints.push([x, y]);
|
|
428
|
+
drawCalibCanvas();
|
|
429
|
+
});
|
|
430
|
+
document.getElementById('resetPtsBtn').addEventListener('click', () => { calibPoints = []; drawCalibCanvas(); });
|
|
431
|
+
|
|
432
|
+
function drawCalibCanvas() {
|
|
433
|
+
if (!DATA) return;
|
|
434
|
+
const ctx = calibCanvas.getContext('2d');
|
|
435
|
+
const fw = DATA.summary.frame_width || 800;
|
|
436
|
+
const fh = DATA.summary.frame_height || 450;
|
|
437
|
+
const sx = calibCanvas.width / fw, sy = calibCanvas.height / fh;
|
|
438
|
+
ctx.clearRect(0, 0, calibCanvas.width, calibCanvas.height);
|
|
439
|
+
|
|
440
|
+
if (DATA.has_frames && DATA.frames.length) {
|
|
441
|
+
const firstIdx = DATA.frames[0].frame_idx;
|
|
442
|
+
const bg = getFrameImage(firstIdx, drawCalibCanvas);
|
|
443
|
+
if (bg) {
|
|
444
|
+
ctx.drawImage(bg, 0, 0, calibCanvas.width, calibCanvas.height);
|
|
445
|
+
ctx.fillStyle = 'rgba(9, 13, 26, 0.30)';
|
|
446
|
+
ctx.fillRect(0, 0, calibCanvas.width, calibCanvas.height);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// Draw all foot points in image space as spatial reference
|
|
451
|
+
ctx.fillStyle = 'rgba(56, 189, 248, 0.38)';
|
|
452
|
+
for (const f of DATA.frames) {
|
|
453
|
+
for (const tr of f.tracks) {
|
|
454
|
+
ctx.fillRect(((tr.x1 + tr.x2) * 0.5) * sx - 1.5, tr.y2 * sy - 1.5, 3, 3);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
if (calibPoints.length) {
|
|
459
|
+
ctx.strokeStyle = '#34d399'; ctx.lineWidth = 2;
|
|
460
|
+
ctx.beginPath();
|
|
461
|
+
calibPoints.forEach(([x,y], i) => i ? ctx.lineTo(x*sx, y*sy) : ctx.moveTo(x*sx, y*sy));
|
|
462
|
+
if (calibPoints.length === 4) ctx.closePath();
|
|
463
|
+
ctx.stroke();
|
|
464
|
+
calibPoints.forEach(([x,y], i) => {
|
|
465
|
+
ctx.fillStyle = '#fbbf24';
|
|
466
|
+
ctx.beginPath(); ctx.arc(x*sx, y*sy, 6, 0, Math.PI*2); ctx.fill();
|
|
467
|
+
ctx.fillStyle = '#090d1a'; ctx.font = 'bold 11px sans-serif';
|
|
468
|
+
ctx.fillText(String(i+1), x*sx - 3, y*sy + 4);
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
document.getElementById('calibStatus').textContent = `${calibPoints.length}/4 corners selected.`;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
document.getElementById('projectBtn').addEventListener('click', async () => {
|
|
475
|
+
if (calibPoints.length !== 4) {
|
|
476
|
+
document.getElementById('calibStatus').textContent = 'Please click exactly 4 ground points first.';
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const width_m = Number(document.getElementById('worldW').value) || 10;
|
|
480
|
+
const height_m = Number(document.getElementById('worldH').value) || 8;
|
|
481
|
+
const res = await fetch('/api/homography', {
|
|
482
|
+
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
483
|
+
body: JSON.stringify({ image_points: calibPoints, width_m, height_m })
|
|
484
|
+
});
|
|
485
|
+
const out = await res.json();
|
|
486
|
+
if (!res.ok) { document.getElementById('calibStatus').textContent = out.error; return; }
|
|
487
|
+
drawFloorplan(out.trajectories, width_m, height_m);
|
|
488
|
+
document.getElementById('calibStatus').textContent = 'Projected & saved homography.json + floorplan.png.';
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
function drawFloorplan(trajectories, wm, hm) {
|
|
492
|
+
const c = document.getElementById('floorCanvas');
|
|
493
|
+
const ctx = c.getContext('2d');
|
|
494
|
+
ctx.clearRect(0, 0, c.width, c.height);
|
|
495
|
+
ctx.strokeStyle = '#192440'; ctx.lineWidth = 1;
|
|
496
|
+
for (let i = 0; i <= Math.ceil(wm); i++) {
|
|
497
|
+
const x = (i / wm) * c.width; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, c.height); ctx.stroke();
|
|
498
|
+
}
|
|
499
|
+
for (let j = 0; j <= Math.ceil(hm); j++) {
|
|
500
|
+
const y = (j / hm) * c.height; ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(c.width, y); ctx.stroke();
|
|
501
|
+
}
|
|
502
|
+
for (const [tid, pts] of Object.entries(trajectories)) {
|
|
503
|
+
if (pts.length < 2) continue;
|
|
504
|
+
ctx.strokeStyle = colorFor(Number(tid));
|
|
505
|
+
ctx.lineWidth = 2;
|
|
506
|
+
ctx.beginPath();
|
|
507
|
+
pts.forEach(([wx, wy], idx) => {
|
|
508
|
+
const px = (wx / wm) * c.width, py = (wy / hm) * c.height;
|
|
509
|
+
idx ? ctx.lineTo(px, py) : ctx.moveTo(px, py);
|
|
510
|
+
});
|
|
511
|
+
ctx.stroke();
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function renderCompare() {
|
|
516
|
+
if (!DATA.compare) return;
|
|
517
|
+
const a = DATA, b = DATA.compare;
|
|
518
|
+
const rows = [
|
|
519
|
+
['Tracker', a.summary.tracker, b.summary.tracker],
|
|
520
|
+
['Model', a.summary.model, b.summary.model],
|
|
521
|
+
['Avg FPS', a.summary.avg_fps?.toFixed(1), b.summary.avg_fps?.toFixed(1)],
|
|
522
|
+
['Unique Tracks', a.summary.unique_tracks, b.summary.unique_tracks],
|
|
523
|
+
['Possible ID Switches', a.diagnostics.possible_id_switches, b.diagnostics.possible_id_switches],
|
|
524
|
+
['Track Recoveries', a.diagnostics.recoveries, b.diagnostics.recoveries],
|
|
525
|
+
['Cross-Exit Re-ID Merges', a.diagnostics.reid_merges, b.diagnostics.reid_merges],
|
|
526
|
+
['Total Observations', a.diagnostics.total_observations, b.diagnostics.total_observations],
|
|
527
|
+
];
|
|
528
|
+
document.getElementById('compareContent').innerHTML = `
|
|
529
|
+
<table>
|
|
530
|
+
<thead><tr><th>Metric</th><th>Run A (${escapeText(a.summary.tracker)})</th><th>Run B (${escapeText(b.summary.tracker)})</th></tr></thead>
|
|
531
|
+
<tbody>${rows.map(([m,va,vb]) => `<tr><td>${m}</td><td><b>${escapeText(va)}</b></td><td><b>${escapeText(vb)}</b></td></tr>`).join('')}</tbody>
|
|
532
|
+
</table>`;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
init();
|
|
536
|
+
</script>
|
|
537
|
+
</body>
|
|
538
|
+
</html>
|
trackflow/lines.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Line counting: count tracks whose foot point crosses a line segment drawn in image pixels."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from trackflow.types import Track
|
|
11
|
+
|
|
12
|
+
Point = tuple[float, float]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class CountingLine:
|
|
17
|
+
"""Named line segment in image pixels.
|
|
18
|
+
|
|
19
|
+
A crossing to the right of the direction from ``start`` to ``end`` counts as ``in``, the
|
|
20
|
+
other way as ``out``. For a line drawn left to right, ``in`` means moving down the frame.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
name: str
|
|
24
|
+
start: Point
|
|
25
|
+
end: Point
|
|
26
|
+
|
|
27
|
+
def __post_init__(self) -> None:
|
|
28
|
+
if not self.name:
|
|
29
|
+
raise ValueError("A counting line needs a name.")
|
|
30
|
+
if not all(math.isfinite(v) for v in (*self.start, *self.end)):
|
|
31
|
+
raise ValueError(f"Line {self.name!r} needs finite coordinates.")
|
|
32
|
+
if self.start == self.end:
|
|
33
|
+
raise ValueError(f"Line {self.name!r} needs two different points.")
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def parse(cls, spec: str, default_name: str) -> CountingLine:
|
|
37
|
+
"""Parse ``[name=]x1,y1,x2,y2``, as passed to ``trackflow run --line``."""
|
|
38
|
+
name, _, coords = spec.rpartition("=")
|
|
39
|
+
try:
|
|
40
|
+
x1, y1, x2, y2 = (float(v) for v in coords.split(","))
|
|
41
|
+
except ValueError:
|
|
42
|
+
raise ValueError(
|
|
43
|
+
f"--line {spec!r} must be x1,y1,x2,y2 or name=x1,y1,x2,y2 in image pixels."
|
|
44
|
+
) from None
|
|
45
|
+
return cls(name.strip() or default_name, (x1, y1), (x2, y2))
|
|
46
|
+
|
|
47
|
+
def side(self, point: Point) -> float:
|
|
48
|
+
"""Positive on the ``in`` side, negative on the ``out`` side, zero on the line."""
|
|
49
|
+
(x1, y1), (x2, y2) = self.start, self.end
|
|
50
|
+
return (x2 - x1) * (point[1] - y1) - (y2 - y1) * (point[0] - x1)
|
|
51
|
+
|
|
52
|
+
def spans(self, p: Point, q: Point) -> bool:
|
|
53
|
+
"""Whether the infinite line through ``p`` and ``q`` meets this segment."""
|
|
54
|
+
dx, dy = q[0] - p[0], q[1] - p[1]
|
|
55
|
+
a = dx * (self.start[1] - p[1]) - dy * (self.start[0] - p[0])
|
|
56
|
+
b = dx * (self.end[1] - p[1]) - dy * (self.end[0] - p[0])
|
|
57
|
+
return a * b <= 0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(slots=True)
|
|
61
|
+
class _TrackSide:
|
|
62
|
+
side: float # side the track was last confirmed on
|
|
63
|
+
point: Point # its latest foot point on that side
|
|
64
|
+
pending_since_s: float | None = None # when it was first seen on the other side
|
|
65
|
+
pending_spans: bool = False # whether that move went through the segment
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class LineCounter:
|
|
69
|
+
"""Counts crossings of each line, per direction, for one run or stream.
|
|
70
|
+
|
|
71
|
+
A crossing counts once the track has stayed on the new side for ``hold_s`` seconds. When
|
|
72
|
+
people overlap, a box's bottom edge can jump back and forth across a line for a few
|
|
73
|
+
frames, and each jump would otherwise count.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def __init__(self, lines: Sequence[CountingLine], hold_s: float = 0.3) -> None:
|
|
77
|
+
names = [line.name for line in lines]
|
|
78
|
+
if len(set(names)) != len(names):
|
|
79
|
+
raise ValueError(f"Counting line names must be unique, got {names}.")
|
|
80
|
+
self.lines = list(lines)
|
|
81
|
+
self.hold_s = hold_s
|
|
82
|
+
self.counts = {name: {"in": 0, "out": 0} for name in names}
|
|
83
|
+
self._sides: dict[tuple[str, int], _TrackSide] = {}
|
|
84
|
+
|
|
85
|
+
def update(self, tracks: Sequence[Track], timestamp_s: float) -> list[dict[str, Any]]:
|
|
86
|
+
"""Record this frame's tracks and return a ``line_crossed`` event per new crossing."""
|
|
87
|
+
events: list[dict[str, Any]] = []
|
|
88
|
+
for tr in tracks:
|
|
89
|
+
point = tr.foot_point
|
|
90
|
+
for line in self.lines:
|
|
91
|
+
side = line.side(point)
|
|
92
|
+
if side == 0:
|
|
93
|
+
continue
|
|
94
|
+
key = (line.name, tr.track_id)
|
|
95
|
+
state = self._sides.get(key)
|
|
96
|
+
if state is None:
|
|
97
|
+
self._sides[key] = _TrackSide(side, point)
|
|
98
|
+
continue
|
|
99
|
+
if (state.side > 0) == (side > 0):
|
|
100
|
+
state.point, state.pending_since_s = point, None
|
|
101
|
+
continue
|
|
102
|
+
if state.pending_since_s is None:
|
|
103
|
+
state.pending_since_s = timestamp_s
|
|
104
|
+
state.pending_spans = line.spans(state.point, point)
|
|
105
|
+
if timestamp_s - state.pending_since_s < self.hold_s:
|
|
106
|
+
continue
|
|
107
|
+
if state.pending_spans:
|
|
108
|
+
direction = "in" if side > 0 else "out"
|
|
109
|
+
self.counts[line.name][direction] += 1
|
|
110
|
+
events.append(
|
|
111
|
+
{
|
|
112
|
+
"type": "line_crossed",
|
|
113
|
+
"line": line.name,
|
|
114
|
+
"direction": direction,
|
|
115
|
+
"track_id": tr.track_id,
|
|
116
|
+
"class_name": tr.class_name,
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
state.side, state.point, state.pending_since_s = side, point, None
|
|
120
|
+
return events
|