Beispiel #1
0
 def __init__(self, size=10, frameRate=40, hflip=False, vflip=False):
     """A wrapper class for the Raspberry Pi camera using the picamera
     python library. The size parameter sets the camera resolution to
     size * (64, 48)."""
     self.active = False
     try:
         if type(size) is not int:
             raise TypeError("Size must be an integer")
         elif 1 <= size and size <= 51:
             self.size = size
             self.hRes = size * 64
             self.vRes = size * 48
         else:
             raise ValueError("Size must be in range 1 to 51")
     except TypeError or ValueError:
         raise
     self.picam = PiCamera()
     self.picam.resolution = (self.hRes, self.vRes)
     self.picam.framerate = frameRate
     self.picam.hflip = hflip
     self.picam.vflip = vflip
     time.sleep(1)
     self.stream = PiCameraCircularIO(self.picam, seconds=1)
     self.frameRateTimer = timer.Timer()
     self.frameRateFilter = filters.Filter1D(maxSize=21)
     self.start()
Beispiel #2
0
 def __init__(self, are_some_movement):
     logger.info("Building binoculars")
     self._lens = PiCamera()
     self._lens.rotation = 180
     self.buffer = PiCameraCircularIO(self._lens, seconds=PRESECONDS)
     self.watcher = Watcher(self._lens, are_some_movement)
     self.is_recording = False
Beispiel #3
0
    def __init__(self,
                 camera,
                 storage,
                 h264_args,
                 temporary_recordings_output_path="./temp_recordings/",
                 record_seconds_after_motion=12,
                 max_recording_seconds=600,
                 record_seconds_before_motion=5,
                 ffmpeg_path="/usr/local/bin/ffmpeg",
                 convert_h264_to_mp4=True):
        self.camera = camera
        self.storage = storage
        self.h264_args = h264_args
        self.temporary_recordings_output_path = temporary_recordings_output_path
        self.record_seconds_after_motion = record_seconds_after_motion
        self.max_recording_seconds = max_recording_seconds
        self.timer = 0
        self.record_seconds_before_motion = record_seconds_before_motion
        self.ffmpeg_path = ffmpeg_path
        self.convert_h264_to_mp4 = convert_h264_to_mp4

        # Make sure PiCameraCircularIO contains at least 20 seconds of footage. Since this is the minimum for it work.
        if record_seconds_before_motion > 20:
            delayed_storage_length_seconds = record_seconds_before_motion
        else:
            delayed_storage_length_seconds = 20
        # Create the delayed frames stream.
        self.delayed_recording_stream = PiCameraCircularIO(
            self.camera, seconds=delayed_storage_length_seconds)
        # For some reason the PiCameraCircularIO has to be on splitter_port 1. Splitter port 2 or 3 doesn't work.
        self.camera.start_recording(self.delayed_recording_stream,
                                    splitter_port=1,
                                    **h264_args)
Beispiel #4
0
def start_buffer_recording(camera, BITRATE, SHADOWPLAY_TIME):
    print("Creating shadowplay circular buffer...")
    shadowplay_stream = PiCameraCircularIO(
        camera, seconds=ceil(SHADOWPLAY_TIME / 4.2)
    )  #divide by 4 because bitrate is so low it would record way more (fourth of normal bitrate so 10s buffer would actually be 40s)
    camera.start_recording(
        shadowplay_stream, format='h264', bitrate=BITRATE,
        splitter_port=1)  #,bitrate=BITRATE) #,splitter_port=2)
    return shadowplay_stream
def start(cam):

    # setup globals
    global camera, stream
    camera = cam

    stream = PiCameraCircularIO(camera, seconds=record_time_before_detection)
    camera.start_recording(stream, format='h264')

    camera.wait_recording(5)  # make sure recording is loaded
    print("recording initialized")
    def run(self):
        with PiCamera() as camera:
            count = 0
            camera.resolution = (1280, 720)
            stream = PiCameraCircularIO(camera, seconds=10)
            camera.start_recording(stream, format='h264')
            try:
                camera.wait_recording(3)
                while True:
                    camera.wait_recording(0)
                    if self.detect_motion(camera):
                        print('Motion detected!')

                        if not self.dryrun:
                            timestamp = datetime.now().isoformat('_')

                            # As soon as we detect motion, split the recording to
                            # record the frames "after" motion
                            camera.split_recording(
                                '{}_capture_{:04d}.h264'.format(
                                    timestamp, count))
                            # Write the 10 seconds "before" motion to disk as well
                            stream.copy_to('{}_before_{:04d}.h264'.format(
                                timestamp, count),
                                           seconds=10)

                        stream.clear()

                        # Wait until motion is no longer detected, then split
                        # recording back to the in-memory circular buffer
                        while self.detect_motion(camera):
                            camera.wait_recording(0)

                        print('Motion stopped!')
                        camera.split_recording(stream)

                        count += 1

                    if user_freespace_gb() < 0.5:
                        print("CLosing program to avoid using all free space.")
                        print("There is {} GB remaining.".format(
                            user_freespace_gb()))
                        break

            except KeyboardInterrupt:
                print("Stopped")

            finally:
                camera.stop_recording()

                print("Motion detection values:")
                print("\tMin: {}".format(self.result_min))
                print("\tMax: {}".format(self.result_max))
                print("\tAvg: {}".format(self.result_avg))
    def __init__(self):
        # TODO: Make resolution configurable
        # Initialize the camera
        self.camera = PiCamera()
        self.camera.resolution = (1280, 720)

        # Record to a circular stream for retroactive recording
        self.stream = PiCameraCircularIO(self.camera,
                                         seconds=sum(
                                             CameraHandler.retroactive_time))

        # Start recording
        self.camera.start_recording(self.stream, format='h264')
