Advertisement
DiamondMiner88

Python Motion Detector

Dec 9th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.48 KB | None | 0 0
  1. from imutils.video import VideoStream
  2. import numpy as np
  3. import argparse
  4. import datetime
  5. import imutils
  6. import time
  7. import cv2
  8. import os
  9.  
  10. # construct the argument parser and parse the arguments
  11. ap = argparse.ArgumentParser()
  12. ap.add_argument("-v", "--video", help="path to the video file")
  13. ap.add_argument("-a", "--min-area", type=int, default=500, help="minimum area size")
  14. args = vars(ap.parse_args())
  15.  
  16. # Initialize VideoStream
  17. vs = VideoStream(usePiCamera=True, resolution=(640, 480), framerate=30).start()
  18. time.sleep(2.0)
  19. writer = None
  20.  
  21. # initialize the first frame in the video stream
  22. firstFrame = None
  23.  
  24. # loop over the frames of the video
  25. while True:
  26.     isMotion = False
  27.     # grab the current frame and initialize the occupied/unoccupied
  28.     # text
  29.     frame = vs.read()
  30.     frame = frame if args.get("video", None) is None else frame[1]
  31.     text = "Monitoring..."
  32.  
  33.     # if the frame could not be grabbed, then we have reached the end
  34.     # of the video
  35.     if frame is None:
  36.         break
  37.  
  38.     # resize the frame, convert it to grayscale, and blur it
  39.     frame = imutils.resize(frame, width=500)
  40.     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  41.     gray = cv2.GaussianBlur(gray, (21, 21), 0)
  42.  
  43.     # if the first frame is None, initialize it
  44.     if firstFrame is None:
  45.         firstFrame = gray
  46.         continue
  47.  
  48.     # compute the absolute difference between the current frame and
  49.     # first frame
  50.     frameDelta = cv2.absdiff(firstFrame, gray)
  51.     thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
  52.  
  53.     # dilate the thresholded image to fill in holes, then find contours
  54.     # on thresholded image
  55.     thresh = cv2.dilate(thresh, None, iterations=2)
  56.     cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  57.     cnts = cnts[0] if imutils.is_cv2() else cnts[1]
  58.  
  59.     # loop over the contours
  60.     for c in cnts:
  61.         # if the contour is too small, ignore it
  62.         if cv2.contourArea(c) < args["min_area"]:
  63.             continue
  64.  
  65.         # compute the bounding box for the contour, draw it on the frame,
  66.         # and update the text
  67.         (x, y, w, h) = cv2.boundingRect(c)
  68.         cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
  69.         text = "Motion detected."
  70.     isMotion = True
  71.  
  72.  
  73.     # draw the text and timestamp on the frame
  74.     cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
  75.       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  76.     cv2.putText(frame, datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
  77.       (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
  78.  
  79.     if isMotion:
  80.         if writer is None:
  81.         # initialize our video writer
  82.         fileName = datetime.datetime.now().strftime("%Y-%d-%m_%I-%M-%S-%p.avi")
  83.         print(fileName)
  84.             fourcc = cv2.VideoWriter_fourcc(*"MPEG")
  85.             writer = cv2.VideoWriter(fileName, fourcc, 30, (frame.shape[1], frame.shape[0]), True)
  86.  
  87.         # write the output frame to disk
  88.         writer.write(frame)
  89.     else:
  90.         if not (writer is None):
  91.         writer.release()
  92.             writer = None
  93.         print("Video Ended")
  94.  
  95.  
  96.     # show the frame and record if the user presses a key
  97.     cv2.imshow("Security Feed", frame)
  98.     key = cv2.waitKey(1) & 0xFF
  99.  
  100.     # if the `q` key is pressed, break from the lop
  101.     if key == ord("q"):
  102.         break
  103.  
  104. # cleanup the camera and close any open windows
  105. vs.stop() if args.get("video", None) is None else vs.release()
  106. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement