From 2f15cb639cf04fa8c69cf9ea5bc50cf917201554 Mon Sep 17 00:00:00 2001 From: Accusys Date: Thu, 19 Nov 2026 23:23:47 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20face=20cluster=20over-merge=20=E2=80=94?= =?UTF-8?q?=20merge=5Fsmall=5Fclusters=20=E9=81=B5=E5=AE=88=E5=90=8C?= =?UTF-8?q?=E5=B9=80=E7=B4=84=E6=9D=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因 (bd9ebfc): - 影片實際 2 人(戴眼鏡男性 16 trace + 年輕女性 5 trace) - seed-leader clustering 用 0.65 閾值把所有人合成 1-2 群 - apply_cooccurrence_constraints 正確拆出同幀女性 trace([SPLIT]) - 但 merge_small_clusters 用單純 embedding similarity (0.7) 又把拆出的 女性 trace 合回男性群(女性小脸 90x90 embedding 不準,sim 高達 0.98) - 結果: frame 3 的男性 t2 和女性 t3 被標同一 Person_1 → over-merge 修復: - merge_small_clusters 加入 cooccurrence_constraints 參數 - 改為迭代式合併:每輪重新計算 centroid,選最相似且無同幀衝突的群對合併 - 合併前檢查兩群的 trace 是否有 co-occurrence(同幀 bbox 不重疊)衝突, 有則拒絕合併([KEEP]) 驗證: bd9ebfc re-run → frame 3 男性 t2=Person_1, 女性 t3=Person_7, 不同人不再合併;clusters 2→3(過度分割可接受,優於 over-merge) --- tools/cli/rust/src/bin/rust_face_cluster.rs | 140 +++++++++----------- 1 file changed, 60 insertions(+), 80 deletions(-) diff --git a/tools/cli/rust/src/bin/rust_face_cluster.rs b/tools/cli/rust/src/bin/rust_face_cluster.rs index e251fd48..74568503 100644 --- a/tools/cli/rust/src/bin/rust_face_cluster.rs +++ b/tools/cli/rust/src/bin/rust_face_cluster.rs @@ -578,94 +578,73 @@ fn apply_cooccurrence_constraints( fn merge_small_clusters( trace_to_person: std::collections::BTreeMap, trace_embeddings: &std::collections::BTreeMap>, - trace_similarities: &std::collections::BTreeMap, - min_large_cluster_size: usize, + _trace_similarities: &std::collections::BTreeMap, + _min_large_cluster_size: usize, merge_similarity_threshold: f64, + cooccurrence: &std::collections::HashSet<(i64, i64)>, ) -> std::collections::BTreeMap { let mut trace_to_person = trace_to_person; - - // Count traces per person - let mut person_trace_count: std::collections::HashMap = std::collections::HashMap::new(); - for (_, pid) in &trace_to_person { - *person_trace_count.entry(*pid).or_insert(0) += 1; - } - - // Identify large clusters (seeds) and small clusters - let mut large_clusters: std::collections::HashSet = std::collections::HashSet::new(); - let mut small_clusters: std::collections::HashSet = std::collections::HashSet::new(); - - for (pid, count) in &person_trace_count { - if *count >= min_large_cluster_size { - large_clusters.insert(*pid); - } else { - small_clusters.insert(*pid); + let merge_sim = merge_similarity_threshold; + + // Iteratively merge the most-similar compatible pair until no merge is + // possible. Recompute centroids each round so chained merges use fresh data. + // Co-occurrence constraint prevents merging traces that appeared together + // in a frame (different physical people). + loop { + let mut cur_traces: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (tid, pid) in &trace_to_person { + cur_traces.entry(*pid).or_default().push(*tid); } - } - - if small_clusters.is_empty() || large_clusters.is_empty() { - return trace_to_person; - } - - eprintln!("[MERGE] Large clusters: {:?}, Small clusters: {:?}", large_clusters, small_clusters); - - // Compute mean embedding for each person - let mut person_embeddings: std::collections::HashMap> = std::collections::HashMap::new(); - for (tid, pid) in &trace_to_person { - if let Some(emb) = trace_embeddings.get(tid) { - person_embeddings.entry(*pid).or_insert_with(|| vec![0.0; emb.len()]); - let pe = person_embeddings.get_mut(pid).unwrap(); - for (i, &v) in emb.iter().enumerate() { - pe[i] += v; - } - } - } - // Normalize - for (pid, traces) in &person_trace_count { - if let Some(pe) = person_embeddings.get_mut(pid) { - let count = *traces as f64; - for v in pe.iter_mut() { - *v /= count; - } - } - } - - // Merge each small cluster into most similar large cluster - for small_pid in small_clusters { - let mut best_sim = -1.0; - let mut best_large_pid: Option = None; - - for large_pid in &large_clusters { - if let (Some(emb_small), Some(emb_large)) = (person_embeddings.get(&small_pid), person_embeddings.get(large_pid)) { - let sim = cosine_similarity(emb_small, emb_large); - if sim > best_sim { - best_sim = sim; - best_large_pid = Some(*large_pid); - } - } - } - - if let Some(target_pid) = best_large_pid { - if best_sim >= merge_similarity_threshold { - eprintln!(" [MERGE] Person_{} ({} traces) -> Person_{} (sim={:.3})", - small_pid, person_trace_count.get(&small_pid).unwrap_or(&0), target_pid, best_sim); - - // Reassign all traces from small to large - for (tid, pid) in trace_to_person.iter_mut() { - if *pid == small_pid { - *pid = target_pid; + let mut centroids: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (pid, tids) in &cur_traces { + let mut mean: Option> = None; + for tid in tids { + if let Some(e) = trace_embeddings.get(tid) { + if let Some(m) = mean.as_mut() { + for (i, &v) in e.iter().enumerate() { m[i] += v; } + } else { + mean = Some(vec![0.0; e.len()]); + for (i, &v) in e.iter().enumerate() { mean.as_mut().unwrap()[i] += v; } } } - } else { - eprintln!(" [SKIP] Person_{} not similar enough to any large cluster (best sim={:.3})", small_pid, best_sim); + } + if let Some(mut m) = mean { + let n = tids.len() as f64; + for v in m.iter_mut() { *v /= n; } + centroids.insert(*pid, m); } } + let pids: Vec = cur_traces.keys().copied().collect(); + let mut best: Option<(f64, i64, i64)> = None; + for (i, &pa) in pids.iter().enumerate() { + for &pb in pids.iter().skip(i + 1) { + let (ea, eb) = match (centroids.get(&pa), centroids.get(&pb)) { + (Some(a), Some(b)) => (a, b), + _ => continue, + }; + let sim = cosine_similarity(ea, eb); + if sim < merge_sim { continue; } + let conflict = cur_traces[&pa].iter().any(|a| { + cur_traces[&pb].iter().any(|b| { + cooccurrence.contains(&((*a).min(*b), (*a).max(*b))) + }) + }); + if !conflict && best.map_or(true, |(bs, _, _)| sim > bs) { + best = Some((sim, pa, pb)); + } + } + } + match best { + Some((sim, from, to)) => { + eprintln!(" [MERGE] Person_{} ({} traces) -> Person_{} (sim={:.3})", + from, cur_traces[&from].len(), to, sim); + for (tid, pid) in trace_to_person.iter_mut() { + if *pid == from { *pid = to; } + } + } + None => break, + } } - - // Re-index person IDs - let unique_pids: std::collections::BTreeSet = trace_to_person.values().copied().collect(); - let pid_map: std::collections::HashMap = unique_pids.into_iter().enumerate().map(|(new, old)| (old, new as i64)).collect(); - trace_to_person = trace_to_person.into_iter().map(|(tid, pid)| (tid, *pid_map.get(&pid).unwrap())).collect(); - trace_to_person } @@ -844,7 +823,8 @@ fn main() { &trace_embeddings, &trace_similarities, 5, // min traces to be considered a "large" cluster - 0.7 // similarity threshold for merging + 0.7, // similarity threshold for merging + &cooccurrence_constraints, // never merge same-frame (different-person) traces ); let n_persons: usize = trace_to_person.values().collect::>().len();