Face Mask Detection
By: Aman Kharwal
Tags: Artificial Intelligence, Machine Learning, Programming, Python, Data Science

In the age of Covid-19, face masks and social distancing have become the new normal. In this article, I will introduce you to a machine learning project on real-time face mask detection with Python.

Real-Time Face Mask Detection System

Indoor places, such as restaurants and grocery stores, are legally required to have rules in place for the mandatory use of face masks. Having a worker manually examining each person to make sure their mask is on simply defeats the goal of limiting contact with people as much as possible. So, a real-time face mask detection system can be used to address this issue that will not only maximize efficiency but will also ensure to potentially save lives.

The technology behind the real-time face mask detection system is not new. In Machine Learning, face mask detection is the problem of computer vision. Too often we see computer vision applications of this technology in our daily lives. A common example is a face unlocking in smartphones.

The goal of a face mask detection system is to create an image recognition system that understands how image classification works, and it should work with great accuracy so that our model can be applied in the realtime situations. It will work by recognizing the boundaries of the face and predicting whether or not you are wearing a face mask in real-time.

Real-time Face Mask Detection with Python

Now, I’m going to create a convolutional neural network to create a real-time facial mask detection model with Python. Here, I will use three dense layers in our model with respectively 50, 35 and finally 2 neurons. The dense network produces the probability of the binary classification of no mask = 1 and mask = 0:

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dropout, Dense

cnn = Sequential([Conv2D(filters=100, kernel_size=(3,3),

activation='relu'),

MaxPooling2D(pool_size=(2,2)),

Conv2D(filters=100, kernel_size=(3,3),

activation='relu'),

MaxPooling2D(pool_size=(2,2)),

Flatten(),

Dropout(0.5),

Dense(50),

Dense(35),

Dense(2)])

cnn.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])

Testing The Model in Real-Time

To test our model in real-time, I’ll be using the VideoCapture function in the OpenCV library in Python. The Cascade classifier, designed by OpenCV, was used to detect the frontal face in live video via detectMultiScale. We can use a while loop to continue capturing images from the webcam.

Our machine learning model will then determine whether or not a face mask is worn in real-time. Based on the performance and accuracy of our model, the result of the binary classifier will be indicated by showing a green rectangle superimposed around the section of the face indicating that the person at the camera is wearing a mask, or a red rectangle indicating that the person on camera is not wearing a mask.

Now let’s implement the above steps for testing the face mask detection model in real-time by using the Python programming language:

import cv2

import numpy as np

labels_dict={0:'No mask',1:'Mask'}

color_dict={0:(0,0,255),1:(0,255,0)}

imgsize = 4 #set image resize

camera = cv2.VideoCapture(0) # Turn on camera

# Identify frontal face

classifier = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

while True:

(rval, im) = camera.read()

im=cv2.flip(im,1,1) #mirrow the image

imgs = cv2.resize(im, (im.shape[1] // imgsize, im.shape[0] //

imgsize))

face_rec = classifier.detectMultiScale(imgs)

for i in face_rec: # Overlay rectangle on face

(x, y, l, w) = [v * imgsize for v in i]

face_img = im[y:y+w, x:x+l]

resized=cv2.resize(face_img,(150,150))

normalized=resized/255.0

reshaped=np.reshape(normalized,(1,150,150,3))

reshaped = np.vstack([reshaped])

result=cnn.predict(reshaped)

label=np.argmax(result,axis=1)[0]

cv2.rectangle(im,(x,y),(x+l,y+w),color_dict[label],2)

cv2.rectangle(im,(x,y-40),(x+l,y),color_dict[label],-1)

cv2.putText(im, labels_dict[label], (x, y-

10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2)

cv2.imshow('LIVE',im)

key = cv2.waitKey(10)

# stop loop by ESC

if key == 27: # The Esc key

break

webcam.release()

cv2.destroyAllWindows()

So you can see that our model gave good results and it can be used in real-time scenarios. Hope you liked this article on machine learning project on Real-Time Face Mask Detection with Python. Please feel free to ask your valuable questions in the comments section below.