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:
@@ -0,0 +1,204 @@
|
||||
# 020.mp4 Ingestion 卡住問題最終分析
|
||||
|
||||
**日期**: 2026-09-27
|
||||
**視頻**: 020.mp4 (UUID: b496a68800f90770aa7246c877f38985)
|
||||
**狀態**: ❌ Ingestion 卡在 40% (待修復)
|
||||
|
||||
---
|
||||
|
||||
## 問題鏈完整分析
|
||||
|
||||
### 問題 1: Face.json 格式變更 ❌
|
||||
|
||||
**現象**: `face.json` 的 `frames` 從 dict 改為 list
|
||||
|
||||
**影響**: `face_tracker.py` 期望 dict 格式,報錯
|
||||
|
||||
**修復**: ✅ 已修復
|
||||
- 添加了對 list 格式的支持
|
||||
- 自動轉換為 dict 格式
|
||||
|
||||
**提交**: `696ede8`
|
||||
|
||||
---
|
||||
|
||||
### 問題 2: Qdrant bbox 信息錯誤 ❌ (根本原因)
|
||||
|
||||
**現象**: Qdrant 中的 bbox 信息都是 `x=0, y=0, width=0, height=0`
|
||||
|
||||
**檢查**:
|
||||
```bash
|
||||
curl -X POST -H "api-key: Test3200Test3200Test3200" \
|
||||
"http://127.0.0.1:6333/collections/_faces/points/scroll" \
|
||||
-d '{"limit": 1, "filter": {"must": [{"key": "file_uuid", "match": {"value": "b496a68800f90770aa7246c877f38985"}}]}}'
|
||||
```
|
||||
|
||||
**結果**:
|
||||
```json
|
||||
{
|
||||
"payload": {
|
||||
"file_uuid": "b496a68800f90770aa7246c877f38985",
|
||||
"frame": 480,
|
||||
"x": 0, "y": 0, "width": 0, "height": 0, // ❌ 錯誤!
|
||||
"trace_id": -1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**原因**: `store_face_embeddings_to_qdrant.py` 存儲時使用了錯誤的 bbox 信息
|
||||
|
||||
**影響**:
|
||||
1. `store_traced_faces.py` 無法正確匹配 embeddings
|
||||
2. `emb_lookup` 構建失敗
|
||||
3. Face tracking 缺少 embeddings
|
||||
4. 追蹤質量下降
|
||||
|
||||
---
|
||||
|
||||
### 問題 3: Embedding 匹配失敗 ❌
|
||||
|
||||
**現象**: `Attached 0 embeddings to face data`
|
||||
|
||||
**根本原因**:
|
||||
```python
|
||||
# store_traced_faces.py 中的匹配邏輯
|
||||
emb_lookup[(frame, x, y)] = vec
|
||||
|
||||
# Qdrant 中的 key: (480, 0, 0)
|
||||
# face.json 中的 key: (480, 1377, 219)
|
||||
# 不匹配!
|
||||
```
|
||||
|
||||
**影響**:
|
||||
- Face tracking 沒有 embeddings
|
||||
- 追蹤算法降級為只用 IoU + 距離
|
||||
- 追蹤質量下降
|
||||
|
||||
---
|
||||
|
||||
### 問題 4: trace_id 未更新到 Qdrant ❌
|
||||
|
||||
**現象**: `Updated 0 Qdrant points with trace_id`
|
||||
|
||||
**原因**:
|
||||
1. `update_trace_ids()` 依賴 bbox 匹配
|
||||
2. Qdrant 中的 bbox 信息錯誤
|
||||
3. 無法匹配 faces
|
||||
|
||||
**影響**:
|
||||
- TKG builder 找不到 traced faces
|
||||
- TKG 無法構建
|
||||
- Ingestion 卡住
|
||||
|
||||
---
|
||||
|
||||
## 根本原因
|
||||
|
||||
**`store_face_embeddings_to_qdrant.py` 的 bbox 存儲問題**:
|
||||
|
||||
```python
|
||||
# Line 66-77
|
||||
payload = {
|
||||
"file_uuid": file_uuid,
|
||||
"frame": frame_num,
|
||||
"timestamp_secs": timestamp,
|
||||
"face_id": face.get("face_id", ""),
|
||||
"confidence": face.get("confidence", 0.0),
|
||||
"x": face.get("x", 0), # ❌ 如果 face 中沒有這些字段,就是 0
|
||||
"y": face.get("y", 0), # ❌
|
||||
"width": face.get("width", 0), # ❌
|
||||
"height": face.get("height", 0), # ❌
|
||||
"trace_id": -1,
|
||||
}
|
||||
```
|
||||
|
||||
**問題**: face.json 的結構可能沒有直接的 x, y, width, height 字段
|
||||
|
||||
---
|
||||
|
||||
## 修復方案
|
||||
|
||||
### 方案 1: 修復 store_face_embeddings_to_qdrant.py
|
||||
|
||||
**檢查 face.json 的實際結構**:
|
||||
```python
|
||||
# 檢查 face 是否有 bbox 字段
|
||||
bbox = face.get("bbox", {})
|
||||
if bbox:
|
||||
x = bbox.get("x", 0)
|
||||
y = bbox.get("y", 0)
|
||||
width = bbox.get("width", 0)
|
||||
height = bbox.get("height", 0)
|
||||
else:
|
||||
x = face.get("x", 0)
|
||||
y = face.get("y", 0)
|
||||
width = face.get("width", 0)
|
||||
height = face.get("height", 0)
|
||||
```
|
||||
|
||||
### 方案 2: 修復 update_trace_ids() 匹配邏輯
|
||||
|
||||
**不依賴 bbox,改用 frame 匹配**:
|
||||
```python
|
||||
# 構建 trace_mapping
|
||||
trace_mapping = {}
|
||||
for trace_id, trace_data in traces.items():
|
||||
start_frame = trace_data["start_frame"]
|
||||
end_frame = trace_data["end_frame"]
|
||||
|
||||
# 對於每個 frame,找到該 frame 的所有 faces
|
||||
for frame in range(start_frame, end_frame + 1):
|
||||
if frame not in trace_mapping:
|
||||
trace_mapping[frame] = {}
|
||||
|
||||
# 從 face_traced.json 的 frames 中找到該 frame 的 faces
|
||||
# 根據 face index 匹配
|
||||
```
|
||||
|
||||
### 方案 3: 重新生成 embeddings
|
||||
|
||||
**刪除舊的 Qdrant points,重新生成**:
|
||||
```bash
|
||||
# 1. 刪除該文件的所有 points
|
||||
curl -X POST -H "api-key: Test3200Test3200Test3200" \
|
||||
"http://127.0.0.1:6333/collections/_faces/points/delete" \
|
||||
-d '{"filter": {"must": [{"key": "file_uuid", "match": {"value": "b496a68800f90770aa7246c877f38985"}}]}}'
|
||||
|
||||
# 2. 重新運行 store_face_embeddings_to_qdrant.py
|
||||
python3 scripts/store_face_embeddings_to_qdrant.py --file-uuid b496a68800f90770aa7246c877f38985
|
||||
|
||||
# 3. 重新運行 store_traced_faces.py
|
||||
python3 scripts/store_traced_faces.py --file-uuid b496a68800f90770aa7246c877f38985 --uuid b496a68800f90770aa7246c877f38985
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 當前狀態
|
||||
|
||||
### 已修復 ✅
|
||||
1. ✅ face_tracker.py 支持 list 格式
|
||||
2. ✅ update_trace_ids() 支持兩種 bbox 格式
|
||||
|
||||
### 待修復 ❌
|
||||
1. ❌ store_face_embeddings_to_qdrant.py bbox 存儲
|
||||
2. ❌ 重新生成 020.mp4 的 embeddings
|
||||
3. ❌ 更新 Qdrant trace_id
|
||||
|
||||
---
|
||||
|
||||
## 下一步
|
||||
|
||||
### 立即執行
|
||||
1. ✅ 檢查 face.json 的實際結構
|
||||
2. ✅ 修復 store_face_embeddings_to_qdrant.py
|
||||
3. ✅ 重新生成 embeddings
|
||||
4. ✅ 驗證 trace_id 更新
|
||||
|
||||
### 長期改進
|
||||
1. 統一 bbox 存儲格式
|
||||
2. 添加更多的調試日誌
|
||||
3. 添加單元測試
|
||||
|
||||
---
|
||||
|
||||
**分析完成時間**: 2026-09-27 01:20:00 UTC
|
||||
@@ -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());
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user