Real-Time Face Mask Detector with Python, OpenCV, and Keras
Build a real-time Face Mask Detector using Python, OpenCV, and Keras to detect mask usage during the COVID-19 pandemic.
Project Overview
We will create a system that detects in real-time whether a person visible on a webcam is wearing a mask or not. The model will be trained using Keras and OpenCV.
Dataset
The dataset contains 1376 images, with 690 images of people wearing masks and 686 of people without masks.
Tools Required
We will use Jupyter Notebook for development. After installing it using:
bash
pip3 install notebook
You can run the server by typing:
bash
jupyter notebook
This will open Jupyter in your browser. Create a new project and write your code.
Project Structure
We’ll build the project in two parts:
Train a Face Mask Detector model using Keras.
Test the model in real-time using a webcam with OpenCV.
Part 1: Model Training (train.py)
1. Import Required Libraries
python
from keras.optimizers import RMSprop from keras.preprocessing.image import ImageDataGenerator import cv2 from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dropout, Dense from keras.callbacks import ModelCheckpoint import numpy as np
2. Build CNN Model
python
model = Sequential([ Conv2D(100, (3,3), activation='relu', input_shape=(150, 150, 3)), MaxPooling2D(2,2), Conv2D(100, (3,3), activation='relu'), MaxPooling2D(2,2), Flatten(), Dropout(0.5), Dense(50, activation='relu'), Dense(2, activation='softmax') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
3. Data Augmentation
python
train_datagen = ImageDataGenerator(rescale=1.0/255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') train_generator = train_datagen.flow_from_directory('./train', batch_size=10, target_size=(150, 150)) validation_datagen = ImageDataGenerator(rescale=1.0/255) validation_generator = validation_datagen.flow_from_directory('./test', batch_size=10, target_size=(150, 150))
4. Save Best Model
python
checkpoint = ModelCheckpoint('model2-{epoch:03d}.model', monitor='val_loss', save_best_only=True, mode='auto')
5. Train the Model
python
history = model.fit_generator(train_generator, epochs=10, validation_data=validation_generator, callbacks=[checkpoint])
Part 2: Real-Time Mask Detection (test.py)
python
import cv2 import numpy as np from keras.models import load_model model = load_model("./model-010.h5") results = {0: 'without mask', 1: 'mask'} GR_dict = {0: (0, 0, 255), 1: (0, 255, 0)} rect_size = 4 cap = cv2.VideoCapture(0) haarcascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') while True: (rval, im) = cap.read() im = cv2.flip(im, 1, 1) rerect_size = cv2.resize(im, (im.shape[1] // rect_size, im.shape[0] // rect_size)) faces = haarcascade.detectMultiScale(rerect_size) for f in faces: (x, y, w, h) = [v * rect_size for v in f] face_img = im[y:y+h, x:x+w] rerect_sized = cv2.resize(face_img, (150, 150)) normalized = rerect_sized / 255.0 reshaped = np.reshape(normalized, (1, 150, 150, 3)) result = model.predict(reshaped) label = np.argmax(result, axis=1)[0] cv2.rectangle(im, (x, y), (x+w, y+h), GR_dict[label], 2) cv2.rectangle(im, (x, y-40), (x+w, y), GR_dict[label], -1) cv2.putText(im, results[label], (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) cv2.imshow('LIVE', im) key = cv2.waitKey(10) if key == 27: break cap.release() cv2.destroyAllWindows()
Run this script using:
bash
python3 test.py
Summary
In this project, we built a real-time Face Mask Detector using Python, Keras, and OpenCV. The project involved training a convolutional neural network to detect whether a person is wearing a mask, followed by deploying the model to work with a live webcam feed.
Write A Comment
No Comments