File size: 2,071 Bytes
3150336
 
 
 
 
 
 
 
 
 
dfb58d9
 
97d50e2
3150336
 
97d50e2
3150336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792544e
3150336
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#Basic libraries
import gradio as gr
import numpy as np
import pandas as pd
#Image Processing
import cv2 as cv
from PIL import Image
#Model processing
from tensorflow.keras.models import load_model

TF_ENABLE_ONEDNN_OPTS=0

model = load_model('Mask_Detection_MobileNetV2.h5')

#Loading the cascade
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')

def predict_image(filename):
    #Reading the input image
    img = cv.imread(str(filename))
    img = cv.resize(img,(1024,1024))
    #Converting the image into grayscale
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    #Detecting the faces in the images using face_casced
    faces_rect = face_cascade.detectMultiScale(gray, 1.1, 4)
    for (x,y,w,h) in faces_rect:

        faces_roi = img[y:y+h,x:x+h]
        #Resizing the image of face to 32x32x3
        faces_roi = cv.resize(faces_roi,(160,160))
        #Reshaping the array to convert it into input shape of the model
        faces_roi = faces_roi.reshape(1,160,160,3)
        #Finding the probability using the model.predict
        confidence = model.predict(faces_roi)
        if confidence >= 0.5:
            label = "Masked"+ ' Probability={}'.format(confidence)
            #Putting Masked text in the images
            cv.putText(img, label, (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.45, (0,255,0), 2)
            #Drawing a GREEN coloured rectangle around the face
            cv.rectangle(img, (x,y), (x+w,y+h), (0,255,0), thickness=2)
        else:
            label = "Not Masked"+ ' Probability={}'.format(confidence)
            #Putting Not Masked text in the images
            cv.putText(img, label, (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.45, (0,0,255), 2)
            #Drawing a RED coloured rectangle around the face
            cv.rectangle(img, (x,y), (x+w,y+h), (0,0,255), thickness=2)

    img = Image.fromarray(img, 'RGB')
    return img

gr.Interface(fn=predict_image,
             inputs=gr.Image(type="filepath", sources = ['webcam','upload']),
             outputs=gr.Image()).launch(share=True, debug = True)