feat: face_tracker v2 schema - add schema_version, TraceBBox with x2/y2/center, TracePoint with pose/landmarks

This commit is contained in:
Accusys
2026-11-02 14:51:31 +08:00
parent 5d18183d82
commit adcc5a1dc1
+183 -28
View File
@@ -4,49 +4,151 @@ use std::collections::{HashMap, HashSet};
use super::{Face, FaceFrame, FaceResult}; use super::{Face, FaceFrame, FaceResult};
fn default_schema_version() -> String {
"2.0".to_string()
}
/// Trace statistics for a single face trace /// Trace statistics for a single face trace
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceStats { pub struct TraceStats {
pub trace_id: i32, pub trace_id: i32,
pub start_frame: u64, pub start_frame: u64,
pub end_frame: u64, pub end_frame: u64,
pub start_time: f64,
pub end_time: f64,
pub frame_count: u64,
pub duration_frames: u64, pub duration_frames: u64,
pub duration_seconds: f64, pub duration_seconds: f64,
pub total_appearances: usize, pub total_appearances: usize,
pub avg_confidence: f64, pub avg_confidence: f64,
pub avg_capture_quality: f64,
pub best_frame: u64,
pub best_confidence: f64,
#[serde(default)]
pub avg_bbox: TraceBBox,
#[serde(default)]
pub path: Vec<TracePoint>, pub path: Vec<TracePoint>,
} }
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TraceBBox {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
#[serde(default)]
pub x2: i32,
#[serde(default)]
pub y2: i32,
#[serde(default)]
pub center_x: i32,
#[serde(default)]
pub center_y: i32,
}
/// A single point in a trace /// A single point in a trace
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracePoint { pub struct TracePoint {
pub frame: u64, pub frame: u64,
pub timestamp: f64,
pub face_index: usize, pub face_index: usize,
pub bbox: BoundingBox, #[serde(default)]
pub bbox: TraceBBox,
pub confidence: f32, pub confidence: f32,
#[serde(default)]
pub capture_quality: f32,
#[serde(default)]
pub pose: Option<serde_json::Value>,
#[serde(default)]
pub landmarks: Option<serde_json::Value>,
} }
/// Bounding box /// Bounding box (legacy, kept for backward compatibility)
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoundingBox { pub struct BoundingBox {
pub x: i32, pub x: i32,
pub y: i32, pub y: i32,
pub width: i32, pub width: i32,
pub height: i32, pub height: i32,
#[serde(default)]
pub x2: i32,
#[serde(default)]
pub y2: i32,
#[serde(default)]
pub center_x: i32,
#[serde(default)]
pub center_y: i32,
} }
/// Result of face tracking /// Result of face tracking (v2 schema)
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaceTrackingResult { pub struct FaceTrackingResult {
#[serde(default = "default_schema_version")]
pub schema_version: String,
#[serde(default)]
pub file_uuid: Option<String>,
pub status: Option<String>, pub status: Option<String>,
pub frame_count: u64, pub frame_count: u64,
pub fps: f64, pub fps: f64,
pub frames: HashMap<String, FaceFrame>, pub frames: HashMap<String, FaceFrame>,
#[serde(default)]
pub total_faces: usize, pub total_faces: usize,
pub traces: HashMap<String, TraceStats>, pub traces: Vec<TraceInfo>,
#[serde(default)]
pub stats: TraceStatsSummary,
#[serde(default)]
pub metadata: serde_json::Value, pub metadata: serde_json::Value,
} }
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TraceStatsSummary {
#[serde(default)]
pub total_traces: usize,
#[serde(default)]
pub total_face_instances: usize,
#[serde(default)]
pub avg_trace_length: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceInfo {
pub trace_id: i32,
pub frame_count: u64,
pub start_frame: u64,
pub end_frame: u64,
pub start_time: f64,
pub end_time: f64,
pub avg_confidence: f64,
pub avg_capture_quality: f64,
pub best_frame: u64,
pub best_confidence: f64,
#[serde(default)]
pub avg_bbox: TraceBBox,
#[serde(default)]
pub face_instances: Vec<TracePoint>,
}
impl FaceTrackingResult {
pub fn add_metadata(&mut self, file_uuid: &str, fps: f64) {
self.file_uuid = Some(file_uuid.to_string());
self.fps = fps;
self.status = Some("completed".to_string());
self.stats.total_traces = self.traces.len();
self.stats.total_face_instances = self.traces.iter().map(|t| t.frame_count as usize).sum();
self.stats.avg_trace_length = if self.traces.is_empty() {
0.0
} else {
self.traces.iter().map(|t| t.frame_count as f64).sum::<f64>() / self.traces.len() as f64
};
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write face_traced.json")?;
Ok(())
}
}
/// Calculate Intersection over Union (IoU) between two bounding boxes /// Calculate Intersection over Union (IoU) between two bounding boxes
fn calculate_bbox_iou(bbox1: &BoundingBox, bbox2: &BoundingBox) -> f64 { fn calculate_bbox_iou(bbox1: &BoundingBox, bbox2: &BoundingBox) -> f64 {
let x1_min = bbox1.x; let x1_min = bbox1.x;
@@ -146,7 +248,7 @@ fn match_faces(
// Scene cut detected - use stricter matching // Scene cut detected - use stricter matching
let mut used_prev = HashSet::new(); let mut used_prev = HashSet::new();
for (curr_idx, curr_face) in current_faces.iter().enumerate() { for (curr_idx, curr_face) in current_faces.iter().enumerate() {
let curr_bbox = BoundingBox { let curr_bbox = BoundingBox { x2: 0, y2: 0, center_x: 0, center_y: 0,
x: curr_face.x, x: curr_face.x,
y: curr_face.y, y: curr_face.y,
width: curr_face.width, width: curr_face.width,
@@ -160,7 +262,7 @@ fn match_faces(
if used_prev.contains(&prev_idx) { if used_prev.contains(&prev_idx) {
continue; continue;
} }
let prev_bbox = BoundingBox { let prev_bbox = BoundingBox { x2: 0, y2: 0, center_x: 0, center_y: 0,
x: prev_face.x, x: prev_face.x,
y: prev_face.y, y: prev_face.y,
width: prev_face.width, width: prev_face.width,
@@ -188,7 +290,7 @@ fn match_faces(
let mut used_prev = HashSet::new(); let mut used_prev = HashSet::new();
for (curr_idx, curr_face) in current_faces.iter().enumerate() { for (curr_idx, curr_face) in current_faces.iter().enumerate() {
let curr_bbox = BoundingBox { let curr_bbox = BoundingBox { x2: 0, y2: 0, center_x: 0, center_y: 0,
x: curr_face.x, x: curr_face.x,
y: curr_face.y, y: curr_face.y,
width: curr_face.width, width: curr_face.width,
@@ -203,7 +305,7 @@ fn match_faces(
continue; continue;
} }
let prev_bbox = BoundingBox { let prev_bbox = BoundingBox { x2: 0, y2: 0, center_x: 0, center_y: 0,
x: prev_face.x, x: prev_face.x,
y: prev_face.y, y: prev_face.y,
width: prev_face.width, width: prev_face.width,
@@ -370,14 +472,22 @@ pub fn track_faces(
let face = &faces[curr_idx]; let face = &faces[curr_idx];
let trace_point = TracePoint { let trace_point = TracePoint {
frame: frame_num, frame: frame_num,
timestamp: frame_num as f64 / fps,
face_index: curr_idx, face_index: curr_idx,
bbox: BoundingBox { bbox: TraceBBox {
x: face.x, x: face.x,
y: face.y, y: face.y,
width: face.width, width: face.width,
height: face.height, height: face.height,
x2: face.x2,
y2: face.y2,
center_x: face.center_x,
center_y: face.center_y,
}, },
confidence: face.confidence, confidence: face.confidence,
capture_quality: face.capture_quality.unwrap_or(0.0),
pose: face.pose_angle.clone(),
landmarks: face.landmarks.clone(),
}; };
traces traces
@@ -400,38 +510,67 @@ pub fn track_faces(
} }
} }
// Build trace statistics // Build trace statistics (v2 format)
let trace_stats: HashMap<String, TraceStats> = traces let traces: Vec<TraceInfo> = traces
.into_iter() .into_iter()
.filter(|(_, path)| path.len() >= 1) .filter(|(_, path)| path.len() >= 1)
.map(|(trace_id, path)| { .map(|(trace_id, path)| {
let start_frame = path.first().unwrap().frame; let start_frame = path.first().unwrap().frame;
let end_frame = path.last().unwrap().frame; let end_frame = path.last().unwrap().frame;
let start_time = path.first().unwrap().timestamp;
let end_time = path.last().unwrap().timestamp;
let frame_count = path.len() as u64;
let duration_frames = end_frame - start_frame + 1; let duration_frames = end_frame - start_frame + 1;
let avg_confidence = let avg_confidence =
path.iter().map(|p| p.confidence as f64).sum::<f64>() / path.len() as f64; path.iter().map(|p| p.confidence as f64).sum::<f64>() / path.len() as f64;
let avg_capture_quality =
let stats = TraceStats { path.iter().map(|p| p.capture_quality as f64).sum::<f64>() / path.len() as f64;
trace_id,
start_frame, // Find best frame
end_frame, let best = path.iter().max_by(|a, b| a.confidence.partial_cmp(&b.confidence).unwrap()).unwrap();
duration_frames, let best_frame = best.frame;
duration_seconds: duration_frames as f64 / fps, let best_confidence = best.confidence as f64;
total_appearances: path.len(),
avg_confidence, // Calculate average bbox
path, let avg_bbox = TraceBBox {
x: (path.iter().map(|p| p.bbox.x).sum::<i32>() as f64 / path.len() as f64) as i32,
y: (path.iter().map(|p| p.bbox.y).sum::<i32>() as f64 / path.len() as f64) as i32,
width: (path.iter().map(|p| p.bbox.width).sum::<i32>() as f64 / path.len() as f64) as i32,
height: (path.iter().map(|p| p.bbox.height).sum::<i32>() as f64 / path.len() as f64) as i32,
x2: (path.iter().map(|p| p.bbox.x2).sum::<i32>() as f64 / path.len() as f64) as i32,
y2: (path.iter().map(|p| p.bbox.y2).sum::<i32>() as f64 / path.len() as f64) as i32,
center_x: (path.iter().map(|p| p.bbox.center_x).sum::<i32>() as f64 / path.len() as f64) as i32,
center_y: (path.iter().map(|p| p.bbox.center_y).sum::<i32>() as f64 / path.len() as f64) as i32,
}; };
(trace_id.to_string(), stats) TraceInfo {
trace_id,
frame_count,
start_frame,
end_frame,
start_time,
end_time,
avg_confidence,
avg_capture_quality,
best_frame,
best_confidence,
avg_bbox,
face_instances: path,
}
}) })
.collect(); .collect();
// Store traces in metadata let total_traces = traces.len();
// Store traces in metadata (v2 format)
let trace_custom = serde_json::json!({ let trace_custom = serde_json::json!({
"traces": trace_stats, "traces": traces,
"trace_stats": { "stats": {
"total_traces": next_trace_id, "total_traces": total_traces,
"active_traces": trace_stats.len(), "total_face_instances": traces.iter().map(|t| t.frame_count as usize).sum::<usize>(),
"avg_trace_length": if traces.is_empty() { 0.0 } else {
traces.iter().map(|t| t.frame_count as f64).sum::<f64>() / traces.len() as f64
}
} }
}); });
@@ -459,7 +598,7 @@ pub fn track_faces(
}); });
} }
tracing::info!("✅ Tracking complete: {} traces", trace_stats.len()); tracing::info!("✅ Tracking complete: {} traces", total_traces);
Ok(()) Ok(())
} }
@@ -475,12 +614,20 @@ mod tests {
y: 0, y: 0,
width: 100, width: 100,
height: 100, height: 100,
x2: 100,
y2: 100,
center_x: 50,
center_y: 50,
}; };
let bbox2 = BoundingBox { let bbox2 = BoundingBox {
x: 50, x: 50,
y: 50, y: 50,
width: 100, width: 100,
height: 100, height: 100,
x2: 150,
y2: 150,
center_x: 100,
center_y: 100,
}; };
let iou = calculate_bbox_iou(&bbox1, &bbox2); let iou = calculate_bbox_iou(&bbox1, &bbox2);
@@ -494,12 +641,20 @@ mod tests {
y: 0, y: 0,
width: 100, width: 100,
height: 100, height: 100,
x2: 100,
y2: 100,
center_x: 50,
center_y: 50,
}; };
let bbox2 = BoundingBox { let bbox2 = BoundingBox {
x: 200, x: 200,
y: 200, y: 200,
width: 100, width: 100,
height: 100, height: 100,
x2: 300,
y2: 300,
center_x: 250,
center_y: 250,
}; };
let distance = calculate_bbox_distance(&bbox1, &bbox2); let distance = calculate_bbox_distance(&bbox1, &bbox2);