Face Mask Detection Using Keras and OpenCv

Syed Shoyab
2 min readAug 13, 2020
Face mask Detection

Step 1 : Pre-processing the data

The data set consists of images with mask and without mask. Take two lists named withmask and withoutmask and append all the images of withmask and wihout mask in to the lists respectively. you can download the dataset from below link.

https://github.com/prajnasb/observations/tree/master/experiements/data

import oswith_mask = []
image_path = r'/content/drive/My Drive/Colab Notebooks/with_mask'
for image in os.walk(image_path):
with_mask.append(image[2])
without_mask = []
image_path = r'/content/drive/My Drive/Colab Notebooks/without_mask'
for image in os.walk(image_path):
without_mask.append(image[2])

convert the two lists to numpy arrays by importing numpy module and reshape the arrays as follows.

import numpy as np
with_mask = np.array(with_mask)
without_mask = np.array(without_mask)
without_mask = np.reshape(without_mask,-1)
with_mask = np.reshape(with_mask,-1)

Now convert each image to gray scale image using OpenCv and make the array of them as follows.

Normalize the array to 0 to 1 and make output as categorical using keras utils.

Step 2 : Using Convolutional Neural Network(CNN) to build model

The Layers should be added are

  1. 2 Conv2d Layers each layer with a Relu layer followed by pooling layer
  2. Flatten layer
  3. Dropout layer
  4. Dense layer
  5. softmax layer

Now compile the model with ‘Adam’ optimizer and ‘categorical_crossentropy’ as loss and add checkpoint as follows.

model.compile(loss=’categorical_crossentropy’,optimizer=’adam’,metrics=[‘accuracy’])checkpoint = ModelCheckpoint(‘model-{epoch:03d}.model’,monitor=’val_loss’,verbose=0,save_best_only=True,mode=’auto’)

Now fit the model using with at least 20 epochs and save the model and you can set batch size also.

history=model.fit(xtrain,ytrain,epochs=20,callbacks=[checkpoint],validation_split=0.2)model.save('mymodel')   #to save the model

Step 3 : Using OpenCV to Detect the Face Mask

First Load the saved model and import the required libraries such as Opencv and do not forget to download ‘haarcascade_frontalface_default.xml’ classifier you can download from the below link.

https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml

Use this classifier to detect faces from the frame. Now use your default camera to capture the video as follows.

import cv2
import numpy as np
face_clsfr=cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
source=cv2.VideoCapture(0)
labels_dict={0:’MASK’,1:’NO MASK’}
color_dict={0:(0,255,0),1:(0,0,255)}

The camera captures each frame and the classifier detects the face and for each face we have to convert in to gray scale image and resize it to 100*100 pixels and sent to the model to predict the result.The outputs of the each face are kept a text above it.

Hope you all love this project and the total source code is available at https://github.com/Shoyabsyed4m3/FaceMask-Detection

This is my first post and If you have any queries feel free to email me sayedshoyab1333@gmail.com. Thank You!!..

--

--