コード例 #1
0
        it_frames = it_frames if it_frames < n_loaded_frames else 0
        update_image = True

    if key == ord(keymap['next_frame']):
        it_frames += 1
        it_frames = it_frames if it_frames < n_loaded_frames else 0

        altura_instantanea.append(altura_da_pessoa(localizations[it_frames]))
        log.info(" Altura: {}", altura_instantanea)

        if SkeletonsCoord.avg_limb_length(localizations[it_frames], links):
            joint = SkeletonsCoord.avg_limb_length(localizations[it_frames],
                                                   links)
            log.info("Joint: {}", joint)
        else:
            log.warn("Some joint was not found")

        update_image = True

    if key == ord(keymap['previous_frames']):
        it_frames -= keymap['big_step']
        it_frames = n_loaded_frames - 1 if it_frames < 0 else it_frames
        update_image = True

    if key == ord(keymap['previous_frame']):
        it_frames -= 1
        it_frames = n_loaded_frames - 1 if it_frames < 0 else it_frames
        update_image = True

    if key == ord(keymap["left_foot"]):
        initial_foot = "left"
コード例 #2
0
        new_requests = {}
        for cid in list(requests.keys()):
            request = requests[cid]
            if (request['requested_at'] + DEADLINE_SEC) > time.time():
                continue
            msg = Message(content=request['content'], reply_to=subscription)
            msg.timeout = DEADLINE_SEC
            channel.publish(msg, topic='SkeletonsDetector.Detect')
            new_requests[msg.correlation_id] = {
                'content': request['content'],
                'base_name': request['base_name'],
                'frame_id': request['frame_id'],
                'requested_at': time.time()
            }
            del requests[cid]
            log.warn("Message '{}' timeouted. Sending another request.", cid)

        requests.update(new_requests)
        state = State.MAKE_REQUESTS
        continue

    elif state == State.EXIT:

        log.info("Exiting...")
        sys.exit(-1)

    else:

        state = State.MAKE_REQUESTS
        continue
コード例 #3
0
    Loading CameraConfig protobuf from a json file
"""
with open('camera_config.json', 'r') as f:
    try:
        set_config = Parse(f.read(), CameraConfig())
        log.info('CameraConfig:\n{}', set_config)
    except Exception as ex:
        log.critical('Unable to camera settings. \n{}', ex)
"""
    Another way to create a CameraConfig message
