Beispiel #1
0
    def setup(self):
        bg_path = os.path.join(config.root, 'backgrounds')
        if not os.path.exists(bg_path):
            os.mkdir(bg_path)
            self.bgfile = os.path.join(bg_path, 'bg1.pkl')
        else:
            bgfiles = os.listdir(bg_path)
            bgfiles = sorted(
                bgfiles,
                key=lambda x: os.path.getmtime(os.path.join(bg_path, x)))

            # load the most recent bg file
            with open(os.path.join(bg_path, bgfiles[-1]), 'rb') as file:
                self.background = pickle.load(file)
            logger.debug('loaded background from ' + bgfiles[-1])

            # now make a new file
            ix = int(bgfiles[-1].split('.')[0].replace('bg', '')) + 1
            fn = os.path.join(bg_path, f'bg{ix}.pkl')
            while os.path.exists(fn):
                ix += 1
                fn = os.path.join(bg_path, f'bg{ix}.pkl')
            self.bgfile = fn
            self.save_bg()

        self.cam.resolution = (self._config['width'], self._config['height'])
        time.sleep(2)
Beispiel #2
0
 def fire(self, **kwargs):
     self.processing = True
     self.auto_filename()
     self.rename()
     if self.connect():
         logger.debug('Cleaning up.')
         self.clean()
     self.processing = False
Beispiel #3
0
 def tidy(self):
     untidy_files = [
         f for f in os.listdir(self.file_root) if f.endswith(self.filetype)
     ]
     logger.debug(f'Tidying up {len(untidy_files)} leftover files.')
     for f in untidy_files:
         self.path = os.path.join(self.file_root, f)
         self.connect()
         self.clean()
Beispiel #4
0
    def run(self, uploads=None, value2='', value3=''):
        payload = {
            'value1': uploads.get('s3', ''),
            'value2': value2,
            'value3': value3
        }

        requests.post(self._config['url'], payload)
        logger.debug('Sent payload to IFTTT notifier.')
Beispiel #5
0
 def auth(self):
     store = oauth2client.file.Storage(self._config['credential_path'])
     credentials = store.get()
     if not credentials or credentials.invalid:
         flow = client.flow_from_clientsecrets(
             self._config['client_secret'], self._config['scopes'])
         flow.user_agent = self._config['app_name']
         credentials = tools.run_flow(
             flow, store,
             argparse.ArgumentParser(
                 parents=[tools.argparser]).parse_args())
         logger.debug('Storing credentials to ' +
                      self._config['credential_path'])
     http = credentials.authorize(httplib2.Http())
     service = discovery.build('drive', 'v3', http=http)
     return service
Beispiel #6
0
 def run(self, file):
     _, filename = os.path.split(file)
     try:
         self.client.upload_file(file,
                                 self._config['bucket'],
                                 filename,
                                 ExtraArgs={'ACL': self._config['acl']})
     except Exception as e:
         logger.error(e)
     media_url = self.client.generate_presigned_url(
         'get_object',
         Params={
             'Bucket': self._config['bucket'],
             'Key': filename
         }).split('?')[0]
     logger.debug(f'Uploaded {file} to S3 object store: {media_url}')
     return media_url
Beispiel #7
0
    def run(self):
        raw_frame = PiRGBArray(self.cam, size=self.cam.resolution)
        vid_frames = []
        avg_centroids = []
        moving_frames = 0
        silent_frames = 0
        total_frames = 0
        total_time = 0
        fps = 0
        for f in self.cam.capture_continuous(raw_frame,
                                             format='bgr',
                                             use_video_port=True):
            start = dt.now()
            if not self.cont:
                break
            frame = f.array[
                int(480 *
                    self._config['crop_top']):int(480 *
                                                  self._config['crop_bottom']),
                int(640 *
                    self._config['crop_left']):int(640 *
                                                   self._config['crop_right'])]
            imgrey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            imgrey = cv2.GaussianBlur(imgrey, (21, 21), 0)
            if self.background is None:
                self.background = imgrey.copy().astype('float')
                self.save_bg()
                raw_frame.truncate(0)
                logger.debug('initialised background')
                continue

            cv2.accumulateWeighted(imgrey, self.background, 0.5)
            frame_delta = cv2.absdiff(imgrey,
                                      cv2.convertScaleAbs(self.background))
            frame_threshold = cv2.threshold(frame_delta, 20, 255,
                                            cv2.THRESH_BINARY)[1]
            frame_dilated = cv2.dilate(frame_threshold, None, iterations=10)
            contours, hier = cv2.findContours(frame_dilated, cv2.RETR_TREE,
                                              cv2.CHAIN_APPROX_SIMPLE)

            motion = [
                c for c in contours
                if cv2.contourArea(c) >= self._config['min_area']
            ]
            frame_centroids = []

            for c in motion:
                m = cv2.moments(c)
                cx = int(m['m10'] / m['m00'])
                frame_centroids.append(cx)

            if len(motion) == 0:
                if moving_frames != 0:
                    silent_frames += 1
                    if silent_frames == self._config['max_silent_frames']:
                        self._motion = False
                        if moving_frames >= self._config['min_moving_frames']:
                            logger.debug('movement ended')
                            try:
                                self.output(vid_frames,
                                            math.floor(fps * 0.6),
                                            centroids=avg_centroids)
                            except Exception as e:
                                logger.debug('failed to upload video')
                                logger.debug(e)
                        else:
                            logger.debug('false alarm, sorry')
                        self.save_bg()
                        moving_frames = 0
                        vid_frames.clear()
                        avg_centroids.clear()
                    else:
                        vid_frames.append(f.array)
                        avg_centroids.append(avg_centroids[-1])
            else:
                moving_frames += 1
                silent_frames = 0
                vid_frames.append(f.array)
                avg_centroids.append(np.mean(frame_centroids))
                if moving_frames == 1:
                    logger.debug('what was that??')
                if moving_frames == self._config['min_moving_frames']:
                    self._motion = True
                    logger.debug('movement detected')

            raw_frame.truncate(0)
            total_time += (dt.now() - start).total_seconds()
            total_frames += 1
            fps = total_frames / total_time
            frame_centroids.clear()
        self.cam.close()
        logger.debug('camera closed, thread terminated')
Beispiel #8
0
 def run(self, file):
     metadata = {'name': file}
     self.service.files().create(body=metadata, media_body=file).execute()
     logger.debug(f'Uploaded {file} to Google Drive.')
     return ''
Beispiel #9
0
 def rename(self):
     if os.path.exists(self.initial):
         os.rename(self.initial, self.path)
         logger.debug(f'renamed {self.initial} to {self.path}')