Skip to main content

A lightweight face recognition module using OpenCV LBPH (Local Binary Patterns Histograms)

Project description

facerecog — Face Recognition Module

Python OpenCV

A lightweight face recognition module based on OpenCV LBPH (Local Binary Patterns Histograms).
Use it via the interactive CLI or embed it directly as a Python API in your own project.


Features

  • Register faces from camera or image files / folders
  • Train the LBPH recognition model
  • Detect & recognize faces real-time from camera or from image files
  • Manage registered users (list, delete)
  • Clean Python API — one class, zero boilerplate
  • Customizable window titles via app_name

Requirements

  • Python 3.10+
  • opencv-contrib-python >= 4.8.0
  • numpy >= 1.24.0

Installation

From PyPI (recommended)

pip install facerecog-lbph

From source

git clone https://github.com/AlulCode45/FaceRecon-Module.git
cd FaceRecon-Module
pip install -r requirements.txt

Important: Use opencv-contrib-python, not opencv-python.
The cv2.face.LBPHFaceRecognizer module is only available in the contrib build.


Project Structure

When you use this module, it will automatically create the following in your working directory:

your-project/
├── facerecog/          ← this repo (if using from source)
│   ├── facerecog/      ← the Python package
│   ├── example.py      ← standalone CLI demo
│   ├── pyproject.toml
│   └── README.md
├── dataset/            ← auto created: face photos per person
├── trainer/            ← auto created: trained model output
└── labels.json         ← auto created: ID → name mapping

Usage — Interactive CLI

Run the built-in CLI demo:

python example.py

Menu:

==============================================
         FACE RECOGNITION SYSTEM
==============================================
  [1]  Register  — Register face via camera
  [2]  Train     — Train the model
  [3]  Detect    — Real-time face detection
  [4]  List      — List registered users
  [5]  Delete    — Delete a user
  [6]  Detect    — Detect face from image
  [7]  Register  — Register face from image
  [0]  Exit
==============================================

Basic flow

[1] or [7] Register  →  [2] Train  →  [3] or [6] Detect

Usage — Python API

from facerecog import FaceRecog

fr = FaceRecog()

Configuration (optional)

fr = FaceRecog(
    threshold=75,                # LBPH confidence: lower = stricter match (default 75)
    max_photos=40,               # photos captured per camera session (default 40)
    camera_index=0,              # camera device index (default 0)
    app_name="My App",           # label in OpenCV window titles (default "Face Recognition")
)

Register Faces

Via camera:

saved = fr.register_from_camera("Alice")
print(f"{saved} photos saved")

Via single image file:

saved = fr.register_from_image("Alice", "/path/to/alice.jpg")

Via folder containing multiple images:

saved = fr.register_from_image("Alice", "/path/to/alice_photos/")

Supported formats: .jpg, .jpeg, .png, .bmp, .webp

Overwrite / append:

# Replace existing data
fr.register_from_image("Alice", "/photos/", overwrite=True)

# Add to existing data (default)
fr.register_from_image("Alice", "/photos/", append=True)

Train the Model

info = fr.train()
print(info)
# {"total_images": 80, "total_persons": 2, "model_path": "trainer/trainer.yml"}

Must be re-run whenever faces are added or deleted.


Detect Faces

Real-time from camera:

fr.detect_camera()
# Close with q, Esc, or click X on the window

From image file (with result window):

result = fr.detect_image("photo.jpg", show=True)

From image file (data only, no window):

result = fr.detect_image("photo.jpg", show=False)

print(f"Faces found: {result.total_faces}")

for face in result.faces:
    print(face.name)        # person name / "Unknown"
    print(face.recognized)  # True / False
    print(face.score)       # confidence percentage (0–100)
    print(face.confidence)  # raw LBPH value (lower = more confident)
    print(face.x, face.y, face.w, face.h)  # bounding box

Check if a face is recognized:

result = fr.detect_image("photo.jpg", show=False)

for face in result.faces:
    if face.recognized:
        print(f"Recognized: {face.name} ({face.score}%)")
    else:
        print("Unknown face")

User Management

List all users:

users = fr.list_users()
for u in users:
    print(u["id"], u["name"], u["photos"])
# 1  Alice   40
# 2  Bob     35

Delete a user:

info = fr.delete_user("Alice")
print(info)
# {"id": 1, "name": "Alice", "photos_deleted": 40}

After deleting, call fr.train() again to update the model.


Instance Info

print(fr)
# FaceRecog(app_name='Face Recognition', users=2, threshold=75, max_photos=40)

Full Example

from facerecog import FaceRecog

fr = FaceRecog(threshold=70, app_name="Security System")

# 1. Register people from photo folders
fr.register_from_image("Alice", "./photos/alice/")
fr.register_from_image("Bob",   "./photos/bob/")

# 2. Train the model
info = fr.train()
print(f"Done: {info['total_images']} images, {info['total_persons']} people")

# 3. Detect faces in a group photo
result = fr.detect_image("group.jpg", show=True)
for face in result.faces:
    status = f"{face.name} ({face.score}%)" if face.recognized else "Unknown"
    print(f"Face at ({face.x},{face.y}): {status}")

# 4. Real-time detection
fr.detect_camera()

Notes

  • dataset/, trainer/, and labels.json are created in your current working directory — not inside the module folder.
  • More training photos = better accuracy.
  • If the camera is not detected, try camera_index=1 or camera_index=2.
  • Use clear, well-lit, front-facing photos for best results.
  • The app_name parameter sets the title of all OpenCV windows — useful when integrating into a larger app.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

facerecog_lbph-1.0.0.tar.gz (14.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

facerecog_lbph-1.0.0-py3-none-any.whl (15.2 kB view details)

Uploaded Python 3

File details

Details for the file facerecog_lbph-1.0.0.tar.gz.

File metadata

  • Download URL: facerecog_lbph-1.0.0.tar.gz
  • Upload date:
  • Size: 14.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for facerecog_lbph-1.0.0.tar.gz
Algorithm Hash digest
SHA256 c18ab7170b780f158662ad7bfc57a7e7b09148947c67e42b9e35690e0d841081
MD5 048f1b1d0969d7f349d61a6b5e94d1ab
BLAKE2b-256 04bc8ba2987505a6e578a2ce846e6f25cce0ae0fa16e7416a71341ba45dcfaab

See more details on using hashes here.

File details

Details for the file facerecog_lbph-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: facerecog_lbph-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 15.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for facerecog_lbph-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 eb0a89331602049d79b871ad56d412e8ca0af9f3834913c56ee631cd0edf9053
MD5 d855ec7b62924b12796c55083571f09b
BLAKE2b-256 e2575cbc5eb83d323ea405fbf0b9b2a6270b215424fefa4394100166f4ead78f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page