Face Clustering From Pixels To People
On this page47
A from-scratch visual tutorial on face detection, landmarks, alignment, embeddings, thresholds, clustering, prototypes, and human review, backed by an actual ClusterLens run.
Article details
- Status
- Building Publicly
- Subcategory
- ClusterLens
- Last reviewed
- 2 Sept 2026
- Prerequisites
- No computer-vision, machine-learning, or clustering knowledge required
Put photographs of the same person together.
1. Five face problems that are often confused
| Task | Question | Output |
|---|---|---|
| Detection | Is there a face, and where? | rectangle, confidence, landmarks |
| Verification | Are these two faces the same identity? | similarity plus a threshold decision |
| Search | Which indexed faces resemble this query? | ranked candidates |
| Clustering | Which faces seem to belong together without names? | unlabeled groups and outliers |
| Identification | Which known identity best matches this face? | a proposed name or unknown |
Never choose a model or metric until the question has been made precise.
The gallery changes the meaning of the task
2. A photograph begins as pixels, not a person
Decoded RGB image
Each location contains red, green, and blue values. None is explicitly labelled eye, nose, face, or identity.

Nearby coloured squares are numbers, not semantic labels. A detector must learn recurring spatial patterns from many examples.
How does a detector learn visual structure from numbers?
One convolution location
The same filter weights are reused at every location. That weight sharing lets one learned pattern be detected anywhere in the image.
3. Detection: finding a face before describing it
One detection
The rectangle runs from top-left (x₁,y₁) to bottom-right (x₂,y₂), c is detector confidence, and L contains landmarks.
How face detectors evolved
Viola–Jones: reject empty windows cheaply
Integral image
Once cumulative sums exist, a large rectangle is no more expensive to sum than a small one.
HOG: count edge directions
MTCNN: coarse proposals, then refinement
RetinaFace: dense multi-scale predictions
YuNet: tiny CPU-friendly detection
SCRFD: redistribute samples and computation
4. Bounding boxes, area, clipping, and why tiny faces are hard
Bounding-box geometry
A box touching the image edge may be clipped; a tiny box contains little identity information after resizing.
Feature pyramids: let different resolutions specialize
Intersection over union
IoU is 0 for disjoint boxes and 1 for identical boxes. Strongly overlapping proposals can be reduced to the more confident one.
Intersection over union: .
5. Five landmarks: a small geometric description
left eye (417.7, 402.4) right eye (605.4, 400.5)
nose (516.5, 519.3)
left mouth (429.1, 616.7) right mouth (588.8, 617.0)
Select detections in the previous panel; this ledger follows the same evidence record.
6. Alignment: give the embedder the same coordinate system
Two-dimensional affine transform
The coefficients can rotate, scale, shear, and translate. Pixels are then resampled into the canonical crop.
The score measures how much the representation changed. It is not an alignment-quality probability.
7. The complete image tensor ledger
- JPEG bytes
variable length - decoded RGB
1024×1024×3 uint8 - detected crop
box-dependent H×W×3 - aligned crop
112×112×3 - model tensor
1×3×112×112 float32 - raw model output
1×128 float32 - normalized embedding
128 numbers, norm = 1
Preprocessing is part of the model
Two different preprocessing recipes
Both values are valid floats. Only the training recipe tells us which one the network learned to interpret.
8. What a face embedding actually is
Face encoder
The network compresses 37,632 RGB channel values into 128 coordinates useful for distinguishing identities in its training objective.
Colour is the known synthetic identity and is used only to evaluate the experiment. Hover or tap a dot to inspect it.
Choose a pointWhat happens inside the encoder?
112 × 112 × 3
height × width × colour channels
becomes, conceptually,
56 × 56 × 64
height × width × learned feature channels
1. A convolution does not search for a whole face
One convolution output
The filter uses a local patch across every input channel. Training learns W and b. The output location h,w and output channel c identify one resulting activation.
2. Downsampling trades position for context
Receptive-field growth
r is receptive-field size, k is kernel size, s is stride, and j is the spacing in input pixels between neighbouring activations. A theoretical field says what can influence a unit; actual learned influence is usually concentrated unevenly inside it.
3. Residual blocks help a deep model remain trainable
Residual block
If the useful change F is small, the shortcut preserves an easier information path. It also gives gradients shorter routes during training.
4. Global pooling turns maps into a list
Global average pooling for channel c
One H×W map becomes one number. Applying the same operation to C channels produces a C-value vector.
No cells have been pooled yet.
5. Projection and normalization finish the descriptor
Final projection
This is still learned: changing one pooled channel can affect many embedding coordinates. Some architectures add normalization layers or a training head around this projection.
9. How a model learns identity-shaped geometry
Maya / studio light
Maya / side light
Maya / tilted pose
Daniel / studio light
Daniel / padded crop
Serena / studio light
Serena / smiling
The training loop, one causal step at a time
One parameter update
L is the batch loss, ∂L/∂w is the gradient describing local sensitivity, and η is the learning rate. A real optimizer updates millions of parameters and may use momentum or adaptive statistics.
Before deep embeddings: Eigenfaces and local texture
Classification training
Classification loss
The classifier weights can be interpreted as training identity directions. Deployment keeps the encoder and discards the fixed list of training names.
Maya 2.2
Daniel 1.9
Serena −0.3
Crossing a decision boundary is enough to be correct, but it may not be enough to create a reusable verification space with a safety gap.
FaceNet and triplet loss
Triplet objective
The negative should be farther than the positive by margin α. Hard examples supply useful pressure; already-separated examples contribute little.
ArcFace and angular margin
Normalized class logit
A smaller angle means the sample points more directly toward class j. A scale s is applied because cosine values alone occupy a small numerical range for softmax.
Simplified ArcFace target logit
s controls logit scale; m is the additive angular margin for the correct class.
Why there are so many margin losses
Softmax
Is the correct training identity on the winning side?
Metric learning
Are same-identity samples closer than different-identity samples?
Angular margins
Does the winning identity have geometric clearance?
Robust objectives
Should every low-loss, hard, or suspicious example push equally?
Quality-aware objectives
Should a blurred crop receive the same geometric demand as a clean crop?
Curriculum and sampled classifiers
How can hard examples and millions of classes be trained efficiently?
Problem 1: ordinary softmax allows a narrow victory
Angular softmax logit
The sample wins class j when its angle to that class direction is sufficiently smaller than its angles to competing directions. The common scale s changes softmax sharpness, not the angle ordering.
Problem 2: where should the extra clearance be measured?
Three margin locations
Only the correct-class logit is modified. SphereFace multiplies the angle, CosFace subtracts in cosine space, and ArcFace adds in angle space. Their hyperparameter values are not numerically interchangeable.
The loss temporarily makes the correct answer harder during training so the unmodified embedding has more clearance during inference.
SphereFace: multiply the target angle
CosFace: subtract in cosine space
ArcFace: add in angle space
Why not choose an enormous margin?
Problem 3: not every gradient deserves equal trust
Problem 4: image quality changes what is achievable
embedding direction
→ identity comparison
raw embedding magnitude
→ learned recognizability signal
Problem 5: what counts as useful difficulty changes during training
The sample position and pressure bars summarize one motivation. They are not measured performance rankings between the methods.
What failure dominates my data?
insufficient angular clearance?
bad triplet sampling?
label noise?
poor-quality evidence?
hard-negative scheduling?
classifier scale?
Training scale and Partial FC
10. Normalization and cosine similarity
Unit-length embedding
After normalization, every embedding lies on a unit hypersphere.
Cosine similarity
1 means the same direction, 0 means perpendicular, and −1 means opposite. It is a geometric score—not a probability of identity.
cos(°) = .
Cosine–Euclidean relationship on the unit sphere
If cosine is 0.98, squared Euclidean distance is 0.04. This equivalence disappears when vectors are not normalized.
11. The pairwise similarity matrix: where clustering begins
Similarity matrix
Rows of E are normalized face embeddings. The diagonal is 1 because every face is identical to itself.

