COVID-19 has affected the whole world very badly. It has a huge impact on our everyday life, and this crisis is increasing day by day. In the near future, it seems difficult to eradicate this virus completely.To counter this virus, Face Masks have become an integral part of our lives. These Masks are capable of stopping the spread of this deadly virus, which will help to control the spread. As we have started moving forward in this ‘new normal’ world, the necessity of the face mask has increased. So here, we are going to build a model that will be able to classify whether the person is wearing a mask or not. This model can be used in crowded areas like Malls, Bus stands, and other public places.

Let’s get started with our Face Mask detector:

Step 1: Import libraries to be used:

import cv2,os
import numpy as np
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import  Dense, Activation, Dropout, Conv2D, Flatten, MaxPooling2D
from keras.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
from keras.models import load_model

**Step 2: Add data path and label the categories:**For building this model, We will be using the face mask dataset provided by Prajna Bhandary. It consists of about 1,376 images with 690 images containing people with face masks and 686 images containing people without face masks.

#use the file path where your dataset is stored
data_path = r'C:\Users\admin\Desktop\face mask detection\face-mask-detector\dataset'

categories = os.listdir(data_path)
labels = [i for i in range(len(categories))]
label_dict = dict(zip(categories,labels))


Image for post

Step 3: Make lists for data and target:

img_size = 150
data = []
target = []

for category in categories:
    folder_path = os.path.join(data_path,category) 
    img_names = os.listdir(folder_path)

    for img_name in img_names:
        img_path = os.path.join(folder_path,img_name)
        img = cv2.imread(img_path)
            gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
            resized = cv2.resize(gray,(img_size,img_size))

        except Exception as e:
            print("Exception: ",e)

The lists which are formed (data and target) are converted into NumPy arrays for easier data pre-processing. The data array is reshaped so that it can be given to Neural Network Architecture as an input. After that, these are saved as a .npy file.

data = np.array(data)/255.0  #data values are normalized

#reshaping of data                                                data = np.reshape(data,(data.shape[0],img_size,img_size,1))
target = np.array(target)
new_target = np_utils.to_categorical(target)
#saving the files                      'data',data)'target',new_target)

**Step 4: Build a Neural Network model:**First, we will load the data from the files that we created in the previous step. Then we are making a Neural network using Convolutional and MaxPooling layers. At last, the output is flattened and fed into a fully connected Dense layer with 50 neurons and finally into layers with 2 neurons as it will output the probabilities for a person wearing a mask or not, respectively.

Image for post

Neural Network model used (Photo by author)

data = np.load('data.npy')
target = np.load('target.npy')

model = Sequential()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics = ['acc'])

#deep-learning #deep learning

COVID-19: Face Mask Detection Using Deep Learning and OpenCV
3.65 GEEK