Guest User

Untitled

a guest
Nov 20th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.01 KB | None | 0 0
  1. from imutils.video import VideoStream
  2. from imutils.video import FPS
  3. import face_recognition
  4. import warnings
  5. import argparse
  6. import datetime
  7. import imutils
  8. import json
  9. import time
  10. import cv2
  11.  
  12. def main():
  13.  
  14. # Construct argument parser for motion detection rules
  15. ap = argparse.ArgumentParser()
  16. ap.add_argument("-c", "--conf", default="surveillance_conf.json", help="path to the JSON configuration file")
  17. args = vars(ap.parse_args())
  18.  
  19. # Filter warnings and load configuration file
  20. warnings.filterwarnings("ignore")
  21. conf = json.load(open(args["conf"]))
  22.  
  23. # Setup facial recog classifier
  24. face_cascade_path = "haarcascade_frontalface_default.xml"
  25. face_cascade = cv2.CascadeClassifier(face_cascade_path)
  26.  
  27. # Initialize video stream and allow the camera sensor to warm up
  28. print("[INFO] warming up...")
  29. vs = VideoStream(src=0).start()
  30. time.sleep(conf["camera_warmup_time"])
  31.  
  32. # Start the FPS counter
  33. fps = FPS().start()
  34.  
  35. # Store comparison frame used for motion detection
  36. average_frame = None
  37.  
  38. # ...
  39. motion_counter = 0
  40.  
  41. # Loop over frames from the video file stream
  42. while True:
  43.  
  44. # Set initial status message for the frame and record a timestamp
  45. text = "No motion detected"
  46. timestamp = datetime.datetime.now()
  47.  
  48. # Grab the frame from the threaded video stream and resize it
  49. # to 500px (to speedup processing)
  50. frame = vs.read()
  51. frame = imutils.resize(frame, width=500)
  52.  
  53. # Convert the input frame from (1) BGR to grayscale (for face
  54. # detection)
  55. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  56.  
  57. # Detect faces in the grayscale frame
  58. faces = face_cascade.detectMultiScale(
  59. gray,
  60. scaleFactor=1.1,
  61. minNeighbors=5,
  62. minSize=(30, 30)
  63. )
  64.  
  65. # Proceed if faces have been detected
  66. if len(faces):
  67.  
  68. # Draw rectangle around detected faces
  69. for (x, y, w, h) in faces:
  70. cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 255), 2)
  71.  
  72. # Blur the frame and initialize the average frame
  73. gray = cv2.GaussianBlur(gray, (21, 21), 0)
  74. if average_frame is None:
  75. #average_frame = gray
  76. average_frame = gray.copy().astype("float")
  77. continue
  78.  
  79. # Compute the absolute difference between the current frame and the previous frame
  80. cv2.accumulateWeighted(gray, average_frame, 0.5)
  81. frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(average_frame))
  82.  
  83. # Dialate the thresholded image to fill in holes, then find contours on thresholded image
  84. thresh = cv2.threshold(frameDelta, conf["delta_thresh"], 255, cv2.THRESH_BINARY)[1]
  85. thresh = cv2.dilate(thresh, None, iterations=2)
  86. cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  87. cnts = cnts[0] if imutils.is_cv2() else cnts[1]
  88.  
  89. # Loop over contours
  90. for c in cnts:
  91.  
  92. # If the contours is too small, ignore it
  93. if cv2.contourArea(c) < conf["min_area"]:
  94. continue
  95.  
  96. # Compute the bounding box for the contour, draw it on the frame
  97. # and update the text
  98. (x, y, w, h) = cv2.boundingRect(c)
  99. cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
  100. text = "Motion detected"
  101.  
  102. # Draw the text and timestamp on the frame
  103. ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p")
  104. cv2.putText(frame, "Surveillance Status: {}".format(text), (10, 20),
  105. cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  106. cv2.putText(frame, ts, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX,
  107. 0.35, (0, 0, 255), 1)
  108.  
  109. # Show the surveillance feed when should be displayed to screen
  110. if conf["show_video"]:
  111. cv2.imshow("Surveillance Feed", frame)
  112. key = cv2.waitKey(1) & 0xFF
  113.  
  114. # Break the loop when `q` key is pressed
  115. if key == ord("q"):
  116. break
  117.  
  118. # Stop the timer and display FPS information
  119. fps.stop()
  120. print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
  121. print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
  122.  
  123. # Clean up the camera and close open windows
  124. vs.stop()
  125. cv2.destroyAllWindows()
  126.  
  127. if __name__ == '__main__' :
  128. main()
Add Comment
Please, Sign In to add comment