#!/usr/bin/env python3 """ Test facenet-pytorch for face clustering """ import os import sys import json import cv2 import numpy as np from pathlib import Path from collections import defaultdict try: from facenet_pytorch import InceptionResnetV1 import torch except ImportError: print("❌ facenet-pytorch or torch not found") sys.exit(1) def test_facenet_pytorch_clustering(video_path: str, face_json_path: str): """Test facenet-pytorch clustering""" print(f"[TEST] facenet-pytorch Clustering") print(f" Video: {video_path}") print(f" Face JSON: {face_json_path}") # Load model print("\n[MODEL] Loading InceptionResnetV1...") device = torch.device('mps' if torch.backends.mps.is_available() else 'cpu') print(f" Device: {device}") model = InceptionResnetV1(pretrained='vggface2').eval().to(device) print(f" ✅ Model loaded") # Load face.json with open(face_json_path) as f: face_data = json.load(f) print(f"\n[INFO] Loaded {len(face_data['frames'])} frames") # Open video cap = cv2.VideoCapture(video_path) if not cap.isOpened(): print(f"[ERROR] Cannot open video") return fps = cap.get(cv2.CAP_PROP_FPS) total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) print(f"[INFO] Video: {total_frames} frames, {fps} fps") # Extract embeddings for trace_id trace_embeddings = defaultdict(list) for frame_data in face_data['frames']: frame_idx = frame_data['frame'] faces = frame_data.get('faces', []) # Read frame cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx) ret, frame = cap.read() if not ret: continue for face in faces: trace_id = face.get('trace_id') if trace_id is None: continue # Get bbox x, y, w, h = face['x'], face['y'], face['width'], face['height'] # Add margin margin = 5 crop = frame[ max(0, y - margin) : y + h + margin, max(0, x - margin) : x + w + margin ] if crop.size == 0: continue # Preprocess for facenet-pytorch # Resize to 160x160 crop_resized = cv2.resize(crop, (160, 160)) # Convert BGR to RGB crop_rgb = cv2.cvtColor(crop_resized, cv2.COLOR_BGR2RGB) # Normalize to [-1, 1] crop_norm = (crop_rgb.astype(np.float32) / 127.5) - 1.0 # Convert to tensor: (160, 160, 3) -> (1, 3, 160, 160) crop_tensor = torch.from_numpy(crop_norm).permute(2, 0, 1).unsqueeze(0).to(device) # Extract embedding with torch.no_grad(): embedding = model(crop_tensor).cpu().numpy().flatten() trace_embeddings[trace_id].append(embedding) cap.release() print(f"\n[INFO] Extracted embeddings for {len(trace_embeddings)} traces") for tid, embs in sorted(trace_embeddings.items()): print(f" Trace {tid}: {len(embs)} embeddings") # Average embeddings per trace trace_avg_emb = {} for tid, embs in trace_embeddings.items(): if len(embs) > 0: avg_emb = np.mean(embs, axis=0) trace_avg_emb[tid] = avg_emb print(f"\n[INFO] Averaged embeddings for {len(trace_avg_emb)} traces") # Calculate pairwise distances print(f"\n[DISTANCES] Pairwise cosine distances:") trace_ids = sorted(trace_avg_emb.keys()) from scipy.spatial.distance import cosine distance_matrix = np.zeros((len(trace_ids), len(trace_ids))) for i, tid1 in enumerate(trace_ids): for j, tid2 in enumerate(trace_ids): if i == j: distance_matrix[i][j] = 0.0 else: dist = cosine(trace_avg_emb[tid1], trace_avg_emb[tid2]) distance_matrix[i][j] = dist # Print distance matrix print("\nDistance Matrix (showing distances < 0.15):") print(f"{'':>8}", end='') for tid in trace_ids: print(f"{f'FS#{tid}':>10}", end='') print() for i, tid1 in enumerate(trace_ids): print(f"{'FS#' + str(tid1):>8}", end='') for j, tid2 in enumerate(trace_ids): dist = distance_matrix[i][j] if i == j: print(f"{'---':>10}", end='') elif dist < 0.15: print(f"{dist:>10.4f}", end='') else: print(f"{'':>10}", end='') print() # Find close pairs print(f"\n[CLOSE PAIRS] Distance < 0.15:") close_pairs = [] for i, tid1 in enumerate(trace_ids): for j, tid2 in enumerate(trace_ids): if i < j and distance_matrix[i][j] < 0.15: close_pairs.append((tid1, tid2, distance_matrix[i][j])) if close_pairs: for tid1, tid2, dist in sorted(close_pairs, key=lambda x: x[2]): print(f" FS#{tid1} - FS#{tid2}: {dist:.4f}") else: print(" None found") # Clustering (使用 metric 参数而不是 affinity) from sklearn.cluster import AgglomerativeClustering clustering = AgglomerativeClustering( n_clusters=None, distance_threshold=0.15, metric='cosine', # 使用 metric 而不是 affinity linkage='average' ) embeddings = np.array([trace_avg_emb[tid] for tid in trace_ids]) labels = clustering.fit_predict(embeddings) print(f"\n[CLUSTERS] Threshold = 0.15:") clusters = defaultdict(list) for tid, label in zip(trace_ids, labels): clusters[label].append(tid) for label in sorted(clusters.keys()): members = clusters[label] print(f" Cluster {label}: {[f'FS#{t}' for t in sorted(members)]}") print(f"\n[RESULT] {len(clusters)} clusters found") # Compare with expected groups print(f"\n[EXPECTED GROUPS]:") print(f" Group 1: FS#0, 1, 3, 5, 7, 9, 12, 14") print(f" Group 2: FS#2, 4, 6, 8, 10, 13, 15") print(f" Group 3: FS#11 (hand, misdetection)") # Check accuracy print(f"\n[ACCURACY CHECK]:") group1 = {0, 1, 3, 5, 7, 9, 12, 14} group2 = {2, 4, 6, 8, 10, 13, 15} for label, members in clusters.items(): member_set = set(members) if member_set == group1: print(f" ✅ Cluster {label} matches Group 1") elif member_set == group2: print(f" ✅ Cluster {label} matches Group 2") elif len(members) == 1 and 11 in members: print(f" ✅ Cluster {label} matches Group 3 (FS#11)") else: print(f" ❓ Cluster {label}: {member_set}") if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python test_facenet_pytorch.py ") sys.exit(1) test_facenet_pytorch_clustering(sys.argv[1], sys.argv[2])