code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def __init__(self, model_adapter, configuration=None, preload=False): '''Model constructor Args: model_adapter (ModelAdapter): allows working with the specified executor configuration (dict, optional): it contains values for parameters accepted by specific wrapper ...
Model constructor Args: model_adapter (ModelAdapter): allows working with the specified executor configuration (dict, optional): it contains values for parameters accepted by specific wrapper (`confidence_threshold`, `labels` etc.) which are set as data attributes ...
__init__
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/model.py
Apache-2.0
def __call__(self, inputs): ''' Applies preprocessing, synchronous inference, postprocessing routines while one call. Args: inputs: raw input data, the data type is defined by wrapper Returns: - postprocessed data in the format defined by wrapper - t...
Applies preprocessing, synchronous inference, postprocessing routines while one call. Args: inputs: raw input data, the data type is defined by wrapper Returns: - postprocessed data in the format defined by wrapper - the input metadata obtained from `prepro...
__call__
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/model.py
Apache-2.0
def log_layers_info(self): '''Prints the shape, precision and layout for all model inputs/outputs. ''' for name, metadata in self.inputs.items(): self.logger.info('\tInput layer: {}, shape: {}, precision: {}, layout: {}'.format( name, metadata.shape, metadata.precisio...
Prints the shape, precision and layout for all model inputs/outputs.
log_layers_info
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/model.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/model.py
Apache-2.0
def permute_to_N_HWA_K(tensor, K, output_layout): """ Transpose/reshape a tensor from (N, (A x K), H, W) to (N, (HxWxA), K) """ assert tensor.ndim == 4, tensor.shape if output_layout == 'NHWC': tensor = tensor.transpose(0, 3, 1, 2) N, _, H, W = tensor.shape tensor = tensor.reshape(N,...
Transpose/reshape a tensor from (N, (A x K), H, W) to (N, (HxWxA), K)
permute_to_N_HWA_K
python
openvinotoolkit/open_model_zoo
demos/common/python/model_zoo/model_api/models/yolo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/model_zoo/model_api/models/yolo.py
Apache-2.0
def strip_internal_spaces(text): """ Removes spaces between digits, digit and dot, dot and digit; after opening brackets and parentheses and before closing ones; spaces around ^ symbol. """ text = text.replace("{ ", "{") text = text.replace(" }", "}") text = text.replace("( ", "(") t...
Removes spaces between digits, digit and dot, dot and digit; after opening brackets and parentheses and before closing ones; spaces around ^ symbol.
strip_internal_spaces
python
openvinotoolkit/open_model_zoo
demos/formula_recognition_demo/python/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/formula_recognition_demo/python/utils.py
Apache-2.0
def create_renderer(): """ Checks if pdflatex is installed and rendering of latex formula could be performed """ command = subprocess.run(["pdflatex", "--version"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, shell=True) # shell=True is used to pro...
Checks if pdflatex is installed and rendering of latex formula could be performed
create_renderer
python
openvinotoolkit/open_model_zoo
demos/formula_recognition_demo/python/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/formula_recognition_demo/python/utils.py
Apache-2.0
def preprocess_image(preprocess, image_raw, tgt_shape): """ Crop or resize with constant aspect ratio and bottom right pad resulting image """ target_height, target_width = tgt_shape image_raw = preprocess(image_raw, tgt_shape) img_h, img_w = image_raw.shape[0:2] image_raw = cv.copyMakeB...
Crop or resize with constant aspect ratio and bottom right pad resulting image
preprocess_image
python
openvinotoolkit/open_model_zoo
demos/formula_recognition_demo/python/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/formula_recognition_demo/python/utils.py
Apache-2.0
def change_layout(model_input): """ Change layout of the image from [H, W, C] to [N, C, H, W] where N is equal to one (batch dimension) """ model_input = model_input.transpose((2, 0, 1)) model_input = np.expand_dims(model_input, axis=0) return model_input
Change layout of the image from [H, W, C] to [N, C, H, W] where N is equal to one (batch dimension)
change_layout
python
openvinotoolkit/open_model_zoo
demos/formula_recognition_demo/python/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/formula_recognition_demo/python/utils.py
Apache-2.0
def render(self, formula): """ Synchronous method. Returns rendered image and text of the formula, corresponding to the rendered image when rendering is done. """ if self.cur_formula is None: self.cur_formula = formula elif self.cur_formula == formula: ...
Synchronous method. Returns rendered image and text of the formula, corresponding to the rendered image when rendering is done.
render
python
openvinotoolkit/open_model_zoo
demos/formula_recognition_demo/python/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/formula_recognition_demo/python/utils.py
Apache-2.0
def thread_render(self, formula): """ Provides asynchronous interface to the rendering process. In contrast with the self.render, this one returns image and formula only when rendering is complete. If rendering is incomplete at the moment of method call, method returns None """ ...
Provides asynchronous interface to the rendering process. In contrast with the self.render, this one returns image and formula only when rendering is complete. If rendering is incomplete at the moment of method call, method returns None
thread_render
python
openvinotoolkit/open_model_zoo
demos/formula_recognition_demo/python/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/formula_recognition_demo/python/utils.py
Apache-2.0
def construct_phrase(self, indices): """Function to get latex formula from sequence of tokens Args: indices (list): sequence of int Returns: str: decoded formula """ phrase_converted = [] for token in indices: if token == END_TOKEN: ...
Function to get latex formula from sequence of tokens Args: indices (list): sequence of int Returns: str: decoded formula
construct_phrase
python
openvinotoolkit/open_model_zoo
demos/formula_recognition_demo/python/utils.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/formula_recognition_demo/python/utils.py
Apache-2.0
def _convert_to_central_roi(src_roi, input_height, input_width, img_scale): """Extracts from the input ROI the central square part with specified side size""" src_roi_height, src_roi_width = src_roi[3] - src_roi[1], src_roi[2] - src_roi[0] src_roi_center_x = 0.5 * (src_roi[0] + src_roi[2]) ...
Extracts from the input ROI the central square part with specified side size
_convert_to_central_roi
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/action_recognizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/action_recognizer.py
Apache-2.0
def _process_image(self, input_image, roi): """Converts input image according to model requirements""" cropped_image = input_image[roi[1]:roi[3], roi[0]:roi[2]] resized_image = cv2.resize(cropped_image, (self.input_width, self.input_height)) out_image = cv2.cvtColor(resized_image, cv2.C...
Converts input image according to model requirements
_process_image
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/action_recognizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/action_recognizer.py
Apache-2.0
def _prepare_net_input(self, images, roi): """Converts input sequence of images into blob of data""" data = np.stack([self._process_image(img, roi) for img in images], axis=0) data = data.reshape((1,) + data.shape) data = np.transpose(data, (0, 2, 1, 3, 4)) return data
Converts input sequence of images into blob of data
_prepare_net_input
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/action_recognizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/action_recognizer.py
Apache-2.0
def __call__(self, frame_buffer, person_roi): """Runs model on the specified input""" central_roi = self._convert_to_central_roi(person_roi, self.input_height, self.input_width, self.img_scale) ...
Runs model on the specified input
__call__
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/action_recognizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/action_recognizer.py
Apache-2.0
def wait_request(self, req_id): """Waits for the model output by the specified request ID""" self.infer_queue[req_id].wait() return self.outputs.pop(req_id, None)
Waits for the model output by the specified request ID
wait_request
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/common.py
Apache-2.0
def _prepare_frame(self, frame): """Converts input image according model requirements""" initial_h, initial_w = frame.shape[:2] scale_h, scale_w = initial_h / float(self.input_height), initial_w / float(self.input_width) in_frame = cv2.resize(frame, (self.input_width, self.input_height...
Converts input image according model requirements
_prepare_frame
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/person_detector.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/person_detector.py
Apache-2.0
def _process_output(self, result): """Converts network output to the internal format""" scale_h, scale_w = self.last_scales if result.shape[-1] == 5: # format: [xmin, ymin, xmax, ymax, conf] return np.array([[scale_w, scale_h, scale_w, scale_h, 1.0]]) * result else: # for...
Converts network output to the internal format
_process_output
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/person_detector.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/person_detector.py
Apache-2.0
def async_infer(self, frame, req_id): """Requests model inference for the specified image""" in_frame, scale_h, scale_w = self._prepare_frame(frame) self.last_scales = scale_h, scale_w super().async_infer(in_frame, req_id)
Requests model inference for the specified image
async_infer
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/person_detector.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/person_detector.py
Apache-2.0
def _matrix_iou(set_a, set_b): """Computes IoU metric for the two sets of vectors""" intersect_ymin = np.maximum(set_a[:, 0].reshape([-1, 1]), set_b[:, 0].reshape([1, -1])) intersect_xmin = np.maximum(set_a[:, 1].reshape([-1, 1]), set_b[:, 1].reshape([1, -1])) intersect_ymax = np.minimu...
Computes IoU metric for the two sets of vectors
_matrix_iou
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/tracker.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/tracker.py
Apache-2.0
def filter_rois(new_rois, score_threshold): """Filters input ROIs by valid height/width and score threshold values""" heights = new_rois[:, 2] - new_rois[:, 0] widths = new_rois[:, 3] - new_rois[:, 1] valid_sizes_mask = np.logical_and(heights > 0.0, widths > 0.0) valid_conf_mask...
Filters input ROIs by valid height/width and score threshold values
filter_rois
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/tracker.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/tracker.py
Apache-2.0
def _track(self, last_detections, new_rois): """Updates current tracks according new observations""" filtered_rois, filtered_conf = self.filter_rois(new_rois, self._score_threshold) if filtered_rois.shape[0] == 0: out_detections = [] for det in last_detections: ...
Updates current tracks according new observations
_track
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/tracker.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/tracker.py
Apache-2.0
def add_frame(self, frame, max_num_detections, labels_map): """Adds new detections and returns active tracks""" self._detector.async_infer(frame, self._next_req_id) new_rois = self._detector.wait_request(self._cur_req_id) self._cur_req_id, self._next_req_id = self._next_req_id, self._cu...
Adds new detections and returns active tracks
add_frame
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/tracker.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/tracker.py
Apache-2.0
def parse_source_paths(input_dir, valid_names): """Returns the list of valid video sources""" valid_names = {n.lower() for n in valid_names} all_file_paths = [f for f in listdir(input_dir) if isfile(join(input_dir, f))] all_file_paths.sort() out_file_paths = [] for file...
Returns the list of valid video sources
parse_source_paths
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
Apache-2.0
def next(self): """Moves pointer to the next video source""" with self.cur_source_id.get_lock(): self.cur_source_id.value += 1 if self.cur_source_id.value >= self.num_sources: self.cur_source_id.value = 0
Moves pointer to the next video source
next
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
Apache-2.0
def prev(self): """Moves pointer to the previous video source""" with self.cur_source_id.get_lock(): self.cur_source_id.value -= 1 if self.cur_source_id.value < 0: self.cur_source_id.value = self.num_sources - 1
Moves pointer to the previous video source
prev
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
Apache-2.0
def release(self): """Stops playing and releases internal storages""" if self._play_process is not None: self._play_process.terminate() self._play_process.join() self._play_process = None
Stops playing and releases internal storages
release
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
Apache-2.0
def _play(visualizer_queue, cur_source_id, source_paths, max_image_size, trg_time_step): """Produces live frame from the active video source""" cap = None last_source_id = cur_source_id.value while True: start_time = time.perf_counter() if cur_source_id.value !...
Produces live frame from the active video source
_play
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_library.py
Apache-2.0
def get_live_frame(self): """Returns last live frame from the input stream""" if self._source_finished.value: return None with self._raw_frame.get_lock(): buffer = np.frombuffer(self._raw_frame.get_obj(), dtype=np.uint8) frame = np.copy(buffer.reshape(self._...
Returns last live frame from the input stream
get_live_frame
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_stream.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_stream.py
Apache-2.0
def get_batch(self): """Returns last batch of frames with constant framerate from the input stream""" if self._source_finished.value: return None with self._slow_batch.get_lock(): buffer = np.frombuffer(self._slow_batch.get_obj(), dtype=np.uint8) batch = np....
Returns last batch of frames with constant framerate from the input stream
get_batch
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_stream.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_stream.py
Apache-2.0
def _frame_generator(input_source, out_frame, frame_shape, finish_flag): """Produces live frames from the input stream""" cap = cv2.VideoCapture(input_source) cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) source_fps = cap.get(cv2.CAP_PROP_FPS) if source_fps > 0: trg_time_step...
Produces live frames from the input stream
_frame_generator
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_stream.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_stream.py
Apache-2.0
def _producer(input_frame, out_frame, out_batch, trg_fps, batch_size, image_shape, finish_flag): """Produces frames and batch of frames with constant framerate from the internal stream of frames""" trg_time_step = 1.0 / float(trg_fps) batch_shape = [batch_size] + image_shape ...
Produces frames and batch of frames with constant framerate from the internal stream of frames
_producer
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/video_stream.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/video_stream.py
Apache-2.0
def register_window(self, name): """Allocates resources for the new window""" if self._worker_process is not None and self._worker_process.is_alive(): raise RuntimeError('Cannot add the window for running visualizer') self._tasks[name] = Queue(1)
Allocates resources for the new window
register_window
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/visualizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/visualizer.py
Apache-2.0
def get_key(self): """Returns the value of pressed key""" with self._last_key.get_lock(): out_key = self._last_key.value self._last_key.value = -1 return out_key
Returns the value of pressed key
get_key
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/visualizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/visualizer.py
Apache-2.0
def put_queue(self, frame, name): """Adds frame in the queue of the specified window""" if name not in self._tasks.keys(): raise ValueError('Cannot show unregistered window: {}'.format(name)) self._tasks[name].put(np.copy(frame), True)
Adds frame in the queue of the specified window
put_queue
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/visualizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/visualizer.py
Apache-2.0
def _worker(tasks, last_key, trg_time_step, need_stop): """Shows new frames in appropriate screens""" while not need_stop.value: start_time = time.perf_counter() for name, frame_queue in tasks.items(): if not frame_queue.empty(): frame = fram...
Shows new frames in appropriate screens
_worker
python
openvinotoolkit/open_model_zoo
demos/gesture_recognition_demo/python/gesture_recognition_demo/visualizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/gesture_recognition_demo/python/gesture_recognition_demo/visualizer.py
Apache-2.0
def propagate_ids(previous_poses, current_poses, threshold=3): """Propagate poses ids from previous frame results. Id is propagated, if there are at least `threshold` similar keypoints between pose from previous frame and current. :param previous_poses: poses from previous frame with ids :param current...
Propagate poses ids from previous frame results. Id is propagated, if there are at least `threshold` similar keypoints between pose from previous frame and current. :param previous_poses: poses from previous frame with ids :param current_poses: poses from current frame to assign ids :param threshold: m...
propagate_ids
python
openvinotoolkit/open_model_zoo
demos/human_pose_estimation_3d_demo/python/modules/pose.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/human_pose_estimation_3d_demo/python/modules/pose.py
Apache-2.0
def time_elapsed(func, *args): """ Auxiliary function that helps measure elapsed time. """ start_time = perf_counter() res = func(*args) elapsed = perf_counter() - start_time return elapsed, res
Auxiliary function that helps measure elapsed time.
time_elapsed
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo.py
Apache-2.0
def max_central_square_crop(image): ''' Makes max-sized central squared crop. ''' height, width = image.shape[:2] if width > height: image = image[:, (width - height) // 2:(width - height) // 2 + height] else: image = image[(height - width) // 2:(height - width) // 2 + width, :] r...
Makes max-sized central squared crop.
max_central_square_crop
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/common.py
Apache-2.0
def crop_resize(image, input_size): ''' Makes max-sized central crop, resizes to input_size ''' image = max_central_square_crop(image) image = cv2.resize(image, (input_size, input_size)) image = np.expand_dims(image, axis=0) return image
Makes max-sized central crop, resizes to input_size
crop_resize
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/common.py
Apache-2.0
def central_crop(image, divide_by, shift): ''' Makes central crops dividing input image by number of equal cells. ''' height, width = image.shape[0:2] image = image[height // divide_by * shift: height // divide_by * (divide_by - shift), width // divide_by * shift: width // divide_by * (di...
Makes central crops dividing input image by number of equal cells.
central_crop
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/common.py
Apache-2.0
def predict(self, image): ''' Takes input image and returns L2-normalized embedding vector. ''' if self.model.input(self.input_tensor_name).shape[1] == 3: image = np.transpose(image, (0, 3, 1, 2)) input_data = {self.input_tensor_name: image} return self.infer_request.infer(i...
Takes input image and returns L2-normalized embedding vector.
predict
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/image_retrieval.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/image_retrieval.py
Apache-2.0
def compute_embedding(self, image): ''' Takes input image and computes embedding vector. ''' image = crop_resize(image, self.input_size) embedding = self.model.predict(image) return embedding
Takes input image and computes embedding vector.
compute_embedding
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/image_retrieval.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/image_retrieval.py
Apache-2.0
def search_in_gallery(self, embedding): ''' Takes input embedding vector and searches it in the gallery. ''' distances = cosine_distances(embedding, self.embeddings).reshape([-1]) sorted_indexes = np.argsort(distances) return sorted_indexes, distances
Takes input embedding vector and searches it in the gallery.
search_in_gallery
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/image_retrieval.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/image_retrieval.py
Apache-2.0
def compute_gallery_embeddings(self): ''' Computes embedding vectors for the gallery. ''' images = [] for full_path in tqdm(self.impaths, desc='Reading gallery images.'): image = cv2.imread(full_path) if image is None: log.error("Cannot find image, full_...
Computes embedding vectors for the gallery.
compute_gallery_embeddings
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/image_retrieval.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/image_retrieval.py
Apache-2.0
def __next__(self): """ Returns cropped frame (ROI) and original frame with ROI drawn as a rectangle. """ frame = self.cap.read() if frame is None: raise StopIteration view_frame = frame.copy() bbox = self.roi_detector.handle_frame(frame) if bbox is not No...
Returns cropped frame (ROI) and original frame with ROI drawn as a rectangle.
__next__
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/roi_detector_on_video.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/roi_detector_on_video.py
Apache-2.0
def add_top10_gallery_images(demo_image, impaths, distances, input_image, target_pos): """ Add top-10 most similar images from the gallery to demo image. """ for index, impath in enumerate(impaths[:10]): image = cv2.imread(impath) image = cv2.resize(image, (SIZE, SIZE)) h_shift = 2 * B...
Add top-10 most similar images from the gallery to demo image.
add_top10_gallery_images
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/visualizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/visualizer.py
Apache-2.0
def visualize(image, target_pos, impaths, distances, input_size, compute_embedding_time, search_in_gallery_time, imshow_delay, presenter, no_show=False): """ Visualizes input video frame with detected ROI and top-10 most similar images from the gallery. """ input_image = cv2.resize(image,...
Visualizes input video frame with detected ROI and top-10 most similar images from the gallery.
visualize
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/visualizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/visualizer.py
Apache-2.0
def get_rect_br(rect): """ Returns namedtuple Point that is bottom-right corner of the given namedtuple Rect """ tl_x, tl_y, w, h = rect return Point(tl_x + w - 1, tl_y + h - 1)
Returns namedtuple Point that is bottom-right corner of the given namedtuple Rect
get_rect_br
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
Apache-2.0
def handle_image(self, frame, prev_frame): """ The method receives the current frame and the previous frame and updates the field total_v that stores the estimates regular motion on the last frames of the video sequence. """ begin_work_time = datetime.datetime.now() ...
The method receives the current frame and the previous frame and updates the field total_v that stores the estimates regular motion on the last frames of the video sequence.
handle_image
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
Apache-2.0
def handle_frame(self, frame, prev_frame, frame_id): """ The method receives frame, the previous frame, and the frame number, and returns roi where there is some regular motion on several last frames of the video sequence. """ if self.frame_size is None: h, w = frame....
The method receives frame, the previous frame, and the frame number, and returns roi where there is some regular motion on several last frames of the video sequence.
handle_frame
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
Apache-2.0
def __init__(self, frame_step): """ Constructor. The only parameter of the constructor is frame step that should be used during detection. The value depends on the frame rate of the input video. The recommended value for video stream with frame rate 30 frames per second is frame_...
Constructor. The only parameter of the constructor is frame step that should be used during detection. The value depends on the frame rate of the input video. The recommended value for video stream with frame rate 30 frames per second is frame_step=5.
__init__
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
Apache-2.0
def handle_frame(self, frame): """ The main method of the class. The frames should be passed to the method with a constant frame rate (~30 frames per second). The method returns * either bounding box of detected ROI, (in this case it returns bounding box as nam...
The main method of the class. The frames should be passed to the method with a constant frame rate (~30 frames per second). The method returns * either bounding box of detected ROI, (in this case it returns bounding box as namedtuple Rect), * or None if it can...
handle_frame
python
openvinotoolkit/open_model_zoo
demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/image_retrieval_demo/python/image_retrieval_demo/roi_cv_detector/detect_by_simple_dense_optical_flow.py
Apache-2.0
def __call__(self, sentence, remove_repeats=True): """ Main translation method. Arguments: sentence (str): sentence for translate. remove_repeats (bool): remove repeated words. Returns: translation (str): translated sentence. """ tokens = sel...
Main translation method. Arguments: sentence (str): sentence for translate. remove_repeats (bool): remove repeated words. Returns: translation (str): translated sentence.
__call__
python
openvinotoolkit/open_model_zoo
demos/machine_translation_demo/python/machine_translation_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/machine_translation_demo/python/machine_translation_demo.py
Apache-2.0
def decode(self, tokens, remove_repeats=True): """ Decode method for tokens. Arguments: tokens (np.array): sentence in tokenized format. remove_repeats (bool): remove repeated words. Returns: sentence (str): output sentence. """ sentence = se...
Decode method for tokens. Arguments: tokens (np.array): sentence in tokenized format. remove_repeats (bool): remove repeated words. Returns: sentence (str): output sentence.
decode
python
openvinotoolkit/open_model_zoo
demos/machine_translation_demo/python/machine_translation_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/machine_translation_demo/python/machine_translation_demo.py
Apache-2.0
def _extend_tokens(self, tokens): """ Extend tokens. Arguments: tokens (np.array): sentence in tokenized format. Returns: tokens (np.array): extended tokens. """ tokens = [self.idx['<s>']] + tokens + [self.idx['</s>']] pad_length = self.max_token...
Extend tokens. Arguments: tokens (np.array): sentence in tokenized format. Returns: tokens (np.array): extended tokens.
_extend_tokens
python
openvinotoolkit/open_model_zoo
demos/machine_translation_demo/python/machine_translation_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/machine_translation_demo/python/machine_translation_demo.py
Apache-2.0
def _remove_repeats(self, sentence): """ Remove repeated words. Arguments: sentence (str): sentence. Returns: sentence (str): sentence in lowercase without repeated words. """ tokens = sentence.lower().split() return " ".join(key for key, _ in it...
Remove repeated words. Arguments: sentence (str): sentence. Returns: sentence (str): sentence in lowercase without repeated words.
_remove_repeats
python
openvinotoolkit/open_model_zoo
demos/machine_translation_demo/python/machine_translation_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/machine_translation_demo/python/machine_translation_demo.py
Apache-2.0
def main(): """Computes MOT metrics for the multi camera multi person tracker""" parser = argparse.ArgumentParser(description='Multi camera multi person \ tracking visualization demo script') parser.add_argument('--history_file', type=str, default='', requir...
Computes MOT metrics for the multi camera multi person tracker
main
python
openvinotoolkit/open_model_zoo
demos/multi_camera_multi_target_tracking_demo/python/run_evaluate.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/multi_camera_multi_target_tracking_demo/python/run_evaluate.py
Apache-2.0
def main(): """Visualize the results of the multi camera multi person tracker demo""" parser = argparse.ArgumentParser(description='Multi camera multi person \ tracking visualization demo script') parser.add_argument('-i', type=str, nargs='+', ...
Visualize the results of the multi camera multi person tracker demo
main
python
openvinotoolkit/open_model_zoo
demos/multi_camera_multi_target_tracking_demo/python/run_history_visualize.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/multi_camera_multi_target_tracking_demo/python/run_history_visualize.py
Apache-2.0
def forward(self, img): """Performs forward pass of the wrapped model""" self.forward_async(img, 0) self.infer_queue.wait_all() return self.outputs.pop(0)
Performs forward pass of the wrapped model
forward
python
openvinotoolkit/open_model_zoo
demos/multi_camera_multi_target_tracking_demo/python/utils/ie_tools.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/multi_camera_multi_target_tracking_demo/python/utils/ie_tools.py
Apache-2.0
def load_model(self, core, model_path, device, model_type, num_reqs=1): """Loads a model in the OpenVINO Runtime format""" log.info('Reading {} model {}'.format(model_type, model_path)) self.model = core.read_model(model_path) if len(self.model.inputs) not in self.get_allowed_inputs_le...
Loads a model in the OpenVINO Runtime format
load_model
python
openvinotoolkit/open_model_zoo
demos/multi_camera_multi_target_tracking_demo/python/utils/ie_tools.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/multi_camera_multi_target_tracking_demo/python/utils/ie_tools.py
Apache-2.0
def forward(self, batch): """Performs forward of the underlying network on a given batch""" assert len(batch) <= self.max_reqs for id, frame in enumerate(batch): super().forward_async(frame, id) outputs = self.grab_all_async() _remove_batch_dim_from_each_element_becau...
Performs forward of the underlying network on a given batch
forward
python
openvinotoolkit/open_model_zoo
demos/multi_camera_multi_target_tracking_demo/python/utils/network_wrappers.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/multi_camera_multi_target_tracking_demo/python/utils/network_wrappers.py
Apache-2.0
def forward_async(self, batch): """Performs async forward of the underlying network on a given batch""" assert len(batch) <= self.max_reqs for frame in batch: super().forward_async(frame)
Performs async forward of the underlying network on a given batch
forward_async
python
openvinotoolkit/open_model_zoo
demos/multi_camera_multi_target_tracking_demo/python/utils/network_wrappers.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/multi_camera_multi_target_tracking_demo/python/utils/network_wrappers.py
Apache-2.0
def expand_boxes(boxes, scale): """Expand an array of boxes by a given scale.""" w_half = (boxes[:, 2] - boxes[:, 0]) * .5 h_half = (boxes[:, 3] - boxes[:, 1]) * .5 x_c = (boxes[:, 2] + boxes[:, 0]) * .5 y_c = (boxes[:, 3] + boxes[:, 1]) * .5 w_half *= scale h_half *= scale boxes_exp =...
Expand an array of boxes by a given scale.
expand_boxes
python
openvinotoolkit/open_model_zoo
demos/multi_camera_multi_target_tracking_demo/python/utils/segm_postprocess.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/multi_camera_multi_target_tracking_demo/python/utils/segm_postprocess.py
Apache-2.0
def time_elapsed(func, *args): """ Auxiliary function that helps to measure elapsed time. """ start_time = perf_counter() res = func(*args) elapsed = perf_counter() - start_time return elapsed, res
Auxiliary function that helps to measure elapsed time.
time_elapsed
python
openvinotoolkit/open_model_zoo
demos/place_recognition_demo/python/place_recognition_demo.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/place_recognition_demo/python/place_recognition_demo.py
Apache-2.0
def crop_resize(image, input_size): ''' Makes max-sized central squared crop and resize to input_size ''' if input_size[0].is_static and input_size[1].is_static: image = max_central_square_crop(image) image = cv2.resize(image, (input_size[1].get_length(), input_size[0].get_length())) return ...
Makes max-sized central squared crop and resize to input_size
crop_resize
python
openvinotoolkit/open_model_zoo
demos/place_recognition_demo/python/place_recognition_demo/common.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/place_recognition_demo/python/place_recognition_demo/common.py
Apache-2.0
def compute_gallery_embeddings(self): ''' Computes embedding vectors for the gallery images. ''' images = [] for full_path in tqdm(self.impaths, desc='Reading gallery images.'): image = cv2.imread(str(full_path)) if image is None: log.error("Cannot proce...
Computes embedding vectors for the gallery images.
compute_gallery_embeddings
python
openvinotoolkit/open_model_zoo
demos/place_recognition_demo/python/place_recognition_demo/place_recognition.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/place_recognition_demo/python/place_recognition_demo/place_recognition.py
Apache-2.0
def visualize(image, impaths, distances, input_size, compute_embedding_time, search_in_gallery_time, imshow_delay, presenter, no_show=False): """ Visualizes input frame and top-10 most similar images from the gallery. """ input_image = cv2.resize(image, (SIZE * 4, SIZE * 3)) demo_image = np....
Visualizes input frame and top-10 most similar images from the gallery.
visualize
python
openvinotoolkit/open_model_zoo
demos/place_recognition_demo/python/place_recognition_demo/visualizer.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/place_recognition_demo/python/place_recognition_demo/visualizer.py
Apache-2.0
def inference(self, top_det_results, side_det_results, action_seg_results, frame_top, frame_side, frame_counter, mode): """ Args: top_det_results: side_de...
Args: top_det_results: side_det_results: action_seg_results: action_seg_results: Returns: Progress of the frame index
inference
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def check_consecutive(self): """ Given a list: ['noise','noise','noise','put_take','noise','noise','noise'], this function calculate number of consecutive element, store in count_list and return the first action that persist more than filter_action_threshold frame count_list = [('noise'...
Given a list: ['noise','noise','noise','put_take','noise','noise','noise'], this function calculate number of consecutive element, store in count_list and return the first action that persist more than filter_action_threshold frame count_list = [('noise', 3), ('put_take', 1), ('adjust_rider', ...
check_consecutive
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def filter_action(self, action_seg_results, mode): """filter action segmentation result. action which persists less than filter_action_threshold frame will be ignored""" if mode == 'multiview': # at beginning of evaluation (less than self.buffer_size frame), action is None if len...
filter action segmentation result. action which persists less than filter_action_threshold frame will be ignored
filter_action
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def get_object(self, det_results): """ Most object return list of obj coordinate in dict except weight most object: return a dictionary of list of object coordinate, eg.[array([x_min,y_min,x_max,y_max]),...] weight: weights_obj_coor return list of object nam...
Most object return list of obj coordinate in dict except weight most object: return a dictionary of list of object coordinate, eg.[array([x_min,y_min,x_max,y_max]),...] weight: weights_obj_coor return list of object name and coordinate, eg.[[[weights5_g,...
get_object
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def classify_state(self, action_seg_results): """ filter input data for action so that only action persists more than certain frame taken as true data Parameters ---------- action_seg_results: str action label """ if action_seg_results in ["pu...
filter input data for action so that only action persists more than certain frame taken as true data Parameters ---------- action_seg_results: str action label
classify_state
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def rotate(self, left, right, center): """ Given 3 points, fix the left point, rotate until the right point is horizontal to the left point Return the rotated coordinate of the three points Used to correct angle in adjust_rider (roundscrew1 and rider) and balance(roundscrew2 and pointer...
Given 3 points, fix the left point, rotate until the right point is horizontal to the left point Return the rotated coordinate of the three points Used to correct angle in adjust_rider (roundscrew1 and rider) and balance(roundscrew2 and pointerhead)
rotate
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def evaluate_rider(self): """ Function: To evaluate whether rider is pushed to zero position """ roundscrew1_coor = self.side_object_dict['roundscrew1'] rider_coor = self.side_object_dict['rider'] # only evaluate rider_zero if 2 roundscrew1 and 1 rider are fou...
Function: To evaluate whether rider is pushed to zero position
evaluate_rider
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def evaluate_rider_tweezers(self): """ Function: To evaluate whether rider is pushed using tweezers Logic: if rider moves, tweezers coordinate should within certain pixels (defined in self.use_tweezers_threshold) from the rider coordinate """ rider_coor ...
Function: To evaluate whether rider is pushed using tweezers Logic: if rider moves, tweezers coordinate should within certain pixels (defined in self.use_tweezers_threshold) from the rider coordinate
evaluate_rider_tweezers
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def evaluate_scale_balance(self): """ In initial state, this function always running until first put_take action is detected In measuring state, after object is put, if the balance is balance more than self.balance_persist_duration_threshold frames, consider balance however, everytime we...
In initial state, this function always running until first put_take action is detected In measuring state, after object is put, if the balance is balance more than self.balance_persist_duration_threshold frames, consider balance however, everytime weights are added to the balance, the mark and ...
evaluate_scale_balance
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/evaluator.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/evaluator.py
Apache-2.0
def nms(boxes, scores, nms_thr): """Single class NMS implemented in Numpy.""" x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.a...
Single class NMS implemented in Numpy.
nms
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/object_detection/deploy_util.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/object_detection/deploy_util.py
Apache-2.0
def inference(self, img_top, img_side): """ Given input arrays for two view, need to generate and save the corresponding detection results in the specific data structure. Args: img_top: img array of H x W x C for the top view img_front: img_array of H x W x C for the ...
Given input arrays for two view, need to generate and save the corresponding detection results in the specific data structure. Args: img_top: img array of H x W x C for the top view img_front: img_array of H x W x C for the front view Returns: prediction resu...
inference
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/object_detection/detector.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/object_detection/detector.py
Apache-2.0
def inference_multithread(self, img_top, img_side, frame_index): """ Given input arrays for two view, need to generate and save the corresponding detection results in the specific data structure. Args: img_top: img array of H x W x C for the top view img_side: img_arr...
Given input arrays for two view, need to generate and save the corresponding detection results in the specific data structure. Args: img_top: img array of H x W x C for the top view img_side: img_array of H x W x C for the side view Returns: prediction result...
inference_multithread
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/object_detection/detector.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/object_detection/detector.py
Apache-2.0
def reverse_crop_pad_resize( xyxys: np.ndarray, pad_img_size: tuple, dsize: int, pad_left: int, pad_top: int, roi_xyxy: np.ndarray): ''' reversal of crop_pad_resize xyxys: bboxes in xyxy format pad_img_size, pad_left, pad_top are from outputs of crop_pad_resize() ...
reversal of crop_pad_resize xyxys: bboxes in xyxy format pad_img_size, pad_left, pad_top are from outputs of crop_pad_resize() dsize is the resize params used in crop_pad_resize() roi_xyxy is the ROI used to crop original image
reverse_crop_pad_resize
python
openvinotoolkit/open_model_zoo
demos/smartlab_demo/python/object_detection/postprocess.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smartlab_demo/python/object_detection/postprocess.py
Apache-2.0
def load_detections(file_path): """Loads dumped detections from the specified file :param file_path: Path to file with detections :return: Loaded detections """ with open(file_path, 'r') as read_file: detections = json.load(read_file)['data'] out_detections = {} for det in tqdm(de...
Loads dumped detections from the specified file :param file_path: Path to file with detections :return: Loaded detections
load_detections
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def load_annotation(file_path): """Loads annotation from the specified file. :param file_path: Path to file with annotation :return: Loaded annotation """ tree = etree.parse(file_path) root = tree.getroot() detections_by_frame_id = {} ordered_track_id = -1 for track in tqdm(root,...
Loads annotation from the specified file. :param file_path: Path to file with annotation :return: Loaded annotation
load_annotation
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def iou(box_a, box_b): """ Calculates Intersection over Union (IoU) metric. :param box_a: First bbox :param box_b: Second bbox :return: Scalar value of metric """ intersect_top_left_x = max(box_a.xmin, box_b.xmin) intersect_top_left_y = max(box_a.ymin, box_b.ymin) intersect_width = max...
Calculates Intersection over Union (IoU) metric. :param box_a: First bbox :param box_b: Second bbox :return: Scalar value of metric
iou
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def match_detections(predicted_data, gt_data, min_iou): """Carry out matching between detected and ground truth bboxes. :param predicted_data: List of predicted bboxes :param gt_data: List of ground truth bboxes :param min_iou: Min IoU value to match bboxes :return: List of matches """ all...
Carry out matching between detected and ground truth bboxes. :param predicted_data: List of predicted bboxes :param gt_data: List of ground truth bboxes :param min_iou: Min IoU value to match bboxes :return: List of matches
match_detections
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def split_to_tracks(gt_data): """Splits data to tracks according ID. :param gt_data: Input data :return: List of tracks """ tracks = {} for frame_id in tqdm(gt_data, desc='Splitting GT'): gt_frame_data = gt_data[frame_id] for bbox in gt_frame_data: track_id = bbox.i...
Splits data to tracks according ID. :param gt_data: Input data :return: List of tracks
split_to_tracks
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def add_matched_predictions(tracks, all_matched_ids, predicted_data, gt_data): """Adds matched predicted events to the input tracks. :param tracks: Input tracks :param all_matched_ids: List of matches :param predicted_data: Predicted data :param gt_data: ground-truth data :return: Updated list ...
Adds matched predicted events to the input tracks. :param tracks: Input tracks :param all_matched_ids: List of matches :param predicted_data: Predicted data :param gt_data: ground-truth data :return: Updated list of tracks
add_matched_predictions
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def _smooth(input_events): """Merge frames into the events of the same action. :param input_events: Frame-based actions :return: List of events """ out_events = [] if len(input_events) > 0: last_range = Range(input_events[0][0], input_events[0][0] + 1, inpu...
Merge frames into the events of the same action. :param input_events: Frame-based actions :return: List of events
_smooth
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def _interpolate(input_events): """Fills event-free ranges by interpolating neighbouring events. :param input_events: List of events :return: Filled list of events """ out_events = [] if len(input_events) > 0: last_event = input_events[0] for ev...
Fills event-free ranges by interpolating neighbouring events. :param input_events: List of events :return: Filled list of events
_interpolate
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def _merge(input_events): """Merges consecutive events of the same action. :param input_events: List of events :return: Merged list of events """ out_events = [] if len(input_events) > 0: last_event = input_events[0] for cur_event in input_event...
Merges consecutive events of the same action. :param input_events: List of events :return: Merged list of events
_merge
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def match_events(gt_events, pred_events): """Carry out matching between two input sets of events. :param gt_events: Input ground-truth events :param pred_events: Input predicted events :return: List of matched events """ num_gt = len(gt_events) num_pred = len(pred_events) if num_gt == ...
Carry out matching between two input sets of events. :param gt_events: Input ground-truth events :param pred_events: Input predicted events :return: List of matched events
match_events
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def process_tracks(all_tracks, window_size, min_length): """Carry out smoothing of the input tracks :param all_tracks: Input tracks :param window_size: Size of smooth window :param min_length: Min duration of event :return: List of smoothed tracks """ out_tracks = {} for track_id in tq...
Carry out smoothing of the input tracks :param all_tracks: Input tracks :param window_size: Size of smooth window :param min_length: Min duration of event :return: List of smoothed tracks
process_tracks
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def calculate_metrics(all_tracks): """Calculates Precision and Recall metrics. :param all_tracks: Input matched events :return: Precision and Recall scalar values """ total_num_pred_events = 0 total_num_valid_pred_events = 0 total_num_gt_events = 0 total_num_valid_gt_events = 0 fo...
Calculates Precision and Recall metrics. :param all_tracks: Input matched events :return: Precision and Recall scalar values
calculate_metrics
python
openvinotoolkit/open_model_zoo
demos/smart_classroom_demo/utils/action_event_metrics.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/smart_classroom_demo/utils/action_event_metrics.py
Apache-2.0
def _process_blocks(self, audio, finish=False): """ audio (numpy.ndarray), this buffer is guaranteed to contain data for 1 or more blocks (audio.shape[0]>=self._block_len+self._context_len) """ # Cut the buffer to the end of the last frame audio_len = audio.shape[0] ...
audio (numpy.ndarray), this buffer is guaranteed to contain data for 1 or more blocks (audio.shape[0]>=self._block_len+self._context_len)
_process_blocks
python
openvinotoolkit/open_model_zoo
demos/speech_recognition_deepspeech_demo/python/asr_utils/audio_features.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/speech_recognition_deepspeech_demo/python/asr_utils/audio_features.py
Apache-2.0
def recognize_audio(self, audio, sampling_rate, finish=True): """ Run a segment of audio through ASR pipeline. Use finish=True (default) to run recognition once for a whole utterance. Use finish=False for online recognition, provinging data cut into segments and getting updated recogniti...
Run a segment of audio through ASR pipeline. Use finish=True (default) to run recognition once for a whole utterance. Use finish=False for online recognition, provinging data cut into segments and getting updated recognition result after each segment. Set finish=True for the last segmen...
recognize_audio
python
openvinotoolkit/open_model_zoo
demos/speech_recognition_deepspeech_demo/python/asr_utils/deep_speech_seq_pipeline.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/speech_recognition_deepspeech_demo/python/asr_utils/deep_speech_seq_pipeline.py
Apache-2.0
def process_data(self, data, finish=False): """ Args: data (numpy.ndarray or None), new data to be concatenated with the older data along axis=0, None for no new data finish (bool), set to True for the last segment of data to finalize processing and flush buffers Returns...
Args: data (numpy.ndarray or None), new data to be concatenated with the older data along axis=0, None for no new data finish (bool), set to True for the last segment of data to finalize processing and flush buffers Returns: numpy.ndarray or None, output data (any data ...
process_data
python
openvinotoolkit/open_model_zoo
demos/speech_recognition_deepspeech_demo/python/asr_utils/pipelines.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/speech_recognition_deepspeech_demo/python/asr_utils/pipelines.py
Apache-2.0
def __init__(self, profile, core, model_path, device='CPU'): """ Load/compile to the target device the Core IR file with the model and initialize the pipeline stage. profile (dict), a dict with pre/post-processing parameters, see profiles.py core (Core), Core object for model loading/co...
Load/compile to the target device the Core IR file with the model and initialize the pipeline stage. profile (dict), a dict with pre/post-processing parameters, see profiles.py core (Core), Core object for model loading/compilation/inference model_path (str), filename of .xml IR file ...
__init__
python
openvinotoolkit/open_model_zoo
demos/speech_recognition_deepspeech_demo/python/asr_utils/rnn_seq_pipeline.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/speech_recognition_deepspeech_demo/python/asr_utils/rnn_seq_pipeline.py
Apache-2.0
def append_data(self, probs, log_probs): """ Args: probs (numpy.ndarray), 2d array with symbol probabilities (frames x symbols) log_probs (bool), True to accept natural-logarithmic probabilities, False to accept probabilities directly. """ assert len(probs.shape) == 2 ...
Args: probs (numpy.ndarray), 2d array with symbol probabilities (frames x symbols) log_probs (bool), True to accept natural-logarithmic probabilities, False to accept probabilities directly.
append_data
python
openvinotoolkit/open_model_zoo
demos/speech_recognition_deepspeech_demo/python/ctcdecode-numpy/ctcdecode_numpy/__init__.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/speech_recognition_deepspeech_demo/python/ctcdecode-numpy/ctcdecode_numpy/__init__.py
Apache-2.0
def __init__(self, model_upsample, model_rnn, core, target=11000, overlap=550, hop_length=275, bits=9, device='CPU', verbose=False, upsampler_width=-1): """ return class provided WaveRNN inference. :param model_upsample: path to xml with upsample model of WaveRNN :param...
return class provided WaveRNN inference. :param model_upsample: path to xml with upsample model of WaveRNN :param model_rnn: path to xml with rnn parameters of WaveRNN model :param core: OpenVINO Core instance :param target: length of the processed fragments :param over...
__init__
python
openvinotoolkit/open_model_zoo
demos/text_to_speech_demo/python/models/mel2wave_ie.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/text_to_speech_demo/python/models/mel2wave_ie.py
Apache-2.0
def __init__(self, model, core, device='CPU', default_width=80): """ return class provided MelGAN inference. :param model: path to xml with MelGAN model of WaveRNN :param core: OpenVINO Core instance :param device: target device :return: """ self.device =...
return class provided MelGAN inference. :param model: path to xml with MelGAN model of WaveRNN :param core: OpenVINO Core instance :param device: target device :return:
__init__
python
openvinotoolkit/open_model_zoo
demos/text_to_speech_demo/python/models/mel2wave_ie.py
https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/text_to_speech_demo/python/models/mel2wave_ie.py
Apache-2.0