sportslabkit.utils#

Overview#

Function#

tqdm(*args, level, **kwargs)

Wrapper for tqdm.tqdm that uses the logger’s level.

read_image(img)

Reads an image from a file, URL, a numpy array, or a torch tensor.

auto_string_parser(value)

Auxiliary function to parse string values.

count_iter_items(iterable)

Consume an iterable not reading it into memory; return the number of items.

load_config(yaml_path)

Load config from yaml file.

write_config(yaml_path, cfg)

Write config to yaml file.

pil2cv(image)

Convert PIL image to OpenCV image.

cv2pil(image, convert_bgr2rgb)

Convert OpenCV image to PIL image.

get_fps(path)

-

make_video(frames, outpath, vcodec, pix_fmt, preset, crf, ss, t, c, height, width, input_framerate, logging, custom_ffmpeg)

Make video from a list of opencv format frames.

merge_dict_of_lists(d1, d2)

Merge two dicts of lists.

get_git_root()

Get the root of the git repository.

download_file_from_google_drive(id, destination)

-

get_confirm_token(response)

-

save_response_content(response, destination)

-

increment_path(path, exist_ok, mkdir)

Increments a path (appends a suffix) if it already exists.

load_keypoints(keypoint_json)

Loads source and target keypoints from a JSON file.

sanitize_url_name(url)

Sanitize the URL to create a safe filename for caching.

fetch_or_cache_model(url, dst, hash_prefix, progress)

Fetches a model from a URL or uses a cached version if it exists.

Attributes#

PathLike

-

Classes#

class sportslabkit.utils.HiddenPrints[source]#
class sportslabkit.utils.MovieIterator(path: str)[source]#
class sportslabkit.utils.ImageIterator(path: str)[source]#

Functions#

sportslabkit.utils.tqdm(*args, level: str = 'INFO', **kwargs) collections.abc.Iterable#

Wrapper for tqdm.tqdm that uses the logger’s level.

Parameters:
  • *args – Arguments to pass to tqdm.tqdm

  • **kwargs – Keyword arguments to pass to tqdm.tqdm

  • level (str, optional) – Logging level to set. Defaults to “INFO”.

Returns:

Iterable from tqdm progress bar

Return type:

Iterable

sportslabkit.utils.read_image(img)[source]#

Reads an image from a file, URL, a numpy array, or a torch tensor. :param img: The image to read. :type img: str, Path, Image.Image, np.ndarray, or torch.Tensor

Returns:

The image as a numpy array.

Return type:

np.ndarray

sportslabkit.utils.auto_string_parser(value: str) Any[source]#

Auxiliary function to parse string values.

Parameters:

value (str) – String value to parse.

Returns:

Parsed string value.

Return type:

value (any)

sportslabkit.utils.count_iter_items(iterable: collections.abc.Iterable) int[source]#

Consume an iterable not reading it into memory; return the number of items.

Parameters:

iterable (Iterable) – Iterable object

Returns:

Number of items

Return type:

int

sportslabkit.utils.load_config(yaml_path: str) omegaconf.OmegaConf[source]#

Load config from yaml file.

Parameters:

yaml_path (str) – Path to yaml file

Returns:

Config object loaded from yaml file

Return type:

OmegaConf

sportslabkit.utils.write_config(yaml_path: str, cfg: omegaconf.OmegaConf) None[source]#

Write config to yaml file.

Parameters:
  • yaml_path (str) – Path to yaml file

  • cfg (OmegaConf) – Config object

sportslabkit.utils.pil2cv(image: PIL.Image.Image) numpy.typing.NDArray[numpy.uint8][source]#

Convert PIL image to OpenCV image.

Parameters:

image (Image.Image) – PIL image

Returns:

Numpy Array (OpenCV image)

Return type:

NDArray[np.uint8]

sportslabkit.utils.cv2pil(image: numpy.typing.NDArray[numpy.uint8], convert_bgr2rgb=True) PIL.Image.Image[source]#

Convert OpenCV image to PIL image.

Parameters:

image (NDArray[np.uint8]) – Numpy Array (OpenCV image)

Returns:

PIL image

Return type:

Image.Image

