fix: face cluster over-merge — merge_small_clusters 遵守同幀約束
Cross-Project Integration / integration (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
根因 (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)
This commit is contained in:
@@ -578,94 +578,73 @@ fn apply_cooccurrence_constraints(
|
||||
fn merge_small_clusters(
|
||||
trace_to_person: std::collections::BTreeMap<i64, i64>,
|
||||
trace_embeddings: &std::collections::BTreeMap<i64, Vec<f64>>,
|
||||
trace_similarities: &std::collections::BTreeMap<i64, f64>,
|
||||
min_large_cluster_size: usize,
|
||||
_trace_similarities: &std::collections::BTreeMap<i64, f64>,
|
||||
_min_large_cluster_size: usize,
|
||||
merge_similarity_threshold: f64,
|
||||
cooccurrence: &std::collections::HashSet<(i64, i64)>,
|
||||
) -> std::collections::BTreeMap<i64, i64> {
|
||||
let mut trace_to_person = trace_to_person;
|
||||
|
||||
// Count traces per person
|
||||
let mut person_trace_count: std::collections::HashMap<i64, usize> = 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<i64> = std::collections::HashSet::new();
|
||||
let mut small_clusters: std::collections::HashSet<i64> = 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<i64, Vec<i64>> = 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<i64, Vec<f64>> = 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<i64> = 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<i64, Vec<f64>> = std::collections::BTreeMap::new();
|
||||
for (pid, tids) in &cur_traces {
|
||||
let mut mean: Option<Vec<f64>> = 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<i64> = 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<i64> = trace_to_person.values().copied().collect();
|
||||
let pid_map: std::collections::HashMap<i64, i64> = 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::<std::collections::HashSet<_>>().len();
|
||||
|
||||
Reference in New Issue
Block a user