Ejemplo n.º 1
0
    def __init__(self,
                 path,
                 headless,
                 buffer_size,
                 codec,
                 fps,
                 net,
                 confidence,
                 frameCount=32,
                 notifier=None,
                 url=None,
                 debugmemory=False,
                 blocking=False):
        # initialize the video stream, allow the camera sensor to warm up,
        # and initialize the FPS counter
        print("[INFO] starting video stream...")
        self.vs = VideoStream(src=0).start()
        # vs = VideoStream(usePiCamera=True).start()
        time.sleep(2.0)
        self.fps = FPS().start()

        # initialize the key clip writer and the motionFrames
        # and consecFrames to track frames without motion
        self.buffer_size = buffer_size
        self.kcw = KeyClipWriter(bufSize=buffer_size)
        self.consecFrames = 0  # number of frames with no motion
        self.prev_detections = None

        # initialize the output frame and a lock used to ensure thread-safe
        # exchanges of the output frames (useful when multiple browsers/tabs
        # are viewing the stream)
        self.outputFrame = None
        self.lock = threading.Lock()

        self.path = path
        self.headless = headless
        self.codec = codec
        self.fps_rate = fps
        self.net = net
        self.confidence = confidence
        self.frameCount = frameCount
        self.notifier = notifier
        self.url = url
        self.debugmemory = debugmemory
        self.blocking = blocking

        if not self.blocking:
            self.inputQueue = Queue(maxsize=1)
            self.outputQueue = Queue(maxsize=1)
Ejemplo n.º 2
0
direction = ""

# TODO add "duration" to highlights. Currently only passes start time
# and assumes a constant time for highlight duration.
#class HighlightClass:
#  def __init__(self, time, duration):
#    self.time = time
#   self.duration = duration
highlight_duration = 4
state = ""
state_prev = ""
state_count = 0

# initialize key clip writer and the consecutive number of
# frames that have *not* contained any action
kcw = KeyClipWriter(bufSize=args["buffer_size"])
consecFrames = 0

# keep looping
while True:
    is_highlight = False
    # grab the current frame, resize it, and initialize a
    # boolean used to indicate if the consecutive frames
    # counter should be updated
    frame = vs.read()
    frame = imutils.resize(frame, width=600)
    updateConsecFrames = True

    # blur the frame and convert it to the HSV color space
    blurred = cv2.GaussianBlur(frame, (11, 11), 0)
    hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
Ejemplo n.º 3
0
import argparse
import datetime
import imutils
import time
import cv2

from upload import upload
from menu import Menu

mn = Menu()

print("[INFO] Esquentando a câmera")
vs = VideoStream(usePiCamera=mn.parametros['camera'] > 0).start()
time.sleep(2.0)

kcw = KeyClipWriter(mn.parametros['buffer'])
consecFrames = 0 #conta o numero de frames que não contém um evento de interesse

while True:

    #pega o frame atual, redimensiona
    frame = vs.read()
    frame = imutils.resize(frame, width = mn.parametros['resolucao_w'])
    updateConsecFrames = True

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord('q'): #finaliza o monitoramento
        break
    
	"GMG": cv2.bgsegm.createBackgroundSubtractorGMG,
	"MOG": cv2.bgsegm.createBackgroundSubtractorMOG,
	"GSOC": cv2.bgsegm.createBackgroundSubtractorGSOC,
	"LSBP": cv2.bgsegm.createBackgroundSubtractorLSBP
}

# create our background subtractor
fgbg = OPENCV_BG_SUBTRACTORS[conf["bg_sub"]]()

# create erosion and dilation kernels
eKernel = np.ones(tuple(conf["erode"]["kernel"]), "uint8")
dKernel = np.ones(tuple(conf["dilate"]["kernel"]), "uint8")

# initialize key clip writer, the consecutive number of frames without
# motion and frames since the last snapshot was written
kcw = KeyClipWriter(bufSize=conf["keyclipwriter_buffersize"])
framesWithoutMotion = 0
framesSinceSnap = 0

# begin capturing "ctrl + c" signals
signal.signal(signal.SIGINT, signal_handler)
images = " and images..." if conf["write_snaps"] else "..."
print("[INFO] detecting motion and storing videos{}".format(images))

# loop through the frames
while True:
	# grab a frame from the video stream
	fullFrame = vs.read()

	# if no frame was read, the stream has ended
	if fullFrame is None:
Ejemplo n.º 5
0
avg = None
peds = 0

#if dropbox is enabled initialize DB
if conf["use_dropbox"]:
    uploader = DBUpload(conf["dropbox_key"], conf["dropbox_secret"])

#initialize the video stream and let the camera warmup
logging.info("warming up camera...")
vs = VideoStream(usePiCamera=conf["picamera"]>0, resolution=(640,480)).start()
time.sleep(conf["camera_warmup_time"])


#initialize the key clip writer and the motionFrames
# and consecFrames to track frames without motion
kcw = KeyClipWriter(bufSize=conf["buffer_size"])
pDet = PedDetect()
consecFrames = 0 #number of frames with no motion
motionFrames = 0 #number of frames with motion
pedFrames = 0
boundingbox = [conf["resolution"][0],conf["resolution"][1],0,0] #motion detection x,y,w,h
p = ""
bbROIH = conf["HeightROIfactor"]
bbROIW = conf["WidthROIfactor"]

while True:
    #grab the current frame, resize, add status Text and timestamp
    frame = vs.read()
    frame = imutils.resize(frame, width=conf["resize_width"])
    timestamp = datetime.datetime.now()
    text = "Standby"
