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 _run_pylint_stdio(pylint_executable, document, flags): """Run pylint in popen. :param pylint_executable: path to pylint executable :type pylint_executable: string :param document: document to run pylint on :type document: pyls.workspace.Document :param flags: arguments to path to pylint :type flags: list :return: result of calling pylint :rtype: string """ log.debug("Calling %s with args: '%s'", pylint_executable, flags) try: cmd = [pylint_executable] cmd.extend(flags) cmd.extend(['--from-stdin', document.path]) p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) except IOError: log.debug("Can't execute %s. Trying with 'python -m pylint'", pylint_executable) cmd = ['python', '-m', 'pylint'] cmd.extend(flags) cmd.extend(['--from-stdin', document.path]) p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) (stdout, stderr) = p.communicate(document.source.encode()) if stderr: log.error("Error while running pylint '%s'", stderr.decode()) return stdout.decode()
Run pylint in popen. :param pylint_executable: path to pylint executable :type pylint_executable: string :param document: document to run pylint on :type document: pyls.workspace.Document :param flags: arguments to path to pylint :type flags: list :return: result of calling pylint :rtype: string
_run_pylint_stdio
python
palantir/python-language-server
pyls/plugins/pylint_lint.py
https://github.com/palantir/python-language-server/blob/master/pyls/plugins/pylint_lint.py
MIT
def _parse_pylint_stdio_result(document, stdout): """Parse pylint results. :param document: document to run pylint on :type document: pyls.workspace.Document :param stdout: pylint results to parse :type stdout: string :return: linting diagnostics :rtype: list """ diagnostics = [] lines = stdout.splitlines() for raw_line in lines: parsed_line = re.match(r'(.*):(\d*):(\d*): (\w*): (.*)', raw_line) if not parsed_line: log.debug("Pylint output parser can't parse line '%s'", raw_line) continue parsed_line = parsed_line.groups() if len(parsed_line) != 5: log.debug("Pylint output parser can't parse line '%s'", raw_line) continue _, line, character, code, msg = parsed_line line = int(line) - 1 character = int(character) severity_map = { 'C': lsp.DiagnosticSeverity.Information, 'E': lsp.DiagnosticSeverity.Error, 'F': lsp.DiagnosticSeverity.Error, 'R': lsp.DiagnosticSeverity.Hint, 'W': lsp.DiagnosticSeverity.Warning, } severity = severity_map[code[0]] diagnostics.append( { 'source': 'pylint', 'code': code, 'range': { 'start': { 'line': line, 'character': character }, 'end': { 'line': line, # no way to determine the column 'character': len(document.lines[line]) - 1 } }, 'message': msg, 'severity': severity, } ) return diagnostics
Parse pylint results. :param document: document to run pylint on :type document: pyls.workspace.Document :param stdout: pylint results to parse :type stdout: string :return: linting diagnostics :rtype: list
_parse_pylint_stdio_result
python
palantir/python-language-server
pyls/plugins/pylint_lint.py
https://github.com/palantir/python-language-server/blob/master/pyls/plugins/pylint_lint.py
MIT
def workspace_other_root_path(tmpdir): """Return a workspace with a root_path other than tmpdir.""" ws_path = str(tmpdir.mkdir('test123').mkdir('test456')) ws = Workspace(uris.from_fs_path(ws_path), Mock()) ws._config = Config(ws.root_uri, {}, 0, {}) return ws
Return a workspace with a root_path other than tmpdir.
workspace_other_root_path
python
palantir/python-language-server
test/fixtures.py
https://github.com/palantir/python-language-server/blob/master/test/fixtures.py
MIT
def temp_workspace_factory(workspace): # pylint: disable=redefined-outer-name ''' Returns a function that creates a temporary workspace from the files dict. The dict is in the format {"file_name": "file_contents"} ''' def fn(files): def create_file(name, content): fn = os.path.join(workspace.root_path, name) with open(fn, 'w') as f: f.write(content) workspace.put_document(uris.from_fs_path(fn), content) for name, content in files.items(): create_file(name, content) return workspace return fn
Returns a function that creates a temporary workspace from the files dict. The dict is in the format {"file_name": "file_contents"}
temp_workspace_factory
python
palantir/python-language-server
test/fixtures.py
https://github.com/palantir/python-language-server/blob/master/test/fixtures.py
MIT
def test_word_at_position(doc): """ Return the position under the cursor (or last in line if past the end) """ # import sys assert doc.word_at_position({'line': 0, 'character': 8}) == 'sys' # Past end of import sys assert doc.word_at_position({'line': 0, 'character': 1000}) == 'sys' # Empty line assert doc.word_at_position({'line': 1, 'character': 5}) == '' # def main(): assert doc.word_at_position({'line': 2, 'character': 0}) == 'def' # Past end of file assert doc.word_at_position({'line': 4, 'character': 0}) == ''
Return the position under the cursor (or last in line if past the end)
test_word_at_position
python
palantir/python-language-server
test/test_document.py
https://github.com/palantir/python-language-server/blob/master/test/test_document.py
MIT
def client_server(): """ A fixture that sets up a client/server pair and shuts down the server This client/server pair does not support checking parent process aliveness """ client_server_pair = _ClientServer() yield client_server_pair.client shutdown_response = client_server_pair.client._endpoint.request('shutdown').result(timeout=CALL_TIMEOUT) assert shutdown_response is None client_server_pair.client._endpoint.notify('exit')
A fixture that sets up a client/server pair and shuts down the server This client/server pair does not support checking parent process aliveness
client_server
python
palantir/python-language-server
test/test_language_server.py
https://github.com/palantir/python-language-server/blob/master/test/test_language_server.py
MIT
def client_exited_server(): """ A fixture that sets up a client/server pair that support checking parent process aliveness and assert the server has already exited """ client_server_pair = _ClientServer(True) # yield client_server_pair.client yield client_server_pair assert client_server_pair.process.is_alive() is False
A fixture that sets up a client/server pair that support checking parent process aliveness and assert the server has already exited
client_exited_server
python
palantir/python-language-server
test/test_language_server.py
https://github.com/palantir/python-language-server/blob/master/test/test_language_server.py
MIT
def test_pycodestyle_config(workspace): """ Test that we load config files properly. Config files are loaded in the following order: tox.ini pep8.cfg setup.cfg pycodestyle.cfg Each overriding the values in the last. These files are first looked for in the current document's directory and then each parent directory until any one is found terminating at the workspace root. If any section called 'pycodestyle' exists that will be solely used and any config in a 'pep8' section will be ignored """ doc_uri = uris.from_fs_path(os.path.join(workspace.root_path, 'test.py')) workspace.put_document(doc_uri, DOC) doc = workspace.get_document(doc_uri) # Make sure we get a warning for 'indentation contains tabs' diags = pycodestyle_lint.pyls_lint(workspace, doc) assert [d for d in diags if d['code'] == 'W191'] content = { 'setup.cfg': ('[pycodestyle]\nignore = W191, E201, E128', True), 'tox.ini': ('', False) } for conf_file, (content, working) in list(content.items()): # Now we'll add config file to ignore it with open(os.path.join(workspace.root_path, conf_file), 'w+') as f: f.write(content) workspace._config.settings.cache_clear() # And make sure we don't get any warnings diags = pycodestyle_lint.pyls_lint(workspace, doc) assert len([d for d in diags if d['code'] == 'W191']) == (0 if working else 1) assert len([d for d in diags if d['code'] == 'E201']) == (0 if working else 1) assert [d for d in diags if d['code'] == 'W391'] os.unlink(os.path.join(workspace.root_path, conf_file)) # Make sure we can ignore via the PYLS config as well workspace._config.update({'plugins': {'pycodestyle': {'ignore': ['W191', 'E201']}}}) # And make sure we only get one warning diags = pycodestyle_lint.pyls_lint(workspace, doc) assert not [d for d in diags if d['code'] == 'W191'] assert not [d for d in diags if d['code'] == 'E201'] assert [d for d in diags if d['code'] == 'W391']
Test that we load config files properly. Config files are loaded in the following order: tox.ini pep8.cfg setup.cfg pycodestyle.cfg Each overriding the values in the last. These files are first looked for in the current document's directory and then each parent directory until any one is found terminating at the workspace root. If any section called 'pycodestyle' exists that will be solely used and any config in a 'pep8' section will be ignored
test_pycodestyle_config
python
palantir/python-language-server
test/plugins/test_pycodestyle_lint.py
https://github.com/palantir/python-language-server/blob/master/test/plugins/test_pycodestyle_lint.py
MIT
def get_args(add_help=True): """get_args Parse all args using argparse lib Args: add_help: Whether to add -h option on args Returns: An object which contains many parameters used for inference. """ import argparse parser = argparse.ArgumentParser( description='PaddlePaddle Args', add_help=add_help) args = parser.parse_args() return args
get_args Parse all args using argparse lib Args: add_help: Whether to add -h option on args Returns: An object which contains many parameters used for inference.
get_args
python
PaddlePaddle/models
docs/tipc/train_infer_python/template/code/export_model.py
https://github.com/PaddlePaddle/models/blob/master/docs/tipc/train_infer_python/template/code/export_model.py
Apache-2.0
def export(args): """export export inference model using jit.save Args: args: Parameters generated using argparser. Returns: None """ model = build_model(args) # decorate model with jit.save model = paddle.jit.to_static( model, input_spec=[ InputSpec( shape=[None, 3, args.img_size, args.img_size], dtype='float32') ]) # save inference model paddle.jit.save(model, os.path.join(args.save_inference_dir, "inference")) print(f"inference model is saved in {args.save_inference_dir}")
export export inference model using jit.save Args: args: Parameters generated using argparser. Returns: None
export
python
PaddlePaddle/models
docs/tipc/train_infer_python/template/code/export_model.py
https://github.com/PaddlePaddle/models/blob/master/docs/tipc/train_infer_python/template/code/export_model.py
Apache-2.0
def infer_main(args): """infer_main Main inference function. Args: args: Parameters generated using argparser. Returns: class_id: Class index of the input. prob: : Probability of the input. """ # init inference engine inference_engine = InferenceEngine(args) # init benchmark log if args.benchmark: import auto_log autolog = auto_log.AutoLogger( model_name="example", batch_size=args.batch_size, inference_config=inference_engine.config, gpu_ids="auto" if args.use_gpu else None) # enable benchmark if args.benchmark: autolog.times.start() # preprocess img = inference_engine.preprocess(args.img_path) if args.benchmark: autolog.times.stamp() output = inference_engine.run(img) if args.benchmark: autolog.times.stamp() # postprocess class_id, prob = inference_engine.postprocess(output) if args.benchmark: autolog.times.stamp() autolog.times.end(stamp=True) autolog.report() return class_id, prob
infer_main Main inference function. Args: args: Parameters generated using argparser. Returns: class_id: Class index of the input. prob: : Probability of the input.
infer_main
python
PaddlePaddle/models
docs/tipc/train_infer_python/template/code/infer.py
https://github.com/PaddlePaddle/models/blob/master/docs/tipc/train_infer_python/template/code/infer.py
Apache-2.0
def is_url(path): """ Whether path is URL. Args: path (string): URL string or not. """ return path.startswith('http://') \ or path.startswith('https://') \ or path.startswith('paddlecv://')
Whether path is URL. Args: path (string): URL string or not.
is_url
python
PaddlePaddle/models
modelcenter/PLSC-ViT/APP/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PLSC-ViT/APP/download.py
Apache-2.0
def get_model_path(path): """Get model path from WEIGHTS_HOME, if not exists, download it from url. """ if not is_url(path): return path url = parse_url(path) path, _ = get_path(url, WEIGHTS_HOME, path_depth=3) return path
Get model path from WEIGHTS_HOME, if not exists, download it from url.
get_model_path
python
PaddlePaddle/models
modelcenter/PLSC-ViT/APP/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PLSC-ViT/APP/download.py
Apache-2.0
def get_data_path(path): """Get model path from DATA_HOME, if not exists, download it from url. """ if not is_url(path): return path url = parse_url(path) path, _ = get_path(url, DATA_HOME, path_depth=1) return path
Get model path from DATA_HOME, if not exists, download it from url.
get_data_path
python
PaddlePaddle/models
modelcenter/PLSC-ViT/APP/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PLSC-ViT/APP/download.py
Apache-2.0
def get_config_path(path): """Get config path from CONFIGS_HOME, if not exists, download it from url. """ if not is_url(path): return path url = parse_url(path) path, _ = get_path(url, CONFIGS_HOME) return path
Get config path from CONFIGS_HOME, if not exists, download it from url.
get_config_path
python
PaddlePaddle/models
modelcenter/PLSC-ViT/APP/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PLSC-ViT/APP/download.py
Apache-2.0
def get_path(url, root_dir, md5sum=None, check_exist=True, path_depth=1): """ Download from given url to root_dir. if file or directory specified by url is exists under root_dir, return the path directly, otherwise download from url, return the path. url (str): download url root_dir (str): root dir for downloading, it should be WEIGHTS_HOME md5sum (str): md5 sum of download package """ # parse path after download to decompress under root_dir fullpath, dirname = map_path(url, root_dir, path_depth) if osp.exists(fullpath) and check_exist: if not osp.isfile(fullpath) or \ _check_exist_file_md5(fullpath, md5sum, url): return fullpath, True else: os.remove(fullpath) fullname = _download(url, dirname, md5sum) return fullpath, False
Download from given url to root_dir. if file or directory specified by url is exists under root_dir, return the path directly, otherwise download from url, return the path. url (str): download url root_dir (str): root dir for downloading, it should be WEIGHTS_HOME md5sum (str): md5 sum of download package
get_path
python
PaddlePaddle/models
modelcenter/PLSC-ViT/APP/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PLSC-ViT/APP/download.py
Apache-2.0
def _download(url, path, md5sum=None): """ Download from url, save to path. url (str): download url path (str): download to given path """ if not osp.exists(path): os.makedirs(path) fname = osp.split(url)[-1] fullname = osp.join(path, fname) retry_cnt = 0 while not (osp.exists(fullname) and _check_exist_file_md5(fullname, md5sum, url)): if retry_cnt < DOWNLOAD_RETRY_LIMIT: retry_cnt += 1 else: raise RuntimeError("Download from {} failed. " "Retry limit reached".format(url)) # NOTE: windows path join may incur \, which is invalid in url if sys.platform == "win32": url = url.replace('\\', '/') req = requests.get(url, stream=True) if req.status_code != 200: raise RuntimeError("Downloading from {} failed with code " "{}!".format(url, req.status_code)) # For protecting download interupted, download to # tmp_fullname firstly, move tmp_fullname to fullname # after download finished tmp_fullname = fullname + "_tmp" total_size = req.headers.get('content-length') with open(tmp_fullname, 'wb') as f: if total_size: for chunk in tqdm.tqdm( req.iter_content(chunk_size=1024), total=(int(total_size) + 1023) // 1024, unit='KB'): f.write(chunk) else: for chunk in req.iter_content(chunk_size=1024): if chunk: f.write(chunk) shutil.move(tmp_fullname, fullname) return fullname
Download from url, save to path. url (str): download url path (str): download to given path
_download
python
PaddlePaddle/models
modelcenter/PLSC-ViT/APP/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PLSC-ViT/APP/download.py
Apache-2.0
def __init__(self, model_type="paddle", model_path=None, params_path=None, label_path=None): ''' model_path: str, http url params_path: str, http url, could be downloaded ''' assert model_type in ["paddle"] assert model_path is not None and os.path.splitext(model_path)[ 1] == '.pdmodel' assert params_path is not None and os.path.splitext(params_path)[ 1] == '.pdiparams' import paddle.inference as paddle_infer infer_model = get_model_path(model_path) infer_params = get_model_path(params_path) config = paddle_infer.Config(infer_model, infer_params) self.predictor = paddle_infer.create_predictor(config) self.input_names = self.predictor.get_input_names() self.output_names = self.predictor.get_output_names() self.labels = self.parse_labes(get_data_path(label_path)) self.model_type = model_type
model_path: str, http url params_path: str, http url, could be downloaded
__init__
python
PaddlePaddle/models
modelcenter/PLSC-ViT/APP/predictor.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PLSC-ViT/APP/predictor.py
Apache-2.0
def __init__(self, cfg): """ Prepare for prediction. The usage and docs of paddle inference, please refer to https://paddleinference.paddlepaddle.org.cn/product_introduction/summary.html """ self.cfg = DeployConfig(cfg) self._init_base_config() self._init_cpu_config() self.predictor = create_predictor(self.pred_cfg)
Prepare for prediction. The usage and docs of paddle inference, please refer to https://paddleinference.paddlepaddle.org.cn/product_introduction/summary.html
__init__
python
PaddlePaddle/models
modelcenter/PP-HumanSegV2/APP/app.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanSegV2/APP/app.py
Apache-2.0
def _move_and_merge_tree(src, dst): """ Move src directory to dst, if dst is already exists, merge src to dst """ if not osp.exists(dst): shutil.move(src, dst) elif osp.isfile(src): shutil.move(src, dst) else: for fp in os.listdir(src): src_fp = osp.join(src, fp) dst_fp = osp.join(dst, fp) if osp.isdir(src_fp): if osp.isdir(dst_fp): _move_and_merge_tree(src_fp, dst_fp) else: shutil.move(src_fp, dst_fp) elif osp.isfile(src_fp) and \ not osp.isfile(dst_fp): shutil.move(src_fp, dst_fp)
Move src directory to dst, if dst is already exists, merge src to dst
_move_and_merge_tree
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/download.py
Apache-2.0
def _decompress(fname): """ Decompress for zip and tar file """ # For protecting decompressing interupted, # decompress to fpath_tmp directory firstly, if decompress # successed, move decompress files to fpath and delete # fpath_tmp and remove download compress file. fpath = osp.split(fname)[0] fpath_tmp = osp.join(fpath, 'tmp') if osp.isdir(fpath_tmp): shutil.rmtree(fpath_tmp) os.makedirs(fpath_tmp) if fname.find('tar') >= 0: with tarfile.open(fname) as tf: tf.extractall(path=fpath_tmp) elif fname.find('zip') >= 0: with zipfile.ZipFile(fname) as zf: zf.extractall(path=fpath_tmp) elif fname.find('.txt') >= 0: return else: raise TypeError("Unsupport compress file type {}".format(fname)) for f in os.listdir(fpath_tmp): src_dir = osp.join(fpath_tmp, f) dst_dir = osp.join(fpath, f) _move_and_merge_tree(src_dir, dst_dir) shutil.rmtree(fpath_tmp) os.remove(fname)
Decompress for zip and tar file
_decompress
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/download.py
Apache-2.0
def get_path(url, root_dir=WEIGHTS_HOME, md5sum=None, check_exist=True): """ Download from given url to root_dir. if file or directory specified by url is exists under root_dir, return the path directly, otherwise download from url and decompress it, return the path. url (str): download url root_dir (str): root dir for downloading md5sum (str): md5 sum of download package """ # parse path after download to decompress under root_dir fullpath = map_path(url, root_dir) # For same zip file, decompressed directory name different # from zip file name, rename by following map decompress_name_map = {"ppTSM_fight": "ppTSM", } for k, v in decompress_name_map.items(): if fullpath.find(k) >= 0: fullpath = osp.join(osp.split(fullpath)[0], v) if osp.exists(fullpath) and check_exist: if not osp.isfile(fullpath) or \ _check_exist_file_md5(fullpath, md5sum, url): return fullpath, True else: os.remove(fullpath) fullname = _download_dist(url, root_dir, md5sum) # new weights format which postfix is 'pdparams' not # need to decompress if osp.splitext(fullname)[-1] not in ['.pdparams', '.yml']: _decompress_dist(fullname) return fullpath, False
Download from given url to root_dir. if file or directory specified by url is exists under root_dir, return the path directly, otherwise download from url and decompress it, return the path. url (str): download url root_dir (str): root dir for downloading md5sum (str): md5 sum of download package
get_path
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/download.py
Apache-2.0
def get_weights_path(url): """Get weights path from WEIGHTS_HOME, if not exists, download it from url. """ url = parse_url(url) md5sum = None if url in MODEL_URL_MD5_DICT.keys(): md5sum = MODEL_URL_MD5_DICT[url] path, _ = get_path(url, WEIGHTS_HOME, md5sum) return path
Get weights path from WEIGHTS_HOME, if not exists, download it from url.
get_weights_path
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/download.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/download.py
Apache-2.0
def get_model_dir(cfg): """ Auto download inference model if the model_path is a url link. Otherwise it will use the model_path directly. """ for key in cfg.keys(): if type(cfg[key]) == dict and \ ("enable" in cfg[key].keys() and cfg[key]['enable'] or "enable" not in cfg[key].keys()): if "model_dir" in cfg[key].keys(): model_dir = cfg[key]["model_dir"] downloaded_model_dir = auto_download_model(model_dir) if downloaded_model_dir: model_dir = downloaded_model_dir cfg[key]["model_dir"] = model_dir print(key, " model dir: ", model_dir) elif key == "VEHICLE_PLATE": det_model_dir = cfg[key]["det_model_dir"] downloaded_det_model_dir = auto_download_model(det_model_dir) if downloaded_det_model_dir: det_model_dir = downloaded_det_model_dir cfg[key]["det_model_dir"] = det_model_dir print("det_model_dir model dir: ", det_model_dir) rec_model_dir = cfg[key]["rec_model_dir"] downloaded_rec_model_dir = auto_download_model(rec_model_dir) if downloaded_rec_model_dir: rec_model_dir = downloaded_rec_model_dir cfg[key]["rec_model_dir"] = rec_model_dir print("rec_model_dir model dir: ", rec_model_dir) elif key == "MOT": # for idbased and skeletonbased actions model_dir = cfg[key]["model_dir"] downloaded_model_dir = auto_download_model(model_dir) if downloaded_model_dir: model_dir = downloaded_model_dir cfg[key]["model_dir"] = model_dir print("mot_model_dir model_dir: ", model_dir)
Auto download inference model if the model_path is a url link. Otherwise it will use the model_path directly.
get_model_dir
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pipeline.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pipeline.py
Apache-2.0
def get_test_images(infer_dir, infer_img): """ Get image path list in TEST mode """ assert infer_img is not None or infer_dir is not None, \ "--infer_img or --infer_dir should be set" assert infer_img is None or os.path.isfile(infer_img), \ "{} is not a file".format(infer_img) assert infer_dir is None or os.path.isdir(infer_dir), \ "{} is not a directory".format(infer_dir) # infer_img has a higher priority if infer_img and os.path.isfile(infer_img): return [infer_img] images = set() infer_dir = os.path.abspath(infer_dir) assert os.path.isdir(infer_dir), \ "infer_dir {} is not a directory".format(infer_dir) exts = ['jpg', 'jpeg', 'png', 'bmp'] exts += [ext.upper() for ext in exts] for ext in exts: images.update(glob.glob('{}/*.{}'.format(infer_dir, ext))) images = list(images) assert len(images) > 0, "no image found in {}".format(infer_dir) print("Found {} inference images in total.".format(len(images))) return images
Get image path list in TEST mode
get_test_images
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pipe_utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pipe_utils.py
Apache-2.0
def refine_keypoint_coordinary(kpts, bbox, coord_size): """ This function is used to adjust coordinate values to a fixed scale. """ tl = bbox[:, 0:2] wh = bbox[:, 2:] - tl tl = np.expand_dims(np.transpose(tl, (1, 0)), (2, 3)) wh = np.expand_dims(np.transpose(wh, (1, 0)), (2, 3)) target_w, target_h = coord_size res = (kpts - tl) / wh * np.expand_dims( np.array([[target_w], [target_h]]), (2, 3)) return res
This function is used to adjust coordinate values to a fixed scale.
refine_keypoint_coordinary
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pipe_utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pipe_utils.py
Apache-2.0
def predict(self, repeats=1): ''' Args: repeats (int): repeat number for prediction Returns: results (dict): ''' # model prediction output_names = self.predictor.get_output_names() for i in range(repeats): self.predictor.run() output_tensor = self.predictor.get_output_handle(output_names[0]) np_output = output_tensor.copy_to_cpu() result = dict(output=np_output) return result
Args: repeats (int): repeat number for prediction Returns: results (dict):
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/action_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/action_infer.py
Apache-2.0
def predict_skeleton_with_mot(self, skeleton_with_mot, run_benchmark=False): """ skeleton_with_mot (dict): includes individual skeleton sequences, which shape is [C, T, K, 1] and its corresponding track id. """ skeleton_list = skeleton_with_mot["skeleton"] mot_id = skeleton_with_mot["mot_id"] act_res = self.predict_skeleton( skeleton_list, run_benchmark, repeats=1) results = list(zip(mot_id, act_res)) return results
skeleton_with_mot (dict): includes individual skeleton sequences, which shape is [C, T, K, 1] and its corresponding track id.
predict_skeleton_with_mot
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/action_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/action_infer.py
Apache-2.0
def action_preprocess(input, preprocess_ops): """ input (str | numpy.array): if input is str, it should be a legal file path with numpy array saved. Otherwise it should be numpy.array as direct input. return (numpy.array) """ if isinstance(input, str): assert os.path.isfile(input) is not None, "{0} not exists".format( input) data = np.load(input) else: data = input for operator in preprocess_ops: data = operator(data) return data
input (str | numpy.array): if input is str, it should be a legal file path with numpy array saved. Otherwise it should be numpy.array as direct input. return (numpy.array)
action_preprocess
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/action_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/action_infer.py
Apache-2.0
def get_collected_keypoint(self): """ Output (List): List of keypoint results for Skeletonbased Recognition task, where the format of each element is [tracker_id, KeyPointSequence of tracker_id] """ output = [] for tracker_id in self.id_to_pop: output.append([tracker_id, self.keypoint_saver[tracker_id]]) del (self.keypoint_saver[tracker_id]) self.flag_to_pop = False self.id_to_pop.clear() return output
Output (List): List of keypoint results for Skeletonbased Recognition task, where the format of each element is [tracker_id, KeyPointSequence of tracker_id]
get_collected_keypoint
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/action_utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/action_utils.py
Apache-2.0
def predict(self, repeats=1): ''' Args: repeats (int): repeats number for prediction Returns: result (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] MaskRCNN's result include 'masks': np.ndarray: shape: [N, im_h, im_w] ''' # model prediction for i in range(repeats): self.predictor.run() output_names = self.predictor.get_output_names() output_tensor = self.predictor.get_output_handle(output_names[0]) np_output = output_tensor.copy_to_cpu() result = dict(output=np_output) return result
Args: repeats (int): repeats number for prediction Returns: result (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] MaskRCNN's result include 'masks': np.ndarray: shape: [N, im_h, im_w]
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/attr_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/attr_infer.py
Apache-2.0
def cosine_similarity(x, y, eps=1e-12): """ Computes cosine similarity between two tensors. Value == 1 means the same vector Value == 0 means perpendicular vectors """ x_n, y_n = np.linalg.norm( x, axis=1, keepdims=True), np.linalg.norm( y, axis=1, keepdims=True) x_norm = x / np.maximum(x_n, eps * np.ones_like(x_n)) y_norm = y / np.maximum(y_n, eps * np.ones_like(y_n)) sim_mt = np.dot(x_norm, y_norm.T) return sim_mt
Computes cosine similarity between two tensors. Value == 1 means the same vector Value == 0 means perpendicular vectors
cosine_similarity
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/mtmct.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/mtmct.py
Apache-2.0
def predict(self, input): ''' Args: input (str) or (list): video file path or image data list Returns: results (dict): ''' input_names = self.predictor.get_input_names() input_tensor = self.predictor.get_input_handle(input_names[0]) output_names = self.predictor.get_output_names() output_tensor = self.predictor.get_output_handle(output_names[0]) # preprocess self.recognize_times.preprocess_time_s.start() if type(input) == str: inputs = self.preprocess_video(input) else: inputs = self.preprocess_frames(input) self.recognize_times.preprocess_time_s.end() inputs = np.expand_dims( inputs, axis=0).repeat( self.batch_size, axis=0).copy() input_tensor.copy_from_cpu(inputs) # model prediction self.recognize_times.inference_time_s.start() self.predictor.run() self.recognize_times.inference_time_s.end() output = output_tensor.copy_to_cpu() # postprocess self.recognize_times.postprocess_time_s.start() classes, scores = self.postprocess(output) self.recognize_times.postprocess_time_s.end() return classes, scores
Args: input (str) or (list): video file path or image data list Returns: results (dict):
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_infer.py
Apache-2.0
def __call__(self, results): """ Args: frames_len: length of frames. return: sampling id. """ frames_len = int(results['frames_len']) # total number of frames frames_idx = [] if self.frame_interval is not None: assert isinstance(self.frame_interval, int) if not self.valid_mode: offsets = self._get_train_clips(frames_len) else: offsets = self._get_test_clips(frames_len) offsets = offsets[:, None] + np.arange(self.seg_len)[ None, :] * self.frame_interval offsets = np.concatenate(offsets) offsets = offsets.reshape((-1, self.seg_len)) offsets = np.mod(offsets, frames_len) offsets = np.concatenate(offsets) if results['format'] == 'video': frames_idx = offsets elif results['format'] == 'frame': frames_idx = list(offsets + 1) else: raise NotImplementedError return self._get(frames_idx, results) print("self.frame_interval:", self.frame_interval) if self.linspace_sample: # default if False if 'start_idx' in results and 'end_idx' in results: offsets = np.linspace(results['start_idx'], results['end_idx'], self.num_seg) else: offsets = np.linspace(0, frames_len - 1, self.num_seg) offsets = np.clip(offsets, 0, frames_len - 1).astype(np.int64) if results['format'] == 'video': frames_idx = list(offsets) frames_idx = [x % frames_len for x in frames_idx] elif results['format'] == 'frame': frames_idx = list(offsets + 1) else: raise NotImplementedError return self._get(frames_idx, results) average_dur = int(frames_len / self.num_seg) print("results['format']:", results['format']) if self.dense_sample: # For ppTSM, default is False if not self.valid_mode: # train sample_pos = max(1, 1 + frames_len - 64) t_stride = 64 // self.num_seg start_idx = 0 if sample_pos == 1 else np.random.randint( 0, sample_pos - 1) offsets = [(idx * t_stride + start_idx) % frames_len + 1 for idx in range(self.num_seg)] frames_idx = offsets else: sample_pos = max(1, 1 + frames_len - 64) t_stride = 64 // self.num_seg start_list = np.linspace(0, sample_pos - 1, num=10, dtype=int) offsets = [] for start_idx in start_list.tolist(): offsets += [(idx * t_stride + start_idx) % frames_len + 1 for idx in range(self.num_seg)] frames_idx = offsets else: for i in range(self.num_seg): idx = 0 if not self.valid_mode: if average_dur >= self.seg_len: idx = random.randint(0, average_dur - self.seg_len) idx += i * average_dur elif average_dur >= 1: idx += i * average_dur else: idx = i else: if average_dur >= self.seg_len: idx = (average_dur - 1) // 2 idx += i * average_dur elif average_dur >= 1: idx += i * average_dur else: idx = i for jj in range(idx, idx + self.seg_len): if results['format'] == 'video': frames_idx.append(int(jj % frames_len)) elif results['format'] == 'frame': frames_idx.append(jj + 1) elif results['format'] == 'MRI': frames_idx.append(jj) else: raise NotImplementedError return self._get(frames_idx, results)
Args: frames_len: length of frames. return: sampling id.
__call__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
Apache-2.0
def __call__(self, results): """ Performs resize operations. Args: imgs (Sequence[PIL.Image]): List where each item is a PIL.Image. For example, [PIL.Image0, PIL.Image1, PIL.Image2, ...] return: resized_imgs: List where each item is a PIL.Image after scaling. """ imgs = results['imgs'] resized_imgs = [] for i in range(len(imgs)): img = imgs[i] if isinstance(img, np.ndarray): h, w, _ = img.shape elif isinstance(img, Image.Image): w, h = img.size else: raise NotImplementedError if w <= h: ow = self.short_size if self.fixed_ratio: # default is True oh = int(self.short_size * 4.0 / 3.0) elif not self.keep_ratio: # no oh = self.short_size else: scale_factor = self.short_size / w oh = int(h * float(scale_factor) + 0.5) if self.do_round else int( h * self.short_size / w) ow = int(w * float(scale_factor) + 0.5) if self.do_round else int( w * self.short_size / h) else: oh = self.short_size if self.fixed_ratio: ow = int(self.short_size * 4.0 / 3.0) elif not self.keep_ratio: # no ow = self.short_size else: scale_factor = self.short_size / h oh = int(h * float(scale_factor) + 0.5) if self.do_round else int( h * self.short_size / w) ow = int(w * float(scale_factor) + 0.5) if self.do_round else int( w * self.short_size / h) if type(img) == np.ndarray: img = Image.fromarray(img, mode='RGB') if self.backend == 'pillow': resized_imgs.append(img.resize((ow, oh), Image.BILINEAR)) elif self.backend == 'cv2' and (self.keep_ratio is not None): resized_imgs.append( cv2.resize( img, (ow, oh), interpolation=cv2.INTER_LINEAR)) else: resized_imgs.append( Image.fromarray( cv2.resize( np.asarray(img), (ow, oh), interpolation=cv2.INTER_LINEAR))) results['imgs'] = resized_imgs return results
Performs resize operations. Args: imgs (Sequence[PIL.Image]): List where each item is a PIL.Image. For example, [PIL.Image0, PIL.Image1, PIL.Image2, ...] return: resized_imgs: List where each item is a PIL.Image after scaling.
__call__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
Apache-2.0
def __call__(self, results): """ Performs Center crop operations. Args: imgs: List where each item is a PIL.Image. For example, [PIL.Image0, PIL.Image1, PIL.Image2, ...] return: ccrop_imgs: List where each item is a PIL.Image after Center crop. """ imgs = results['imgs'] ccrop_imgs = [] th, tw = self.target_size, self.target_size if isinstance(imgs, paddle.Tensor): h, w = imgs.shape[-2:] x1 = int(round((w - tw) / 2.0)) if self.do_round else (w - tw) // 2 y1 = int(round((h - th) / 2.0)) if self.do_round else (h - th) // 2 ccrop_imgs = imgs[:, :, y1:y1 + th, x1:x1 + tw] else: for img in imgs: if self.backend == 'pillow': w, h = img.size elif self.backend == 'cv2': h, w, _ = img.shape else: raise NotImplementedError assert (w >= self.target_size) and (h >= self.target_size), \ "image width({}) and height({}) should be larger than crop size".format( w, h, self.target_size) x1 = int(round((w - tw) / 2.0)) if self.do_round else ( w - tw) // 2 y1 = int(round((h - th) / 2.0)) if self.do_round else ( h - th) // 2 if self.backend == 'cv2': ccrop_imgs.append(img[y1:y1 + th, x1:x1 + tw]) elif self.backend == 'pillow': ccrop_imgs.append(img.crop((x1, y1, x1 + tw, y1 + th))) results['imgs'] = ccrop_imgs return results
Performs Center crop operations. Args: imgs: List where each item is a PIL.Image. For example, [PIL.Image0, PIL.Image1, PIL.Image2, ...] return: ccrop_imgs: List where each item is a PIL.Image after Center crop.
__call__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
Apache-2.0
def __call__(self, results): """ Performs Image to NumpyArray operations. Args: imgs: List where each item is a PIL.Image. For example, [PIL.Image0, PIL.Image1, PIL.Image2, ...] return: np_imgs: Numpy array. """ imgs = results['imgs'] if 'backend' in results and results[ 'backend'] == 'pyav': # [T,H,W,C] in [0, 1] if self.transpose: if self.data_format == 'tchw': t_imgs = imgs.transpose((0, 3, 1, 2)) # tchw else: t_imgs = imgs.transpose((3, 0, 1, 2)) # cthw results['imgs'] = t_imgs else: t_imgs = np.stack(imgs).astype('float32') if self.transpose: if self.data_format == 'tchw': t_imgs = t_imgs.transpose(0, 3, 1, 2) # tchw else: t_imgs = t_imgs.transpose(3, 0, 1, 2) # cthw results['imgs'] = t_imgs return results
Performs Image to NumpyArray operations. Args: imgs: List where each item is a PIL.Image. For example, [PIL.Image0, PIL.Image1, PIL.Image2, ...] return: np_imgs: Numpy array.
__call__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
Apache-2.0
def __call__(self, results): """ Perform mp4 decode operations. return: List where each item is a numpy array after decoder. """ file_path = results['filename'] results['format'] = 'video' results['backend'] = self.backend if self.backend == 'cv2': # here cap = cv2.VideoCapture(file_path) videolen = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) sampledFrames = [] for i in range(videolen): ret, frame = cap.read() # maybe first frame is empty if ret == False: continue img = frame[:, :, ::-1] sampledFrames.append(img) results['frames'] = sampledFrames results['frames_len'] = len(sampledFrames) elif self.backend == 'decord': container = de.VideoReader(file_path) frames_len = len(container) results['frames'] = container results['frames_len'] = frames_len else: raise NotImplementedError return results
Perform mp4 decode operations. return: List where each item is a numpy array after decoder.
__call__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
Apache-2.0
def __call__(self, results): """ Performs normalization operations. Args: imgs: Numpy array. return: np_imgs: Numpy array after normalization. """ if self.inplace: # default is False n = len(results['imgs']) h, w, c = results['imgs'][0].shape norm_imgs = np.empty((n, h, w, c), dtype=np.float32) for i, img in enumerate(results['imgs']): norm_imgs[i] = img for img in norm_imgs: # [n,h,w,c] mean = np.float64(self.mean.reshape(1, -1)) # [1, 3] stdinv = 1 / np.float64(self.std.reshape(1, -1)) # [1, 3] cv2.subtract(img, mean, img) cv2.multiply(img, stdinv, img) else: imgs = results['imgs'] norm_imgs = imgs / 255.0 norm_imgs -= self.mean norm_imgs /= self.std if 'backend' in results and results['backend'] == 'pyav': norm_imgs = paddle.to_tensor(norm_imgs, dtype=paddle.float32) results['imgs'] = norm_imgs return results
Performs normalization operations. Args: imgs: Numpy array. return: np_imgs: Numpy array after normalization.
__call__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/pphuman/video_action_preprocess.py
Apache-2.0
def predict(self, repeats=1): ''' Args: repeats (int): repeats number for prediction Returns: result (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] ''' # model prediction np_boxes, np_boxes_num = None, None for i in range(repeats): self.predictor.run() output_names = self.predictor.get_output_names() boxes_tensor = self.predictor.get_output_handle(output_names[0]) np_boxes = boxes_tensor.copy_to_cpu() boxes_num = self.predictor.get_output_handle(output_names[1]) np_boxes_num = boxes_num.copy_to_cpu() result = dict(boxes=np_boxes, boxes_num=np_boxes_num) return result
Args: repeats (int): repeats number for prediction Returns: result (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max]
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/det_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/det_infer.py
Apache-2.0
def create_inputs(imgs, im_info): """generate input for different model type Args: imgs (list(numpy)): list of images (np.ndarray) im_info (list(dict)): list of image info Returns: inputs (dict): input of model """ inputs = {} im_shape = [] scale_factor = [] if len(imgs) == 1: inputs['image'] = np.array((imgs[0], )).astype('float32') inputs['im_shape'] = np.array( (im_info[0]['im_shape'], )).astype('float32') inputs['scale_factor'] = np.array( (im_info[0]['scale_factor'], )).astype('float32') return inputs for e in im_info: im_shape.append(np.array((e['im_shape'], )).astype('float32')) scale_factor.append(np.array((e['scale_factor'], )).astype('float32')) inputs['im_shape'] = np.concatenate(im_shape, axis=0) inputs['scale_factor'] = np.concatenate(scale_factor, axis=0) imgs_shape = [[e.shape[1], e.shape[2]] for e in imgs] max_shape_h = max([e[0] for e in imgs_shape]) max_shape_w = max([e[1] for e in imgs_shape]) padding_imgs = [] for img in imgs: im_c, im_h, im_w = img.shape[:] padding_im = np.zeros( (im_c, max_shape_h, max_shape_w), dtype=np.float32) padding_im[:, :im_h, :im_w] = img padding_imgs.append(padding_im) inputs['image'] = np.stack(padding_imgs, axis=0) return inputs
generate input for different model type Args: imgs (list(numpy)): list of images (np.ndarray) im_info (list(dict)): list of image info Returns: inputs (dict): input of model
create_inputs
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/det_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/det_infer.py
Apache-2.0
def check_model(self, yml_conf): """ Raises: ValueError: loaded model not in supported model type """ for support_model in SUPPORT_MODELS: if support_model in yml_conf['arch']: return True raise ValueError("Unsupported arch: {}, expect {}".format(yml_conf[ 'arch'], SUPPORT_MODELS))
Raises: ValueError: loaded model not in supported model type
check_model
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/det_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/det_infer.py
Apache-2.0
def load_predictor(model_dir, run_mode='paddle', batch_size=1, device='CPU', min_subgraph_size=3, use_dynamic_shape=False, trt_min_shape=1, trt_max_shape=1280, trt_opt_shape=640, trt_calib_mode=False, cpu_threads=1, enable_mkldnn=False): """set AnalysisConfig, generate AnalysisPredictor Args: model_dir (str): root path of __model__ and __params__ device (str): Choose the device you want to run, it can be: CPU/GPU/XPU, default is CPU run_mode (str): mode of running(paddle/trt_fp32/trt_fp16/trt_int8) use_dynamic_shape (bool): use dynamic shape or not trt_min_shape (int): min shape for dynamic shape in trt trt_max_shape (int): max shape for dynamic shape in trt trt_opt_shape (int): opt shape for dynamic shape in trt trt_calib_mode (bool): If the model is produced by TRT offline quantitative calibration, trt_calib_mode need to set True Returns: predictor (PaddlePredictor): AnalysisPredictor Raises: ValueError: predict by TensorRT need device == 'GPU'. """ if device != 'GPU' and run_mode != 'paddle': raise ValueError( "Predict by TensorRT mode: {}, expect device=='GPU', but device == {}" .format(run_mode, device)) infer_model = os.path.join(model_dir, 'model.pdmodel') infer_params = os.path.join(model_dir, 'model.pdiparams') if not os.path.exists(infer_model): infer_model = os.path.join(model_dir, 'inference.pdmodel') infer_params = os.path.join(model_dir, 'inference.pdiparams') if not os.path.exists(infer_model): raise ValueError("Cannot find any inference model in dir: {},". format(model_dir)) config = Config(infer_model, infer_params) if device == 'GPU': # initial GPU memory(M), device ID config.enable_use_gpu(200, 0) # optimize graph and fuse op config.switch_ir_optim(True) elif device == 'XPU': config.enable_lite_engine() config.enable_xpu(10 * 1024 * 1024) else: config.disable_gpu() config.set_cpu_math_library_num_threads(cpu_threads) if enable_mkldnn: try: # cache 10 different shapes for mkldnn to avoid memory leak config.set_mkldnn_cache_capacity(10) config.enable_mkldnn() except Exception as e: print( "The current environment does not support `mkldnn`, so disable mkldnn." ) pass precision_map = { 'trt_int8': Config.Precision.Int8, 'trt_fp32': Config.Precision.Float32, 'trt_fp16': Config.Precision.Half } if run_mode in precision_map.keys(): config.enable_tensorrt_engine( workspace_size=1 << 25, max_batch_size=batch_size, min_subgraph_size=min_subgraph_size, precision_mode=precision_map[run_mode], use_static=False, use_calib_mode=trt_calib_mode) if use_dynamic_shape: min_input_shape = { 'image': [batch_size, 3, trt_min_shape, trt_min_shape] } max_input_shape = { 'image': [batch_size, 3, trt_max_shape, trt_max_shape] } opt_input_shape = { 'image': [batch_size, 3, trt_opt_shape, trt_opt_shape] } config.set_trt_dynamic_shape_info(min_input_shape, max_input_shape, opt_input_shape) print('trt set dynamic shape done!') # disable print log when predict config.disable_glog_info() # enable shared memory config.enable_memory_optim() # disable feed, fetch OP, needed by zero_copy_run config.switch_use_feed_fetch_ops(False) predictor = create_predictor(config) return predictor, config
set AnalysisConfig, generate AnalysisPredictor Args: model_dir (str): root path of __model__ and __params__ device (str): Choose the device you want to run, it can be: CPU/GPU/XPU, default is CPU run_mode (str): mode of running(paddle/trt_fp32/trt_fp16/trt_int8) use_dynamic_shape (bool): use dynamic shape or not trt_min_shape (int): min shape for dynamic shape in trt trt_max_shape (int): max shape for dynamic shape in trt trt_opt_shape (int): opt shape for dynamic shape in trt trt_calib_mode (bool): If the model is produced by TRT offline quantitative calibration, trt_calib_mode need to set True Returns: predictor (PaddlePredictor): AnalysisPredictor Raises: ValueError: predict by TensorRT need device == 'GPU'.
load_predictor
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/det_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/det_infer.py
Apache-2.0
def predict(self, repeats=1): ''' Args: repeats (int): repeats number for prediction Returns: result (dict): include 'pred_dets': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] FairMOT(JDE)'s result include 'pred_embs': np.ndarray: shape: [N, 128] ''' # model prediction np_pred_dets, np_pred_embs = None, None for i in range(repeats): self.predictor.run() output_names = self.predictor.get_output_names() boxes_tensor = self.predictor.get_output_handle(output_names[0]) np_pred_dets = boxes_tensor.copy_to_cpu() embs_tensor = self.predictor.get_output_handle(output_names[1]) np_pred_embs = embs_tensor.copy_to_cpu() result = dict(pred_dets=np_pred_dets, pred_embs=np_pred_embs) return result
Args: repeats (int): repeats number for prediction Returns: result (dict): include 'pred_dets': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] FairMOT(JDE)'s result include 'pred_embs': np.ndarray: shape: [N, 128]
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot_jde_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot_jde_infer.py
Apache-2.0
def get_current_memory_mb(): """ It is used to Obtain the memory usage of the CPU and GPU during the running of the program. And this function Current program is time-consuming. """ import pynvml import psutil import GPUtil gpu_id = int(os.environ.get('CUDA_VISIBLE_DEVICES', 0)) pid = os.getpid() p = psutil.Process(pid) info = p.memory_full_info() cpu_mem = info.uss / 1024. / 1024. gpu_mem = 0 gpu_percent = 0 gpus = GPUtil.getGPUs() if gpu_id is not None and len(gpus) > 0: gpu_percent = gpus[gpu_id].load pynvml.nvmlInit() handle = pynvml.nvmlDeviceGetHandleByIndex(0) meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle) gpu_mem = meminfo.used / 1024. / 1024. return round(cpu_mem, 4), round(gpu_mem, 4), round(gpu_percent, 4)
It is used to Obtain the memory usage of the CPU and GPU during the running of the program. And this function Current program is time-consuming.
get_current_memory_mb
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot_utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot_utils.py
Apache-2.0
def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200): """ Args: box_scores (N, 5): boxes in corner-form and probabilities. iou_threshold: intersection over union threshold. top_k: keep top_k results. If k <= 0, keep all the results. candidate_size: only consider the candidates with the highest scores. Returns: picked: a list of indexes of the kept boxes """ scores = box_scores[:, -1] boxes = box_scores[:, :-1] picked = [] indexes = np.argsort(scores) indexes = indexes[-candidate_size:] while len(indexes) > 0: current = indexes[-1] picked.append(current) if 0 < top_k == len(picked) or len(indexes) == 1: break current_box = boxes[current, :] indexes = indexes[:-1] rest_boxes = boxes[indexes, :] iou = iou_of( rest_boxes, np.expand_dims( current_box, axis=0), ) indexes = indexes[iou <= iou_threshold] return box_scores[picked, :]
Args: box_scores (N, 5): boxes in corner-form and probabilities. iou_threshold: intersection over union threshold. top_k: keep top_k results. If k <= 0, keep all the results. candidate_size: only consider the candidates with the highest scores. Returns: picked: a list of indexes of the kept boxes
hard_nms
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/picodet_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/picodet_postprocess.py
Apache-2.0
def iou_of(boxes0, boxes1, eps=1e-5): """Return intersection-over-union (Jaccard index) of boxes. Args: boxes0 (N, 4): ground truth boxes. boxes1 (N or 1, 4): predicted boxes. eps: a small number to avoid 0 as denominator. Returns: iou (N): IoU values. """ overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2]) overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:]) overlap_area = area_of(overlap_left_top, overlap_right_bottom) area0 = area_of(boxes0[..., :2], boxes0[..., 2:]) area1 = area_of(boxes1[..., :2], boxes1[..., 2:]) return overlap_area / (area0 + area1 - overlap_area + eps)
Return intersection-over-union (Jaccard index) of boxes. Args: boxes0 (N, 4): ground truth boxes. boxes1 (N or 1, 4): predicted boxes. eps: a small number to avoid 0 as denominator. Returns: iou (N): IoU values.
iou_of
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/picodet_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/picodet_postprocess.py
Apache-2.0
def area_of(left_top, right_bottom): """Compute the areas of rectangles given two corners. Args: left_top (N, 2): left top corner. right_bottom (N, 2): right bottom corner. Returns: area (N): return the area. """ hw = np.clip(right_bottom - left_top, 0.0, None) return hw[..., 0] * hw[..., 1]
Compute the areas of rectangles given two corners. Args: left_top (N, 2): left top corner. right_bottom (N, 2): right bottom corner. Returns: area (N): return the area.
area_of
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/picodet_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/picodet_postprocess.py
Apache-2.0
def decode_image(im_file, im_info): """read rgb image Args: im_file (str|np.ndarray): input can be image path or np.ndarray im_info (dict): info of image Returns: im (np.ndarray): processed image (np.ndarray) im_info (dict): info of processed image """ if isinstance(im_file, str): with open(im_file, 'rb') as f: im_read = f.read() data = np.frombuffer(im_read, dtype='uint8') im = cv2.imdecode(data, 1) # BGR mode, but need RGB mode im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) else: im = im_file im_info['im_shape'] = np.array(im.shape[:2], dtype=np.float32) im_info['scale_factor'] = np.array([1., 1.], dtype=np.float32) return im, im_info
read rgb image Args: im_file (str|np.ndarray): input can be image path or np.ndarray im_info (dict): info of image Returns: im (np.ndarray): processed image (np.ndarray) im_info (dict): info of processed image
decode_image
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
Apache-2.0
def __call__(self, im, im_info): """ Args: im (np.ndarray): image (np.ndarray) im_info (dict): info of image Returns: im (np.ndarray): processed image (np.ndarray) im_info (dict): info of processed image """ assert len(self.target_size) == 2 assert self.target_size[0] > 0 and self.target_size[1] > 0 im_channel = im.shape[2] im_scale_y, im_scale_x = self.generate_scale(im) im = cv2.resize( im, None, None, fx=im_scale_x, fy=im_scale_y, interpolation=self.interp) im_info['im_shape'] = np.array(im.shape[:2]).astype('float32') im_info['scale_factor'] = np.array( [im_scale_y, im_scale_x]).astype('float32') return im, im_info
Args: im (np.ndarray): image (np.ndarray) im_info (dict): info of image Returns: im (np.ndarray): processed image (np.ndarray) im_info (dict): info of processed image
__call__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
Apache-2.0
def generate_scale(self, im): """ Args: im (np.ndarray): image (np.ndarray) Returns: im_scale_x: the resize ratio of X im_scale_y: the resize ratio of Y """ origin_shape = im.shape[:2] im_c = im.shape[2] if self.keep_ratio: im_size_min = np.min(origin_shape) im_size_max = np.max(origin_shape) target_size_min = np.min(self.target_size) target_size_max = np.max(self.target_size) im_scale = float(target_size_min) / float(im_size_min) if np.round(im_scale * im_size_max) > target_size_max: im_scale = float(target_size_max) / float(im_size_max) im_scale_x = im_scale im_scale_y = im_scale else: resize_h, resize_w = self.target_size im_scale_y = resize_h / float(origin_shape[0]) im_scale_x = resize_w / float(origin_shape[1]) return im_scale_y, im_scale_x
Args: im (np.ndarray): image (np.ndarray) Returns: im_scale_x: the resize ratio of X im_scale_y: the resize ratio of Y
generate_scale
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
Apache-2.0
def __init__(self, target_size): """ Resize image to target size, convert normalized xywh to pixel xyxy format ([x_center, y_center, width, height] -> [x0, y0, x1, y1]). Args: target_size (int|list): image target size. """ super(LetterBoxResize, self).__init__() if isinstance(target_size, int): target_size = [target_size, target_size] self.target_size = target_size
Resize image to target size, convert normalized xywh to pixel xyxy format ([x_center, y_center, width, height] -> [x0, y0, x1, y1]). Args: target_size (int|list): image target size.
__init__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
Apache-2.0
def __init__(self, size, fill_value=[114.0, 114.0, 114.0]): """ Pad image to a specified size. Args: size (list[int]): image target size fill_value (list[float]): rgb value of pad area, default (114.0, 114.0, 114.0) """ super(Pad, self).__init__() if isinstance(size, int): size = [size, size] self.size = size self.fill_value = fill_value
Pad image to a specified size. Args: size (list[int]): image target size fill_value (list[float]): rgb value of pad area, default (114.0, 114.0, 114.0)
__init__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/preprocess.py
Apache-2.0
def to_tlbr(self): """ Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[2:] += ret[:2] return ret
Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`.
to_tlbr
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/utils.py
Apache-2.0
def to_xyah(self): """ Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`. """ ret = self.tlwh.copy() ret[:2] += ret[2:] / 2 ret[2] /= ret[3] return ret
Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`.
to_xyah
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/utils.py
Apache-2.0
def update_object_info(object_in_region_info, result, region_type, entrance, fps, illegal_parking_time, distance_threshold_frame=3, distance_threshold_interval=50): ''' For consecutive frames, the distance between two frame is smaller than distance_threshold_frame, regard as parking For parking in general, the move distance should smaller than distance_threshold_interval The moving distance of the vehicle is scaled according to the y, which is inversely proportional to y. ''' assert region_type in [ 'custom' ], "region_type should be 'custom' when do break_in counting." assert len( entrance ) >= 4, "entrance should be at least 3 points and (w,h) of image when do break_in counting." frame_id, tlwhs, tscores, track_ids = result # result from mot im_w, im_h = entrance[-1][:] entrance = np.array(entrance[:-1]) illegal_parking_dict = {} for tlwh, score, track_id in zip(tlwhs, tscores, track_ids): if track_id < 0: continue x1, y1, w, h = tlwh center_x = min(x1 + w / 2., im_w - 1) center_y = min(y1 + h / 2, im_h - 1) if not in_quadrangle([center_x, center_y], entrance, im_h, im_w): continue current_center = (center_x, center_y) if track_id not in object_in_region_info.keys( ): # first time appear in region object_in_region_info[track_id] = {} object_in_region_info[track_id]["start_frame"] = frame_id object_in_region_info[track_id]["end_frame"] = frame_id object_in_region_info[track_id]["prev_center"] = current_center object_in_region_info[track_id]["start_center"] = current_center else: prev_center = object_in_region_info[track_id]["prev_center"] dis = distance(current_center, prev_center) scaled_dis = 200 * dis / ( current_center[1] + 1) # scale distance according to y dis = scaled_dis if dis < distance_threshold_frame: # not move object_in_region_info[track_id]["end_frame"] = frame_id object_in_region_info[track_id]["prev_center"] = current_center else: # move object_in_region_info[track_id]["start_frame"] = frame_id object_in_region_info[track_id]["end_frame"] = frame_id object_in_region_info[track_id]["prev_center"] = current_center object_in_region_info[track_id][ "start_center"] = current_center # whether current object parking distance_from_start = distance( object_in_region_info[track_id]["start_center"], current_center) if distance_from_start > distance_threshold_interval: # moved object_in_region_info[track_id]["start_frame"] = frame_id object_in_region_info[track_id]["end_frame"] = frame_id object_in_region_info[track_id]["prev_center"] = current_center object_in_region_info[track_id]["start_center"] = current_center continue if (object_in_region_info[track_id]["end_frame"]-object_in_region_info[track_id]["start_frame"]) /fps >= illegal_parking_time \ and distance_from_start<distance_threshold_interval: illegal_parking_dict[track_id] = {"bbox": [x1, y1, w, h]} return object_in_region_info, illegal_parking_dict
For consecutive frames, the distance between two frame is smaller than distance_threshold_frame, regard as parking For parking in general, the move distance should smaller than distance_threshold_interval The moving distance of the vehicle is scaled according to the y, which is inversely proportional to y.
update_object_info
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/utils.py
Apache-2.0
def visualize_box_mask(im, results, labels, threshold=0.5): """ Args: im (str/np.ndarray): path of image/np.ndarray read by cv2 results (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] labels (list): labels:['class1', ..., 'classn'] threshold (float): Threshold of score. Returns: im (PIL.Image.Image): visualized image """ if isinstance(im, str): im = Image.open(im).convert('RGB') else: im = Image.fromarray(im) if 'boxes' in results and len(results['boxes']) > 0: im = draw_box(im, results['boxes'], labels, threshold=threshold) return im
Args: im (str/np.ndarray): path of image/np.ndarray read by cv2 results (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] labels (list): labels:['class1', ..., 'classn'] threshold (float): Threshold of score. Returns: im (PIL.Image.Image): visualized image
visualize_box_mask
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/visualize.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/visualize.py
Apache-2.0
def get_color_map_list(num_classes): """ Args: num_classes (int): number of class Returns: color_map (list): RGB color list """ color_map = num_classes * [0, 0, 0] for i in range(0, num_classes): j = 0 lab = i while lab: color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j)) color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j)) color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j)) j += 1 lab >>= 3 color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)] return color_map
Args: num_classes (int): number of class Returns: color_map (list): RGB color list
get_color_map_list
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/visualize.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/visualize.py
Apache-2.0
def draw_box(im, np_boxes, labels, threshold=0.5): """ Args: im (PIL.Image.Image): PIL image np_boxes (np.ndarray): shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] labels (list): labels:['class1', ..., 'classn'] threshold (float): threshold of box Returns: im (PIL.Image.Image): visualized image """ draw_thickness = min(im.size) // 320 draw = ImageDraw.Draw(im) clsid2color = {} color_list = get_color_map_list(len(labels)) expect_boxes = (np_boxes[:, 1] > threshold) & (np_boxes[:, 0] > -1) np_boxes = np_boxes[expect_boxes, :] for dt in np_boxes: clsid, bbox, score = int(dt[0]), dt[2:], dt[1] if clsid not in clsid2color: clsid2color[clsid] = color_list[clsid] color = tuple(clsid2color[clsid]) if len(bbox) == 4: xmin, ymin, xmax, ymax = bbox print('class_id:{:d}, confidence:{:.4f}, left_top:[{:.2f},{:.2f}],' 'right_bottom:[{:.2f},{:.2f}]'.format( int(clsid), score, xmin, ymin, xmax, ymax)) # draw bbox draw.line( [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin)], width=draw_thickness, fill=color) elif len(bbox) == 8: x1, y1, x2, y2, x3, y3, x4, y4 = bbox draw.line( [(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1)], width=2, fill=color) xmin = min(x1, x2, x3, x4) ymin = min(y1, y2, y3, y4) # draw label text = "{} {:.4f}".format(labels[clsid], score) tw, th = draw.textsize(text) draw.rectangle( [(xmin + 1, ymin - th), (xmin + tw + 1, ymin)], fill=color) draw.text((xmin + 1, ymin - th), text, fill=(255, 255, 255)) return im
Args: im (PIL.Image.Image): PIL image np_boxes (np.ndarray): shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] labels (list): labels:['class1', ..., 'classn'] threshold (float): threshold of box Returns: im (PIL.Image.Image): visualized image
draw_box
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/visualize.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/visualize.py
Apache-2.0
def iou_1toN(bbox, candidates): """ Computer intersection over union (IoU) by one box to N candidates. Args: bbox (ndarray): A bounding box in format `(top left x, top left y, width, height)`. candidates (ndarray): A matrix of candidate bounding boxes (one per row) in the same format as `bbox`. Returns: ious (ndarray): The intersection over union in [0, 1] between the `bbox` and each candidate. A higher score means a larger fraction of the `bbox` is occluded by the candidate. """ bbox_tl = bbox[:2] bbox_br = bbox[:2] + bbox[2:] candidates_tl = candidates[:, :2] candidates_br = candidates[:, :2] + candidates[:, 2:] tl = np.c_[np.maximum(bbox_tl[0], candidates_tl[:, 0])[:, np.newaxis], np.maximum(bbox_tl[1], candidates_tl[:, 1])[:, np.newaxis]] br = np.c_[np.minimum(bbox_br[0], candidates_br[:, 0])[:, np.newaxis], np.minimum(bbox_br[1], candidates_br[:, 1])[:, np.newaxis]] wh = np.maximum(0., br - tl) area_intersection = wh.prod(axis=1) area_bbox = bbox[2:].prod() area_candidates = candidates[:, 2:].prod(axis=1) ious = area_intersection / ( area_bbox + area_candidates - area_intersection) return ious
Computer intersection over union (IoU) by one box to N candidates. Args: bbox (ndarray): A bounding box in format `(top left x, top left y, width, height)`. candidates (ndarray): A matrix of candidate bounding boxes (one per row) in the same format as `bbox`. Returns: ious (ndarray): The intersection over union in [0, 1] between the `bbox` and each candidate. A higher score means a larger fraction of the `bbox` is occluded by the candidate.
iou_1toN
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def iou_cost(tracks, detections, track_indices=None, detection_indices=None): """ IoU distance metric. Args: tracks (list[Track]): A list of tracks. detections (list[Detection]): A list of detections. track_indices (Optional[list[int]]): A list of indices to tracks that should be matched. Defaults to all `tracks`. detection_indices (Optional[list[int]]): A list of indices to detections that should be matched. Defaults to all `detections`. Returns: cost_matrix (ndarray): A cost matrix of shape len(track_indices), len(detection_indices) where entry (i, j) is `1 - iou(tracks[track_indices[i]], detections[detection_indices[j]])`. """ if track_indices is None: track_indices = np.arange(len(tracks)) if detection_indices is None: detection_indices = np.arange(len(detections)) cost_matrix = np.zeros((len(track_indices), len(detection_indices))) for row, track_idx in enumerate(track_indices): if tracks[track_idx].time_since_update > 1: cost_matrix[row, :] = 1e+5 continue bbox = tracks[track_idx].to_tlwh() candidates = np.asarray( [detections[i].tlwh for i in detection_indices]) cost_matrix[row, :] = 1. - iou_1toN(bbox, candidates) return cost_matrix
IoU distance metric. Args: tracks (list[Track]): A list of tracks. detections (list[Detection]): A list of detections. track_indices (Optional[list[int]]): A list of indices to tracks that should be matched. Defaults to all `tracks`. detection_indices (Optional[list[int]]): A list of indices to detections that should be matched. Defaults to all `detections`. Returns: cost_matrix (ndarray): A cost matrix of shape len(track_indices), len(detection_indices) where entry (i, j) is `1 - iou(tracks[track_indices[i]], detections[detection_indices[j]])`.
iou_cost
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def _nn_euclidean_distance(s, q): """ Compute pair-wise squared (Euclidean) distance between points in `s` and `q`. Args: s (ndarray): Sample points: an NxM matrix of N samples of dimensionality M. q (ndarray): Query points: an LxM matrix of L samples of dimensionality M. Returns: distances (ndarray): A vector of length M that contains for each entry in `q` the smallest Euclidean distance to a sample in `s`. """ s, q = np.asarray(s), np.asarray(q) if len(s) == 0 or len(q) == 0: return np.zeros((len(s), len(q))) s2, q2 = np.square(s).sum(axis=1), np.square(q).sum(axis=1) distances = -2. * np.dot(s, q.T) + s2[:, None] + q2[None, :] distances = np.clip(distances, 0., float(np.inf)) return np.maximum(0.0, distances.min(axis=0))
Compute pair-wise squared (Euclidean) distance between points in `s` and `q`. Args: s (ndarray): Sample points: an NxM matrix of N samples of dimensionality M. q (ndarray): Query points: an LxM matrix of L samples of dimensionality M. Returns: distances (ndarray): A vector of length M that contains for each entry in `q` the smallest Euclidean distance to a sample in `s`.
_nn_euclidean_distance
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def _nn_cosine_distance(s, q): """ Compute pair-wise cosine distance between points in `s` and `q`. Args: s (ndarray): Sample points: an NxM matrix of N samples of dimensionality M. q (ndarray): Query points: an LxM matrix of L samples of dimensionality M. Returns: distances (ndarray): A vector of length M that contains for each entry in `q` the smallest Euclidean distance to a sample in `s`. """ s = np.asarray(s) / np.linalg.norm(s, axis=1, keepdims=True) q = np.asarray(q) / np.linalg.norm(q, axis=1, keepdims=True) distances = 1. - np.dot(s, q.T) return distances.min(axis=0)
Compute pair-wise cosine distance between points in `s` and `q`. Args: s (ndarray): Sample points: an NxM matrix of N samples of dimensionality M. q (ndarray): Query points: an LxM matrix of L samples of dimensionality M. Returns: distances (ndarray): A vector of length M that contains for each entry in `q` the smallest Euclidean distance to a sample in `s`.
_nn_cosine_distance
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def partial_fit(self, features, targets, active_targets): """ Update the distance metric with new data. Args: features (ndarray): An NxM matrix of N features of dimensionality M. targets (ndarray): An integer array of associated target identities. active_targets (List[int]): A list of targets that are currently present in the scene. """ for feature, target in zip(features, targets): self.samples.setdefault(target, []).append(feature) if self.budget is not None: self.samples[target] = self.samples[target][-self.budget:] self.samples = {k: self.samples[k] for k in active_targets}
Update the distance metric with new data. Args: features (ndarray): An NxM matrix of N features of dimensionality M. targets (ndarray): An integer array of associated target identities. active_targets (List[int]): A list of targets that are currently present in the scene.
partial_fit
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def distance(self, features, targets): """ Compute distance between features and targets. Args: features (ndarray): An NxM matrix of N features of dimensionality M. targets (list[int]): A list of targets to match the given `features` against. Returns: cost_matrix (ndarray): a cost matrix of shape len(targets), len(features), where element (i, j) contains the closest squared distance between `targets[i]` and `features[j]`. """ cost_matrix = np.zeros((len(targets), len(features))) for i, target in enumerate(targets): cost_matrix[i, :] = self._metric(self.samples[target], features) return cost_matrix
Compute distance between features and targets. Args: features (ndarray): An NxM matrix of N features of dimensionality M. targets (list[int]): A list of targets to match the given `features` against. Returns: cost_matrix (ndarray): a cost matrix of shape len(targets), len(features), where element (i, j) contains the closest squared distance between `targets[i]` and `features[j]`.
distance
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def min_cost_matching(distance_metric, max_distance, tracks, detections, track_indices=None, detection_indices=None): """ Solve linear assignment problem. Args: distance_metric : Callable[List[Track], List[Detection], List[int], List[int]) -> ndarray The distance metric is given a list of tracks and detections as well as a list of N track indices and M detection indices. The metric should return the NxM dimensional cost matrix, where element (i, j) is the association cost between the i-th track in the given track indices and the j-th detection in the given detection_indices. max_distance (float): Gating threshold. Associations with cost larger than this value are disregarded. tracks (list[Track]): A list of predicted tracks at the current time step. detections (list[Detection]): A list of detections at the current time step. track_indices (list[int]): List of track indices that maps rows in `cost_matrix` to tracks in `tracks`. detection_indices (List[int]): List of detection indices that maps columns in `cost_matrix` to detections in `detections`. Returns: A tuple (List[(int, int)], List[int], List[int]) with the following three entries: * A list of matched track and detection indices. * A list of unmatched track indices. * A list of unmatched detection indices. """ if track_indices is None: track_indices = np.arange(len(tracks)) if detection_indices is None: detection_indices = np.arange(len(detections)) if len(detection_indices) == 0 or len(track_indices) == 0: return [], track_indices, detection_indices # Nothing to match. cost_matrix = distance_metric(tracks, detections, track_indices, detection_indices) cost_matrix[cost_matrix > max_distance] = max_distance + 1e-5 indices = linear_sum_assignment(cost_matrix) matches, unmatched_tracks, unmatched_detections = [], [], [] for col, detection_idx in enumerate(detection_indices): if col not in indices[1]: unmatched_detections.append(detection_idx) for row, track_idx in enumerate(track_indices): if row not in indices[0]: unmatched_tracks.append(track_idx) for row, col in zip(indices[0], indices[1]): track_idx = track_indices[row] detection_idx = detection_indices[col] if cost_matrix[row, col] > max_distance: unmatched_tracks.append(track_idx) unmatched_detections.append(detection_idx) else: matches.append((track_idx, detection_idx)) return matches, unmatched_tracks, unmatched_detections
Solve linear assignment problem. Args: distance_metric : Callable[List[Track], List[Detection], List[int], List[int]) -> ndarray The distance metric is given a list of tracks and detections as well as a list of N track indices and M detection indices. The metric should return the NxM dimensional cost matrix, where element (i, j) is the association cost between the i-th track in the given track indices and the j-th detection in the given detection_indices. max_distance (float): Gating threshold. Associations with cost larger than this value are disregarded. tracks (list[Track]): A list of predicted tracks at the current time step. detections (list[Detection]): A list of detections at the current time step. track_indices (list[int]): List of track indices that maps rows in `cost_matrix` to tracks in `tracks`. detection_indices (List[int]): List of detection indices that maps columns in `cost_matrix` to detections in `detections`. Returns: A tuple (List[(int, int)], List[int], List[int]) with the following three entries: * A list of matched track and detection indices. * A list of unmatched track indices. * A list of unmatched detection indices.
min_cost_matching
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def matching_cascade(distance_metric, max_distance, cascade_depth, tracks, detections, track_indices=None, detection_indices=None): """ Run matching cascade. Args: distance_metric : Callable[List[Track], List[Detection], List[int], List[int]) -> ndarray The distance metric is given a list of tracks and detections as well as a list of N track indices and M detection indices. The metric should return the NxM dimensional cost matrix, where element (i, j) is the association cost between the i-th track in the given track indices and the j-th detection in the given detection_indices. max_distance (float): Gating threshold. Associations with cost larger than this value are disregarded. cascade_depth (int): The cascade depth, should be se to the maximum track age. tracks (list[Track]): A list of predicted tracks at the current time step. detections (list[Detection]): A list of detections at the current time step. track_indices (list[int]): List of track indices that maps rows in `cost_matrix` to tracks in `tracks`. detection_indices (List[int]): List of detection indices that maps columns in `cost_matrix` to detections in `detections`. Returns: A tuple (List[(int, int)], List[int], List[int]) with the following three entries: * A list of matched track and detection indices. * A list of unmatched track indices. * A list of unmatched detection indices. """ if track_indices is None: track_indices = list(range(len(tracks))) if detection_indices is None: detection_indices = list(range(len(detections))) unmatched_detections = detection_indices matches = [] for level in range(cascade_depth): if len(unmatched_detections) == 0: # No detections left break track_indices_l = [ k for k in track_indices if tracks[k].time_since_update == 1 + level ] if len(track_indices_l) == 0: # Nothing to match at this level continue matches_l, _, unmatched_detections = \ min_cost_matching( distance_metric, max_distance, tracks, detections, track_indices_l, unmatched_detections) matches += matches_l unmatched_tracks = list(set(track_indices) - set(k for k, _ in matches)) return matches, unmatched_tracks, unmatched_detections
Run matching cascade. Args: distance_metric : Callable[List[Track], List[Detection], List[int], List[int]) -> ndarray The distance metric is given a list of tracks and detections as well as a list of N track indices and M detection indices. The metric should return the NxM dimensional cost matrix, where element (i, j) is the association cost between the i-th track in the given track indices and the j-th detection in the given detection_indices. max_distance (float): Gating threshold. Associations with cost larger than this value are disregarded. cascade_depth (int): The cascade depth, should be se to the maximum track age. tracks (list[Track]): A list of predicted tracks at the current time step. detections (list[Detection]): A list of detections at the current time step. track_indices (list[int]): List of track indices that maps rows in `cost_matrix` to tracks in `tracks`. detection_indices (List[int]): List of detection indices that maps columns in `cost_matrix` to detections in `detections`. Returns: A tuple (List[(int, int)], List[int], List[int]) with the following three entries: * A list of matched track and detection indices. * A list of unmatched track indices. * A list of unmatched detection indices.
matching_cascade
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def gate_cost_matrix(kf, cost_matrix, tracks, detections, track_indices, detection_indices, gated_cost=INFTY_COST, only_position=False): """ Invalidate infeasible entries in cost matrix based on the state distributions obtained by Kalman filtering. Args: kf (object): The Kalman filter. cost_matrix (ndarray): The NxM dimensional cost matrix, where N is the number of track indices and M is the number of detection indices, such that entry (i, j) is the association cost between `tracks[track_indices[i]]` and `detections[detection_indices[j]]`. tracks (list[Track]): A list of predicted tracks at the current time step. detections (list[Detection]): A list of detections at the current time step. track_indices (List[int]): List of track indices that maps rows in `cost_matrix` to tracks in `tracks`. detection_indices (List[int]): List of detection indices that maps columns in `cost_matrix` to detections in `detections`. gated_cost (Optional[float]): Entries in the cost matrix corresponding to infeasible associations are set this value. Defaults to a very large value. only_position (Optional[bool]): If True, only the x, y position of the state distribution is considered during gating. Default False. """ gating_dim = 2 if only_position else 4 gating_threshold = kalman_filter.chi2inv95[gating_dim] measurements = np.asarray( [detections[i].to_xyah() for i in detection_indices]) for row, track_idx in enumerate(track_indices): track = tracks[track_idx] gating_distance = kf.gating_distance(track.mean, track.covariance, measurements, only_position) cost_matrix[row, gating_distance > gating_threshold] = gated_cost return cost_matrix
Invalidate infeasible entries in cost matrix based on the state distributions obtained by Kalman filtering. Args: kf (object): The Kalman filter. cost_matrix (ndarray): The NxM dimensional cost matrix, where N is the number of track indices and M is the number of detection indices, such that entry (i, j) is the association cost between `tracks[track_indices[i]]` and `detections[detection_indices[j]]`. tracks (list[Track]): A list of predicted tracks at the current time step. detections (list[Detection]): A list of detections at the current time step. track_indices (List[int]): List of track indices that maps rows in `cost_matrix` to tracks in `tracks`. detection_indices (List[int]): List of detection indices that maps columns in `cost_matrix` to detections in `detections`. gated_cost (Optional[float]): Entries in the cost matrix corresponding to infeasible associations are set this value. Defaults to a very large value. only_position (Optional[bool]): If True, only the x, y position of the state distribution is considered during gating. Default False.
gate_cost_matrix
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/deepsort_matching.py
Apache-2.0
def iou_distance(atracks, btracks): """ Compute cost based on IoU between two list[STrack]. """ if (len(atracks) > 0 and isinstance(atracks[0], np.ndarray)) or ( len(btracks) > 0 and isinstance(btracks[0], np.ndarray)): atlbrs = atracks btlbrs = btracks else: atlbrs = [track.tlbr for track in atracks] btlbrs = [track.tlbr for track in btracks] _ious = bbox_ious(atlbrs, btlbrs) cost_matrix = 1 - _ious return cost_matrix
Compute cost based on IoU between two list[STrack].
iou_distance
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/jde_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/jde_matching.py
Apache-2.0
def embedding_distance(tracks, detections, metric='euclidean'): """ Compute cost based on features between two list[STrack]. """ cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float) if cost_matrix.size == 0: return cost_matrix det_features = np.asarray( [track.curr_feat for track in detections], dtype=np.float) track_features = np.asarray( [track.smooth_feat for track in tracks], dtype=np.float) cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric)) # Nomalized features return cost_matrix
Compute cost based on features between two list[STrack].
embedding_distance
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/jde_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/jde_matching.py
Apache-2.0
def iou_batch(bboxes1, bboxes2): """ From SORT: Computes IOU between two bboxes in the form [x1,y1,x2,y2] """ bboxes2 = np.expand_dims(bboxes2, 0) bboxes1 = np.expand_dims(bboxes1, 1) xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0]) yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1]) xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2]) yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3]) w = np.maximum(0., xx2 - xx1) h = np.maximum(0., yy2 - yy1) wh = w * h o = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1]) + (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh) return (o)
From SORT: Computes IOU between two bboxes in the form [x1,y1,x2,y2]
iou_batch
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/ocsort_matching.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/matching/ocsort_matching.py
Apache-2.0
def initiate(self, measurement): """ Create track from unassociated measurement. Args: measurement (ndarray): Bounding box coordinates (x, y, a, h) with center position (x, y), aspect ratio a, and height h. Returns: The mean vector (8 dimensional) and covariance matrix (8x8 dimensional) of the new track. Unobserved velocities are initialized to 0 mean. """ mean_pos = measurement mean_vel = np.zeros_like(mean_pos) mean = np.r_[mean_pos, mean_vel] std = [ 2 * self._std_weight_position * measurement[3], 2 * self._std_weight_position * measurement[3], 1e-2, 2 * self._std_weight_position * measurement[3], 10 * self._std_weight_velocity * measurement[3], 10 * self._std_weight_velocity * measurement[3], 1e-5, 10 * self._std_weight_velocity * measurement[3] ] covariance = np.diag(np.square(std)) return mean, covariance
Create track from unassociated measurement. Args: measurement (ndarray): Bounding box coordinates (x, y, a, h) with center position (x, y), aspect ratio a, and height h. Returns: The mean vector (8 dimensional) and covariance matrix (8x8 dimensional) of the new track. Unobserved velocities are initialized to 0 mean.
initiate
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
Apache-2.0
def predict(self, mean, covariance): """ Run Kalman filter prediction step. Args: mean (ndarray): The 8 dimensional mean vector of the object state at the previous time step. covariance (ndarray): The 8x8 dimensional covariance matrix of the object state at the previous time step. Returns: The mean vector and covariance matrix of the predicted state. Unobserved velocities are initialized to 0 mean. """ std_pos = [ self._std_weight_position * mean[3], self._std_weight_position * mean[3], 1e-2, self._std_weight_position * mean[3] ] std_vel = [ self._std_weight_velocity * mean[3], self._std_weight_velocity * mean[3], 1e-5, self._std_weight_velocity * mean[3] ] motion_cov = np.diag(np.square(np.r_[std_pos, std_vel])) #mean = np.dot(self._motion_mat, mean) mean = np.dot(mean, self._motion_mat.T) covariance = np.linalg.multi_dot( (self._motion_mat, covariance, self._motion_mat.T)) + motion_cov return mean, covariance
Run Kalman filter prediction step. Args: mean (ndarray): The 8 dimensional mean vector of the object state at the previous time step. covariance (ndarray): The 8x8 dimensional covariance matrix of the object state at the previous time step. Returns: The mean vector and covariance matrix of the predicted state. Unobserved velocities are initialized to 0 mean.
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
Apache-2.0
def project(self, mean, covariance): """ Project state distribution to measurement space. Args mean (ndarray): The state's mean vector (8 dimensional array). covariance (ndarray): The state's covariance matrix (8x8 dimensional). Returns: The projected mean and covariance matrix of the given state estimate. """ std = [ self._std_weight_position * mean[3], self._std_weight_position * mean[3], 1e-1, self._std_weight_position * mean[3] ] innovation_cov = np.diag(np.square(std)) mean = np.dot(self._update_mat, mean) covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T)) return mean, covariance + innovation_cov
Project state distribution to measurement space. Args mean (ndarray): The state's mean vector (8 dimensional array). covariance (ndarray): The state's covariance matrix (8x8 dimensional). Returns: The projected mean and covariance matrix of the given state estimate.
project
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
Apache-2.0
def multi_predict(self, mean, covariance): """ Run Kalman filter prediction step (Vectorized version). Args: mean (ndarray): The Nx8 dimensional mean matrix of the object states at the previous time step. covariance (ndarray): The Nx8x8 dimensional covariance matrics of the object states at the previous time step. Returns: The mean vector and covariance matrix of the predicted state. Unobserved velocities are initialized to 0 mean. """ std_pos = [ self._std_weight_position * mean[:, 3], self._std_weight_position * mean[:, 3], 1e-2 * np.ones_like(mean[:, 3]), self._std_weight_position * mean[:, 3] ] std_vel = [ self._std_weight_velocity * mean[:, 3], self._std_weight_velocity * mean[:, 3], 1e-5 * np.ones_like(mean[:, 3]), self._std_weight_velocity * mean[:, 3] ] sqr = np.square(np.r_[std_pos, std_vel]).T motion_cov = [] for i in range(len(mean)): motion_cov.append(np.diag(sqr[i])) motion_cov = np.asarray(motion_cov) mean = np.dot(mean, self._motion_mat.T) left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2)) covariance = np.dot(left, self._motion_mat.T) + motion_cov return mean, covariance
Run Kalman filter prediction step (Vectorized version). Args: mean (ndarray): The Nx8 dimensional mean matrix of the object states at the previous time step. covariance (ndarray): The Nx8x8 dimensional covariance matrics of the object states at the previous time step. Returns: The mean vector and covariance matrix of the predicted state. Unobserved velocities are initialized to 0 mean.
multi_predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
Apache-2.0
def update(self, mean, covariance, measurement): """ Run Kalman filter correction step. Args: mean (ndarray): The predicted state's mean vector (8 dimensional). covariance (ndarray): The state's covariance matrix (8x8 dimensional). measurement (ndarray): The 4 dimensional measurement vector (x, y, a, h), where (x, y) is the center position, a the aspect ratio, and h the height of the bounding box. Returns: The measurement-corrected state distribution. """ projected_mean, projected_cov = self.project(mean, covariance) chol_factor, lower = scipy.linalg.cho_factor( projected_cov, lower=True, check_finite=False) kalman_gain = scipy.linalg.cho_solve( (chol_factor, lower), np.dot(covariance, self._update_mat.T).T, check_finite=False).T innovation = measurement - projected_mean new_mean = mean + np.dot(innovation, kalman_gain.T) new_covariance = covariance - np.linalg.multi_dot( (kalman_gain, projected_cov, kalman_gain.T)) return new_mean, new_covariance
Run Kalman filter correction step. Args: mean (ndarray): The predicted state's mean vector (8 dimensional). covariance (ndarray): The state's covariance matrix (8x8 dimensional). measurement (ndarray): The 4 dimensional measurement vector (x, y, a, h), where (x, y) is the center position, a the aspect ratio, and h the height of the bounding box. Returns: The measurement-corrected state distribution.
update
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
Apache-2.0
def gating_distance(self, mean, covariance, measurements, only_position=False, metric='maha'): """ Compute gating distance between state distribution and measurements. A suitable distance threshold can be obtained from `chi2inv95`. If `only_position` is False, the chi-square distribution has 4 degrees of freedom, otherwise 2. Args: mean (ndarray): Mean vector over the state distribution (8 dimensional). covariance (ndarray): Covariance of the state distribution (8x8 dimensional). measurements (ndarray): An Nx4 dimensional matrix of N measurements, each in format (x, y, a, h) where (x, y) is the bounding box center position, a the aspect ratio, and h the height. only_position (Optional[bool]): If True, distance computation is done with respect to the bounding box center position only. metric (str): Metric type, 'gaussian' or 'maha'. Returns An array of length N, where the i-th element contains the squared Mahalanobis distance between (mean, covariance) and `measurements[i]`. """ mean, covariance = self.project(mean, covariance) if only_position: mean, covariance = mean[:2], covariance[:2, :2] measurements = measurements[:, :2] d = measurements - mean if metric == 'gaussian': return np.sum(d * d, axis=1) elif metric == 'maha': cholesky_factor = np.linalg.cholesky(covariance) z = scipy.linalg.solve_triangular( cholesky_factor, d.T, lower=True, check_finite=False, overwrite_b=True) squared_maha = np.sum(z * z, axis=0) return squared_maha else: raise ValueError('invalid distance metric')
Compute gating distance between state distribution and measurements. A suitable distance threshold can be obtained from `chi2inv95`. If `only_position` is False, the chi-square distribution has 4 degrees of freedom, otherwise 2. Args: mean (ndarray): Mean vector over the state distribution (8 dimensional). covariance (ndarray): Covariance of the state distribution (8x8 dimensional). measurements (ndarray): An Nx4 dimensional matrix of N measurements, each in format (x, y, a, h) where (x, y) is the bounding box center position, a the aspect ratio, and h the height. only_position (Optional[bool]): If True, distance computation is done with respect to the bounding box center position only. metric (str): Metric type, 'gaussian' or 'maha'. Returns An array of length N, where the i-th element contains the squared Mahalanobis distance between (mean, covariance) and `measurements[i]`.
gating_distance
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/motion/kalman_filter.py
Apache-2.0
def sub_cluster(cid_tid_dict, scene_cluster, use_ff=True, use_rerank=True, use_camera=False, use_st_filter=False): ''' cid_tid_dict: all camera_id and track_id scene_cluster: like [41, 42, 43, 44, 45, 46] in AIC21 MTMCT S06 test videos ''' assert (len(scene_cluster) != 0), "Error: scene_cluster length equals 0" cid_tids = sorted( [key for key in cid_tid_dict.keys() if key[0] in scene_cluster]) if use_camera: clu = get_labels_with_camera( cid_tid_dict, cid_tids, use_ff=use_ff, use_rerank=use_rerank, use_st_filter=use_st_filter) else: clu = get_labels( cid_tid_dict, cid_tids, use_ff=use_ff, use_rerank=use_rerank, use_st_filter=use_st_filter) new_clu = list() for c_list in clu: if len(c_list) <= 1: continue cam_list = [cid_tids[c][0] for c in c_list] if len(cam_list) != len(set(cam_list)): continue new_clu.append([cid_tids[c] for c in c_list]) all_clu = new_clu cid_tid_label = dict() for i, c_list in enumerate(all_clu): for c in c_list: cid_tid_label[c] = i + 1 return cid_tid_label
cid_tid_dict: all camera_id and track_id scene_cluster: like [41, 42, 43, 44, 45, 46] in AIC21 MTMCT S06 test videos
sub_cluster
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/mtmct/postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/mtmct/postprocess.py
Apache-2.0
def getData(fpath, names=None, sep='\s+|\t+|,'): """ Get the necessary track data from a file handle. Args: fpath (str) : Original path of file reading from. names (list[str]): List of column names for the data. sep (str): Allowed separators regular expression string. Return: df (pandas.DataFrame): Data frame containing the data loaded from the stream with optionally assigned column names. No index is set on the data. """ try: df = pd.read_csv( fpath, sep=sep, index_col=None, skipinitialspace=True, header=None, names=names, engine='python') return df except Exception as e: raise ValueError("Could not read input from %s. Error: %s" % (fpath, repr(e)))
Get the necessary track data from a file handle. Args: fpath (str) : Original path of file reading from. names (list[str]): List of column names for the data. sep (str): Allowed separators regular expression string. Return: df (pandas.DataFrame): Data frame containing the data loaded from the stream with optionally assigned column names. No index is set on the data.
getData
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/mtmct/utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/mtmct/utils.py
Apache-2.0
def init_count(num_classes): """ Initiate _count for all object classes :param num_classes: """ for cls_id in range(num_classes): BaseTrack._count_dict[cls_id] = 0
Initiate _count for all object classes :param num_classes:
init_count
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_jde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_jde_tracker.py
Apache-2.0
def tlwh(self): """Get current position in bounding box format `(top left x, top left y, width, height)`. """ if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() ret[2] *= ret[3] ret[:2] -= ret[2:] / 2 return ret
Get current position in bounding box format `(top left x, top left y, width, height)`.
tlwh
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_jde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_jde_tracker.py
Apache-2.0
def tlbr(self): """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[2:] += ret[:2] return ret
Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`.
tlbr
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_jde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_jde_tracker.py
Apache-2.0
def tlwh_to_xyah(tlwh): """Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`. """ ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 ret[2] /= ret[3] return ret
Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`.
tlwh_to_xyah
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_jde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_jde_tracker.py
Apache-2.0
def to_tlwh(self): """Get position in format `(top left x, top left y, width, height)`.""" ret = self.mean[:4].copy() ret[2] *= ret[3] ret[:2] -= ret[2:] / 2 return ret
Get position in format `(top left x, top left y, width, height)`.
to_tlwh
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
Apache-2.0
def to_tlbr(self): """Get position in bounding box format `(min x, miny, max x, max y)`.""" ret = self.to_tlwh() ret[2:] = ret[:2] + ret[2:] return ret
Get position in bounding box format `(min x, miny, max x, max y)`.
to_tlbr
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
Apache-2.0
def predict(self, kalman_filter): """ Propagate the state distribution to the current time step using a Kalman filter prediction step. """ self.mean, self.covariance = kalman_filter.predict(self.mean, self.covariance) self.age += 1 self.time_since_update += 1
Propagate the state distribution to the current time step using a Kalman filter prediction step.
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
Apache-2.0
def update(self, kalman_filter, detection): """ Perform Kalman filter measurement update step and update the associated detection feature cache. """ self.mean, self.covariance = kalman_filter.update(self.mean, self.covariance, detection.to_xyah()) self.features.append(detection.feature) self.feat = detection.feature self.cls_id = detection.cls_id self.score = detection.score self.hits += 1 self.time_since_update = 0 if self.state == TrackState.Tentative and self.hits >= self._n_init: self.state = TrackState.Confirmed
Perform Kalman filter measurement update step and update the associated detection feature cache.
update
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
Apache-2.0
def mark_missed(self): """Mark this track as missed (no association at the current time step). """ if self.state == TrackState.Tentative: self.state = TrackState.Deleted elif self.time_since_update > self._max_age: self.state = TrackState.Deleted
Mark this track as missed (no association at the current time step).
mark_missed
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/base_sde_tracker.py
Apache-2.0
def update(self, pred_dets, pred_embs): """ Perform measurement update and track management. Args: pred_dets (np.array): Detection results of the image, the shape is [N, 6], means 'cls_id, score, x0, y0, x1, y1'. pred_embs (np.array): Embedding results of the image, the shape is [N, 128], usually pred_embs.shape[1] is a multiple of 128. """ pred_cls_ids = pred_dets[:, 0:1] pred_scores = pred_dets[:, 1:2] pred_xyxys = pred_dets[:, 2:6] pred_tlwhs = np.concatenate( (pred_xyxys[:, 0:2], pred_xyxys[:, 2:4] - pred_xyxys[:, 0:2] + 1), axis=1) detections = [ Detection(tlwh, score, feat, cls_id) for tlwh, score, feat, cls_id in zip(pred_tlwhs, pred_scores, pred_embs, pred_cls_ids) ] # Run matching cascade. matches, unmatched_tracks, unmatched_detections = \ self._match(detections) # Update track set. for track_idx, detection_idx in matches: self.tracks[track_idx].update(self.motion, detections[detection_idx]) for track_idx in unmatched_tracks: self.tracks[track_idx].mark_missed() for detection_idx in unmatched_detections: self._initiate_track(detections[detection_idx]) self.tracks = [t for t in self.tracks if not t.is_deleted()] # Update distance metric. active_targets = [t.track_id for t in self.tracks if t.is_confirmed()] features, targets = [], [] for track in self.tracks: if not track.is_confirmed(): continue features += track.features targets += [track.track_id for _ in track.features] track.features = [] self.metric.partial_fit( np.asarray(features), np.asarray(targets), active_targets) output_stracks = self.tracks return output_stracks
Perform measurement update and track management. Args: pred_dets (np.array): Detection results of the image, the shape is [N, 6], means 'cls_id, score, x0, y0, x1, y1'. pred_embs (np.array): Embedding results of the image, the shape is [N, 128], usually pred_embs.shape[1] is a multiple of 128.
update
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/deepsort_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/deepsort_tracker.py
Apache-2.0
def update(self, pred_dets, pred_embs=None): """ Processes the image frame and finds bounding box(detections). Associates the detection with corresponding tracklets and also handles lost, removed, refound and active tracklets. Args: pred_dets (np.array): Detection results of the image, the shape is [N, 6], means 'cls_id, score, x0, y0, x1, y1'. pred_embs (np.array): Embedding results of the image, the shape is [N, 128] or [N, 512]. Return: output_stracks_dict (dict(list)): The list contains information regarding the online_tracklets for the received image tensor. """ self.frame_id += 1 if self.frame_id == 1: STrack.init_count(self.num_classes) activated_tracks_dict = defaultdict(list) refined_tracks_dict = defaultdict(list) lost_tracks_dict = defaultdict(list) removed_tracks_dict = defaultdict(list) output_tracks_dict = defaultdict(list) pred_dets_dict = defaultdict(list) pred_embs_dict = defaultdict(list) # unify single and multi classes detection and embedding results for cls_id in range(self.num_classes): cls_idx = (pred_dets[:, 0:1] == cls_id).squeeze(-1) pred_dets_dict[cls_id] = pred_dets[cls_idx] if pred_embs is not None: pred_embs_dict[cls_id] = pred_embs[cls_idx] else: pred_embs_dict[cls_id] = None for cls_id in range(self.num_classes): """ Step 1: Get detections by class""" pred_dets_cls = pred_dets_dict[cls_id] pred_embs_cls = pred_embs_dict[cls_id] remain_inds = (pred_dets_cls[:, 1:2] > self.conf_thres).squeeze(-1) if remain_inds.sum() > 0: pred_dets_cls = pred_dets_cls[remain_inds] if pred_embs_cls is None: # in original ByteTrack detections = [ STrack( STrack.tlbr_to_tlwh(tlbrs[2:6]), tlbrs[1], cls_id, 30, temp_feat=None) for tlbrs in pred_dets_cls ] else: pred_embs_cls = pred_embs_cls[remain_inds] detections = [ STrack( STrack.tlbr_to_tlwh(tlbrs[2:6]), tlbrs[1], cls_id, 30, temp_feat) for (tlbrs, temp_feat ) in zip(pred_dets_cls, pred_embs_cls) ] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed_dict = defaultdict(list) tracked_tracks_dict = defaultdict(list) for track in self.tracked_tracks_dict[cls_id]: if not track.is_activated: # previous tracks which are not active in the current frame are added in unconfirmed list unconfirmed_dict[cls_id].append(track) else: # Active tracks are added to the local list 'tracked_stracks' tracked_tracks_dict[cls_id].append(track) """ Step 2: First association, with embedding""" # building tracking pool for the current frame track_pool_dict = defaultdict(list) track_pool_dict[cls_id] = joint_stracks( tracked_tracks_dict[cls_id], self.lost_tracks_dict[cls_id]) # Predict the current location with KalmanFilter STrack.multi_predict(track_pool_dict[cls_id], self.motion) if pred_embs_cls is None: # in original ByteTrack dists = matching.iou_distance(track_pool_dict[cls_id], detections) matches, u_track, u_detection = matching.linear_assignment( dists, thresh=self.match_thres) # not self.tracked_thresh else: dists = matching.embedding_distance( track_pool_dict[cls_id], detections, metric=self.metric_type) dists = matching.fuse_motion( self.motion, dists, track_pool_dict[cls_id], detections) matches, u_track, u_detection = matching.linear_assignment( dists, thresh=self.tracked_thresh) for i_tracked, idet in matches: # i_tracked is the id of the track and idet is the detection track = track_pool_dict[cls_id][i_tracked] det = detections[idet] if track.state == TrackState.Tracked: # If the track is active, add the detection to the track track.update(detections[idet], self.frame_id) activated_tracks_dict[cls_id].append(track) else: # We have obtained a detection from a track which is not active, # hence put the track in refind_stracks list track.re_activate(det, self.frame_id, new_id=False) refined_tracks_dict[cls_id].append(track) # None of the steps below happen if there are no undetected tracks. """ Step 3: Second association, with IOU""" if self.use_byte: inds_low = pred_dets_dict[cls_id][:, 1:2] > self.low_conf_thres inds_high = pred_dets_dict[cls_id][:, 1:2] < self.conf_thres inds_second = np.logical_and(inds_low, inds_high).squeeze(-1) pred_dets_cls_second = pred_dets_dict[cls_id][inds_second] # association the untrack to the low score detections if len(pred_dets_cls_second) > 0: if pred_embs_dict[cls_id] is None: # in original ByteTrack detections_second = [ STrack( STrack.tlbr_to_tlwh(tlbrs[2:6]), tlbrs[1], cls_id, 30, temp_feat=None) for tlbrs in pred_dets_cls_second ] else: pred_embs_cls_second = pred_embs_dict[cls_id][ inds_second] detections_second = [ STrack( STrack.tlbr_to_tlwh(tlbrs[2:6]), tlbrs[1], cls_id, 30, temp_feat) for (tlbrs, temp_feat) in zip(pred_dets_cls_second, pred_embs_cls_second) ] else: detections_second = [] r_tracked_stracks = [ track_pool_dict[cls_id][i] for i in u_track if track_pool_dict[cls_id][i].state == TrackState.Tracked ] dists = matching.iou_distance(r_tracked_stracks, detections_second) matches, u_track, u_detection_second = matching.linear_assignment( dists, thresh=0.4) # not r_tracked_thresh else: detections = [detections[i] for i in u_detection] r_tracked_stracks = [] for i in u_track: if track_pool_dict[cls_id][i].state == TrackState.Tracked: r_tracked_stracks.append(track_pool_dict[cls_id][i]) dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment( dists, thresh=self.r_tracked_thresh) for i_tracked, idet in matches: track = r_tracked_stracks[i_tracked] det = detections[ idet] if not self.use_byte else detections_second[idet] if track.state == TrackState.Tracked: track.update(det, self.frame_id) activated_tracks_dict[cls_id].append(track) else: track.re_activate(det, self.frame_id, new_id=False) refined_tracks_dict[cls_id].append(track) for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_tracks_dict[cls_id].append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed_dict[cls_id], detections) matches, u_unconfirmed, u_detection = matching.linear_assignment( dists, thresh=self.unconfirmed_thresh) for i_tracked, idet in matches: unconfirmed_dict[cls_id][i_tracked].update(detections[idet], self.frame_id) activated_tracks_dict[cls_id].append(unconfirmed_dict[cls_id][ i_tracked]) for it in u_unconfirmed: track = unconfirmed_dict[cls_id][it] track.mark_removed() removed_tracks_dict[cls_id].append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate(self.motion, self.frame_id) activated_tracks_dict[cls_id].append(track) """ Step 5: Update state""" for track in self.lost_tracks_dict[cls_id]: if self.frame_id - track.end_frame > self.max_time_lost: track.mark_removed() removed_tracks_dict[cls_id].append(track) self.tracked_tracks_dict[cls_id] = [ t for t in self.tracked_tracks_dict[cls_id] if t.state == TrackState.Tracked ] self.tracked_tracks_dict[cls_id] = joint_stracks( self.tracked_tracks_dict[cls_id], activated_tracks_dict[cls_id]) self.tracked_tracks_dict[cls_id] = joint_stracks( self.tracked_tracks_dict[cls_id], refined_tracks_dict[cls_id]) self.lost_tracks_dict[cls_id] = sub_stracks( self.lost_tracks_dict[cls_id], self.tracked_tracks_dict[cls_id]) self.lost_tracks_dict[cls_id].extend(lost_tracks_dict[cls_id]) self.lost_tracks_dict[cls_id] = sub_stracks( self.lost_tracks_dict[cls_id], self.removed_tracks_dict[cls_id]) self.removed_tracks_dict[cls_id].extend(removed_tracks_dict[ cls_id]) self.tracked_tracks_dict[cls_id], self.lost_tracks_dict[ cls_id] = remove_duplicate_stracks( self.tracked_tracks_dict[cls_id], self.lost_tracks_dict[cls_id]) # get scores of lost tracks output_tracks_dict[cls_id] = [ track for track in self.tracked_tracks_dict[cls_id] if track.is_activated ] return output_tracks_dict
Processes the image frame and finds bounding box(detections). Associates the detection with corresponding tracklets and also handles lost, removed, refound and active tracklets. Args: pred_dets (np.array): Detection results of the image, the shape is [N, 6], means 'cls_id, score, x0, y0, x1, y1'. pred_embs (np.array): Embedding results of the image, the shape is [N, 128] or [N, 512]. Return: output_stracks_dict (dict(list)): The list contains information regarding the online_tracklets for the received image tensor.
update
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/jde_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/jde_tracker.py
Apache-2.0
def convert_bbox_to_z(bbox): """ Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form [x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is the aspect ratio """ w = bbox[2] - bbox[0] h = bbox[3] - bbox[1] x = bbox[0] + w / 2. y = bbox[1] + h / 2. s = w * h # scale is just area r = w / float(h + 1e-6) return np.array([x, y, s, r]).reshape((4, 1))
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form [x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is the aspect ratio
convert_bbox_to_z
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
Apache-2.0
def convert_x_to_bbox(x, score=None): """ Takes a bounding box in the centre form [x,y,s,r] and returns it in the form [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right """ w = np.sqrt(x[2] * x[3]) h = x[2] / w if (score == None): return np.array( [x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2.]).reshape((1, 4)) else: score = np.array([score]) return np.array([ x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2., score ]).reshape((1, 5))
Takes a bounding box in the centre form [x,y,s,r] and returns it in the form [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right
convert_x_to_bbox
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
Apache-2.0
def update(self, bbox): """ Updates the state vector with observed bbox. """ if bbox is not None: if self.last_observation.sum() >= 0: # no previous observation previous_box = None for i in range(self.delta_t): dt = self.delta_t - i if self.age - dt in self.observations: previous_box = self.observations[self.age - dt] break if previous_box is None: previous_box = self.last_observation """ Estimate the track speed direction with observations \Delta t steps away """ self.velocity = speed_direction(previous_box, bbox) """ Insert new observations. This is a ugly way to maintain both self.observations and self.history_observations. Bear it for the moment. """ self.last_observation = bbox self.observations[self.age] = bbox self.history_observations.append(bbox) self.time_since_update = 0 self.history = [] self.hits += 1 self.hit_streak += 1 self.kf.update(convert_bbox_to_z(bbox)) else: self.kf.update(bbox)
Updates the state vector with observed bbox.
update
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
Apache-2.0
def predict(self): """ Advances the state vector and returns the predicted bounding box estimate. """ if ((self.kf.x[6] + self.kf.x[2]) <= 0): self.kf.x[6] *= 0.0 self.kf.predict() self.age += 1 if (self.time_since_update > 0): self.hit_streak = 0 self.time_since_update += 1 self.history.append(convert_x_to_bbox(self.kf.x, score=self.score)) return self.history[-1]
Advances the state vector and returns the predicted bounding box estimate.
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
Apache-2.0
def update(self, pred_dets, pred_embs=None): """ Args: pred_dets (np.array): Detection results of the image, the shape is [N, 6], means 'cls_id, score, x0, y0, x1, y1'. pred_embs (np.array): Embedding results of the image, the shape is [N, 128] or [N, 512], default as None. Return: tracking boxes (np.array): [M, 6], means 'x0, y0, x1, y1, score, id'. """ if pred_dets is None: return np.empty((0, 6)) self.frame_count += 1 bboxes = pred_dets[:, 2:] scores = pred_dets[:, 1:2] dets = np.concatenate((bboxes, scores), axis=1) scores = scores.squeeze(-1) inds_low = scores > 0.1 inds_high = scores < self.det_thresh inds_second = np.logical_and(inds_low, inds_high) # self.det_thresh > score > 0.1, for second matching dets_second = dets[inds_second] # detections for second matching remain_inds = scores > self.det_thresh dets = dets[remain_inds] # get predicted locations from existing trackers. trks = np.zeros((len(self.trackers), 5)) to_del = [] ret = [] for t, trk in enumerate(trks): pos = self.trackers[t].predict()[0] trk[:] = [pos[0], pos[1], pos[2], pos[3], 0] if np.any(np.isnan(pos)): to_del.append(t) trks = np.ma.compress_rows(np.ma.masked_invalid(trks)) for t in reversed(to_del): self.trackers.pop(t) velocities = np.array([ trk.velocity if trk.velocity is not None else np.array((0, 0)) for trk in self.trackers ]) last_boxes = np.array([trk.last_observation for trk in self.trackers]) k_observations = np.array([ k_previous_obs(trk.observations, trk.age, self.delta_t) for trk in self.trackers ]) """ First round of association """ matched, unmatched_dets, unmatched_trks = associate( dets, trks, self.iou_threshold, velocities, k_observations, self.inertia) for m in matched: self.trackers[m[1]].update(dets[m[0], :]) """ Second round of associaton by OCR """ # BYTE association if self.use_byte and len(dets_second) > 0 and unmatched_trks.shape[ 0] > 0: u_trks = trks[unmatched_trks] iou_left = iou_batch( dets_second, u_trks) # iou between low score detections and unmatched tracks iou_left = np.array(iou_left) if iou_left.max() > self.iou_threshold: """ NOTE: by using a lower threshold, e.g., self.iou_threshold - 0.1, you may get a higher performance especially on MOT17/MOT20 datasets. But we keep it uniform here for simplicity """ matched_indices = linear_assignment(-iou_left) to_remove_trk_indices = [] for m in matched_indices: det_ind, trk_ind = m[0], unmatched_trks[m[1]] if iou_left[m[0], m[1]] < self.iou_threshold: continue self.trackers[trk_ind].update(dets_second[det_ind, :]) to_remove_trk_indices.append(trk_ind) unmatched_trks = np.setdiff1d(unmatched_trks, np.array(to_remove_trk_indices)) if unmatched_dets.shape[0] > 0 and unmatched_trks.shape[0] > 0: left_dets = dets[unmatched_dets] left_trks = last_boxes[unmatched_trks] iou_left = iou_batch(left_dets, left_trks) iou_left = np.array(iou_left) if iou_left.max() > self.iou_threshold: """ NOTE: by using a lower threshold, e.g., self.iou_threshold - 0.1, you may get a higher performance especially on MOT17/MOT20 datasets. But we keep it uniform here for simplicity """ rematched_indices = linear_assignment(-iou_left) to_remove_det_indices = [] to_remove_trk_indices = [] for m in rematched_indices: det_ind, trk_ind = unmatched_dets[m[0]], unmatched_trks[m[ 1]] if iou_left[m[0], m[1]] < self.iou_threshold: continue self.trackers[trk_ind].update(dets[det_ind, :]) to_remove_det_indices.append(det_ind) to_remove_trk_indices.append(trk_ind) unmatched_dets = np.setdiff1d(unmatched_dets, np.array(to_remove_det_indices)) unmatched_trks = np.setdiff1d(unmatched_trks, np.array(to_remove_trk_indices)) for m in unmatched_trks: self.trackers[m].update(None) # create and initialise new trackers for unmatched detections for i in unmatched_dets: trk = KalmanBoxTracker(dets[i, :], delta_t=self.delta_t) self.trackers.append(trk) i = len(self.trackers) for trk in reversed(self.trackers): if trk.last_observation.sum() < 0: d = trk.get_state()[0] else: d = trk.last_observation # tlbr + score if (trk.time_since_update < 1) and ( trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits): # +1 as MOT benchmark requires positive ret.append(np.concatenate((d, [trk.id + 1])).reshape(1, -1)) i -= 1 # remove dead tracklet if (trk.time_since_update > self.max_age): self.trackers.pop(i) if (len(ret) > 0): return np.concatenate(ret) return np.empty((0, 6))
Args: pred_dets (np.array): Detection results of the image, the shape is [N, 6], means 'cls_id, score, x0, y0, x1, y1'. pred_embs (np.array): Embedding results of the image, the shape is [N, 128] or [N, 512], default as None. Return: tracking boxes (np.array): [M, 6], means 'x0, y0, x1, y1, score, id'.
update
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pptracking/python/mot/tracker/ocsort_tracker.py
Apache-2.0
def __init__(self, config, model_info: dict={}, data_info: dict={}, perf_info: dict={}, resource_info: dict={}, **kwargs): """ Construct PaddleInferBenchmark Class to format logs. args: config(paddle.inference.Config): paddle inference config model_info(dict): basic model info {'model_name': 'resnet50' 'precision': 'fp32'} data_info(dict): input data info {'batch_size': 1 'shape': '3,224,224' 'data_num': 1000} perf_info(dict): performance result {'preprocess_time_s': 1.0 'inference_time_s': 2.0 'postprocess_time_s': 1.0 'total_time_s': 4.0} resource_info(dict): cpu and gpu resources {'cpu_rss': 100 'gpu_rss': 100 'gpu_util': 60} """ # PaddleInferBenchmark Log Version self.log_version = "1.0.3" # Paddle Version self.paddle_version = paddle.__version__ self.paddle_commit = paddle.__git_commit__ paddle_infer_info = paddle_infer.get_version() self.paddle_branch = paddle_infer_info.strip().split(': ')[-1] # model info self.model_info = model_info # data info self.data_info = data_info # perf info self.perf_info = perf_info try: # required value self.model_name = model_info['model_name'] self.precision = model_info['precision'] self.batch_size = data_info['batch_size'] self.shape = data_info['shape'] self.data_num = data_info['data_num'] self.inference_time_s = round(perf_info['inference_time_s'], 4) except: self.print_help() raise ValueError( "Set argument wrong, please check input argument and its type") self.preprocess_time_s = perf_info.get('preprocess_time_s', 0) self.postprocess_time_s = perf_info.get('postprocess_time_s', 0) self.with_tracker = True if 'tracking_time_s' in perf_info else False self.tracking_time_s = perf_info.get('tracking_time_s', 0) self.total_time_s = perf_info.get('total_time_s', 0) self.inference_time_s_90 = perf_info.get("inference_time_s_90", "") self.inference_time_s_99 = perf_info.get("inference_time_s_99", "") self.succ_rate = perf_info.get("succ_rate", "") self.qps = perf_info.get("qps", "") # conf info self.config_status = self.parse_config(config) # mem info if isinstance(resource_info, dict): self.cpu_rss_mb = int(resource_info.get('cpu_rss_mb', 0)) self.cpu_vms_mb = int(resource_info.get('cpu_vms_mb', 0)) self.cpu_shared_mb = int(resource_info.get('cpu_shared_mb', 0)) self.cpu_dirty_mb = int(resource_info.get('cpu_dirty_mb', 0)) self.cpu_util = round(resource_info.get('cpu_util', 0), 2) self.gpu_rss_mb = int(resource_info.get('gpu_rss_mb', 0)) self.gpu_util = round(resource_info.get('gpu_util', 0), 2) self.gpu_mem_util = round(resource_info.get('gpu_mem_util', 0), 2) else: self.cpu_rss_mb = 0 self.cpu_vms_mb = 0 self.cpu_shared_mb = 0 self.cpu_dirty_mb = 0 self.cpu_util = 0 self.gpu_rss_mb = 0 self.gpu_util = 0 self.gpu_mem_util = 0 # init benchmark logger self.benchmark_logger()
Construct PaddleInferBenchmark Class to format logs. args: config(paddle.inference.Config): paddle inference config model_info(dict): basic model info {'model_name': 'resnet50' 'precision': 'fp32'} data_info(dict): input data info {'batch_size': 1 'shape': '3,224,224' 'data_num': 1000} perf_info(dict): performance result {'preprocess_time_s': 1.0 'inference_time_s': 2.0 'postprocess_time_s': 1.0 'total_time_s': 4.0} resource_info(dict): cpu and gpu resources {'cpu_rss': 100 'gpu_rss': 100 'gpu_util': 60}
__init__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/benchmark_utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/benchmark_utils.py
Apache-2.0
def parse_config(self, config) -> dict: """ parse paddle predictor config args: config(paddle.inference.Config): paddle inference config return: config_status(dict): dict style config info """ if isinstance(config, paddle_infer.Config): config_status = {} config_status['runtime_device'] = "gpu" if config.use_gpu( ) else "cpu" config_status['ir_optim'] = config.ir_optim() config_status['enable_tensorrt'] = config.tensorrt_engine_enabled() config_status['precision'] = self.precision config_status['enable_mkldnn'] = config.mkldnn_enabled() config_status[ 'cpu_math_library_num_threads'] = config.cpu_math_library_num_threads( ) elif isinstance(config, dict): config_status['runtime_device'] = config.get('runtime_device', "") config_status['ir_optim'] = config.get('ir_optim', "") config_status['enable_tensorrt'] = config.get('enable_tensorrt', "") config_status['precision'] = config.get('precision', "") config_status['enable_mkldnn'] = config.get('enable_mkldnn', "") config_status['cpu_math_library_num_threads'] = config.get( 'cpu_math_library_num_threads', "") else: self.print_help() raise ValueError( "Set argument config wrong, please check input argument and its type" ) return config_status
parse paddle predictor config args: config(paddle.inference.Config): paddle inference config return: config_status(dict): dict style config info
parse_config
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/benchmark_utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/benchmark_utils.py
Apache-2.0
def report(self, identifier=None): """ print log report args: identifier(string): identify log """ if identifier: identifier = f"[{identifier}]" else: identifier = "" self.logger.info("\n") self.logger.info( "---------------------- Paddle info ----------------------") self.logger.info(f"{identifier} paddle_version: {self.paddle_version}") self.logger.info(f"{identifier} paddle_commit: {self.paddle_commit}") self.logger.info(f"{identifier} paddle_branch: {self.paddle_branch}") self.logger.info(f"{identifier} log_api_version: {self.log_version}") self.logger.info( "----------------------- Conf info -----------------------") self.logger.info( f"{identifier} runtime_device: {self.config_status['runtime_device']}" ) self.logger.info( f"{identifier} ir_optim: {self.config_status['ir_optim']}") self.logger.info(f"{identifier} enable_memory_optim: {True}") self.logger.info( f"{identifier} enable_tensorrt: {self.config_status['enable_tensorrt']}" ) self.logger.info( f"{identifier} enable_mkldnn: {self.config_status['enable_mkldnn']}" ) self.logger.info( f"{identifier} cpu_math_library_num_threads: {self.config_status['cpu_math_library_num_threads']}" ) self.logger.info( "----------------------- Model info ----------------------") self.logger.info(f"{identifier} model_name: {self.model_name}") self.logger.info(f"{identifier} precision: {self.precision}") self.logger.info( "----------------------- Data info -----------------------") self.logger.info(f"{identifier} batch_size: {self.batch_size}") self.logger.info(f"{identifier} input_shape: {self.shape}") self.logger.info(f"{identifier} data_num: {self.data_num}") self.logger.info( "----------------------- Perf info -----------------------") self.logger.info( f"{identifier} cpu_rss(MB): {self.cpu_rss_mb}, cpu_vms: {self.cpu_vms_mb}, cpu_shared_mb: {self.cpu_shared_mb}, cpu_dirty_mb: {self.cpu_dirty_mb}, cpu_util: {self.cpu_util}%" ) self.logger.info( f"{identifier} gpu_rss(MB): {self.gpu_rss_mb}, gpu_util: {self.gpu_util}%, gpu_mem_util: {self.gpu_mem_util}%" ) self.logger.info( f"{identifier} total time spent(s): {self.total_time_s}") if self.with_tracker: self.logger.info( f"{identifier} preprocess_time(ms): {round(self.preprocess_time_s*1000, 1)}, " f"inference_time(ms): {round(self.inference_time_s*1000, 1)}, " f"postprocess_time(ms): {round(self.postprocess_time_s*1000, 1)}, " f"tracking_time(ms): {round(self.tracking_time_s*1000, 1)}") else: self.logger.info( f"{identifier} preprocess_time(ms): {round(self.preprocess_time_s*1000, 1)}, " f"inference_time(ms): {round(self.inference_time_s*1000, 1)}, " f"postprocess_time(ms): {round(self.postprocess_time_s*1000, 1)}" ) if self.inference_time_s_90: self.looger.info( f"{identifier} 90%_cost: {self.inference_time_s_90}, 99%_cost: {self.inference_time_s_99}, succ_rate: {self.succ_rate}" ) if self.qps: self.logger.info(f"{identifier} QPS: {self.qps}")
print log report args: identifier(string): identify log
report
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/benchmark_utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/benchmark_utils.py
Apache-2.0
def predict(self, repeats=1): ''' Args: repeats (int): repeat number for prediction Returns: result (dict): 'segm': np.ndarray,shape:[N, im_h, im_w] 'cate_label': label of segm, shape:[N] 'cate_score': confidence score of segm, shape:[N] ''' np_label, np_score, np_segms = None, None, None for i in range(repeats): self.predictor.run() output_names = self.predictor.get_output_names() np_boxes_num = self.predictor.get_output_handle(output_names[ 0]).copy_to_cpu() np_label = self.predictor.get_output_handle(output_names[ 1]).copy_to_cpu() np_score = self.predictor.get_output_handle(output_names[ 2]).copy_to_cpu() np_segms = self.predictor.get_output_handle(output_names[ 3]).copy_to_cpu() result = dict( segm=np_segms, label=np_label, score=np_score, boxes_num=np_boxes_num) return result
Args: repeats (int): repeat number for prediction Returns: result (dict): 'segm': np.ndarray,shape:[N, im_h, im_w] 'cate_label': label of segm, shape:[N] 'cate_score': confidence score of segm, shape:[N]
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/infer.py
Apache-2.0
def predict(self, repeats=1): ''' Args: repeats (int): repeat number for prediction Returns: result (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] ''' np_score_list, np_boxes_list = [], [] for i in range(repeats): self.predictor.run() np_score_list.clear() np_boxes_list.clear() output_names = self.predictor.get_output_names() num_outs = int(len(output_names) / 2) for out_idx in range(num_outs): np_score_list.append( self.predictor.get_output_handle(output_names[out_idx]) .copy_to_cpu()) np_boxes_list.append( self.predictor.get_output_handle(output_names[ out_idx + num_outs]).copy_to_cpu()) result = dict(boxes=np_score_list, boxes_num=np_boxes_list) return result
Args: repeats (int): repeat number for prediction Returns: result (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max]
predict
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/infer.py
Apache-2.0