{"slug": "comparing-3-face-recognition-approaches-in-python-eigenfaces-pca-lbph-and", "title": "Comparing 3 Face Recognition Approaches in Python: Eigenfaces (PCA), LBPH, and DeepFace", "summary": "A developer implemented and compared three Python face recognition approaches — Eigenfaces (PCA), LBPH, and DeepFace — on a small sample dataset, testing each against a simulated 50% brightness reduction to gauge robustness to illumination changes. The writeup includes runnable code, notes that standard opencv-python lacks the cv2.face module required for Eigenfaces and LBPH (fixed by installing opencv-contrib-python), and offers a Google Colab variant that pulls real faces from Scikit-Learn's LFW dataset.", "body_md": "Face recognition has evolved significantly—from classical statistical methods like **Eigenfaces (PCA)** and texture-based descriptors like **LBPH (Local Binary Pattern Histograms)** to modern deep learning frameworks like **DeepFace**.\n\nIn this post, we will implement and compare all three approaches on a small dataset in Python, test how they hold up against **illumination changes** (e.g., low lighting), and look at how to run the code effortlessly without running into environment issues.\n\n**Eigenfaces (PCA-based Representation)**\n\n**LBPH (Local Binary Pattern Histograms)**\n\n**DeepFace (Deep Learning-based Recognition)**\n\n`ModuleNotFoundError: No module named 'cv2'`\nA common mistake when running this code is executing it inside lightweight online compilers (like Programiz or OnlineGDB), which results in:\n\n```\nTraceback (most recent call last):\n  File \"/box/main.py\", line 1, in <module>\n    import cv2\nModuleNotFoundError: No module named 'cv2'\n```\n\n`opencv-contrib-python`` opencv-python`. Standard OpenCV does `cv2.face` module needed for Eigenfaces and LBPH!\nRun this in your terminal:\n\n```\npip uninstall opencv-python -y\npip install opencv-contrib-python deepface scikit-learn tf-keras\n```\n\nIf you have 4 sample face images in your project directory (`p1_1.jpg`, `p1_2.jpg` for Person 0, and `p2_1.jpg`, `p2_2.jpg` for Person 1), here is the cleanest implementation:\n\n``` python\nimport cv2\nimport numpy as np\nfrom deepface import DeepFace\n\n# 1. Load and preprocess the small dataset (Resize to 100x100 & Grayscale)\ndef load_img(path):\n    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n    return cv2.resize(img, (100, 100))\n\n# Training data: 2 images of Person 0, 1 image of Person 1\ntrain_imgs = [load_img('p1_1.jpg'), load_img('p1_2.jpg'), load_img('p2_1.jpg')]\nlabels = np.array([0, 0, 1])\n\n# Test data: Another image of Person 1\ntest_img = load_img('p2_2.jpg')\n\n# Simulate illumination change (reduce brightness by 50%)\ndark_test_img = np.clip(test_img * 0.5, 0, 255).astype(np.uint8)\ncv2.imwrite('dark_test.jpg', dark_test_img) # Save for DeepFace\n\n# ---------------------------------------------------------\n# APPROACH 1: Eigenfaces (PCA-based)\n# ---------------------------------------------------------\neigen_model = cv2.face.EigenFaceRecognizer_create()\neigen_model.train(train_imgs, labels)\n\npred_eigen_norm, _ = eigen_model.predict(test_img)\npred_eigen_dark, _ = eigen_model.predict(dark_test_img)\n\n# ---------------------------------------------------------\n# APPROACH 2: LBPH (Local Binary Pattern Histograms)\n# ---------------------------------------------------------\nlbph_model = cv2.face.LBPHFaceRecognizer_create()\nlbph_model.train(train_imgs, labels)\n\npred_lbph_norm, _ = lbph_model.predict(test_img)\npred_lbph_dark, _ = lbph_model.predict(dark_test_img)\n\n# ---------------------------------------------------------\n# APPROACH 3: DeepFace (Deep Learning-based)\n# ---------------------------------------------------------\n# DeepFace compares images directly without explicit training\ndf_norm = DeepFace.verify('p2_1.jpg', 'p2_2.jpg', enforce_detection=False)\ndf_dark = DeepFace.verify('p2_1.jpg', 'dark_test.jpg', enforce_detection=False)\n\n# ---------------------------------------------------------\n# OUTPUT & COMPARISON (Expected Label = 1 / True)\n# ---------------------------------------------------------\nprint(\"--- COMPARISON RESULTS (Target: Person 1) ---\")\nprint(f\"1. Eigenfaces | Normal: {pred_eigen_norm == 1} | Dark: {pred_eigen_dark == 1}\")\nprint(f\"2. LBPH       | Normal: {pred_lbph_norm == 1} | Dark: {pred_lbph_dark == 1}\")\nprint(f\"3. DeepFace   | Normal: {df_norm['verified']} | Dark: {df_dark['verified']}\")\n```\n\nDon't have sample photos handy? Paste this directly into a **Google Colab** cell. It automatically installs the dependencies and fetches real faces from Scikit-Learn's built-in LFW (Labeled Faces in the Wild) dataset:\n\n```\n# Step 1: Install required libraries in Colab\n!pip install -q opencv-contrib-python deepface scikit-learn\n\nimport cv2\nimport numpy as np\nfrom deepface import DeepFace\nfrom sklearn.datasets import fetch_lfw_people\n\n# Step 2: Load a small built-in face dataset (No manual image upload needed)\nlfw = fetch_lfw_people(min_faces_per_person=10, resize=1.0)\nimg_p1_1 = (lfw.images[0] * 255).astype(np.uint8) # Person 0, Image 1\nimg_p1_2 = (lfw.images[1] * 255).astype(np.uint8) # Person 0, Image 2\nimg_p2_1 = (lfw.images[2] * 255).astype(np.uint8) # Person 1, Image 1 (Train)\ntest_img = (lfw.images[3] * 255).astype(np.uint8) # Person 1, Image 2 (Test)\n\n# Resize all to 100x100\ntrain_imgs = [cv2.resize(x, (100, 100)) for x in [img_p1_1, img_p1_2, img_p2_1]]\ntest_img = cv2.resize(test_img, (100, 100))\nlabels = np.array([0, 0, 1])\n\n# Simulate illumination change (50% darker)\ndark_test_img = (test_img * 0.5).astype(np.uint8)\n\n# Save images temporarily for DeepFace (requires RGB/file paths)\ncv2.imwrite('train_p2.jpg', cv2.cvtColor(train_imgs[2], cv2.COLOR_GRAY2BGR))\ncv2.imwrite('test_norm.jpg', cv2.cvtColor(test_img, cv2.COLOR_GRAY2BGR))\ncv2.imwrite('test_dark.jpg', cv2.cvtColor(dark_test_img, cv2.COLOR_GRAY2BGR))\n\n# 1. Eigenfaces (PCA)\neigen = cv2.face.EigenFaceRecognizer_create()\neigen.train(train_imgs, labels)\nprint(\"Eigenfaces (Normal, Dark):\", eigen.predict(test_img)[0], eigen.predict(dark_test_img)[0])\n\n# 2. LBPH\nlbph = cv2.face.LBPHFaceRecognizer_create()\nlbph.train(train_imgs, labels)\nprint(\"LBPH       (Normal, Dark):\", lbph.predict(test_img)[0], lbph.predict(dark_test_img)[0])\n\n# 3. DeepFace\ndf_norm = DeepFace.verify('train_p2.jpg', 'test_norm.jpg', enforce_detection=False)\ndf_dark = DeepFace.verify('train_p2.jpg', 'test_dark.jpg', enforce_detection=False)\nprint(\"DeepFace   (Normal, Dark):\", df_norm['verified'], df_dark['verified'])\n```\n\nHere is how the three approaches stack up across key metrics:\n\n| Evaluation Metric | 1. Eigenfaces (PCA) | 2. LBPH | 3. DeepFace | \n|---|---|---|---|\n| **Accuracy** | Low to Moderate (struggles with pose and lighting variations). | Moderate to High on small, controlled datasets. | **Very High** (Backed by state-of-the-art CNNs). | \n| **Robustness Under Illumination Changes** | **Poor** — Global pixel intensity changes drastically shift PCA eigenvectors. | **Good** — Local pixel thresholding preserves texture patterns even when darkened. | **Excellent** — Pre-trained on millions of faces across diverse lighting conditions. | \n| **Ease of Implementation** | **Medium** — Requires strictly identical image dimensions and grayscale conversion. | **Easy** — Handles varied sizes and uses the straightforward`cv2.face` API. | **Easiest** — Just 1 line of code (`DeepFace.verify()` ) with no training loop needed. | \n\nHappy coding! Feel free to drop any questions in the comments below. 👇", "url": "https://wpnews.pro/news/comparing-3-face-recognition-approaches-in-python-eigenfaces-pca-lbph-and", "canonical_source": "https://dev.to/hrlpavan/comparing-3-face-recognition-approaches-in-python-eigenfaces-pca-lbph-and-deepface-ihj", "published_at": "2026-10-25 16:38:56+00:00", "updated_at": "2026-10-25 16:44:53.080455+00:00", "lang": "en", "topics": ["computer-vision", "machine-learning", "ai-tools", "developer-tools"], "entities": ["OpenCV", "DeepFace", "Scikit-Learn", "Google Colab", "LFW"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/comparing-3-face-recognition-approaches-in-python-eigenfaces-pca-lbph-and", "markdown": "https://wpnews.pro/news/comparing-3-face-recognition-approaches-in-python-eigenfaces-pca-lbph-and.md", "text": "https://wpnews.pro/news/comparing-3-face-recognition-approaches-in-python-eigenfaces-pca-lbph-and.txt", "jsonld": "https://wpnews.pro/news/comparing-3-face-recognition-approaches-in-python-eigenfaces-pca-lbph-and.jsonld"}}