Python Project - Real-Time Face Mask Detector with Python, OpenCV, Keras
Posted by Superadmin on August 22 2020 10:53:59

Python Project - Real-Time Face Mask Detector with Python, OpenCV, Keras

 

BY  · UPDATED · AUGUST 6, 2020

 

 

During pandemic COVID-19, WHO has made wearing masks compulsory to protect against this deadly virus. In this tutorial we will develop a machine learning project – Real-time Face Mask Detector with Python.

face mask detector project

Real-Time Face Mask Detector with Python

We will build a real-time system to detect whether the person on the webcam is wearing a mask or not. We will train the face mask detector model using Keras and OpenCV.

Download the Dataset

The dataset we are working on consists of 1376 images with 690 images containing images of people wearing masks and 686 images with people without masks.

Download the dataset: Face Mask Dataset

Download the Project Code

Before proceeding ahead, please download the project source code: Face Mask Detector Project

Install Jupyter Notebook

In this machine learning project for beginners, we will use Jupyter Notebook for the development. Let’s see steps for the installation and configuration of Jupyter Notebook.

Using pip python package manager you can install Jupyter notebook:

  1. pip3 install notebook

And that’s it, you have installed jupyter notebook

After installing Jupyter notebook you can run the notebook server. To run the notebook, open terminal and type:

  1. jupyter notebook

It will start the notebook server at http://localhost:8888

jupyter notebook

To create a new project click on the “new” tab on the right panel, it will generate a new .ipynb file.

Create a new file and write the code which you have downloaded

Let’s dive into the code for face mask detector project:

We are going to build this project in two parts. In the first part, we will write a python script using Keras to train face mask detector model. In the second part, we test the results in a real-time webcam using OpenCV.

Make a python file train.py to write the code for training the neural network on our dataset. Follow the steps:

 

1. Imports:

Import all the libraries and modules required.

  1. from keras.optimizers import RMSprop
  2. from keras.preprocessing.image import ImageDataGenerator
  3. import cv2
  4. from keras.models import Sequential
  5. from keras.layers import Conv2D, Input, ZeroPadding2D, BatchNormalization, Activation, MaxPooling2D, Flatten, Dense,Dropout
  6. from keras.models import Model, load_model
  7. from keras.callbacks import TensorBoard, ModelCheckpoint
  8. from sklearn.model_selection import train_test_split
  9. from sklearn.metrics import f1_score
  10. from sklearn.utils import shuffle
  11. import imutils
  12. import numpy as np

2. Build the neural network:

This convolution network consists of two pairs of Conv and MaxPool layers to extract features from the dataset. Which is then followed by a Flatten and Dropout layer to convert the data in 1D and ensure overfitting.

And then two Dense layers for classification.

  1. model = Sequential([ 
  2. Conv2D(100, (3,3), activation='relu', input_shape=(150, 150, 3)),
  3. MaxPooling2D(2,2),
  4. Conv2D(100, (3,3), activation='relu'),
  5. MaxPooling2D(2,2),
  6. Flatten(),
  7. Dropout(0.5),
  8. Dense(50, activation='relu'),
  9. Dense(2, activation='softmax') 
  10.  ]) 
  11. model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])

3. Image Data Generation/Augmentation:

  1. TRAINING_DIR = "./train" 
  2. train_datagen = ImageDataGenerator(rescale=1.0/255,
  3. rotation_range=40,
  4. width_shift_range=0.2,
  5. height_shift_range=0.2,
  6. shear_range=0.2,
  7. zoom_range=0.2,
  8. horizontal_flip=True,
  9. fill_mode='nearest') 
  10.  
  11. train_generator = train_datagen.flow_from_directory(TRAINING_DIR,
  12. batch_size=10,
  13. target_size=(150, 150))
  14. VALIDATION_DIR = "./test"
  15. validation_datagen = ImageDataGenerator(rescale=1.0/255)
  16. validation_generator = validation_datagen.flow_from_directory(VALIDATION_DIR,
  17. batch_size=10,
  18. target_size=(150, 150))

4. Initialize a callback checkpoint to keep saving best model after each epoch while training:

  1. checkpoint = ModelCheckpoint('model2-{epoch:03d}.model',monitor='val_loss',verbose=0,save_best_only=True,mode='auto')

5. Train the model:

  1. history = model.fit_generator(train_generator,
  2. epochs=10,
  3. validation_data=validation_generator,
  4. callbacks=[checkpoint])

project code

 

Now we will test the results of face mask detector model using OpenCV.

Make a python file “test.py” and paste the below script.

  1. import cv2
  2. import numpy as np
  3. from keras.models import load_model
  4. model=load_model("./model-010.h5")
  5. results={0:'without mask',1:'mask'}
  6. GR_dict={0:(0,0,255),1:(0,255,0)}
  7. rect_size = 4
  8. cap = cv2.VideoCapture(0)
  9. haarcascade = cv2.CascadeClassifier('/home/user_name/.local/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml')
  10. while True:
  11. (rval, im) = cap.read()
  12. im=cv2.flip(im,1,1)
  13. rerect_size = cv2.resize(im, (im.shape[1] // rect_size, im.shape[0] // rect_size))
  14. faces = haarcascade.detectMultiScale(rerect_size)
  15. for f in faces:
  16. (x, y, w, h) = [v * rect_size for v in f]
  17. face_img = im[y:y+h, x:x+w]
  18. rerect_sized=cv2.resize(face_img,(150,150))
  19. normalized=rerect_sized/255.0
  20. reshaped=np.reshape(normalized,(1,150,150,3))
  21. reshaped = np.vstack([reshaped])
  22. result=model.predict(reshaped)
  23. label=np.argmax(result,axis=1)[0]
  24. cv2.rectangle(im,(x,y),(x+w,y+h),GR_dict[label],2)
  25. cv2.rectangle(im,(x,y-40),(x+w,y),GR_dict[label],-1)
  26. cv2.putText(im, results[label], (x, y-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2)
  27. cv2.imshow('LIVE', im)
  28. key = cv2.waitKey(10)
  29. if key == 27:
  30. break
  31. cap.release()
  32. cv2.destroyAllWindows()

Run the project and observe the model performance.

  1. python3 test.py

face mask detector project

Summary

In this project, we have developed a deep learning model for face mask detection using Python, Keras, and OpenCV. We developed the face mask detector model for detecting whether person is wearing a mask or not. We have trained the model using Keras with network architecture. Training the model is the first part of this project and testing using webcam using OpenCV is the second part.

This is a nice project for beginners to implement their learnings and gain expertise.