Face Mask Detection using pretrained model

Shashank Lipate
2 min readMar 14, 2021

--

In this pandemic masks and social distancing has became necessity in public places. It is important for managers of malls and marts to continuously look for the rule breakers.

Here we will implement real time face mask detection system which will help the observer to identify people without masks.

We will use the same face detection with opencv approach used in my previous article.

Requirements: Install the below packages first with
pip install <package-name>
imutils==0.5.3
Keras-Preprocessing==1.1.0
numpy
opencv-python==4.4.0.44
pyttsx3==2.90
scipy
tensorboard==2.2.1
tensorboard-plugin-wit==1.6.0
tensorflow==2.2.0
tensorflow-estimator==2.2.0

Download :
mobilenet_v2.model from github.

Code :

Import all libraries

import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as np
import cv2
import os
from imutils.video import VideoStream
import imutils
from scipy.spatial import distance as dist

Initialize variables

cap = cv2.VideoCapture(0) 
face_model = cv2.CascadeClassifier(os.path.join(os.getcwd(),’lbpcascade_frontalface_improved.xml’))
maskNet=load_model(os.path.join(os.getcwd(),’mobilenet_v2.model’))
labels_dict={0:’MASK’,1:’NO MASK’}
color_dict={0:(0,255,0),1:(0,0,255)}

Continously Detect face and predict mask or without mask

while True:
status , photo = cap.read()
faces=face_model.detectMultiScale(photo)
for (x,y,w,h) in faces:
face_img=photo[y:y+w,x:x+w]
face_img=cv2.resize(face_img,(224,224))
face_img=img_to_array(face_img)
reshaped=np.reshape(face_img/255,(1,224,224,3))
result=maskNet.predict(reshaped)
label=0 if result[0][0]>0.8 else 1
cv2.rectangle(photo,(x,y),(x+w,y+h),color_dict[label],2)
cv2.rectangle(photo,(x,y-40),(x+w,y),color_dict[label],-1)
cv2.putText(photo, labels_dict[label], (x, y-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2)

close the program by hitting enter

    cv2.imshow('Camera' , photo)
if cv2.waitKey(100) == 13:
break
cv2.destroyAllWindows()

After running this code your camera screen will pop up, detect face and draw a bounding box around it. It will also show a label of mask or no mask near the bounding box.

Sample output

Next I will write and link the improved version to detect distance between two people and detect danger.

Connect with me on linkedIn : Shashank Lipate

--

--

Shashank Lipate
Shashank Lipate

No responses yet