e0d04e242f
- Add Rust face processor module (detection, embedding, tracking, qdrant) - Add Facenet CoreML/ONNX conversion scripts and tests - Refactor swift_face into Sources/swift_face with ArgumentParser support - Update store_traced_faces to handle face.json correctly - Fix ASRX parsing and TKG bbox reading from Qdrant - Improve admin_config and trace_agent APIs - Add M4 workspace docs for face clustering, dedup, and Facenet validation - Fix worker heartbeat TTL (poll_interval x 3, min 60s) for offline detection
173 lines
5.4 KiB
Python
Executable File
173 lines
5.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Test DeepFace ArcFace for face clustering
|
|
"""
|
|
import os
|
|
import sys
|
|
import json
|
|
import cv2
|
|
import numpy as np
|
|
from pathlib import Path
|
|
from deepface import DeepFace
|
|
from collections import defaultdict
|
|
|
|
def test_deepface_clustering(video_path: str, face_json_path: str):
|
|
"""Test DeepFace ArcFace clustering"""
|
|
print(f"[TEST] DeepFace ArcFace Clustering")
|
|
print(f" Video: {video_path}")
|
|
print(f" Face JSON: {face_json_path}")
|
|
|
|
# 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 (like v1.1)
|
|
margin = 5
|
|
crop = frame[
|
|
max(0, y - margin) : y + h + margin,
|
|
max(0, x - margin) : x + w + margin
|
|
]
|
|
|
|
if crop.size == 0:
|
|
continue
|
|
|
|
# Extract embedding using DeepFace ArcFace
|
|
try:
|
|
result = DeepFace.represent(
|
|
img_path=crop,
|
|
model_name="ArcFace",
|
|
enforce_detection=False
|
|
)
|
|
if result and len(result) > 0:
|
|
embedding = result[0]['embedding']
|
|
trace_embeddings[trace_id].append(embedding)
|
|
except Exception as e:
|
|
print(f"[WARN] DeepFace error at frame {frame_idx}, trace {trace_id}: {e}")
|
|
|
|
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:")
|
|
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='')
|
|
else:
|
|
print(f"{dist:>10.4f}", end='')
|
|
print()
|
|
|
|
# Find close pairs (distance < 0.15)
|
|
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 using AgglomerativeClustering
|
|
from sklearn.cluster import AgglomerativeClustering
|
|
|
|
# Use threshold = 0.15 (distance)
|
|
clustering = AgglomerativeClustering(
|
|
n_clusters=None,
|
|
distance_threshold=0.15,
|
|
affinity='cosine',
|
|
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")
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 3:
|
|
print("Usage: python test_deepface_clustering.py <video_path> <face_json_path>")
|
|
sys.exit(1)
|
|
|
|
test_deepface_clustering(sys.argv[1], sys.argv[2])
|