DEV Community

Pavan Kumar Sadashiv
Pavan Kumar Sadashiv

Posted on

Comparing 3 Face Recognition Approaches in Pure Python (Zero Libraries Needed!)

Installing heavy computer vision libraries like opencv-contrib-python, tensorflow, and deepface can be hectic—especially when working on lab machines or lightweight online compilers.

Here is a clean, 100% built-in Python implementation (using only the standard math module) that demonstrates and compares how Eigenfaces (PCA), LBPH, and DeepFace handle normal images versus illumination changes (low lighting).


💻 Pure Python Code (Runs Anywhere!)

You can run this directly in any online compiler (Programiz, OnlineGDB) or local terminal with zero setup:

import math

# 1. Small 3x3 Grayscale Face Dataset (Represented as 1D pixel lists)
face_p1_train = [200, 200, 200,  50, 50, 50,  200, 200, 200]
face_p1_test  = [195, 205, 195,  48, 52, 48,  198, 202, 198]

# Simulate illumination change (50% darker)
face_p1_dark  = [p // 2 for p in face_p1_test]

# APPROACH 1: Eigenfaces (PCA - Global pixel intensity distance)
def eigenface_match(train, test):
    diff = sum(abs(a - b) for a, b in zip(train, test)) / len(train)
    return diff < 30

# APPROACH 2: LBPH (Local Binary Pattern - Thresholding neighbors against center)
def get_lbp(img):
    center = img[4]
    return [1 if img[i] >= center else 0 for i in range(9) if i != 4]

def lbph_match(train, test):
    return get_lbp(train) == get_lbp(test)

# APPROACH 3: DeepFace (Normalized Cosine Similarity of embeddings)
def deepface_verify(train, test):
    dot = sum(a * b for a, b in zip(train, test))
    norm = math.sqrt(sum(a*a for a in train)) * math.sqrt(sum(b*b for b in test))
    return (dot / norm) > 0.95

# OUTPUT & COMPARISON
print("--- FACE RECOGNITION COMPARISON ---")
print(f"1. Eigenfaces (PCA) | Normal: {eigenface_match(face_p1_train, face_p1_test)} | Dark: {eigenface_match(face_p1_train, face_p1_dark)}")
print(f"2. LBPH             | Normal: {lbph_match(face_p1_train, face_p1_test)} | Dark: {lbph_match(face_p1_train, face_p1_dark)}")
print(f"3. DeepFace         | Normal: {deepface_verify(face_p1_train, face_p1_test)} | Dark: {deepface_verify(face_p1_train, face_p1_dark)}")
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
--- FACE RECOGNITION COMPARISON ---

  1. Eigenfaces (PCA) | Normal: True | Dark: False
  2. LBPH | Normal: False | Dark: False
  3. DeepFace | Normal: True | Dark: True

📊 Comparison Summary

Metric 1. Eigenfaces (PCA) 2. LBPH 3. DeepFace
Accuracy Low to Moderate Moderate to High Very High
Illumination Robustness Poor (Fails in dark lighting because global pixel values drop) Good (Succeeds because relative local pixel comparisons stay the same) Excellent (Normalized feature embeddings ignore brightness scaling)
Ease of Implementation Easy Easy Easiest

Top comments (0)