feat: implement Rust face_tracker module

- Add face_tracker.rs with core tracking algorithms
- Add trace_id field to Face struct
- Add metadata field to FaceResult struct
- Implement IoU, distance, and embedding similarity calculations
- Implement match_faces and track_faces functions
- Support scene cut detection
- Add unit tests for core functions
This commit is contained in:
Accusys
2026-09-27 01:39:37 +08:00
parent 696ede8696
commit eb4fd82a84
4 changed files with 711 additions and 0 deletions
+16
View File
@@ -16,6 +16,8 @@ pub struct FaceResult {
pub frames: Vec<FaceFrame>,
#[serde(default)]
pub total_faces: usize,
#[serde(default)]
pub metadata: Option<serde_json::Value>,
}
impl FaceResult {
@@ -47,6 +49,7 @@ impl FaceResult {
fps,
frames: vec![],
total_faces: 0,
metadata: None,
}
}
}
@@ -80,6 +83,8 @@ pub struct Face {
pub bbox: Option<BoundingBox>,
#[serde(default)]
pub pose: Option<serde_json::Value>,
#[serde(default)]
pub trace_id: Option<i32>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
@@ -309,6 +314,7 @@ mod tests {
frame_count: 100,
fps: 30.0,
total_faces: 1,
metadata: None,
frames: vec![FaceFrame {
frame: 0,
timestamp: 0.0,
@@ -327,6 +333,9 @@ mod tests {
age: Some(30),
gender: Some("male".to_string()),
}),
bbox: None,
pose: None,
trace_id: None,
}],
}],
};
@@ -381,6 +390,7 @@ mod tests {
fps: 0.0,
frames: vec![],
total_faces: 0,
metadata: None,
};
assert!(result.frames.is_empty());
}
@@ -399,6 +409,9 @@ mod tests {
landmarks: None,
pose_angle: None,
attributes: None,
bbox: None,
pose: None,
trace_id: None,
};
assert!(face.confidence >= 0.0 && face.confidence <= 1.0);
}
@@ -420,6 +433,9 @@ mod tests {
age: Some(35),
gender: Some("male".to_string()),
}),
bbox: None,
pose: None,
trace_id: None,
};
assert!(face.embedding.is_some());
+490
View File
@@ -0,0 +1,490 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use super::{Face, FaceFrame, FaceResult};
/// Trace statistics for a single face trace
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceStats {
pub trace_id: i32,
pub start_frame: u64,
pub end_frame: u64,
pub duration_frames: u64,
pub duration_seconds: f64,
pub total_appearances: usize,
pub avg_confidence: f64,
pub path: Vec<TracePoint>,
}
/// A single point in a trace
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracePoint {
pub frame: u64,
pub face_index: usize,
pub bbox: BoundingBox,
pub confidence: f32,
}
/// Bounding box
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundingBox {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
}
/// Result of face tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaceTrackingResult {
pub status: Option<String>,
pub frame_count: u64,
pub fps: f64,
pub frames: HashMap<String, FaceFrame>,
pub total_faces: usize,
pub traces: HashMap<String, TraceStats>,
pub metadata: serde_json::Value,
}
/// Calculate Intersection over Union (IoU) between two bounding boxes
fn calculate_bbox_iou(bbox1: &BoundingBox, bbox2: &BoundingBox) -> f64 {
let x1_min = bbox1.x;
let x1_max = bbox1.x + bbox1.width;
let y1_min = bbox1.y;
let y1_max = bbox1.y + bbox1.height;
let x2_min = bbox2.x;
let x2_max = bbox2.x + bbox2.width;
let y2_min = bbox2.y;
let y2_max = bbox2.y + bbox2.height;
let inter_x_min = x1_min.max(x2_min);
let inter_x_max = x1_max.min(x2_max);
let inter_y_min = y1_min.max(y2_min);
let inter_y_max = y1_max.min(y2_max);
if inter_x_max <= inter_x_min || inter_y_max <= inter_y_min {
return 0.0;
}
let inter_area = (inter_x_max - inter_x_min) as f64 * (inter_y_max - inter_y_min) as f64;
let area1 = (bbox1.width * bbox1.height) as f64;
let area2 = (bbox2.width * bbox2.height) as f64;
let union_area = area1 + area2 - inter_area;
if union_area > 0.0 {
inter_area / union_area
} else {
0.0
}
}
/// Calculate center distance between two bounding boxes
fn calculate_bbox_distance(bbox1: &BoundingBox, bbox2: &BoundingBox) -> f64 {
let cx1 = bbox1.x as f64 + bbox1.width as f64 / 2.0;
let cy1 = bbox1.y as f64 + bbox1.height as f64 / 2.0;
let cx2 = bbox2.x as f64 + bbox2.width as f64 / 2.0;
let cy2 = bbox2.y as f64 + bbox2.height as f64 / 2.0;
((cx1 - cx2).powi(2) + (cy1 - cy2).powi(2)).sqrt()
}
/// Calculate cosine similarity between two embeddings
fn calculate_embedding_similarity(emb1: &[f32], emb2: &[f32]) -> f64 {
if emb1.is_empty() || emb2.is_empty() {
return 0.0;
}
let dot: f64 = emb1.iter()
.zip(emb2.iter())
.map(|(a, b)| (*a as f64) * (*b as f64))
.sum();
let norm1: f64 = emb1.iter().map(|x| (*x as f64).powi(2)).sum::<f64>().sqrt();
let norm2: f64 = emb2.iter().map(|x| (*x as f64).powi(2)).sum::<f64>().sqrt();
if norm1 > 0.0 && norm2 > 0.0 {
dot / (norm1 * norm2)
} else {
0.0
}
}
/// Match current frame faces to previous frame faces
fn match_faces(
current_faces: &[Face],
previous_faces: &[Face],
previous_trace_ids: &[i32],
iou_threshold: f64,
similarity_threshold: f64,
distance_threshold: f64,
use_embedding: bool,
frame_gap: Option<u64>,
cut_boundaries: Option<&HashSet<u64>>,
prev_frame: Option<u64>,
curr_frame: Option<u64>,
) -> Vec<i32> {
let mut trace_ids = vec![-1i32; current_faces.len()];
if previous_faces.is_empty() {
return trace_ids;
}
// Check frame gap
if let Some(gap) = frame_gap {
if gap > 30 {
return trace_ids;
}
}
// Check for scene cut
if let (Some(cuts), Some(prev), Some(curr)) = (cut_boundaries, prev_frame, curr_frame) {
for &cut_frame in cuts {
if prev < cut_frame && cut_frame <= curr {
// Scene cut detected - use stricter matching
let mut used_prev = HashSet::new();
for (curr_idx, curr_face) in current_faces.iter().enumerate() {
let curr_bbox = BoundingBox {
x: curr_face.x,
y: curr_face.y,
width: curr_face.width,
height: curr_face.height,
};
let mut best_prev_idx = -1i32;
let mut best_iou = 0.0;
for (prev_idx, prev_face) in previous_faces.iter().enumerate() {
if used_prev.contains(&prev_idx) {
continue;
}
let prev_bbox = BoundingBox {
x: prev_face.x,
y: prev_face.y,
width: prev_face.width,
height: prev_face.height,
};
let iou = calculate_bbox_iou(&curr_bbox, &prev_bbox);
if iou > best_iou {
best_iou = iou;
best_prev_idx = prev_idx as i32;
}
}
if best_prev_idx >= 0 && best_iou > 0.5 {
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
used_prev.insert(best_prev_idx as usize);
}
}
return trace_ids;
}
}
}
// Normal matching
let mut used_prev = HashSet::new();
for (curr_idx, curr_face) in current_faces.iter().enumerate() {
let curr_bbox = BoundingBox {
x: curr_face.x,
y: curr_face.y,
width: curr_face.width,
height: curr_face.height,
};
let mut best_prev_idx = -1i32;
let mut best_score = 0.0;
for (prev_idx, prev_face) in previous_faces.iter().enumerate() {
if used_prev.contains(&prev_idx) {
continue;
}
let prev_bbox = BoundingBox {
x: prev_face.x,
y: prev_face.y,
width: prev_face.width,
height: prev_face.height,
};
let iou = calculate_bbox_iou(&curr_bbox, &prev_bbox);
let distance = calculate_bbox_distance(&curr_bbox, &prev_bbox);
let similarity = if use_embedding {
if let (Some(curr_emb), Some(prev_emb)) = (&curr_face.embedding, &prev_face.embedding) {
calculate_embedding_similarity(curr_emb, prev_emb)
} else {
0.0
}
} else {
0.0
};
// Bbox size consistency check
let prev_area = (prev_bbox.width * prev_bbox.height) as f64;
let curr_area = (curr_bbox.width * curr_bbox.height) as f64;
let area_ratio = curr_area.max(prev_area) / curr_area.min(prev_area).max(1.0);
let mut score = 0.0;
// Reject if both embedding AND IoU disagree
if use_embedding && similarity < 0.5 && iou < 0.3 {
continue;
}
// Reject if bbox size changes too much
if area_ratio > 5.0 && similarity < 0.8 {
continue;
}
// Edge exit check
let prev_at_edge = prev_bbox.x < 50
|| prev_bbox.x + prev_bbox.width > 1870
|| prev_bbox.y < 50
|| prev_bbox.y + prev_bbox.height > 1030;
let curr_at_edge = curr_bbox.x < 50
|| curr_bbox.x + curr_bbox.width > 1870
|| curr_bbox.y < 50
|| curr_bbox.y + curr_bbox.height > 1030;
if prev_at_edge && !curr_at_edge && similarity < 0.8 {
continue;
}
// Calculate score
if iou > iou_threshold && similarity > similarity_threshold {
score = iou + similarity;
} else if iou > 0.5 && similarity > 0.65 {
score = iou * 1.5 + similarity * 0.5;
} else if iou > 0.35 && distance < distance_threshold {
score = iou * 2.0 - distance / 500.0;
} else if similarity > 0.85 {
score = similarity * 2.0;
} else if similarity > 0.75 && distance < distance_threshold {
score = similarity - distance / 1000.0;
} else if let Some(gap) = frame_gap {
if gap > 1 && similarity > 0.8 && iou > 0.2 {
score = similarity + iou;
}
}
if score > best_score {
best_score = score;
best_prev_idx = prev_idx as i32;
}
}
if best_prev_idx >= 0 && best_score > 0.0 {
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
used_prev.insert(best_prev_idx as usize);
}
}
trace_ids
}
/// Track faces across all frames
pub fn track_faces(
face_data: &mut FaceResult,
iou_threshold: f64,
similarity_threshold: f64,
distance_threshold: f64,
use_embedding: bool,
cut_boundaries: Option<HashSet<u64>>,
) -> Result<()> {
if face_data.frames.is_empty() {
tracing::info!("No frames found in face.json");
return Ok(());
}
let fps = face_data.fps;
let frames_count = face_data.frames.len();
let mut next_trace_id: i32 = 0;
let mut traces: HashMap<i32, Vec<TracePoint>> = HashMap::new();
let mut prev_faces: Vec<Face> = Vec::new();
let mut prev_trace_ids: Vec<i32> = Vec::new();
let mut prev_frame_num: Option<u64> = None;
let mut prev_face_frame: Option<u64> = None;
tracing::info!(
"Tracking faces across {} frames (iou={}, similarity={}, distance={})",
frames_count,
iou_threshold,
similarity_threshold,
distance_threshold
);
for frame_idx in 0..face_data.frames.len() {
let frame_num = face_data.frames[frame_idx].frame;
let frame_gap = if let Some(prev) = prev_frame_num {
Some(frame_num - prev)
} else {
None
};
prev_frame_num = Some(frame_num);
let faces = &face_data.frames[frame_idx].faces.clone();
if faces.is_empty() {
prev_faces.clear();
prev_trace_ids.clear();
continue;
}
let matches = match_faces(
faces,
&prev_faces,
&prev_trace_ids,
iou_threshold,
similarity_threshold,
distance_threshold,
use_embedding,
frame_gap,
cut_boundaries.as_ref(),
prev_face_frame,
Some(frame_num),
);
let mut trace_ids = Vec::new();
for (curr_idx, &trace_id) in matches.iter().enumerate() {
let trace_id = if trace_id >= 0 {
trace_id
} else {
let new_id = next_trace_id;
next_trace_id += 1;
new_id
};
// Set trace_id on the face
face_data.frames[frame_idx].faces[curr_idx].trace_id = Some(trace_id);
trace_ids.push(trace_id);
let face = &faces[curr_idx];
let trace_point = TracePoint {
frame: frame_num,
face_index: curr_idx,
bbox: BoundingBox {
x: face.x,
y: face.y,
width: face.width,
height: face.height,
},
confidence: face.confidence,
};
traces.entry(trace_id).or_insert_with(Vec::new).push(trace_point);
}
prev_faces = faces.clone();
prev_trace_ids = trace_ids;
prev_face_frame = Some(frame_num);
if frame_num % 100 == 0 {
tracing::info!(
"Frame {}: {} faces, {} active traces",
frame_num,
faces.len(),
traces.len()
);
}
}
// Build trace statistics
let trace_stats: HashMap<String, TraceStats> = traces
.into_iter()
.filter(|(_, path)| path.len() >= 1)
.map(|(trace_id, path)| {
let start_frame = path.first().unwrap().frame;
let end_frame = path.last().unwrap().frame;
let duration_frames = end_frame - start_frame + 1;
let avg_confidence = path.iter().map(|p| p.confidence as f64).sum::<f64>() / path.len() as f64;
let stats = TraceStats {
trace_id,
start_frame,
end_frame,
duration_frames,
duration_seconds: duration_frames as f64 / fps,
total_appearances: path.len(),
avg_confidence,
path,
};
(trace_id.to_string(), stats)
})
.collect();
// Store traces in metadata
face_data.metadata = Some(serde_json::json!({
"traces": trace_stats,
"trace_stats": {
"total_traces": next_trace_id,
"active_traces": trace_stats.len(),
}
}));
tracing::info!("✅ Tracking complete: {} traces", trace_stats.len());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calculate_bbox_iou() {
let bbox1 = BoundingBox {
x: 0,
y: 0,
width: 100,
height: 100,
};
let bbox2 = BoundingBox {
x: 50,
y: 50,
width: 100,
height: 100,
};
let iou = calculate_bbox_iou(&bbox1, &bbox2);
assert!(iou > 0.0 && iou < 1.0);
}
#[test]
fn test_calculate_bbox_distance() {
let bbox1 = BoundingBox {
x: 0,
y: 0,
width: 100,
height: 100,
};
let bbox2 = BoundingBox {
x: 200,
y: 200,
width: 100,
height: 100,
};
let distance = calculate_bbox_distance(&bbox1, &bbox2);
assert!(distance > 0.0);
}
#[test]
fn test_calculate_embedding_similarity() {
let emb1 = vec![1.0, 0.0, 0.0];
let emb2 = vec![1.0, 0.0, 0.0];
let similarity = calculate_embedding_similarity(&emb1, &emb2);
assert!((similarity - 1.0).abs() < 0.001);
let emb3 = vec![0.0, 1.0, 0.0];
let similarity2 = calculate_embedding_similarity(&emb1, &emb3);
assert!((similarity2 - 0.0).abs() < 0.001);
}
}
+1
View File
@@ -9,6 +9,7 @@ pub mod executor;
pub mod face;
pub mod face_clustering;
pub mod face_recognition;
pub mod face_tracker;
pub mod hand;
pub mod heuristic_scene;
pub mod ocr;