"""
set_config = CameraConfig(
    sampling=SamplingSettings(frequency=FloatValue(value=5.0)),
    image=ImageSettings(
        resolution=Resolution(width=720, height=540),
        color_space=ColorSpace(value=ColorSpaces.Value('GRAY'))))

msg = Message()
msg.reply_to = subscription
msg.topic = 'CameraGateway.{}.SetConfig'.format(camera_id)
msg.pack(set_config)
channel.publish(msg)

while True:
    msg = channel.consume()
    if msg.status.code == StatusCode.OK:
        log.info('Configuration applied on camera \'{}\'.', camera_id)
    else:
        log.warn('Can\'t apply configuration:\n{}', msg.status)
    sys.exit(0)
コード例 #4
0
    folder = os.path.join(folder, args.foldername)

# get folder from each possible label
labels_folders = utils.get_label_folder(folder, labels)

# create a folder to store timestamps
timestamps_folder = os.path.join(labels_folders[label_id], "timestamps")
if not os.path.exists(timestamps_folder):
    os.makedirs(timestamps_folder)

sequence = "{:03d}".format(int(subject_id))
sequence_folder = os.path.join(labels_folders[label_id], sequence)

if os.path.exists(sequence_folder):
    log.warn(
        'Path to SUBJECT_ID={} LABEL={} ({}) already exists.\n \
      Would you like to proceed? All data will be deleted! [y/n]', subject_id,
        label_id, labels[label_id])
    key = input()
    if key == 'y':
        shutil.rmtree(sequence_folder)
    elif key == 'n':
        sys.exit(0)
    else:
        log.critical('Invalid command \'{}\', exiting.', key)
        sys.exit(-1)

os.makedirs(sequence_folder)

channel = Channel(op.broker_uri)
subscription = Subscription(channel)
コード例 #5
0
    log.critical("Invalid PERSON_ID: {}. Must be between 1 and 999.",
                 person_id)
    sys.exit(-1)

log.info("PERSON_ID: {} GESTURE_ID: {}", person_id, gesture_id)

options = load_options(print_options=False)

if not os.path.exists(options.folder):
    os.makedirs(options.folder)

sequence = 'p{:03d}g{:02d}'.format(person_id, gesture_id)
sequence_folder = os.path.join(options.folder, sequence)
if os.path.exists(sequence_folder):
    log.warn(
        'Path to PERSON_ID={} GESTURE_ID={} already exists.\nWould you like to proceed? All data will be deleted! [y/n]',
        person_id, gesture_id)
    key = input()
    if key == 'y':
        shutil.rmtree(sequence_folder)
    elif key == 'n':
        sys.exit(0)
    else:
        log.critical('Invalid command \'{}\', exiting.', key)
        sys.exit(-1)

os.makedirs(sequence_folder)

channel = Channel(options.broker_uri)
subscription = Subscription(channel)
for camera in options.cameras:
コード例 #6
0
class FramesLoader:
    def __init__(self, video_list, fps=10.0):
        """Given a list a video, uses MultipleVideoLoader object to loaded all videos and
        sample at spefic fps on a diferent thread.
        Args:
            video_list (dict): contais the path of all four video where the key identifies
            the ID of the camera.
            fps (float): frequency of sample of the video.
        """
        self.log = Logger("VideoLoaderThread")

        if len(video_list) == 0:
            self.log.warn("You are trying to initialize with a empty list of videos")

        self.video_loader = MultipleVideoLoader(video_list)
        self.num_samples = self.video_loader.n_frames()
        self.count_sample = 0
        self.fps = fps
        info = {
            "total_samples": self.num_samples
        }
        self.log.info('{}', str(info).replace("'", '"'))
        self.run = True
        self.queue = queue.Queue()
        self.thread = threading.Thread(target=self._reader, daemon=True)
        self.thread.start()

    def _reader(self):
        """Sample the videos and store on a Queue object.
        This is the target of the thread.
        """
        while self.run:
            t_o = time.time()
            _ = self.video_loader.load_next()
            frames = self.video_loader[0]
            if frames is not None:
                self.count_sample += 1
                if not self.queue.empty():
                    try:
                        self.queue.get_nowait()
                    except queue.Empty:
                        pass
                self.queue.put([self.count_sample, frames])
                self.video_loader.release_memory()
            if self.count_sample == self.num_samples:
                self.run = False
                break
            t_f = time.time()
            took_s = t_f - t_o
            dt = (1 / self.fps) - took_s
            if dt > 0:
                time.sleep(dt)

    def read(self):
        """Returns what it is stored at the Queue.
        That is a list, where the first position is the frame_id and
        the second position is a dictionary containing frames from all cameras at same time
        """
        return self.queue.get()

    def release(self):
        """Finish the thread
        """
        self.run = False
        with self.queue.mutex:
            self.queue.queue.clear()
        self.thread.join()
        self.video_loader.release_memory()
        del self.video_loader
コード例 #7
0
        log.info("{}/{}", it, (n_loaded - 1))
        print(len(labels), sorted(labels))

    if key == ord('s'):
        if it == 0 or it == (vl.n_frames() - 1):
            continue
        if it in labels:
            labels.remove(it)
        elif len(labels) < n_labels:
            labels.add(it)
        else:
            log.info("All gestures labeled. Press 'q' to quit and save")

    if key == ord('q'):
        if len(labels) < n_labels:
            log.warn('Only {} of {} gestures were set. Continue spoting!',
                     max(0, (int(len(labels) / 2) - 1)), len(gestures))
            continue

        fps = vl.fps()[0]
        labels_list = sorted(labels)
        spots = []

        g_id = 0
        for begin, end, g_id in zip(labels_list[1:-1:2], labels_list[2:-1:2],
                                    gestures.keys()):
            ss, t = begin / fps, (end - begin) / fps
            log.info('{} -> {} | {:.2f} {:.2f}', begin, end, ss, t)
            spots.append({"gesture": g_id, "ss": ss, "t": t})

        if os.path.exists("samples"):
            shutil.rmtree("samples")