Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

🎓 Face Recognition Attendance System

An intelligent attendance management system built with R, featuring face recognition, data augmentation, and a modern Shiny web interface.

System Status R Version Database


📋 Table of Contents


✨ Features

  • ✅ Face Recognition - AI-powered student identification
  • ✅ Single Photo Enrollment - Works with just one photo per student
  • ✅ Data Augmentation - Generates 15+ variations to improve accuracy
  • ✅ SQLite Database - Lightweight, serverless data storage
  • ✅ Shiny Web Interface - Modern, user-friendly GUI
  • ✅ Attendance Reports - Export to CSV/Excel with visualizations
  • ✅ Webcam Support - Real-time attendance marking
  • ✅ Confidence Scoring - Know how certain each recognition is

🚀 Quick Start

1. Install R Packages

source("install_dependencies.R")

Time: 10-20 minutes | Internet: Required

When prompted about deep learning packages:

  • Type y for best accuracy (requires Python installation)
  • Type n for simpler OpenCV-based approach

2. Verify Installation

source("verify_installation.R")

You should see: ✅ All required packages are installed!

3. Add Student Photos

Place photos in data/original/ folder with this format:

StudentID_FirstName_LastName.jpg

Example: 231004622_Marwan_Mesbah.jpg

4. Initialize Database

Open R and run:

# Load configuration and database functions
source("R/config.R")
source("R/db_setup.R")

# Database is auto-initialized when you source db_setup.R
# Check it worked:
print_db_stats()

5. Enroll a Student (Test)

# Add a test student
add_student(
  student_id = "231004622",
  name = "Marwan Mesbah",
  photo_path = "data/original/231004622_Marwan_Mesbah.jpg",
  email = "marwan@example.com",
  department = "Computer Science"
)

# Verify enrollment
get_all_students()

6. Test Data Augmentation

# Load augmentation functions
source("R/data_augmentation.R")

# Preview what augmentations will look like
preview_augmentations("data/original/231004622_Marwan_Mesbah.jpg", n = 6)

# Generate all augmented versions (creates 15 variations)
results <- augment_all_images()

# Check the augmented folder
list.files("data/augmented")

7. Run the Application (Coming Soon)

shiny::runApp("app.R")

📥 Installation

Prerequisites

  • R (version 4.0 or higher) - Download
  • RStudio (recommended) - Download
  • Internet connection for package downloads

💻 Windows Support

✅ Yes, this project runs normally on Windows!

Notes for Windows Users:

  • RTools: You may need RTools installed to compile some packages (like arrow or shiny). Download RTools here.
  • Paths: The code uses relative paths (e.g., data/original), so it works automatically on both Windows and Linux.
  • Webcam: Shiny's webcam access works in standard browsers (Chrome/Edge) on Windows.

Detailed Installation Steps

Step 1: Clone/Download Project

cd ~/Desktop/R/
git clone <repository-url> Attendance-System-Using-R
cd Attendance-System-Using-R

Step 2: Install R Dependencies

Open R or RStudio and run:

source("install_dependencies.R")

What this installs:

  • Database packages: DBI, RSQLite
  • Image processing: magick, jpeg, png, imager
  • Shiny framework: shiny, shinydashboard, DT
  • Visualization: ggplot2, plotly
  • Data tools: dplyr, tidyr, lubridate
  • Export tools: openxlsx
  • Optional: keras, tensorflow (for deep learning)

Note: The script will ask if you want to install deep learning packages. Choose:

  • y for best accuracy (requires Python + TensorFlow)
  • n for simpler setup (uses OpenCV instead)

Step 3: Verify Installation

source("verify_installation.R")

Expected output:

✅ All required packages are installed!
Required Packages:   20/20
Optional Packages:   3/4

Step 4: Prepare Student Photos

Place photos in data/original/ using this naming format:

[StudentID]_[First_Name]_[Last_Name].jpg

Examples:

231004622_Marwan_Mesbah.jpg
20230001_John_Doe.jpg
STU12345_Jane_Smith.jpg

Photo Requirements:

  • ✅ Format: JPG, JPEG, or PNG
  • ✅ Resolution: Minimum 640×480, recommended 1024×768
  • ✅ Content: Single person, frontal face (looking at camera)
  • ✅ Lighting: Good lighting, avoid heavy shadows
  • ✅ Background: Any (will be ignored)
  • ✅ Expression: Neutral works best

Step 5: Initialize Database

source("STEP_2_test_db.R")