sportslabkit.utils.get_fps(path)[source]#
sportslabkit.utils.make_video(frames: collections.abc.Iterable[numpy.typing.NDArray[numpy.uint8]], outpath: sportslabkit.types.types.PathLike, vcodec: str = 'libx264', pix_fmt: str = 'yuv420p', preset: str = 'medium', crf: int | None = None, ss: int | None = None, t: int | None = None, c: str | None = None, height: int | None = -1, width: int | None = -1, input_framerate: int | None = None, logging: bool = False, custom_ffmpeg: str | None = None) None[source]#

Make video from a list of opencv format frames.

Parameters:
  • frames (Iterable[NDArray[np.uint8]]) – List of opencv format frames

  • outpath (str) – Path to output video file

  • vcodec (str) – Video codec.

  • preset (str) –

    Video encoding preset. A preset is a collection of options that will provide a certain encoding speed to compression ratio. A slower preset will provide better compression (compression is quality per filesize). Use the slowest preset that you have patience for. The available presets in descending order of speed are:

    • ultrafast

    • superfast

    • veryfast

    • faster

    • fast

    • medium (default preset)

    • slow

    • slower

    • veryslow

    Defaults to medium.

  • crf (int) – Constant Rate Factor. Use the crf (Constant Rate Factor) parameter to control the output quality. The lower crf, the higher the quality (range: 0-51). Visually lossless compression corresponds to -crf 18. Use the preset parameter to control the speed of the compression process. Defaults to 23.

  • ss (int) – Start-time of the clip in seconds. Defaults to 0.

  • t (Optional[int]) – Duration of the clip in seconds. Defaults to None.

  • c (bool) – copies the first video, audio, and subtitle bitstream from the input to the output file without re-encoding them. Defaults to False.

  • height (int) – Video height. Defaults to None.

  • width (int) – Video width. Defaults to None.

  • input_framerate (int) – Input framerate. Defaults to 25.

  • logging (bool) – Logging. Defaults to False.

Todo

  • add FPS option

  • functionality to use PIL image

  • reconsider compression (current compression is not good)

sportslabkit.utils.merge_dict_of_lists(d1: dict, d2: dict) dict[source]#

Merge two dicts of lists.

Parameters:
  • d1 (dict) – The first dict to merge.

  • d2 (dict) – The second dict to merge.

Returns:

The merged dict.

Return type:

dict

sportslabkit.utils.get_git_root()[source]#

Get the root of the git repository.

sportslabkit.utils.download_file_from_google_drive(id, destination)[source]#
sportslabkit.utils.get_confirm_token(response)[source]#
sportslabkit.utils.save_response_content(response, destination)[source]#
sportslabkit.utils.increment_path(path: str | Path, exist_ok: bool = False, mkdir: bool = False) pathlib.Path[source]#

Increments a path (appends a suffix) if it already exists.

Parameters:
  • path (Union[str, Path]) – The path to increment.

  • exist_ok (bool, optional) – If set to True, no increment will be done. Defaults to False.

  • mkdir (bool, optional) – If set to True, the directory will be created. Defaults to False.

Returns:

The incremented path.

Return type:

Path

sportslabkit.utils.load_keypoints(keypoint_json)[source]#

Loads source and target keypoints from a JSON file.

Parameters:

keypoint_json (str) – Path to JSON file containing keypoints.

Returns:

Source keypoints. target_keypoints (np.ndarray): Target keypoints.

Return type:

source_keypoints (np.ndarray)

sportslabkit.utils.sanitize_url_name(url: str) str[source]#

Sanitize the URL to create a safe filename for caching.

Parameters:

url (str) – The URL to sanitize.

Returns:

A sanitized version of the URL suitable for use as a filename.

Return type:

str

sportslabkit.utils.fetch_or_cache_model(url: str, dst: PathLike | None = None, hash_prefix: str | None = None, progress: bool = True) str[source]#

Fetches a model from a URL or uses a cached version if it exists.

Parameters:
  • url (str) – URL of the object to download.

  • dst (PathLike | None, optional) – Full path where object will be saved. Defaults to None.

  • hash_prefix (str | None, optional) – Hash prefix to validate downloaded file. Defaults to None.

  • progress (bool, optional) – Whether to show download progress. Defaults to True.

Returns:

The path to the downloaded or cached file.

Return type:

str

Attributes#

sportslabkit.utils.PathLike :TypeAlias#