Face Mask Detection

 Face Mask Detection – IT and Computer Engineering Guide

1. Project Overview

Objective: Develop a system to detect whether a person is wearing a face mask or not using real-time video feeds or static images.
Scope: Utilize deep learning techniques to enhance safety in public spaces by identifying mask compliance.

2. Prerequisites

Knowledge: Understanding of Python programming, convolutional neural networks (CNNs), and OpenCV.
Tools: Python, TensorFlow/Keras, OpenCV, and NumPy.
Dataset: Publicly available face mask datasets or custom-collected data.

3. Project Workflow

- Dataset Collection: Gather labeled images of faces with and without masks.

- Data Preprocessing: Resize, normalize, and augment the dataset for better generalization.

- Model Development: Build a CNN model to classify images as 'Mask' or 'No Mask'.

- Integration: Integrate the trained model with OpenCV for real-time video analysis.

- Deployment: Deploy the system for public use in crowded areas or workplaces.

4. Technical Implementation

Step 1: Import Libraries


import cv2
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator

Step 2: Load and Preprocess Data


# Load dataset
data_dir = 'dataset/'
categories = ['Mask', 'No_Mask']

data = []
for category in categories:
    path = os.path.join(data_dir, category)
    class_num = categories.index(category)
    for img in os.listdir(path):
        try:
            img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_COLOR)
            resized_img = cv2.resize(img_array, (128, 128))
            data.append([resized_img, class_num])
        except Exception as e:
            pass

# Prepare data
X, y = zip(*data)
X = np.array(X) / 255.0
y = np.array(y)

Step 3: Train the Model


# Build CNN model
model = Sequential([
    Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)),
    MaxPooling2D(2, 2),
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Flatten(),
    Dense(128, activation='relu'),
    Dropout(0.5),
    Dense(2, activation='softmax')
])

# Compile model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train model
model.fit(X, y, epochs=10, validation_split=0.2, batch_size=32)

Step 4: Real-Time Detection with OpenCV


# Load the trained model
model.load_weights('face_mask_detection_model.h5')

# Initialize webcam
cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    resized_frame = cv2.resize(frame, (128, 128)).reshape(1, 128, 128, 3) / 255.0
    prediction = model.predict(resized_frame)
    label = "Mask" if np.argmax(prediction) == 0 else "No Mask"
    color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
    cv2.putText(frame, label, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
    cv2.imshow("Face Mask Detection", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

5. Results and Insights

Evaluate the model's accuracy in identifying mask compliance and highlight areas for optimization.

6. Challenges and Mitigation

Dataset Diversity: Include diverse images with various angles and lighting.
Real-Time Efficiency: Optimize the model for faster predictions.

7. Future Enhancements

Incorporate multi-face detection to handle crowded scenarios.
Deploy on edge devices for scalability in public settings.

8. Conclusion

The Face Mask Detection project showcases the application of AI in promoting public health and safety by ensuring mask compliance.