12. A threshold turns a score into a decision
Pair decision
Raising t rejects more impostors but can reject more genuine pairs. Lowering t accepts more genuine pairs but can merge different identities.
| Reality | Decision accepts | Decision rejects |
|---|---|---|
| Same identity | true accept | false reject |
| Different identity | false accept | true reject |
FAR is not “the chance this match is wrong”
impostor comparisons give an approximate probability of at least one false match of .
13. Quality gates protect the representation stage
Perceptual quality is not recognition utility
14. Storing derived face records locally
| Field | Why it exists |
|---|---|
| image path + face index | stable local reference to one face in a photo |
| bounding box + detector confidence | reproduce and inspect detection |
| embedding blob + dimension | compare representations |
| quality status and metrics | filter or review questionable crops |
| hidden/tiny flags | product-level visibility policy |
file mtime + size | invalidate stale derived data |
mtime=100 · 1 faceStorage, indexes, and model versions are separate layers
15. Clustering from scratch
Cosine K-Means
K-Means objective
The algorithm minimizes within-cluster squared distance. It must be told K and tends to prefer compact groups.
HDBSCAN
Mutual-reachability distance
Sparse points cannot form cheap bridges based on one ordinary pairwise distance that happens to be small.
Threshold graph
16. The actual backend comparison—and a useful failure
Silhouette coefficient
Values near 1 indicate separation, around 0 indicate a boundary, and below 0 suggest the point may fit another cluster better.
17. What should happen to outliers?
| Policy | Behaviour | Risk |
|---|---|---|
| Assign | attach outlier to nearest acceptable group | can contaminate a person’s group |
| Isolate | make a singleton group | creates clutter but preserves uncertainty |
| Keep | retain backend noise status | requires UI support for unresolved items |
18. Identity prototypes: summarize several examples
Identity prototype
A prototype represents the central direction of accepted examples. It is not a photograph and cannot express every variation of a person's appearance.
One centroid may not describe a person
Quality-weighted template
High-utility frames contribute more, while many blurred frames should not overwhelm one clear frame through quantity alone.
19. A suggestion is not an identity
Cluster support requirement
A singleton needs one supporting match; larger groups require at least two and roughly half the members.
Required support: . Decision: .
The unknown decision needs two checks
Two-part open-set rule
s₁ is the best prototype score and s₂ is the runner-up. The second condition catches ambiguous near-ties.
20. Pending labels, rejection memory, and undo
21. Failure modes: diagnose the stage, not just the result
22. Privacy, fairness, and scope
Presentation attacks and synthetic media are separate problems
23. What “state of the art” means in 2026
| Direction | What it tries to improve | Why it is not a drop-in answer |
|---|---|---|
| Efficient multi-scale detectors | small/occluded faces per unit compute | hardware and crowd density change the trade-off |
| Quality-aware losses | reduce damage from unrecognizable or noisy samples | feature norm and margins are model-specific |
| Transformer backbones | richer global and patch interactions | require specialized augmentation, mining, and large data |
| Large-scale classifiers / Partial FC | train on millions of identities | solves training infrastructure, not local inference policy |
| Recognizability and FIQA | decide when not to compare | a quality model itself needs domain validation |
| Set/video templates | combine several observations | tracking switches and correlated frames can contaminate templates |
| Foundation-model studies | test whether general representations transfer | domain-specific face models often remain stronger and easier to calibrate |
| Harder evaluation sets | expose saturation on classic benchmarks | leaderboard order can change across capture conditions |
24. Complete actual run: one face through the whole system
12 / 12 faces detected and quality-gated cleanly
128-dimensional normalized embeddings
same-identity aligned cosine mean 0.991241
different-identity cosine mean 0.954315
best tiny-set threshold 0.98 (4 false accepts, 1 false reject)
K-Means / HDBSCAN 3 groups + 1 outlier, ARI 0.879121
threshold graph 1 mixed group + 1 outlier, ARI 0.0
A face-clustering system is not one recognizer. It is a sequence of lossy representations, thresholds, grouping assumptions, persistent state, and human decisions. Correctness comes from making every boundary visible—and making uncertainty reviewable.
Evidence card
- Schema
- Generated
- Dataset
- 12 metadata-free, generated portraits; 3 fictional identities × 4 controlled views
- Models
- Official OpenCV YuNet 2026 May detector and SFace 2021 December embedder, CPU
- Environment
- Python · OpenCV · ONNX Runtime
- Scope limit
- Educational systems experiment; not demographic validation, deployment calibration, or identity ground truth
Primary references
- OpenCV Zoo: YuNet face detection
- OpenCV Zoo: SFace face recognition
- Viola and Jones: Robust Real-Time Face Detection
- Dalal and Triggs: Histograms of Oriented Gradients
- MTCNN: Joint Face Detection and Alignment
- RetinaFace: Single-Shot Multi-Level Face Localisation
- SCRFD: Sample and Computation Redistribution
- YuNet: A Tiny Millisecond-Level Face Detector
- FaceNet: A Unified Embedding for Face Recognition and Clustering
- ArcFace: Additive Angular Margin Loss for Deep Face Recognition
- SFace: Sigmoid-Constrained Hypersphere Loss
- MagFace: Recognition and Quality Assessment
- AdaFace: Quality Adaptive Margin
- TransFace: Transformer Training for Face Recognition
- DSL-FIQA: Landmark-Guided Face Image Quality
- Recognizability Embedding for Unrecognizable Faces
- FRoundation: Are Foundation Models Ready for Face Recognition?
- Goldilocks Test Sets for Face Verification
- HDBSCAN: Hierarchical density based clustering
- NIST Face Recognition Technology Evaluation: Demographic Effects