Learn practical skills, build real-world projects, and advance your career
# Import libraries
from imutils.video import VideoStream
import os
import numpy as np
import imutils
import cv2
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np
import jovian
def predicition():
    # Disable scientific notation for clarity
    np.set_printoptions(suppress=True)

    # Load the model
    model = tensorflow.keras.models.load_model('./TeachMa_FaceMask.h5',compile=False)

    # Create the array of the right shape to feed into the keras model
    # The 'length' or number of images you can put into the array is
    # determined by the first position in the shape tuple, in this case 1.
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)

    # Replace this with the path to your image
    image = Image.open('./face.jpg')

    #resize the image to a 224x224 with the same strategy as in TM2:
    #resizing the image to be at least 224x224 and then cropping from the center
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)

    #turn the image into a numpy array
    image_array = np.asarray(image)

    # display the resized image
#     image.show()

    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1

    # Load the image into the array
    data[0] = normalized_image_array

    # run the inference
    prediction = model.predict(data)
    for i,j in prediction:
        if(i>j):
            return('WithoutMask')
        else:
            return('WithMask')
# Define paths
prototxt_path = 'C:/Users/vsneh/Udemy-notebooks/covid-mask-socialDistance/Face-Detection-using-OpenCV-master/model_data/deploy.prototxt'
caffemodel_path = 'C:/Users/vsneh/Udemy-notebooks/covid-mask-socialDistance/Face-Detection-using-OpenCV-master/model_data/weights.caffemodel'

# Read the model
model = cv2.dnn.readNetFromCaffe(prototxt_path, caffemodel_path)

# Start video capture
vs = cv2.VideoCapture(0)

# Display each video frame
while True:
    ret, frame = vs.read()
    frame = imutils.resize(frame, width = 700, height = 700)
    
    (h, w) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
    
    model.setInput(blob)
    detections = model.forward()
    
    for i in range(0, detections.shape[2]):
        box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
        (startX, startY, endX, endY) = box.astype("int")
        
        confidence = detections[0, 0, i, 2]
        
        # If confidence > 0.5, show box around face
        if (confidence > 0.5):
            text = "{:.2f}%".format(confidence * 100)
            y = startY - 10 if startY - 10 > 10 else startY + 10
            
            roi = frame[startY: endY, startX: endX]
            roi_img = Image.fromarray(roi, 'RGB')
            roi_img.save('face.jpg')
            result = predicition()
#             print(result)
            if(result=='WithoutMask'):
                cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2)
                cv2.putText(frame, result, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 2)
            else:
                cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)
                cv2.putText(frame, result, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 2)
        cv2.imshow("Frame", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

vs.release()
cv2.destroyAllWindows()
jovian.commit(environment='none',files=['./TeachMa_FaceMask.h5','./target.npy','./labels.txt','./Face-Detection-using-OpenCV-master/model_data/deploy.prototxt','./Face-Detection-using-OpenCV-master/model_data/weights.caffemodel'])
[jovian] Attempting to save notebook..
import jovian