AI Based Face Mask Detection System

Original article was published on Deep Learning on Medium

AI Based Face Mask Detection System

As corona virus (covid-19) can spread through close contact with an infected person via their coughs, sneezes, or respiratory droplets, it has become mandatory to wear face masks in the affected regions or public places. The lock down rules have been strictly implemented in public places such as restaurants, shopping malls, and public transport with the help of technology.

But it has become a tedious task for government authorities to identify citizens with or without mask. Despite their untiring efforts to ensure that the lockdown rules are strictly followed by the people, the compulsory wearing of face mask in public is violated more often than not. The government has stipulated a penalty of Rs. 1,000 for not wearing face mask outdoors.

The AI based software tool linked to CCTV cameras installed across the city could identify face mask rule violators. Cameras will flag those not wearing the masks and an alert will be sent to the central command control center at the state police headquarters. This will be passed on to patrolling personnel to trace the violators either riding bikes or walking on foot.

Now, lets get started developing an automated system using Deep Learning and Computer vision.


We will be using the dataset created by PyImageSearch reader Prajna Bhandary. This dataset consists of 1,376 images belonging to two classes:

  • with_mask: 690 images
  • without_mast: 686 images

You can clone repository: git clone

Next, we can use Keras and TensorFlow to train a classifier to automatically detect whether a person is wearing a mask or not. In order to do this, we will be fine-tuning the MobileNet V2 architecture, which is a highly efficient architecture that can be applied to embedded devices such as Raspberry Pi, Google Coral, NVIDIA Jetson Nano, etc. with limited computational capacity.

At first, import necessary libraries as follows:

We load images of size 224×224 from data folders — with_mask and without_mask, and convert the data and labels to Numpy arrays.

Split Data:

We split data into training and testing.

Our model is defined as a sequence of layers with layer. We use as activation function which output a vector that gives the probability of each class.

We used optimizer and binary_crossentropy as loss function.

We have to load and prepare MobileNetV2 model for fine-tuning. Ensure that the head FC layer sets are set to False, and place the head FC model on top of the base model.

Save our model and load it again for prediction of testing data.

Fitting data with 15 iterations and batch_size 32.

Evaluating our model with testing data has given 100% accuracy.


  1. PyImageSearch: Fine-tuning with Keras and Deep Learning
  2. PyImageSearch: Face Mask Detector with OpenCV, Keras/TensorFlow, and Deep Learning