help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
face-recognition
/
models
RSK World
face-recognition
Face Recognition Dataset - Face Recognition + Face Verification + Biometric Authentication + Computer Vision

This directory is empty

load_dataset.pyexample_usage.py
scripts/load_dataset.py
Raw Download
Find: Go to:
"""
Dataset Loader for Face Recognition Dataset

This script loads and organizes face images from the dataset directory structure.

Project Information:
- Project ID: 22
- Title: Face Recognition Dataset
- Category: Image Data
- Technologies: PNG, JPG, NumPy, OpenCV, Face Recognition

Contact Information:
RSK World
Founder: Molla Samser
Designer & Tester: Rima Khatun
Email: help@rskworld.in
Phone: +91 93305 39277
Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
Website: https://rskworld.in/
Year: 2026
"""

import os
import numpy as np
from PIL import Image
import cv2
from typing import List, Tuple, Dict
import config


class FaceDatasetLoader:
    """
    Loads face images from organized directory structure.
    Expected structure: data/train/person_name/image.jpg
    """
    
    def __init__(self, data_dir: str = None):
        """
        Initialize the dataset loader.
        
        Args:
            data_dir: Path to the dataset directory (default: config.TRAIN_DIR)
        """
        self.data_dir = data_dir or config.TRAIN_DIR
        self.images = []
        self.labels = []
        self.label_to_name = {}
        self.name_to_label = {}
        
    def load(self) -> Tuple[np.ndarray, np.ndarray, Dict]:
        """
        Load all images and labels from the dataset.
        
        Returns:
            Tuple of (images, labels, label_mapping)
        """
        if not os.path.exists(self.data_dir):
            raise FileNotFoundError(f"Dataset directory not found: {self.data_dir}")
        
        label_counter = 0
        
        # Iterate through each person's directory
        for person_name in sorted(os.listdir(self.data_dir)):
            person_dir = os.path.join(self.data_dir, person_name)
            
            if not os.path.isdir(person_dir):
                continue
            
            # Assign label to person
            if person_name not in self.name_to_label:
                self.name_to_label[person_name] = label_counter
                self.label_to_name[label_counter] = person_name
                label_counter += 1
            
            label = self.name_to_label[person_name]
            
            # Load all images for this person
            for filename in os.listdir(person_dir):
                if any(filename.lower().endswith(ext) for ext in config.IMAGE_EXTENSIONS):
                    image_path = os.path.join(person_dir, filename)
                    try:
                        image = cv2.imread(image_path)
                        if image is not None:
                            # Convert BGR to RGB
                            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                            self.images.append(image)
                            self.labels.append(label)
                    except Exception as e:
                        print(f"Error loading image {image_path}: {e}")
        
        return np.array(self.images), np.array(self.labels), self.label_to_name
    
    def get_person_images(self, person_name: str) -> List[np.ndarray]:
        """
        Get all images for a specific person.
        
        Args:
            person_name: Name of the person
            
        Returns:
            List of images for that person
        """
        person_dir = os.path.join(self.data_dir, person_name)
        images = []
        
        if os.path.exists(person_dir):
            for filename in os.listdir(person_dir):
                if any(filename.lower().endswith(ext) for ext in config.IMAGE_EXTENSIONS):
                    image_path = os.path.join(person_dir, filename)
                    image = cv2.imread(image_path)
                    if image is not None:
                        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                        images.append(image)
        
        return images
    
    def get_statistics(self) -> Dict:
        """
        Get dataset statistics.
        
        Returns:
            Dictionary with dataset statistics
        """
        if len(self.images) == 0:
            self.load()
        
        unique_labels = len(set(self.labels))
        total_images = len(self.images)
        
        # Count images per person
        images_per_person = {}
        for label, name in self.label_to_name.items():
            count = np.sum(self.labels == label)
            images_per_person[name] = count
        
        return {
            'total_images': total_images,
            'total_identities': unique_labels,
            'images_per_person': images_per_person,
            'average_images_per_person': total_images / unique_labels if unique_labels > 0 else 0
        }


if __name__ == "__main__":
    # Example usage
    loader = FaceDatasetLoader(config.TRAIN_DIR)
    images, labels, label_mapping = loader.load()
    
    print(f"Loaded {len(images)} images")
    print(f"Number of identities: {len(label_mapping)}")
    print("\nLabel mapping:")
    for label, name in label_mapping.items():
        print(f"  {label}: {name}")
    
    stats = loader.get_statistics()
    print("\nDataset Statistics:")
    print(f"  Total images: {stats['total_images']}")
    print(f"  Total identities: {stats['total_identities']}")
    print(f"  Average images per person: {stats['average_images_per_person']:.2f}")