This creates:

  • SQLite database at db/attendance.db
  • Tables: students, face_embeddings, attendance
  • Default configuration settings

Step 6: Test Data Augmentation

source("STEP_3_test_augmentation.R")

This will:

  • Show preview of augmentations
  • Generate 15 variations per photo
  • Save to data/augmented/ folder

📁 Project Structure

Attendance-System-Using-R/
│
├── 📂 db/                          # Database folder
│   └── attendance.db              # SQLite database (auto-created)
│
├── 📂 data/                       # Data folder
│   ├── original/                  # ⭐ Put student photos here
│   │   └── StudentID_Name.jpg    #    Format: ID_FirstName_LastName.jpg
│   ├── augmented/                 # Auto-generated variations
│   └── temp/                      # Temporary uploads
│
├── 📂 models/                     # Pre-trained model weights
│   └── facenet_keras.h5          # (Downloaded when needed)
│
├── 📂 R/                          # R source code
│   ├── config.R                   # ⚙️ System configuration
│   ├── db_setup.R                 # 💾 Database initialization
│   ├── data_augmentation.R        # 🔄 Image augmentation
│   ├── face_detection.R           # 👤 Face detection (coming soon)
│   ├── face_model.R               # 🧠 Face recognition model (coming soon)
│   ├── enrollment.R               # ✍️ Student enrollment (coming soon)
│   ├── mark_attendance.R          # ✅ Attendance marking (coming soon)
│   └── reports.R                  # 📊 Reports & analytics (coming soon)
│
├── 📂 logs/                       # System logs
│
├── 📄 app.R                       # 🌐 Shiny web application (coming soon)
│
├── 📄 install_dependencies.R      # 📦 Package installer
├── 📄 verify_installation.R       # ✔️ Installation checker
│
├── 📄 README.md                   # This file
├── 📄 IMPLEMENTATION_PLAN.md      # Technical implementation plan
├── 📄 QUICK_START.md              # Quick start guide
└── 📄 WORKFLOW_OVERVIEW.md        # System workflow explanation

📖 Usage Guide

Enrolling Students

Method 1: Through Shiny App (Coming Soon)

  1. Run shiny::runApp("app.R")
  2. Go to "Enrollment" tab
  3. Upload photo and enter student details
  4. Click "Enroll Student"

Method 2: Batch Enrollment from Folder

# 1. Place photos in data/original/ with format: StudentID_Name.jpg
# 2. Run:
source("R/enrollment.R")
bulk_enroll_from_folder("data/original/")

Method 3: Manual Enrollment

source("R/db_setup.R")

add_student(
  student_id = "231004622",
  name = "Marwan Mesbah",
  photo_path = "data/original/231004622_Marwan_Mesbah.jpg",
  email = "marwan@example.com",
  department = "Computer Science"
)

Marking Attendance

Through Shiny App: (Coming Soon)

  1. Go to "Mark Attendance" tab
  2. Click "Capture from Webcam" OR upload photo
  3. System detects and recognizes faces
  4. Attendance automatically recorded

Programmatically:

source("R/mark_attendance.R")

# Mark attendance from photo
mark_attendance_from_photo("path/to/photo.jpg")

# Mark attendance from webcam
mark_attendance_from_webcam()

Viewing Reports

Through Shiny App: (Coming Soon)

  1. Go to "Reports" tab
  2. Select date range and filters
  3. View statistics and charts
  4. Export to CSV/Excel

Programmatically:

source("R/reports.R")

# Get attendance for a specific date
get_attendance_by_date("2024-11-23")

# Get attendance for a student
get_student_attendance("231004622")

# Calculate attendance percentage
get_attendance_percentage("231004622")

# Export to CSV
export_attendance_csv("attendance_report.csv")

⚙️ Configuration

Edit R/config.R to customize system behavior:

# Face Recognition Settings
FACE_MATCH_THRESHOLD <- 0.6    # Lower = stricter (0.0-1.0)
FACE_SIZE <- c(160, 160)        # Image size for processing

# Data Augmentation
AUGMENTATION_COUNT <- 15        # Number of variations per photo

# Model Selection
MODEL_TYPE <- "facenet"         # Options: "facenet", "vggface", "opencv_lbph"

# Database
DB_PATH <- "db/attendance.db"   # Database location

# Enable/Disable Features
ENABLE_WEBCAM <- TRUE           # Webcam support
ENABLE_LOGGING <- TRUE          # Detailed logging
DEV_MODE <- FALSE               # Development mode (extra debug info)

