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 update(self, settings):
"""Recursively merge the given settings into the current settings."""
self.settings.cache_clear()
self._settings = settings
log.info("Updated settings to %s", self._settings)
self._update_disabled_plugins() | Recursively merge the given settings into the current settings. | update | python | palantir/python-language-server | pyls/config/config.py | https://github.com/palantir/python-language-server/blob/master/pyls/config/config.py | MIT |
def parse_config(config, key, options):
"""Parse the config with the given options."""
conf = {}
for source, destination, opt_type in options:
opt_value = _get_opt(config, key, source, opt_type)
if opt_value is not None:
_set_opt(conf, destination, opt_value)
return conf | Parse the config with the given options. | parse_config | python | palantir/python-language-server | pyls/config/source.py | https://github.com/palantir/python-language-server/blob/master/pyls/config/source.py | MIT |
def _get_opt(config, key, option, opt_type):
"""Get an option from a configparser with the given type."""
for opt_key in [option, option.replace('-', '_')]:
if not config.has_option(key, opt_key):
continue
if opt_type == bool:
return config.getboolean(key, opt_key)
if opt_type == int:
return config.getint(key, opt_key)
if opt_type == str:
return config.get(key, opt_key)
if opt_type == list:
return _parse_list_opt(config.get(key, opt_key))
raise ValueError("Unknown option type: %s" % opt_type) | Get an option from a configparser with the given type. | _get_opt | python | palantir/python-language-server | pyls/config/source.py | https://github.com/palantir/python-language-server/blob/master/pyls/config/source.py | MIT |
def _set_opt(config_dict, path, value):
"""Set the value in the dictionary at the given path if the value is not None."""
if value is None:
return
if '.' not in path:
config_dict[path] = value
return
key, rest = path.split(".", 1)
if key not in config_dict:
config_dict[key] = {}
_set_opt(config_dict[key], rest, value) | Set the value in the dictionary at the given path if the value is not None. | _set_opt | python | palantir/python-language-server | pyls/config/source.py | https://github.com/palantir/python-language-server/blob/master/pyls/config/source.py | MIT |
def run_flake8(flake8_executable, args, document):
"""Run flake8 with the provided arguments, logs errors
from stderr if any.
"""
# a quick temporary fix to deal with Atom
args = [(i if not i.startswith('--ignore=') else FIX_IGNORES_RE.sub('', i))
for i in args if i is not None]
# if executable looks like a path resolve it
if not os.path.isfile(flake8_executable) and os.sep in flake8_executable:
flake8_executable = os.path.abspath(
os.path.expanduser(os.path.expandvars(flake8_executable))
)
log.debug("Calling %s with args: '%s'", flake8_executable, args)
try:
cmd = [flake8_executable]
cmd.extend(args)
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
except IOError:
log.debug("Can't execute %s. Trying with 'python -m flake8'", flake8_executable)
cmd = ['python', '-m', 'flake8']
cmd.extend(args)
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = p.communicate(document.source.encode())
if stderr:
log.error("Error while running flake8 '%s'", stderr.decode())
return stdout.decode() | Run flake8 with the provided arguments, logs errors
from stderr if any.
| run_flake8 | python | palantir/python-language-server | pyls/plugins/flake8_lint.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/flake8_lint.py | MIT |
def build_args(options):
"""Build arguments for calling flake8.
Args:
options: dictionary of argument names and their values.
"""
args = ['-'] # use stdin
for arg_name, arg_val in options.items():
if arg_val is None:
continue
arg = None
if isinstance(arg_val, list):
arg = '--{}={}'.format(arg_name, ','.join(arg_val))
elif isinstance(arg_val, bool):
if arg_val:
arg = '--{}'.format(arg_name)
else:
arg = '--{}={}'.format(arg_name, arg_val)
args.append(arg)
return args | Build arguments for calling flake8.
Args:
options: dictionary of argument names and their values.
| build_args | python | palantir/python-language-server | pyls/plugins/flake8_lint.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/flake8_lint.py | MIT |
def parse_stdout(document, stdout):
"""
Build a diagnostics from flake8's output, it should extract every result and format
it into a dict that looks like this:
{
'source': 'flake8',
'code': code, # 'E501'
'range': {
'start': {
'line': start_line,
'character': start_column,
},
'end': {
'line': end_line,
'character': end_column,
},
},
'message': msg,
'severity': lsp.DiagnosticSeverity.*,
}
Args:
document: The document to be linted.
stdout: output from flake8
Returns:
A list of dictionaries.
"""
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("Flake8 output parser can't parse line '%s'", raw_line)
continue
parsed_line = parsed_line.groups()
if len(parsed_line) != 5:
log.debug("Flake8 output parser can't parse line '%s'", raw_line)
continue
_, line, character, code, msg = parsed_line
line = int(line) - 1
character = int(character) - 1
# show also the code in message
msg = code + ' ' + msg
diagnostics.append(
{
'source': 'flake8',
'code': code,
'range': {
'start': {
'line': line,
'character': character
},
'end': {
'line': line,
# no way to determine the column
'character': len(document.lines[line])
}
},
'message': msg,
'severity': lsp.DiagnosticSeverity.Warning,
}
)
return diagnostics |
Build a diagnostics from flake8's output, it should extract every result and format
it into a dict that looks like this:
{
'source': 'flake8',
'code': code, # 'E501'
'range': {
'start': {
'line': start_line,
'character': start_column,
},
'end': {
'line': end_line,
'character': end_column,
},
},
'message': msg,
'severity': lsp.DiagnosticSeverity.*,
}
Args:
document: The document to be linted.
stdout: output from flake8
Returns:
A list of dictionaries.
| parse_stdout | python | palantir/python-language-server | pyls/plugins/flake8_lint.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/flake8_lint.py | MIT |
def pyls_completions(config, document, position):
"""Get formatted completions for current code position"""
settings = config.plugin_settings('jedi_completion', document_path=document.path)
code_position = _utils.position_to_jedi_linecolumn(document, position)
code_position["fuzzy"] = settings.get("fuzzy", False)
completions = document.jedi_script(use_document_path=True).complete(**code_position)
if not completions:
return None
completion_capabilities = config.capabilities.get('textDocument', {}).get('completion', {})
snippet_support = completion_capabilities.get('completionItem', {}).get('snippetSupport')
should_include_params = settings.get('include_params')
should_include_class_objects = settings.get('include_class_objects', True)
include_params = snippet_support and should_include_params and use_snippets(document, position)
include_class_objects = snippet_support and should_include_class_objects and use_snippets(document, position)
ready_completions = [
_format_completion(c, include_params)
for c in completions
]
if include_class_objects:
for c in completions:
if c.type == 'class':
completion_dict = _format_completion(c, False)
completion_dict['kind'] = lsp.CompletionItemKind.TypeParameter
completion_dict['label'] += ' object'
ready_completions.append(completion_dict)
return ready_completions or None | Get formatted completions for current code position | pyls_completions | python | palantir/python-language-server | pyls/plugins/jedi_completion.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/jedi_completion.py | MIT |
def is_exception_class(name):
"""
Determine if a class name is an instance of an Exception.
This returns `False` if the name given corresponds with a instance of
the 'Exception' class, `True` otherwise
"""
try:
return name in [cls.__name__ for cls in Exception.__subclasses__()]
except AttributeError:
# Needed in case a class don't uses new-style
# class definition in Python 2
return False |
Determine if a class name is an instance of an Exception.
This returns `False` if the name given corresponds with a instance of
the 'Exception' class, `True` otherwise
| is_exception_class | python | palantir/python-language-server | pyls/plugins/jedi_completion.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/jedi_completion.py | MIT |
def use_snippets(document, position):
"""
Determine if it's necessary to return snippets in code completions.
This returns `False` if a completion is being requested on an import
statement, `True` otherwise.
"""
line = position['line']
lines = document.source.split('\n', line)
act_lines = [lines[line][:position['character']]]
line -= 1
last_character = ''
while line > -1:
act_line = lines[line]
if (act_line.rstrip().endswith('\\') or
act_line.rstrip().endswith('(') or
act_line.rstrip().endswith(',')):
act_lines.insert(0, act_line)
line -= 1
if act_line.rstrip().endswith('('):
# Needs to be added to the end of the code before parsing
# to make it valid, otherwise the node type could end
# being an 'error_node' for multi-line imports that use '('
last_character = ')'
else:
break
if '(' in act_lines[-1].strip():
last_character = ')'
code = '\n'.join(act_lines).split(';')[-1].strip() + last_character
tokens = parso.parse(code)
expr_type = tokens.children[0].type
return (expr_type not in _IMPORTS and
not (expr_type in _ERRORS and 'import' in code)) |
Determine if it's necessary to return snippets in code completions.
This returns `False` if a completion is being requested on an import
statement, `True` otherwise.
| use_snippets | python | palantir/python-language-server | pyls/plugins/jedi_completion.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/jedi_completion.py | MIT |
def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
# If its 'hidden', put it next last
prefix = 'z{}' if definition.name.startswith('_') else 'a{}'
return prefix.format(definition.name) | Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
| _sort_text | python | palantir/python-language-server | pyls/plugins/jedi_completion.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/jedi_completion.py | MIT |
def flake(self, message):
""" Get message like <filename>:<lineno>: <msg> """
err_range = {
'start': {'line': message.lineno - 1, 'character': message.col},
'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])},
}
severity = lsp.DiagnosticSeverity.Warning
for message_type in PYFLAKES_ERROR_MESSAGES:
if isinstance(message, message_type):
severity = lsp.DiagnosticSeverity.Error
break
self.diagnostics.append({
'source': 'pyflakes',
'range': err_range,
'message': message.message % message.message_args,
'severity': severity
}) | Get message like <filename>:<lineno>: <msg> | flake | python | palantir/python-language-server | pyls/plugins/pyflakes_lint.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/pyflakes_lint.py | MIT |
def lint(cls, document, is_saved, flags=''):
"""Plugin interface to pyls linter.
Args:
document: The document to be linted.
is_saved: Whether or not the file has been saved to disk.
flags: Additional flags to pass to pylint. Not exposed to
pyls_lint, but used for testing.
Returns:
A list of dicts with the following format:
{
'source': 'pylint',
'range': {
'start': {
'line': start_line,
'character': start_column,
},
'end': {
'line': end_line,
'character': end_column,
},
}
'message': msg,
'severity': lsp.DiagnosticSeverity.*,
}
"""
if not is_saved:
# Pylint can only be run on files that have been saved to disk.
# Rather than return nothing, return the previous list of
# diagnostics. If we return an empty list, any diagnostics we'd
# previously shown will be cleared until the next save. Instead,
# continue showing (possibly stale) diagnostics until the next
# save.
return cls.last_diags[document.path]
# py_run will call shlex.split on its arguments, and shlex.split does
# not handle Windows paths (it will try to perform escaping). Turn
# backslashes into forward slashes first to avoid this issue.
path = document.path
if sys.platform.startswith('win'):
path = path.replace('\\', '/')
pylint_call = '{} -f json {}'.format(path, flags)
log.debug("Calling pylint with '%s'", pylint_call)
json_out, err = py_run(pylint_call, return_std=True)
# Get strings
json_out = json_out.getvalue()
err = err.getvalue()
if err != '':
log.error("Error calling pylint: '%s'", err)
# pylint prints nothing rather than [] when there are no diagnostics.
# json.loads will not parse an empty string, so just return.
if not json_out.strip():
cls.last_diags[document.path] = []
return []
# Pylint's JSON output is a list of objects with the following format.
#
# {
# "obj": "main",
# "path": "foo.py",
# "message": "Missing function docstring",
# "message-id": "C0111",
# "symbol": "missing-docstring",
# "column": 0,
# "type": "convention",
# "line": 5,
# "module": "foo"
# }
#
# The type can be any of:
#
# * convention
# * error
# * fatal
# * refactor
# * warning
diagnostics = []
for diag in json.loads(json_out):
# pylint lines index from 1, pyls lines index from 0
line = diag['line'] - 1
err_range = {
'start': {
'line': line,
# Index columns start from 0
'character': diag['column'],
},
'end': {
'line': line,
# It's possible that we're linting an empty file. Even an empty
# file might fail linting if it isn't named properly.
'character': len(document.lines[line]) if document.lines else 0,
},
}
if diag['type'] == 'convention':
severity = lsp.DiagnosticSeverity.Information
elif diag['type'] == 'error':
severity = lsp.DiagnosticSeverity.Error
elif diag['type'] == 'fatal':
severity = lsp.DiagnosticSeverity.Error
elif diag['type'] == 'refactor':
severity = lsp.DiagnosticSeverity.Hint
elif diag['type'] == 'warning':
severity = lsp.DiagnosticSeverity.Warning
diagnostics.append({
'source': 'pylint',
'range': err_range,
'message': '[{}] {}'.format(diag['symbol'], diag['message']),
'severity': severity,
'code': diag['message-id']
})
cls.last_diags[document.path] = diagnostics
return diagnostics | Plugin interface to pyls linter.
Args:
document: The document to be linted.
is_saved: Whether or not the file has been saved to disk.
flags: Additional flags to pass to pylint. Not exposed to
pyls_lint, but used for testing.
Returns:
A list of dicts with the following format:
{
'source': 'pylint',
'range': {
'start': {
'line': start_line,
'character': start_column,
},
'end': {
'line': end_line,
'character': end_column,
},
}
'message': msg,
'severity': lsp.DiagnosticSeverity.*,
}
| lint | 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 build_args_stdio(settings):
"""Build arguments for calling pylint.
:param settings: client settings
:type settings: dict
:return: arguments to path to pylint
:rtype: list
"""
pylint_args = settings.get('args')
if pylint_args is None:
return []
return pylint_args | Build arguments for calling pylint.
:param settings: client settings
:type settings: dict
:return: arguments to path to pylint
:rtype: list
| build_args_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 pylint_lint_stdin(pylint_executable, document, flags):
"""Run pylint linter from stdin.
This runs pylint in a subprocess with popen.
This allows passing the file from stdin and as a result
run pylint on unsaved files. Can slowdown the workflow.
: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: linting diagnostics
:rtype: list
"""
pylint_result = _run_pylint_stdio(pylint_executable, document, flags)
return _parse_pylint_stdio_result(document, pylint_result) | Run pylint linter from stdin.
This runs pylint in a subprocess with popen.
This allows passing the file from stdin and as a result
run pylint on unsaved files. Can slowdown the workflow.
: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: linting diagnostics
:rtype: list
| pylint_lint_stdin | 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 _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 _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
if definition.name.startswith("_"):
# It's a 'hidden' func, put it next last
return 'z' + definition.name
elif definition.scope == 'builtin':
return 'y' + definition.name
# Else put it at the front
return 'a' + definition.name | Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
| _sort_text | python | palantir/python-language-server | pyls/plugins/rope_completion.py | https://github.com/palantir/python-language-server/blob/master/pyls/plugins/rope_completion.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_dict_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, DICTS_HOME)
return path | Get config path from CONFIGS_HOME, if not exists,
download it from url.
| get_dict_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 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('ppdet://') |
Whether path is URL.
Args:
path (string): URL string or not.
| is_url | 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 _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/PP-HumanV2/APP/pipeline/download.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/pipeline/download.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 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/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 __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
"""
im = im.astype(np.float32, copy=False)
mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
std = np.array(self.std)[np.newaxis, np.newaxis, :]
if self.is_scale:
im = im / 255.0
im -= mean
im /= std
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 __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
"""
im = im.transpose((2, 0, 1)).copy()
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 __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
"""
coarsest_stride = self.coarsest_stride
if coarsest_stride <= 0:
return im, im_info
im_c, im_h, im_w = im.shape
pad_h = int(np.ceil(float(im_h) / coarsest_stride) * coarsest_stride)
pad_w = int(np.ceil(float(im_w) / coarsest_stride) * coarsest_stride)
padding_im = np.zeros((im_c, pad_h, pad_w), dtype=np.float32)
padding_im[:, :im_h, :im_w] = im
return padding_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 __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 __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
height, width = self.target_size
h, w = im.shape[:2]
im, ratio, padw, padh = self.letterbox(im, height=height, width=width)
new_shape = [round(h * ratio), round(w * ratio)]
im_info['im_shape'] = np.array(new_shape, dtype=np.float32)
im_info['scale_factor'] = np.array([ratio, ratio], dtype=np.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 __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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.