Beispiel #8
0
    def __init__(self, width=640, height=480):
        frame_rate_calc = 1
        freq = cv2.getTickFrequency()
        font = cv2.FONT_HERSHEY_SIMPLEX
        self.IM_WIDTH = width
        self.IMG_HEIGHT = height
        self.objectsOfInterest = [
            'person', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'bear',
            'teddy bear'
        ]
        self.minScore = 0.40
        ipv4 = os.popen('ip addr show eth0').read().split("inet ")[1].split(
            "/")[0]
        self.camId = ipv4[-3:]
        self.imageSaveDeltaSeconds = 10
        self.videoLoopSeconds = 5
        self.videoPreRecordSeconds = 1.5
        self.lastImageSaveTime = time.time()
        self.lastVideoSaveTime = time.time()
        self.saveVideoAtTime = time.time()
        self.videoLoopFlag = 0  # used  to indicate that the current stream will need to be recorded

        # load in the graph and muddle with the default graph
        # this setup allows the same session to be used throughout
        # tf_session is *not* thread-safe
        self.graph = tf.Graph()
        with self.graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')

        self.tf_session = tf.Session(graph=self.graph)

        self.camera = PiCamera(resolution=(width, height), framerate=30)

        #Brittany added for circular stream
        self.stream = PiCameraCircularIO(self.camera,
                                         seconds=5)  #self.videoLoopSeconds)
        #self.camera.stop_recording()
        self.camera.start_recording(self.stream, format='h264')

        # Capture and set all to zero to get a blank array of the right size
        self._frame = PiRGBArray(self.camera, size=(width, height))
        self._frame.truncate(0)
Beispiel #9
0
 def __init__(self, size=10, frameRate=40, horizontalflip=False, verticalflip=False):
     from picamera import PiCamera, PiCameraCircularIO
     self.active = False
     try:
         if type(size) is not int:
             raise TypeError("Size must be an integer")
         elif 1 <= size and size <= 51:
             self.size = size
             self.horizontal_resolution = size * 64
             self.vertical_resolution = size * 48
         else:
             raise ValueError("Size must be in range 1 to 51")
     except TypeError or ValueError:
         raise
     self.picam = PiCamera()
     self.picam.resolution = (self.horizontal_resolution, self.vertical_resolution)
     self.picam.framerate = frameRate
     self.picam.horizontalflip = horizontalflip
     self.picam.verticalflip = verticalflip
     time.sleep(1)
     self.stream = PiCameraCircularIO(self.picam, seconds=1)
     self.frameRateTimer = Timer()
     self.frameRateFilter = Filter1D(maxSize=21)
     self.start()

## Set initial values (while camera warms up)
result, magnitude = False, 0

with PiCamera() as camera:
    with DetectMotion(camera) as output:
        global current_status
        """Set initial twilight settings and camera attributes.
		   Setup stream, start recording, then wait five seconds
		   for the camera to warm up (reduce false positives)."""
        prior_status, illumination = _check_twilight()
        #print prior_status, illumination
        camera = _set_attributes(prior_status, camera)[1]
        sleep(5)
        stream = PiCameraCircularIO(camera, seconds=seconds)
        camera.start_recording(stream, format=formats[0], motion_output=output)
        try:
            while True:
                """Update twilight status and check if current status 
				   is the same as prior status. If it is, then simply 
				   check for motion. If not, then daylight has changed
				   and we must update camera attributes."""
                current_status, illumination = _check_twilight(illumination)
                if current_status == prior_status:
                    """Implement camera.wait_recording(1) to wait on the 
					   video encoder for 1 timeout second. Modify timeout
					   seconds as necessary for your specific application."""
                    if result:
                        """If result, motion detected. Capture start time, 
						   set file name, record magnnitude of motion, and