Gadgets 4 Students Online Courses
Free Tutorials  Go to Your University  Placement Preparation 
0 like 0 dislike
8.6k views
in AI-ML-Data Science Projects by (279 points)

Abstract-About In the present scenario due to Covid-19, there is no efficient face mask detection applications which are now in high demand for transportation means, densely populated areas, residential districts, large-scale manufacturers and other enterprises to ensure safety. 

This system can therefore be used in real-time applications which require face-mask detection for safety purposes due to the outbreak of Covid-19. This project can be integrated with embedded systems for application in airports, railway stations, offices, schools, and public places to ensure that public safety guidelines are followed.



GOEDUHUB's Online Courses @ Udemy



Where can I do online courses From Word's Top Instructors?

UDEMY::  Attend All Udemy Courses in Just INR 450[Coupon]
Coursera:: Join For FREE

2 Answers

0 like 0 dislike
by (279 points)
selected by
 
Best answer

Face Mask Detection

Purpose of the model- considering the covid-19 outbreak, i think this is best project that i can work as python developer. Today everyone is aware of taking precaution and safety measures regarding covid-19, so face mask detection will play a huge role to avoid corona virus. 

This project helps us to spread the awareness among people using face mask properly. It detects the face mask on your face whether the person is hiding his/her face by mask or not. it also check the face mask is properly cover your face both nose and mouth.

Architecture of the model- In this project, we’ll discuss our two-phase COVID-19 face mask detector, detailing how our computer vision/deep learning pipeline will be implemented. From there, we’ll review the dataset we’ll be using to train our custom face mask detector. I’ll then show you how to implement a Python script to train a face mask detector on our dataset using Keras and TensorFlow. We’ll use this Python script to train a face mask detector and review the results. Given the trained COVID-19 face mask detector, we’ll proceed to implement two more additional Python scripts used to Detect face masks in real-time video streams.

​Python implementation for the this project- i have implemented this code on google colab so we have some additional code also.

first import all the libraries-

from keras.models import Sequential

from keras.layers import Conv2D

from keras.layers import MaxPooling2D

from keras.layers import Flatten

from keras.layers import Dense

import tensorflow as tf

print(tf.__version__)

In google colab we have to mount the drive in this code. so

from google.colab import drive

drive.mount('/content/drive') 

after run the above code we get a link click upon the link we will copy the link and past it here so that we give access to our drive here.

Data preprocessing- Now we will preprocess our data set. download the dateset Click here. we can see we have images of with mask and without mask.

image

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = test_datagen.flow_from_directory(

        '/content/drive/My Drive/Colab Notebooks/dest_folder/train',

                                                 target_size = (64, 64),

                                                 batch_size = 32,

                                                 class_mode = 'binary',

                                                    shuffle=True)

test_set = test_datagen.flow_from_directory(

        '/content/drive/My Drive/Colab Notebooks/dest_folder/test',

                                            shuffle=True,

                                            target_size = (64, 64),

                                            batch_size = 32,

                                            class_mode = 'binary')

after this we can see have we get all the training image in train_set of (64,64) size. so we can train the model.

prepare the model-

classifier = Sequential()
classifier.add(Conv2D(16, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Conv2D(64, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

In this model we have two convolutional layer and we take sequential model to prepare our model. then we add two max-pooling layer to extract the features the we add two dense layers for full connected layer and the we complie our model and use the adam optimizer and here we do binary classification so we have binary_crossentropy as loss.

training of model- 

classifier.fit_generator(training_set,

                         steps_per_epoch = 1315,

                         epochs = 3 , 

                         validation_data = test_set,

                         validation_steps = 194)

classifier.save('my_mask.h5')

as we can we have trained model after run this code.

0 like 0 dislike
by (279 points)

after preparing the model now we can check upon images or live web cam that it is working or not.

first we load our model-

from keras.models import load_model

classifier=load_model('my_mask.h5')

Take image-

import numpy as np

from keras.preprocessing import image

test_image = image.load_img('C:/Users/lenovo/dest_folder/val/without_mask/5.jpg',target_size = (300, 300)) 

import matplotlib.pyplot as plt

from matplotlib.pyplot import imshow

%matplotlib inline

#plt.figure(1)

plt.imshow(test_image)

import numpy as np

from keras.preprocessing import image

test_image = image.load_img('C:/Users/lenovo/dest_folder/val/without_mask/5.jpg', target_size = (64, 64))

test_image = image.img_to_array(test_image)

test_image = np.expand_dims(test_image, axis = 0)

result = classifier.predict(test_image)

s=training_set.class_indices

a=result.argmax()

name=[]

for i in s:

    name.append(i)

for i in range(len(s)):

    if(i==a):

        q=name[i]

print(q)

we can see that it will give result upon image so we can check with validation images.

if we want to check how many classes we have in this model and what are the indices we have for the classes . using this [training_set.class_indices] line we check the indices.

Implementation of the project on live camera-

Here we have code for implementing the mask detection project on live camera and for that we use openCV code for that 

from tensorflow.keras.models import load_model

classifier=load_model('my_mask.h5')

from tensorflow.keras.preprocessing import image

import numpy as np

import cv2

#we are starting our web cam

webcam=cv2.VideoCapture(0)

def predictor(test_img):

    #test_img=image.load_img(path,target_size=(48,48))

    test_img=image.img_to_array(test_img)

    test_img=np.expand_dims(test_img,axis=0)

    result=classifier.predict(test_img)

    if result[0][0] == 0:

        prediction = 'with_mask'

    else:

        prediction = 'without_mask'

        

    return prediction

    

    

while(True):

    #capture frame by frame

    #ret is boolean veriable

    #frame capture images bcoz vedio is collection of images

    ret,frame=webcam.read()

    haar_face_cascade=cv2.CascadeClassifier('C:/Users/lenovo/Downloads/

haarcascadefrontalfaces/haarcascade_frontalface_default.xml')

    g_frame=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    

    faces=haar_face_cascade.detectMultiScale(frame,scaleFactor=1.06,minNeighbors=5)

    #print("faces found")

    #print(faces)

    for(x,y,w,h) in faces:

        

        crop=frame[y:y+h,x:x+w]

        roi=cv2.resize(crop,(64,64))

        path='s.jpg'

        #loaded_model_json = json_file.read()

        #loaded_model = model_from_json(loaded_model_json)

        cv2.imwrite(path,roi)

        name=predictor(roi)

        print(name)

        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)

        cv2.putText(frame,name,(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(255, 0, 0),2)

        

    cv2.imshow('frame',frame)

    if(cv2.waitKey(1) & 0xFF==ord('q')):

        cv2.imwrite("myimage.jpg",frame)

        break

    

#when everythong is done we realese the capture

webcam.release()

this code will work on jupyter or any platform of anaconda but if we want to work upon google colab there is inbuild code for live camera we just have to import that cells into our code and capture the images and give that image to our model and it will predict that person is wearing the mask or not.

3.3k questions

7.1k answers

395 comments

4.5k users

Related questions

 Important Lists:

Important Lists, Exams & Cutoffs Exams after Graduation PSUs

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 

 

Free Online Directory
...