def detect_motion(outputDirectory):
    global vs, outputFrame, lock

    frameCount = 32
    md = SingleMotionDetector(accumWeight=0.1)
    total = 0

    recordedFrameCount = 0
    kcw = KeyClipWriter(bufSize=beforeAndAfterFrames)
    lastFileName = None

    while True:
        # read the next frame from the video stream, resize it,
        # convert the frame to grayscale, and blur it
        frame = vs.read()
        frame = imutils.resize(frame, width=600)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (7, 7), 0)

        # grab the current timestamp and draw it on the frame
        timestamp = datetime.datetime.now()
        cv2.putText(frame, timestamp.strftime("%A %d %B %Y %I:%M:%S%p"),
                    (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35,
                    (0, 255, 0), 1)

        # if the total number of frames has reached a sufficient
        # number to construct a reasonable background model, then
        # continue to process the frame
        if total > frameCount:

            kcw.update(frame)

            motion = md.detect(gray)

            # check to see if motion was found in the frame
            if motion is not None:
                # unpack the tuple and draw the box surrounding the
                # "motion area" on the output frame
                (thresh, (minX, minY, maxX, maxY)) = motion
                cv2.rectangle(frame, (minX, minY), (maxX, maxY), (0, 0, 255),
                              2)
                if kcw.recording is False:
                    recordedFrameCount = 0
                    timestamp = datetime.datetime.now()
                    lastFileName = "{}/{}.mp4".format(
                        outputDirectory, timestamp.strftime("%Y%m%d-%H%M%S"))
                    kcw.start(lastFileName, cv2.VideoWriter_fourcc(*"MP4V"),
                              fps)
                    logging.info("Started recording")

            if kcw.recording is True:
                recordedFrameCount += 1

                if recordedFrameCount > beforeAndAfterFrames:
                    logging.info("Stopped recording")
                    kcw.finish()
                    if lastFileName is not None:
                        ah.sendEvent(lastFileName)

        # update the background model and increment the total number
        # of frames read thus far
        md.update(gray)
        total += 1

        # acquire the lock, set the output frame, and release the
        # lock
        with lock:
            outputFrame = frame.copy()
Ejemplo n.º 7
0
def detect_motion(frameCount):
    # grab global references to the video stream, output frame, and
    # lock variables
    global vs, outputFrame, lock

    # initialize the motion detector and the total number of frames
    # read thus far
    md = SingleMotionDetector(accumWeight=0.1)
    total = 0

    # initialize KeyClipWriter, set counter for frames with no motion detected
    kcw = KeyClipWriter()
    consecFramesNoMotion = 0

    # loop over frames from the video stream
    while True:
        timestamp = datetime.datetime.now()
        text = "Unoccupied"
        # read the next frame from the video stream, resize it,
        # convert the frame to grayscale, and blur it
        frame = vs.read()
        frame = imutils.resize(frame, width=400)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (7, 7), 0)

        # if the total number of frames has reached a sufficient
        # number to construct a reasonable background model, then
        # continue to process the frame
        if total > frameCount:
            # detect motion in the image
            motion = md.detect(gray)

            # check to see if motion was found in the frame
            if motion is not None:
                # unpack the tuple and draw the box surrounding the
                # "motion area" on the output frame
                (thresh, (minX, minY, maxX, maxY)) = motion
                cv2.rectangle(frame, (minX, minY), (maxX, maxY), (0, 0, 255),
                              2)
                text = "Occupied"

                # send email to notify user of motion
                # send_email(timestamp)

                # motion has occured, so reset frames with no motion counter
                consecFramesNoMotion = 0
            else:
                consecFramesNoMotion += 1

            record_video(kcw, frame, motion, consecFramesNoMotion, timestamp)

        # grab the current timestamp and draw it on the frame
        cv2.putText(frame, timestamp.strftime("%A %d %B %Y %I:%M:%S%p"),
                    (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35,
                    (0, 0, 255), 1)
        cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

        # update the background model and increment the total number
        # of frames read thus far
        md.update(gray)
        total += 1

        # acquire the lock, set the output frame, and release the
        # lock
        with lock:
            outputFrame = frame.copy()
Ejemplo n.º 8
0
    # finish the authorization and grab the Dropbox client
    (accessToken, userID) = flow.finish(authCode)
    client = DropboxClient(accessToken)
    print("[SUCCESS] dropbox account linked")

# initialize the camera
vs = PiVideoStream(conf["resolution"], conf["fps"], conf["rotation"]).start()

# allow the camera to warmup, then initialize the average frame, last
# uploaded timestamp, and frame motion counter
print("[INFO] warming up...")
time.sleep(conf["camera_warmup_time"])

# initialize key clip writer and the consecutive number of
# frames that have *not* contained any action
kcw = KeyClipWriter(bufSize=conf["videobuffer"], timeout=0.01)
consecFrames = 0
recFrames = 0

avg = None
lastUploaded = datetime.datetime.now()
motionCounter = 0

cv2.namedWindow("Security Feed")
cv2.namedWindow("ctrl", cv2.WINDOW_NORMAL)
cv2.setMouseCallback("Security Feed", moveMask)
cv2.createTrackbar('1:Exit app', "ctrl", 0, 1, quit)
cv2.createTrackbar('Mask size', "ctrl", maskw, 255, setMaskSize)
cv2.createTrackbar('0:Off\n1:On', "ctrl", 0, 1, startDetect)
cv2.resizeWindow("ctrl", 300, 100)
cv2.moveWindow("ctrl", 500, 35)