-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathperson-detection.ts
More file actions
484 lines (418 loc) · 12.9 KB
/
Copy pathperson-detection.ts
File metadata and controls
484 lines (418 loc) · 12.9 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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/**
* Person Detection Library
*
* Hybrid person detection using motion detection as a trigger
* and TensorFlow.js COCO-SSD for AI-based person identification.
*
* @module lib/person-detection
*/
// =============================================================================
// Types
// =============================================================================
export interface PersonDetection {
bbox: [number, number, number, number]; // [x, y, width, height]
confidence: number;
class: 'person';
}
export interface PersonDetectionResult {
personCount: number;
detections: PersonDetection[];
processingTimeMs: number;
frameData?: string;
timestamp: number;
motionTriggered: boolean;
}
export interface PersonDetectorConfig {
/** Minimum confidence threshold for person detection (0-1) */
confidenceThreshold: number;
/** Motion threshold to trigger AI detection (0-100) */
motionThreshold: number;
/** Maximum number of persons to detect */
maxDetections: number;
/** Minimum detection interval in ms */
minDetectionInterval: number;
/** Whether to include frame data in results */
captureFrames: boolean;
/** Target resolution for detection (smaller = faster) */
detectionWidth: number;
detectionHeight: number;
}
export const DEFAULT_DETECTOR_CONFIG: PersonDetectorConfig = {
confidenceThreshold: 0.5,
motionThreshold: 15,
maxDetections: 10,
minDetectionInterval: 500,
captureFrames: true,
detectionWidth: 320,
detectionHeight: 240,
};
// =============================================================================
// Model Loading State
// =============================================================================
type CocoSsdModel = {
detect: (
input: HTMLVideoElement | HTMLImageElement | HTMLCanvasElement,
maxNumBoxes?: number,
minScore?: number
) => Promise<Array<{
bbox: [number, number, number, number];
class: string;
score: number;
}>>;
};
let model: CocoSsdModel | null = null;
let modelLoading: Promise<CocoSsdModel> | null = null;
let modelLoadError: Error | null = null;
/**
* Load the COCO-SSD model for person detection
*/
export async function loadPersonDetectionModel(): Promise<CocoSsdModel> {
if (model) return model;
if (modelLoadError) throw modelLoadError;
if (modelLoading) {
return modelLoading;
}
modelLoading = (async () => {
try {
// Dynamic import to avoid loading TensorFlow.js until needed
const tf = await import('@tensorflow/tfjs');
const cocoSsd = await import('@tensorflow-models/coco-ssd');
// Set backend to webgl for best performance
await tf.setBackend('webgl');
await tf.ready();
console.log('[PersonDetection] Loading COCO-SSD model...');
const loadedModel = await cocoSsd.load({
base: 'lite_mobilenet_v2', // Lighter model for faster inference
});
console.log('[PersonDetection] Model loaded successfully');
model = loadedModel;
return loadedModel;
} catch (error) {
console.error('[PersonDetection] Failed to load model:', error);
modelLoadError = error instanceof Error ? error : new Error(String(error));
throw modelLoadError;
} finally {
modelLoading = null;
}
})();
return modelLoading;
}
/**
* Check if the model is loaded and ready
*/
export function isModelReady(): boolean {
return model !== null;
}
/**
* Get model loading status
*/
export function getModelStatus(): 'not_loaded' | 'loading' | 'ready' | 'error' {
if (modelLoadError) return 'error';
if (model) return 'ready';
if (modelLoading) return 'loading';
return 'not_loaded';
}
/**
* Unload the model to free memory
*/
export function unloadModel(): void {
model = null;
modelLoading = null;
modelLoadError = null;
}
// =============================================================================
// Person Detector Class
// =============================================================================
export class PersonDetector {
private config: PersonDetectorConfig;
private canvas: HTMLCanvasElement | null = null;
private ctx: CanvasRenderingContext2D | null = null;
private previousFrame: ImageData | null = null;
private lastDetectionTime: number = 0;
private isProcessing: boolean = false;
constructor(config: Partial<PersonDetectorConfig> = {}) {
this.config = { ...DEFAULT_DETECTOR_CONFIG, ...config };
}
/**
* Initialize the detector and load the model
*/
async initialize(): Promise<void> {
// Create canvas for frame processing
if (typeof document !== 'undefined') {
this.canvas = document.createElement('canvas');
this.canvas.width = this.config.detectionWidth;
this.canvas.height = this.config.detectionHeight;
this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });
}
// Start loading the model
await loadPersonDetectionModel();
}
/**
* Update detector configuration
*/
updateConfig(config: Partial<PersonDetectorConfig>): void {
this.config = { ...this.config, ...config };
// Resize canvas if dimensions changed
if (this.canvas && (
this.canvas.width !== this.config.detectionWidth ||
this.canvas.height !== this.config.detectionHeight
)) {
this.canvas.width = this.config.detectionWidth;
this.canvas.height = this.config.detectionHeight;
this.previousFrame = null;
}
}
/**
* Check for motion between frames
*/
private detectMotion(currentFrame: ImageData): number {
if (!this.previousFrame) {
this.previousFrame = currentFrame;
return 0;
}
const prev = this.previousFrame.data;
const curr = currentFrame.data;
let diff = 0;
let count = 0;
// Sample every 4th pixel for speed
for (let i = 0; i < curr.length; i += 16) {
const rDiff = Math.abs(curr[i] - prev[i]);
const gDiff = Math.abs(curr[i + 1] - prev[i + 1]);
const bDiff = Math.abs(curr[i + 2] - prev[i + 2]);
diff += (rDiff + gDiff + bDiff) / 3;
count++;
}
this.previousFrame = currentFrame;
return (diff / count / 255) * 100; // Return as percentage
}
/**
* Capture current frame as base64
*/
private captureFrame(): string | undefined {
if (!this.canvas || !this.config.captureFrames) return undefined;
return this.canvas.toDataURL('image/jpeg', 0.8);
}
/**
* Process a video frame for person detection
* Uses hybrid approach: motion triggers AI detection
*/
async processFrame(video: HTMLVideoElement): Promise<PersonDetectionResult | null> {
const now = Date.now();
// Throttle detection
if (now - this.lastDetectionTime < this.config.minDetectionInterval) {
return null;
}
// Prevent concurrent processing
if (this.isProcessing) {
return null;
}
if (!this.canvas || !this.ctx) {
console.warn('[PersonDetection] Canvas not initialized');
return null;
}
this.isProcessing = true;
const startTime = performance.now();
try {
// Draw video frame to canvas
this.ctx.drawImage(
video,
0, 0,
this.config.detectionWidth,
this.config.detectionHeight
);
// Get frame data for motion detection
const frameData = this.ctx.getImageData(
0, 0,
this.config.detectionWidth,
this.config.detectionHeight
);
// Check for motion
const motionLevel = this.detectMotion(frameData);
const motionTriggered = motionLevel >= this.config.motionThreshold;
// Only run AI detection if motion detected
if (!motionTriggered) {
// No motion means we have insufficient evidence to declare "no people";
// callers should treat this as "no update" and keep the last known state.
return null;
}
// Ensure model is loaded
if (!model) {
await loadPersonDetectionModel();
}
if (!model) {
throw new Error('Model not available');
}
// Run person detection
const predictions = await model.detect(
this.canvas,
this.config.maxDetections,
this.config.confidenceThreshold
);
// Filter only person detections
const personDetections: PersonDetection[] = predictions
.filter(p => p.class === 'person' && p.score >= this.config.confidenceThreshold)
.map(p => ({
bbox: p.bbox,
confidence: p.score,
class: 'person' as const,
}));
this.lastDetectionTime = now;
return {
personCount: personDetections.length,
detections: personDetections,
processingTimeMs: performance.now() - startTime,
frameData: this.captureFrame(),
timestamp: now,
motionTriggered: true,
};
} catch (error) {
console.error('[PersonDetection] Detection error:', error);
return null;
} finally {
this.isProcessing = false;
}
}
/**
* Force a detection without motion threshold
*/
async forceDetection(video: HTMLVideoElement): Promise<PersonDetectionResult | null> {
if (!this.canvas || !this.ctx) {
return null;
}
this.isProcessing = true;
const startTime = performance.now();
const now = Date.now();
try {
// Draw video frame
this.ctx.drawImage(
video,
0, 0,
this.config.detectionWidth,
this.config.detectionHeight
);
// Ensure model is loaded
if (!model) {
await loadPersonDetectionModel();
}
if (!model) {
throw new Error('Model not available');
}
// Run detection
const predictions = await model.detect(
this.canvas,
this.config.maxDetections,
this.config.confidenceThreshold
);
const personDetections: PersonDetection[] = predictions
.filter(p => p.class === 'person')
.map(p => ({
bbox: p.bbox,
confidence: p.score,
class: 'person' as const,
}));
return {
personCount: personDetections.length,
detections: personDetections,
processingTimeMs: performance.now() - startTime,
frameData: this.captureFrame(),
timestamp: now,
motionTriggered: false,
};
} catch (error) {
console.error('[PersonDetection] Force detection error:', error);
return null;
} finally {
this.isProcessing = false;
}
}
/**
* Clean up resources
*/
dispose(): void {
this.previousFrame = null;
this.canvas = null;
this.ctx = null;
this.isProcessing = false;
}
}
// =============================================================================
// Singleton Instance
// =============================================================================
let detectorInstance: PersonDetector | null = null;
/**
* Get or create the singleton person detector
*/
export function getPersonDetector(config?: Partial<PersonDetectorConfig>): PersonDetector {
if (!detectorInstance) {
detectorInstance = new PersonDetector(config);
} else if (config) {
detectorInstance.updateConfig(config);
}
return detectorInstance;
}
/**
* Reset the singleton detector
*/
export function resetPersonDetector(): void {
if (detectorInstance) {
detectorInstance.dispose();
detectorInstance = null;
}
}
// =============================================================================
// Utility Functions
// =============================================================================
/**
* Draw detection bounding boxes on a canvas
*/
export function drawDetections(
ctx: CanvasRenderingContext2D,
detections: PersonDetection[],
scaleX: number = 1,
scaleY: number = 1,
color: string = '#ff0000'
): void {
ctx.strokeStyle = color;
ctx.lineWidth = 3;
ctx.font = '16px monospace';
ctx.fillStyle = color;
for (const detection of detections) {
const [x, y, width, height] = detection.bbox;
const scaledX = x * scaleX;
const scaledY = y * scaleY;
const scaledWidth = width * scaleX;
const scaledHeight = height * scaleY;
// Draw bounding box
ctx.strokeRect(scaledX, scaledY, scaledWidth, scaledHeight);
// Draw label background
const label = `Person ${Math.round(detection.confidence * 100)}%`;
const textMetrics = ctx.measureText(label);
ctx.fillRect(scaledX, scaledY - 20, textMetrics.width + 8, 20);
// Draw label text
ctx.fillStyle = '#ffffff';
ctx.fillText(label, scaledX + 4, scaledY - 5);
ctx.fillStyle = color;
}
}
/**
* Calculate person count change for alert logic
*/
export function calculatePersonChange(
currentCount: number,
previousCount: number,
allowedCount: number
): {
exceeded: boolean;
excessCount: number;
isNewIntrusion: boolean;
} {
const exceeded = currentCount > allowedCount;
const excessCount = Math.max(0, currentCount - allowedCount);
const wasExceeded = previousCount > allowedCount;
const isNewIntrusion = exceeded && !wasExceeded;
return {
exceeded,
excessCount,
isNewIntrusion,
};
}