Advertisement
RaspberryPiNews

Untitled

Jun 26th, 2022
977
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.61 KB | None | 0 0
  1. # Small disclaimer
  2. print("[INFO] Starting program... (might take a while to load)")
  3.  
  4. # Import stuff
  5. import numpy as np
  6. import imutils
  7. import threading
  8. import time
  9. import cv2
  10. import os
  11. import argparse
  12.  
  13. # Define important variables
  14. faceDetector = "Face Detector"
  15. minConfidence = 0.7
  16.  
  17. ap = argparse.ArgumentParser()
  18. ap.add_argument("-i", "--image", type=str,
  19.     help="full path to image")
  20. args = vars(ap.parse_args())
  21.  
  22. # load our serialized face detector model from disk
  23. print("[INFO] loading face detector model...")
  24. prototxtPath = os.path.sep.join([args["face"], "deploy.prototxt"])
  25. weightsPath = os.path.sep.join([args["face"],
  26.     "res10_300x300_ssd_iter_140000.caffemodel"])
  27. faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)
  28.  
  29. ''' Load models '''
  30.  
  31. # Load the face detector model (https://github.com/gopinath-balu/computer_vision/tree/master/CAFFE_DNN)
  32. print("[INFO] Loading face detector model...")
  33. prototxtPath = faceDetector + "\\deploy.prototxt"
  34. weightsPath = faceDetector + "\\facedetector.caffemodel"
  35. faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)
  36.  
  37. ''' Define main functions '''
  38.  
  39. def FaceDetector(frame, faceNet):
  40.     global detections  
  41.  
  42.     # Grab webcam size and then construct a blob (group of connected pixels in an image that share some common property https://learnopencv.com/blob-detection-using-opencv-python-c/)
  43.     (h, w) = frame.shape[:2]
  44.     blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300),
  45.         (104.0, 177.0, 123.0))
  46.  
  47.     # Pass the blob through face detector
  48.     faceNet.setInput(blob)
  49.     detections = faceNet.forward()
  50.  
  51. # Main mask detection function
  52. def MaskDetector(frame, maskNet):
  53.     (h, w) = frame.shape[:2]
  54.     FaceDetector(frame, faceNet)
  55.  
  56.     # Init list of faces, their corresponding locations, and the list of predictions from face detector
  57.     faces = []
  58.     locs = []
  59.     preds = []
  60.  
  61.     # Loop over each face detection
  62.     for i in range(0, detections.shape[2]):
  63.        
  64.         # Extract the confidence associated with the detection
  65.         confidence = detections[0, 0, i, 2]
  66.  
  67.         # Filter out weak detections
  68.         if confidence > minConfidence:
  69.            
  70.             # Get the (x, y) coordinates of the bounding box for the object
  71.             box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
  72.             (startX, startY, endX, endY) = box.astype("int")
  73.  
  74.             # Ensure the bounding boxes fit inside the frame
  75.             (startX, startY) = (max(0, startX), max(0, startY))
  76.             (endX, endY) = (min(w - 1, endX), min(h - 1, endY))
  77.  
  78.             # Extract the face return value, convert it from BGR to RGB ordering, resize to 244x244 and process it
  79.             face = frame[startY:endY, startX:endX]
  80.             if face.any():
  81.                 face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
  82.                 face = cv2.resize(face, (224, 224))
  83.                 face = img_to_array(face)
  84.                 face = preprocess_input(face)
  85.  
  86.                 # Add the face and bounding boxes to their respective dicts
  87.                 faces.append(face)
  88.                 locs.append((startX, startY, endX, endY))
  89.  
  90.     # Only make a mask prediction if at least one face was detected
  91.     if len(faces) > 0:
  92.         print("1")
  93.     else:
  94.         print("0")
  95.  
  96. # Loop over each frame from video
  97. while True:
  98.     # Resize to 600x400
  99.     frame = cv2.imread('[args["image"]')
  100.     frame = imutils.resize(frame, width=600, height=400)
  101.  
  102.     # Run the faces through face detector
  103.     MaskDetector(frame, maskNet)
  104.    
  105.     # Close window if `Q` is pressed
  106.     if key == ord("q"):
  107.         break
  108.  
  109. # Close window and stop webcam
  110. vs.stop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement