Utilities module

This module contains various utility functions and classes used throughout the toolkit.

class vot.utilities.ColoredFormatter(**kwargs)

Colored log formatter using colorama package.

class Empty

An empty class used to copy LogRecord objects without reinitializing them.

format(record: LogRecord) str

Formats message by injecting colorama terminal codes for text coloring.

Parameters

record (LogRecord) – Input log record

Returns

Formatted string

Return type

str

class vot.utilities.Progress(description='Processing', total=100)

Wrapper around tqdm progress bar, enables silecing the progress output and some more costumizations.

absolute(value)

Sets the progress to the given value.

Parameters

value – The value to set the progress to.

close()

Closes the progress bar.

relative(n)

Increments the progress by the given value.

Parameters

n – The value to increment the progress by.

total(t)

Sets the total number of steps.

Parameters

t – The total number of steps.

class vot.utilities.Registry(group: str, attr_name: Optional[str] = None)

A class registry for storing classes with a fallback to entry point registry.

classes()

Returns an iterator over the registered classes.

Returns

Iterator over the registered classes

Return type

Iterator

get_class(key: Hashable)

Returns the class associated with the specified key. If the class is not found in the local registry, it is loaded from the entry point registry.

Parameters

key (Hashable) – Key of the class to load

Returns

Loaded class

Return type

Type[T]

items()

Warning

DEPRECATED: use keys() or classes() instead.

Returns the collection of registered key-class pairs, in the order that they were registered.

keys()

Returns an iterator over the registered classes.

Returns

Iterator over the registered classes

Return type

Iterator

class vot.utilities.ThreadPoolExecutor(*args, **kwargs)

Thread pool executor with a shutdown method that waits for all threads to finish.

shutdown(wait=True)

Shuts down the thread pool executor. If wait is True, waits for all threads to finish.

Parameters

wait (bool, optional) – Wait for all threads to finish. Defaults to True.

class vot.utilities.Timer(name=None)

Simple timer class for measuring elapsed time.

vot.utilities.arg_hash(*args, **kwargs) str

Computes hash based on input positional and keyword arguments.

The algorithm tries to convert all arguments to string, then enclose them with delimiters. The positonal arguments are listed as is, keyword arguments are sorted and encoded with their keys as well as values.

Returns

SHA1 hash as hexadecimal string

Return type

str

vot.utilities.class_fullname(o)

Returns the full name of the class of the given object.

Parameters

o – The object to get the class name from.

Returns

The full name of the class of the given object.

vot.utilities.class_string(kls)

Returns the full name of the given class.

Parameters

kls – The class to get the name from.

Returns

The full name of the given class.

vot.utilities.extract_files(archive, destination, callback=None)

Extracts all files from the given archive to the given destination.

Parameters
  • archive – The archive to extract the files from.

  • destination – The destination to extract the files to.

  • callback – An optional callback function that is called after each file is extracted.

vot.utilities.file_hash(filename: str) Tuple[str, str]

Calculates MD5 and SHA1 hashes based on file content.

Parameters

filename (str) – Filename of the file to open and analyze

Returns

MD5 and SHA1 hashes as hexadecimal strings.

Return type

Tuple[str, str]

vot.utilities.flatten(nested_list)

Flattens a nested list.

Parameters

nested_list – The nested list to flatten.

Returns

The flattened list.

vot.utilities.flip(size: Tuple[Number, Number]) Tuple[Number, Number]

Flips the given size tuple.

Parameters

size – The size tuple to flip.

Returns

The flipped size tuple.

vot.utilities.format_size(num, suffix='B')

Formats the given number as a human-readable size string.

Parameters
  • num (int) – Number to format

  • suffix (str, optional) – Suffix to use. Defaults to “B”.

Returns

Formatted string

Return type

str

vot.utilities.import_class(classpath: str) Type

Import a class from a string by importing parent packages.

Parameters

classpath (str) – String representing a canonical class name with all parent packages.

Raises

ImportError – Raised when

Returns

[description]

Return type

[type]

vot.utilities.localize_path(path)

Converts path to local format (backslashes on Windows, slashes on Linux)

Parameters

path (str) – Path to convert

Returns

Converted path

Return type

str

vot.utilities.normalize_path(path, root=None)

Normalizes the given path by making it absolute and removing redundant parts.

Parameters
  • path (str) – Path to normalize

  • root (str, optional) – Root path to use if the given path is relative. Defaults to None.

Returns

Normalized path

Return type

str

vot.utilities.read_properties(filename: str, delimiter: str = '=') Dict[str, str]

Reads a given properties file with each line of the format key=value. Returns a dictionary containing the pairs.

Parameters
  • filename (str) – The name of the file to be read.

  • delimiter (str, optional) – Key-value delimiter. Defaults to ‘=’.

Returns

Resuting properties as a dictionary

Return type

[Dict[str, str]]

vot.utilities.singleton(class_)

Singleton decorator for classes.

Parameters

class (class) – Class to decorate

Returns

Decorated class

Return type

class

Example

@singleton class MyClass:

pass

a = MyClass()

vot.utilities.to_logical(val)

Converts the given value to a logical value (True/False). If the value is not a logical value, a RuntimeError is raised.

Parameters

val (Any) – Value to convert

Returns

Converted value

Return type

bool

vot.utilities.to_number(val, max_n=None, min_n=None, conversion=<class 'int'>)

Converts the given value to a number and checks if it is within the given range. If the value is not a number, a RuntimeError is raised.

Parameters
  • val (Any) – Value to convert

  • max_n (int, optional) – Maximum allowed value. Defaults to None.

  • min_n (int, optional) – Minimum allowed value. Defaults to None.

  • conversion (function, optional) – Conversion function. Defaults to int.

Returns

Converted value

Return type

int

vot.utilities.to_string(n: Any) str

Converts object to string, returs empty string if object is None (so a bit different behaviour than the original string conversion).

Parameters

n (Any) – Object of any kind

Returns

String representation (using built-in conversion)

Return type

str

vot.utilities.which(program: str) str

Locates an executable in system PATH list by its name.

Parameters

program (str) – Name of the executable

Returns

Full path or None if not found

Return type

str

vot.utilities.write_properties(filename: str, dictionary: Mapping[str, Any], delimiter: str = '=')
Writes the provided dictionary in key sorted order to a properties

file with each line in the format: key<delimiter>value

Parameters
  • filename (str) – the name of the file to be written

  • dictionary (Mapping[str, str]) – a dictionary containing the key/value pairs.

  • delimiter (str, optional) – _description_. Defaults to ‘=’.

CLI

Command line interface for the toolkit.

This module provides a command line interface for the toolkit. It is used to run experiments, manage trackers and datasets, and to perform other tasks.

class vot.utilities.cli.EnvDefault(envvar, required=True, default=None, separator=None, **kwargs)

Argparse action that resorts to a value in a specified envvar if no value is provided via program arguments.

vot.utilities.cli.do_analysis(args: Namespace)

Run an analysis for a tracker on an experiment stack and a set of sequences. Analysis results are serialized to disk either as a JSON file or as a YAML file.

Parameters

args (argparse.Namespace) – Configuration

vot.utilities.cli.do_evaluate(config: Namespace)

Run an evaluation for a tracker on an experiment stack and a set of sequences.

Parameters

config (argparse.Namespace) – Configuration

vot.utilities.cli.do_initialize(config: Namespace)

Initialize a workspace. If a stack is provided, the workspace is initialized with the stack. If no stack is provided, but a dataset exists, then a dummy config can be created for this custom dataset. If neither is provided, the user is prompted to provide a stack.

Parameters

config (argparse.Namespace) – Configuration

vot.utilities.cli.do_pack(config: Namespace)

Package results to a ZIP file so that they can be submitted to a challenge.

Parameters

config (argparse.Namespace) – Configuration

vot.utilities.cli.do_report(config: Namespace)

Generate a report for a one or multiple trackers on an experiment stack and a set of sequences.

Parameters

config (argparse.Namespace) – Configuration

vot.utilities.cli.do_test(config: Namespace)

Run a test for a tracker.

Parameters

config (argparse.Namespace) – Configuration

vot.utilities.cli.main()

Entrypoint to the toolkit Command Line Interface utility, should be executed as a program and provided with arguments.

Data

Data structures for storing data in a grid.

class vot.utilities.data.Grid(*size)

A grid is a multidimensional array with named dimensions.

cell(*i)

Returns the element at the given index packed in a scalar grid.

Parameters

i (int) – The index of the element. If the grid is one-dimensional, the index can be an integer.

Returns

The element at the given index packed in a scalar grid.

Return type

object

column(i)

Returns the column at the given index.

Parameters

i (int) – The index of the column.

Returns

The column at the given index.

Return type

Grid

property dimensions

Returns the number of dimensions of the grid.

foreach(cb) Grid

Applies a function to each element of the grid.

Parameters

cb (function) – The function to apply to each element. The first argument is the element, the following arguments are the indices of the element.

Returns

A grid containing the results of the function.

Return type

Grid

row(i)

Returns the row at the given index.

Parameters

i (int) – The index of the row.

Returns

The row at the given index.

Return type

Grid

static scalar(obj)

Creates a grid with a single cell containing the given object.

Parameters

obj (object) – The object to store in the grid.

size(i: int = None)

Returns the size of the grid or the size of a specific dimension.

Parameters

i (int) – The dimension to query. If None, the size of the grid is returned.

Returns

The size of the grid or the size of the given dimension.

Return type

int

class vot.utilities.data.TestGrid(methodName='runTest')

Unit tests for the Grid class.

test_foreach1()

Tests the foreach method.

test_foreach2()

Tests the foreach method.

Drawing

Drawing utilities for visualizing results.

class vot.utilities.draw.DrawHandle(color: Union[Tuple[float, float, float], str] = (1, 0, 0), width: int = 1, fill: bool = False)

Base class for drawing handles.

image(image: Union[ndarray, Image], offset: Tuple[int, int] = None)

Draws an image at the given offset.

line(p1: Tuple[float, float], p2: Tuple[float, float])

Draws a line between two points.

lines(points: List[Tuple[float, float]])

Draws a line between multiple points.

mask(mask: array, offset: Tuple[int, int] = (0, 0))

Draws a mask.

points(points: List[Tuple[float, float]])

Draws points.

polygon(points: List[Tuple[float, float]])

Draws a polygon.

rectangle(left: float, top: float, right: float, bottom: float)

Draws a rectangle.

The rectangle is defined by the top-left and bottom-right corners.

region(region)

Draws a region.

style(color: Union[Tuple[float, float, float], str] = (1, 0, 0), width: int = 1, fill: bool = False) DrawHandle

Sets the style of the drawing handle. Returns self for chaining.

Parameters
  • color (tuple or str) – Color of the drawing handle.

  • width (int) – Width of the drawing handle.

  • fill (bool) – Whether to fill the drawing handle.

Returns

self

class vot.utilities.draw.ImageDrawHandle(image: Union[ndarray, Image], color: Tuple[float, float, float] = (1, 0, 0), width: int = 1, fill: bool = False)

Draw handle for Pillow.

This handle is used for drawing to a Pillow image.

property array: ndarray

Returns the image as a numpy array.

image(image: Union[ndarray, Image], offset: Tuple[int, int] = None)

Draws an image at the given offset.

line(p1, p2)

Draws a line between two points.

lines(points: List[Tuple[float, float]])

Draws a line between multiple points.

mask(mask: array, offset: Tuple[int, int] = (0, 0))

Draws a mask.

points(points: List[Tuple[float, float]])

Draws points.

polygon(points: List[Tuple[float, float]])

Draws a polygon.

property snapshot: Image

Returns a snapshot of the current image.

class vot.utilities.draw.MatplotlibDrawHandle(axis, color: Tuple[float, float, float] = (1, 0, 0), width: int = 1, fill: bool = False, size: Tuple[int, int] = None)

Draw handle for Matplotlib.

This handle is used for drawing to a Matplotlib axis.

image(image: Union[ndarray, Image], offset: Tuple[int, int] = None)

Draws an image at the given offset.

line(p1: Tuple[float, float], p2: Tuple[float, float])

Draws a line between two points.

lines(points: List[Tuple[float, float]])

Draws a line between multiple points.

mask(mask: array, offset: Tuple[int, int] = (0, 0))

Draws a mask.

points(points: List[Tuple[float, float]])

Draws points.

polygon(points: List[Tuple[float, float]])

Draws a polygon.

vot.utilities.draw.resolve_color(color: Union[Tuple[float, float, float], str])

Resolves a color to a tuple of floats.

If the color is a string, it is resolved from an internal palette.

vot.utilities.draw.show_image(a)

Shows an image in the IPython notebook.

Input/Output

class vot.utilities.io.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

JSON encoder for internal types.

default(o)

Default encoder.

class vot.utilities.io.YAMLEncoder(stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True)

YAML encoder for internal types.

represent_object(o)

Represents an object.

represent_tuple(data)

Represents a tuple.

Migration

Migration utilities for old workspaces (legacy Matlab toolkit)

vot.utilities.migration.migrate_matlab_workspace(directory: str)

Migrates a legacy matlab workspace to the new format.

Parameters

directory (str) – The directory of the workspace.

Raises
  • WorkspaceException – If the workspace is already initialized.

  • WorkspaceException – If the workspace is not a legacy workspace.

Network

Network utilities for the toolkit.

exception vot.utilities.net.NetworkException

Exception raised when a network error occurs.

vot.utilities.net.download(url, output, callback=None, chunk_size=32768, retry=10)

Downloads a file from the given url. Supports google drive urls. callback for progress report, automatically resumes download if connection is closed.

Parameters
  • url (str) – The url to parse.

  • output (str) – The output file path or file handle.

  • callback (function) – The callback function for progress report.

  • chunk_size (int) – The chunk size for download.

  • retry (int) – The number of retries.

Raises

NetworkException – If the file is not available.

vot.utilities.net.download_json(url)

Downloads a JSON file from the given url.

Parameters

url (str) – The url to parse.

Returns

The JSON content.

Return type

dict

vot.utilities.net.download_uncompress(url, path)

Downloads a file from the given url and uncompress it to the given path.

Parameters
  • url (str) – The url to parse.

  • path (str) – The path to uncompress the file.

Raises

NetworkException – If the file is not available.

vot.utilities.net.get_base_url(url)

Returns the base url of a given url.

Parameters

url (str) – The url to parse.

Returns

The base url.

Return type

str

vot.utilities.net.get_url_from_gdrive_confirmation(contents)

Returns the url of a google drive file from the confirmation page.

Parameters

contents (str) – The contents of the confirmation page.

Returns

The url of the file.

Return type

str

vot.utilities.net.is_absolute_url(url)

Returns True if the given url is absolute.

Parameters

url (str) – The url to parse.

Returns

True if the url is absolute, False otherwise.

Return type

bool

vot.utilities.net.is_google_drive_url(url)

Returns True if the given url is a google drive url.

Parameters

url (str) – The url to parse.

Returns

True if the url is a google drive url, False otherwise.

Return type

bool

vot.utilities.net.join_url(url_base, url_path)

Joins a base url with a path.

Parameters
  • url_base (str) – The base url.

  • url_path (str) – The path to join.

Returns

The joined url.

Return type

str

Notebook

Utilities for running and visualizing VOT workflows in Jupyter notebooks.

class vot.utilities.notebook.SequenceView(sequence: Sequence)

A compact widget for showing sequence frames and regions.

vot.utilities.notebook.is_notebook() bool

Return True when executed inside an IPython kernel notebook.

vot.utilities.notebook.run_analysis(workspace: Workspace, trackers: List[Tracker], sequences: Optional[List[str]] = None, experiments: Optional[List[str]] = None, output_format: Optional[str] = None, name: Optional[str] = None, **kwargs)

Run stack analyses from a notebook and optionally serialize outputs.

vot.utilities.notebook.run_experiment(experiment: Experiment, sequences: List[Sequence], trackers: List[Tracker], force: bool = False, persist: bool = False)

Run an experiment for one or more trackers from a notebook.

vot.utilities.notebook.visualize_results(experiment: Experiment, sequence: Sequence, trackers=None)

Visualize already computed experiment results for one sequence.

vot.utilities.notebook.visualize_tracker(tracker: Tracker, sequence: Sequence)

Visualize tracker outputs on a sequence inside a notebook.