🔧 Troubleshooting

Installation Issues

Problem: Package installation fails

Solutions:

# Try installing packages individually
install.packages("DBI")
install.packages("RSQLite")
install.packages("magick")
# etc...

# Or run verification to see what's missing
source("verify_installation.R")

Problem: "Error in library(DBI) : there is no package called 'DBI'"

Solution: Package not installed. Run:

install.packages("DBI")

Database Issues

Problem: "Database is locked"

Solution: Close all connections and reset:

source("R/db_setup.R")
reset_database(confirm = TRUE)  # WARNING: Deletes all data

Problem: Database corrupted

Solution:

# Backup first
cp db/attendance.db db/attendance_backup.db

# Reset database
Rscript -e "source('R/db_setup.R'); reset_database(confirm=TRUE)"

Image Processing Issues

Problem: "No faces detected"

Solutions:

  • Ensure photo has good lighting
  • Face should be clearly visible and frontal
  • Check photo format (JPG/PNG)
  • Try adjusting FACE_DETECTION_THRESHOLD in config

Problem: "Low confidence matches"

Solutions:

  • Adjust FACE_MATCH_THRESHOLD (lower value = stricter)
  • Ensure enrollment photo quality
  • Generate more augmented images
  • Consider collecting 2-3 photos per student

Magick Package Issues

Problem: "magick not loading" on Linux

Solution:

# Install ImageMagick system library
sudo apt-get update
sudo apt-get install libmagick++-dev

# Reinstall R package
Rscript -e "install.packages('magick')"

🔬 Technical Details

Database Schema

students table:

CREATE TABLE students (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  student_id TEXT UNIQUE NOT NULL,
  name TEXT NOT NULL,
  photo_path TEXT,
  enrollment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  email TEXT,
  phone TEXT,
  department TEXT,
  status TEXT DEFAULT 'active'
);

face_embeddings table:

CREATE TABLE face_embeddings (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  student_id TEXT NOT NULL,
  embedding_vector BLOB NOT NULL,      -- 128D face embedding
  is_augmented INTEGER DEFAULT 0,       -- 0=original, 1=augmented
  created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (student_id) REFERENCES students(student_id)
);

attendance table:

CREATE TABLE attendance (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  student_id TEXT NOT NULL,
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  confidence_score REAL,                 -- 0.0 to 1.0
  status TEXT DEFAULT 'present',
  photo_path TEXT,
  FOREIGN KEY (student_id) REFERENCES students(student_id)
);

Face Recognition Pipeline

  1. Face Detection - OpenCV Haar Cascades or DNN
  2. Face Alignment - Crop and normalize to 160×160
  3. Embedding Generation - Convert to 128D vector using FaceNet
  4. Similarity Matching - Cosine similarity or Euclidean distance
  5. Threshold Filtering - Accept if similarity > threshold
  6. Record Attendance - Save with confidence score

Data Augmentation Techniques

  • Geometric: Rotation (±15°), scaling (90-110%), flipping
  • Photometric: Brightness (±20%), contrast (±15%), saturation (±10%)
  • Noise: Gaussian noise, subtle blur

📚 Additional Resources


📝 Development Status

✅ Completed

  • Project structure and organization
  • Database schema and initialization
  • Configuration system
  • Data augmentation pipeline
  • Package installation system
  • Installation verification

🔄 In Progress

  • Face detection module
  • Face recognition model integration
  • Student enrollment system
  • Attendance marking system
  • Reporting and analytics
  • Shiny web interface

📅 Planned

  • Batch attendance processing
  • Email notifications
  • Advanced analytics dashboard
  • Mobile app integration
  • Multi-camera support

🤝 Contributing

This is a custom project for educational purposes. Feel free to modify and extend for your needs!


📄 License

Free to use and modify for educational and personal purposes.


💡 Tips for Best Results

  1. Photo Quality Matters: Good lighting and clear faces improve accuracy significantly
  2. Multiple Photos: If possible, collect 3-5 photos per student in different conditions
  3. Threshold Tuning: Adjust FACE_MATCH_THRESHOLD based on your accuracy needs
  4. Regular Backups: Backup db/attendance.db regularly
  5. Test First: Always test with a small group before full deployment

📞 Support

For issues or questions:

  1. Check the troubleshooting section above
  2. Review QUICK_START.md for setup help
  3. Check IMPLEMENTATION_PLAN.md for technical details

Built with ❤️ using R and Shiny

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages