Person Recognition with PCA & Cosine Similarity

๐Ÿ“Œ Introduction

Person recognition is a core task in biometrics and computer vision. This article explores an efficient approach using Principal Component Analysis (PCA) to reduce feature dimensions and Cosine Similarity to compare identity vectors.

๐Ÿ”ข Mathematical Concepts

Principal Component Analysis (PCA) is used to project high-dimensional face images into a lower-dimensional subspace that retains the most variance.

Z = XW

Where:

  • X = mean-centered data matrix
  • W = eigenvectors (principal components)
  • Z = projected data (face embeddings)

Cosine Similarity compares two face vectors A and B:

Cos(ฮธ) = (A ยท B) / (||A|| ร— ||B||)

๐Ÿง  Algorithm Steps

  1. Preprocess all face images (resize, grayscale, flatten).
  2. Apply PCA to reduce dimensionality of image vectors.
  3. Store PCA-projected embeddings for known persons.
  4. Project a test face image using same PCA transformation.
  5. Compare test vector to known embeddings using Cosine Similarity.
  6. Return the identity with the highest similarity score.

๐Ÿ’ป Python Code

import cv2
import numpy as np
from sklearn.decomposition import PCA
from sklearn.metrics.pairwise import cosine_similarity

# Load face data
X = []  # known face vectors
labels = []

for i in range(1, 6):
    img = cv2.imread(f"person{i}.jpg", cv2.IMREAD_GRAYSCALE)
    img = cv2.resize(img, (100, 100)).flatten()
    X.append(img)
    labels.append(f"Person {i}")

X = np.array(X)

# Apply PCA
pca = PCA(n_components=50)
X_pca = pca.fit_transform(X)

# Test image
test_img = cv2.imread("unknown.jpg", cv2.IMREAD_GRAYSCALE)
test_img = cv2.resize(test_img, (100, 100)).flatten()
test_pca = pca.transform([test_img])

# Compare using cosine similarity
similarities = cosine_similarity(test_pca, X_pca)[0]
best_match = labels[np.argmax(similarities)]

print("Identified as:", best_match)

๐Ÿ“Š Applications

  • Face-based access control systems
  • Biometric authentication in devices
  • Attendance systems in schools and offices

โœ… Conclusion

PCA reduces computation by projecting faces into a compact vector space, and cosine similarity enables quick and accurate identity matching. This method is lightweight, interpretable, and performs well on small to mid-scale datasets.

Authored by Amitesh Maurya | ยฉ 2025 Amitesh Maurya