161 lines•5.4 KB
python
example_usage.py
Raw Download
Find: Go to:
"""
Example Usage Script for Face Recognition Dataset

This script demonstrates how to use the face recognition system.

Project Information:
- Project ID: 22
- Title: Face Recognition Dataset
- Category: Image Data
- Technologies: PNG, JPG, NumPy, OpenCV, Face Recognition
- Difficulty: Intermediate

Contact Information:
RSK World
Founder: Molla Samser
Designer & Tester: Rima Khatun
Email: help@rskworld.in
Phone: +91 93305 39277
Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
Website: https://rskworld.in/
Year: 2026
"""

import os
import cv2
import numpy as np
import config
from scripts.load_dataset import FaceDatasetLoader
from scripts.preprocess import preprocess_faces, get_face_encoding
from scripts.recognize_faces import FaceRecognizer


def example_load_dataset():
    """Example: Loading the dataset."""
    print("\n" + "=" * 60)
    print("Example 1: Loading Dataset")
    print("=" * 60)
    
    loader = FaceDatasetLoader(config.TRAIN_DIR)
    images, labels, label_mapping = loader.load()
    
    print(f"Loaded {len(images)} images")
    print(f"Number of identities: {len(label_mapping)}")
    print("\nLabel mapping:")
    for label, name in sorted(label_mapping.items()):
        print(f"  {label}: {name}")
    
    # Get statistics
    stats = loader.get_statistics()
    print("\nDataset Statistics:")
    for key, value in stats.items():
        if key != 'images_per_person':
            print(f"  {key}: {value}")


def example_preprocess():
    """Example: Preprocessing images."""
    print("\n" + "=" * 60)
    print("Example 2: Preprocessing Images")
    print("=" * 60)
    
    processed_images, processed_labels = preprocess_faces(config.TRAIN_DIR)
    
    print(f"\nPreprocessed {len(processed_images)} face images")
    print(f"Image shape: {processed_images[0].shape}")
    print(f"Image dtype: {processed_images[0].dtype}")
    print(f"Number of unique labels: {len(np.unique(processed_labels))}")


def example_train_and_recognize():
    """Example: Training and recognizing faces."""
    print("\n" + "=" * 60)
    print("Example 3: Training and Recognition")
    print("=" * 60)
    
    # Initialize recognizer
    recognizer = FaceRecognizer()
    
    # Train the model
    print("\nTraining the model...")
    recognizer.train(config.TRAIN_DIR, save_model=True)
    
    # Example: Recognize faces in a test image (if available)
    if os.path.exists(config.TEST_DIR):
        test_images = []
        for root, dirs, files in os.walk(config.TEST_DIR):
            for file in files:
                if any(file.lower().endswith(ext) for ext in config.IMAGE_EXTENSIONS):
                    test_images.append(os.path.join(root, file))
                    break  # Just use first image found
        
        if test_images:
            test_image_path = test_images[0]
            print(f"\nRecognizing faces in: {test_image_path}")
            results = recognizer.recognize(test_image_path)
            
            for i, result in enumerate(results):
                print(f"\nFace {i + 1}:")
                print(f"  Name: {result['name']}")
                print(f"  Confidence: {result['confidence']:.2%}")
                if result['distance'] is not None:
                    print(f"  Distance: {result['distance']:.4f}")


def example_face_encoding():
    """Example: Getting face encodings."""
    print("\n" + "=" * 60)
    print("Example 4: Face Encoding")
    print("=" * 60)
    
    loader = FaceDatasetLoader(config.TRAIN_DIR)
    images, labels, label_mapping = loader.load()
    
    if len(images) > 0:
        # Get encoding for first image
        encoding = get_face_encoding(images[0])
        
        if encoding is not None:
            print(f"Face encoding shape: {encoding.shape}")
            print(f"Face encoding dtype: {encoding.dtype}")
            print(f"Encoding sample (first 5 values): {encoding[:5]}")
        else:
            print("No face detected in the first image")


def main():
    """Run all examples."""
    print("=" * 60)
    print("Face Recognition Dataset - Example Usage")
    print("=" * 60)
    print(f"Project: Face Recognition Dataset (ID: 22)")
    print(f"RSK World - https://rskworld.in/")
    print("=" * 60)
    
    # Check if training directory exists
    if not os.path.exists(config.TRAIN_DIR):
        print(f"\nError: Training directory not found: {config.TRAIN_DIR}")
        print("Please ensure the dataset is properly organized.")
        return
    
    try:
        example_load_dataset()
        example_preprocess()
        example_face_encoding()
        example_train_and_recognize()
        
        print("\n" + "=" * 60)
        print("All examples completed!")
        print("=" * 60)
        
    except Exception as e:
        print(f"\nError: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()

160 lines•5 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer