SurvBot/motion_detector.py

87 lines
2.6 KiB
Python
Raw Normal View History

2019-11-15 14:45:37 +00:00
from imutils.video import VideoStream
import argparse
import datetime
import imutils
import time
import cv2
2019-11-16 14:46:38 +00:00
import com
import config
2020-05-24 18:48:40 +00:00
import traceback
import _thread
2019-11-15 14:45:37 +00:00
2019-11-16 14:46:38 +00:00
def compare():
2019-11-23 11:14:19 +00:00
try:
url = config.stream
2020-05-24 18:48:40 +00:00
min_area = 3000
max_area = 10000
2019-11-23 11:14:19 +00:00
counter = 0
threashold = 18
delay = .3
framerate = 30
2020-05-24 18:48:40 +00:00
2019-11-23 11:14:19 +00:00
# initialize the first frame in the video stream
2020-05-24 18:48:40 +00:00
vs = cv2.VideoCapture(url)
2019-11-23 11:14:19 +00:00
firstFrame = None
# loop over the frames of the video
while True:
2020-05-24 18:48:40 +00:00
frame = vs.read()[1]
2019-11-15 14:45:37 +00:00
text = "Unoccupied"
2020-05-24 18:48:40 +00:00
# if the frame could not be grabbed, then we have reached the end of the video
2019-11-15 14:45:37 +00:00
if frame is None:
2019-11-23 11:14:19 +00:00
retry("frame was none")
2019-11-15 14:45:37 +00:00
# resize the frame, convert it to grayscale, and blur it
frame = imutils.resize(frame, width=500)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (31, 31), 0)
# if the first frame is None, initialize it
if firstFrame is None:
firstFrame = gray
continue
frameDelta = cv2.absdiff(gray, firstFrame)
thresh = cv2.threshold(frameDelta, threashold, 255, cv2.THRESH_BINARY)[1]
# dilate the thresholded image to fill in holes, then find contours
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# loop over the contours
for c in cnts:
2020-05-24 18:48:40 +00:00
if cv2.contourArea(c) < min_area or cv2.contourArea(c) > max_area:
2019-11-15 14:45:37 +00:00
continue
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = "Occupied"
# draw the text and timestamp on the frame
cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
2020-05-24 18:48:40 +00:00
2019-11-16 14:46:38 +00:00
if text == "Occupied" and config.monitor:
2019-11-15 14:45:37 +00:00
img = frame
2019-11-16 14:46:38 +00:00
location = com.saveImage(img)
2020-05-24 18:48:40 +00:00
_thread.start_new_thread(com.notify, (location, ) )
#com.notify(location)
2019-11-16 14:46:38 +00:00
2019-11-15 14:45:37 +00:00
counter+=1
if counter % (framerate * delay) == 0:
firstFrame = gray
2019-11-16 14:46:38 +00:00
2019-11-23 11:14:19 +00:00
except Exception as e:
2020-05-24 18:48:40 +00:00
traceback.print_exc()
2019-11-23 11:14:19 +00:00
retry(e)
2020-05-24 18:48:40 +00:00
2019-11-23 11:14:19 +00:00
def retry(error):
print(error)
time.sleep(10)
2020-01-02 22:23:03 +00:00
compare()