### Tuning output example Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/03_core_components/multi_object_tracker.html Example output showing the best parameters and average IoU found after tuning. ```text Best parameters: {'dt': 1, 'process_noise': 1.4181557009163317e-06, 'measurement_noise': 0.010853024957654504, 'confidence_scaler': 0.3001373625265234} Best average IoU: 0.6209559476309358 ``` -------------------------------- ### LoggerMixin Output Example Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/05_dev/logging-demo.html Displays the console output for the LoggerMixin class example. ```text Hello:world:0008 💬| hello world ``` -------------------------------- ### Logger Output Example Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/05_dev/logging-demo.html Displays the console output corresponding to the basic logger usage example. ```text IPython:0007 💬| This is an info message IPython:0008 ✅| success! IPython:0009 🤔| I am warning you Github copilot! IPython:0010 ❌| I am error you Github copilot! IPython:0011 🔥| Fire in the hole! ``` -------------------------------- ### Set up development environment with conda and poetry Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/01_get_started/installation.html Sets up a conda environment for development and installs dependencies with Poetry. First create the environment, then activate it and run poetry install. ```bash conda env create --file dev_environment.yaml --name sportslabkit_dev_env ``` ```bash conda activate sportslabkit_dev_env poetry install ``` -------------------------------- ### Install SportsLabKit from development branch Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/01_get_started/installation.html Installs the latest features from the development branch of SportsLabKit directly from GitHub. ```bash pip install git+https://github.com/atomscott/sportslabkit.git@develop#egg=sportslabkit ``` -------------------------------- ### Serve documentation with make serve Source: https://sportslabkit.readthedocs.io/en/latest/04_contributing.html Start a local server to view the built documentation on port 8000. ```bash make serve ``` -------------------------------- ### Install dependencies with pip3 Source: https://sportslabkit.readthedocs.io/en/latest/04_contributing.html Install project dependencies before running tests or making changes. ```bash pip3 install -r requirements.txt ``` -------------------------------- ### CustomImageModel implementation example Source: https://sportslabkit.readthedocs.io/en/latest/autoapi/sportslabkit/image_model/clip/index.html An example showing how to define a custom image model by inheriting from BaseImageModel and implementing the load and forward methods. ```python class CustomImageModel(BaseImageModel): def load(self): def forward(self, x): # Define the forward pass here pass ``` -------------------------------- ### Load camera objects Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/03_core_components/camera.html Example of initializing Camera objects from a configuration dictionary using the load_cameras function. ```python # from sportslabkit.camera import load_cameras # cameras = load_cameras(cfg['cameras']) # print(f"Loaded {len(cameras)} cameras") # WIP ``` -------------------------------- ### Prepare dataset for tracking Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/07_tracking_method_comparison.html Loads the dataset, camera, and ground truth annotations. The example limits processing to the first 10 frames for speed. ```python import sportslabkit as slk from sportslabkit.logger import set_log_level dataset_path = slk.datasets.get_path("top_view") path_to_csv = sorted(dataset_path.glob("annotations/*.csv"))[0] path_to_mp4 = sorted(dataset_path.glob("videos/*.mp4"))[0] root = slk.utils.get_git_root() cam = slk.Camera(path_to_mp4) # For the sake of speed, we'll only use the first 10 frames n_frames = 10 frames = cam[:n_frames] bbdf_gt = slk.load_df(path_to_csv) # TODO: Hopefully we can get rid of this if bbdf_gt.index[0] == 0: bbdf_gt.index += 1 bbdf_gt = bbdf_gt[:n_frames] ``` -------------------------------- ### Install SportsLabKit with pip Source: https://sportslabkit.readthedocs.io/en/latest/index.html Install the SportsLabKit package using pip. The project is in active development, so expect updates and changes. ```bash pip install SportsLabKit ``` -------------------------------- ### YOLOv5 Download Output Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Example console output showing the download process for the YOLOv5 model. ```text YOLOv5 🚀 v6.2-239-gf33718f Python-3.9.14 torch-1.13.1 CPU Downloading https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5x6.pt to /Users/atom/Github/SoccerTrack/models/yolov5/yolov5x6.pt... ``` -------------------------------- ### Log Level Output Example Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/05_dev/logging-demo.html Displays the console output after adjusting log levels. ```text IPython:0005 🐛| That's it, beautiful and simple logging! IPython:0010 🔥| Fire in the hole! ``` -------------------------------- ### YOLOv5 Model Summary Output Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Example console output showing the model architecture summary. ```text Fusing layers... YOLOv5x6 summary: 574 layers, 140730220 parameters, 0 gradients Adding AutoShape... ``` -------------------------------- ### Visualize frames with CoordinatesDataFrame Source: https://sportslabkit.readthedocs.io/en/latest/_modules/sportslabkit/dataframe/coordinatesdataframe.html Examples of loading data and generating animations using visualize_frames. The second example demonstrates creating an animation from random numpy data with custom frame rates. ```python >>> codf = load_codf("/path/to/codf.csv") >>> codf.visualize_frames("/path/to/save.mp4") ... # Heres a demo using random data >>> codf = CoordinatesDataFrame.from_numpy(np.random.randint(0, 50, (1, 23, 2))) >>> codf = codf.loc[codf.index.repeat(5)] # repeat the same frame 5 times >>> codf += np.array([[0,1,2,3,4]]).T # add some movment >>> codf.visualize_frames('visualize_frames.gif', save_kwargs={'fps':2}) ``` -------------------------------- ### Tracking Performance Output Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Example console output showing tracking performance metrics for a video file. ```text F_20200220_1_0000_0030.mp4 MOTA: 0.02 HOTA: 0.11 ``` -------------------------------- ### Video Generation Progress Output Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/02_dataframe_visualization.html Example output showing the progress of video generation. ```text Writing video: 750it [01:20, 9.30it/s] ``` -------------------------------- ### Detect and visualize hull Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Example workflow for detecting a hull, converting it to a quadrilateral, and drawing it on a frame. ```python hull = FLD(frames[2]) print(hull.shape) quadrilateral = hull_to_quadrilateral(hull) image_with_quadrilateral = draw_quadrilateral_on_image(frames[0], quadrilateral) slk.utils.cv2pil(image_with_quadrilateral, convert_bgr2rgb=False) ``` -------------------------------- ### Display tracking metrics output (alternative) Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Example output showing tracking metrics with higher values for MOTA, HOTA, DetA, AssA, and IDF1. ```text MOTA: 70.41 HOTA: 47.63 DetA: 54.71 AssA: 41.68 IDF1: 65.16 ``` -------------------------------- ### SingleObjectTracker.pre_track() Source: https://sportslabkit.readthedocs.io/en/latest/autoapi/sportslabkit/sot/base/index.html Performs setup before tracking starts. This method is called automatically before the tracking loop begins. ```APIDOC ## SingleObjectTracker.pre_track() ### Description Performs setup before tracking starts. This method is called automatically before the tracking loop begins. ### Method pre_track ### Parameters None ### Returns None ``` -------------------------------- ### Build documentation with make html Source: https://sportslabkit.readthedocs.io/en/latest/04_contributing.html Build the documentation locally. ```bash make html ``` -------------------------------- ### Load dataset and inspect DataFrame with sportslabkit Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/02_dataframe_visualization.html Loads the wide_view dataset, finds the first annotation CSV and video, loads the DataFrame, and displays its head. This is the starting point for visualization examples. ```python import sportslabkit as slk root = slk.utils.get_git_root() dataset_path = slk.datasets.get_path('wide_view') path_to_csv = sorted(dataset_path.glob('annotations/*.csv'))[0] path_to_mp4 = sorted(dataset_path.glob('videos/*.mp4'))[0] df = slk.load_df(path_to_csv) df.head() ``` -------------------------------- ### Load dataset and camera for tracking Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/03_core_components/motion_model.html Sets up the environment by loading a dataset path and initializing a camera instance for video processing. ```python import soccertrack as st dataset_path = st.datasets.get_path("wide_view") path_to_csv = sorted(dataset_path.glob("annotations/*.csv"))[0] path_to_mp4 = sorted(dataset_path.glob("videos/*.mp4"))[0] root = st.utils.get_git_root() cam = st.Camera(path_to_mp4) # let's load the first frame of the video frame = cam.get_frame(0) ``` -------------------------------- ### Tracking started output Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Output from the PrintingCallback indicating the start of tracking with zero tracklets. ```text Tracking started with 0 tracklets ``` -------------------------------- ### Initialize KaggleDownloader Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/00_dataset_preparation.html Initialize the KaggleDownloader helper class to prepare for dataset downloads. Authentication is required during initialization. ```python import sportslabkit as slk dl = slk.datasets.KaggleDownloader() ``` -------------------------------- ### Initialize SportsLabKit environment Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/03_core_components/detection_model.html Sets up the dataset paths and camera object for processing video frames. ```python import sportslabkit as slk dataset_path = slk.datasets.get_path("wide_view") path_to_csv = sorted(dataset_path.glob("annotations/*.csv"))[0] path_to_mp4 = sorted(dataset_path.glob("videos/*.mp4"))[0] root = slk.utils.get_git_root() cam = slk.Camera(path_to_mp4) # let's load the first frame of the video frame = cam.get_frame(0) ``` -------------------------------- ### FileNotFoundError Traceback Example Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/02_dataframe_visualization.html An example of a FileNotFoundError traceback occurring when attempting to open a non-existent JSON file path. ```python --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Cell In[4], line 6 3 import json 4 data_path = '/Users/atom/Github/SoccerTrack/soccertrack/datasets/fisheye_keypoints.json' ----> 6 with open(data_path) as f: 7 keypoints = json.load(f) 9 def draw_f(frame): File ~/miniconda3/envs/sportslabkit-test/lib/python3.10/site-packages/IPython/core/interactiveshell.py:284, in _modified_open(file, *args, **kwargs) 277 if file in {0, 1, 2}: 278 raise ValueError( 279 f"IPython won't let you open fd={file} by default " 280 "as it is likely to crash IPython. If you know what you are doing, " 281 "you can use builtins' open." 282 ) --> 284 return io_open(file, *args, **kwargs) FileNotFoundError: [Errno 2] No such file or directory: '/Users/atom/Github/SoccerTrack/soccertrack/datasets/fisheye_keypoints.json' ``` -------------------------------- ### Initialize and run tracking pipeline Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/01_get_started/introduction_to_sportslabkit.html Configures the camera, detection model, and motion model to track objects using the SORTTracker. ```python from sportslabkit.utils import get_git_root from sportslabkit.mot import SORTTracker root = get_git_root() cam = slk.Camera(path_to_mp4) det_model = slk.detection_model.load('YOLOv8x', imgsz=640) motion_model = slk.motion_model.load('KalmanFilter', dt=1/30, process_noise=10000, measurement_noise=10) tracker = SORTTracker(detection_model=det_model, motion_model=motion_model) tracker.track(cam[:100]) res = tracker.to_bbdf() ``` ```text Tracking Progress: 0%| | 0/100 [00:00 BaseMotionModel ### Parameters - **config** (dict) - Required - The configuration dictionary containing the motion model's parameters. ### Returns - **BaseMotionModel** - A new instance of the motion model initialized with the given configuration. ``` -------------------------------- ### get_frame Source: https://sportslabkit.readthedocs.io/en/latest/autoapi/sportslabkit/dataframe/base/index.html Gets a specific frame from the dataframe. ```APIDOC ## get_frame(frame) ### Description Gets a specific frame from the dataframe. ### Method get_frame ### Endpoint BaseSLKDataFrame.get_frame(frame) ### Parameters - **frame** (int) - Required - Frame to get. ### Returns pd.DataFrame - Dataframe with the frame. ``` -------------------------------- ### Initialize Camera for Video Processing Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/03_core_components/single_object_tracker.html Sets up the Camera object using a video file path derived from the dataset. ```python import sportslabkit as slk dataset_path = slk.datasets.get_path("wide_view") path_to_csv = sorted(dataset_path.glob("annotations/*.csv"))[0] path_to_mp4 = sorted(dataset_path.glob("videos/*.mp4"))[0] root = slk.utils.get_git_root() cam = slk.Camera(path_to_mp4) ``` -------------------------------- ### sportslabkit.utils.get_fps Source: https://sportslabkit.readthedocs.io/en/latest/autoapi/sportslabkit/utils/index.html Get frames per second from a video file. ```APIDOC ## sportslabkit.utils.get_fps ### Description Get frames per second from a video file. ### Parameters - **path** - Path to the video file. ``` -------------------------------- ### get_confirm_token(response) Source: https://sportslabkit.readthedocs.io/en/latest/autoapi/sportslabkit/utils/index.html Get the confirmation token from a Google Drive response. ```APIDOC ## get_confirm_token(response) ### Description Get the confirmation token from a Google Drive response. ### Parameters - **response** - The HTTP response. ### Returns - The confirmation token. ``` -------------------------------- ### Basic Camera usage: read video and get first frame Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/03_core_components/camera.html Creates a Camera instance from a video file and retrieves the first frame, printing its shape. Requires a video path from the SportsLabKit datasets. ```python import sportslabkit as slk # Get a video dataset_path = slk.datasets.get_path("wide_view") path_to_mp4 = sorted(dataset_path.glob("videos/*.mp4"))[0] cam = slk.Camera(path_to_mp4) frame = cam[0] # Get the first frame print(frame.shape) ``` -------------------------------- ### get_gps_loader(format) Source: https://sportslabkit.readthedocs.io/en/latest/autoapi/sportslabkit/io/file/index.html Get GPS loader function for a given format. ```APIDOC ## get_gps_loader(format) ### Description Get GPS loader function for a given format. ### Parameters - **format** (str) - The GPS format. ### Returns callable - The loader function. ``` -------------------------------- ### Initialize and run SORTTracker Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/07_tracking_method_comparison.html Configures the detection model, motion model, and matching function, then executes tracking and calculates the initial HOTA score. ```python from sportslabkit.mot import SORTTracker det_model = slk.detection_model.load( model_name='yolov8', model=root/'models/yolov8/soccer_top_view-model=yolov8x-imgsz=2048.pt', conf=0.25, iou=0.6, imgsz=960, device='mps', classes=0, augment=True, max_det=35 ) motion_model = slk.motion_model.load( model_name='kalmanfilter', dt=1/30, process_noise=500, measurement_noise=10, confidence_scaler=1 ) matching_fn = slk.matching.SimpleMatchingFunction( metric=slk.metrics.IoUCMM(use_pred_box=True), gate=0.9 ) tracker = SORTTracker( detection_model=det_model, motion_model=motion_model, matching_fn=matching_fn, max_staleness=2, min_length=2 ) bbdf_pred = tracker.track(frames) hota = slk.metrics.hota_score(bbdf_gt, bbdf_pred)["HOTA"] print(f"HOTA Score before Tuning (SORTTracker): {hota:.3f}") ``` -------------------------------- ### Complete YOLOv8 Detection Model Source Source: https://sportslabkit.readthedocs.io/en/latest/_modules/sportslabkit/detection_model/yolov8.html The full implementation of the YOLOv8 detection model, including imports, hyperparameter search space, initialization, forward pass, and size-specific subclasses (YOLOv8n, YOLOv8s, YOLOv8m, YOLOv8l, YOLOv8x). Ensure ultralytics is installed using 'pip install ultralytics'. ```python ``` import numpy as np try: from ultralytics import YOLO except ImportError: print( "The ultralytics module is not installed. Please install it using the following command:\n" "pip install ultralytics" ) from sportslabkit.detection_model.base import BaseDetectionModel [docs]class YOLOv8(BaseDetectionModel): """YOLO model wrapper. Receives the arguments controlling inference as 'inference_config' when initialized. """ [docs] hparam_search_space = { "max_det": {"type": "int", "low": 20, "high": 50}, "imgsz": {"type": "int", "low": 1280, "high": 3840}, "conf": {"type": "float", "low": 0.1, "high": 1.0}, "iou": {"type": "float", "low": 0.1, "high": 1.0}, } def __init__( self, model: str = "", agnostic_nms: bool = False, multi_label: bool = False, classes: list[str] | None = None, max_det: int = 1000, amp: bool = False, imgsz: int = 640, conf: float = 0.25, iou: float = 0.45, device: str = "cpu", verbose: bool = False, augment: bool = False, ): """ Initializes the base detection model. Args: model_config (Optional[dict]): The configuration for the model. This is optional and can be used to pass additional parameters to the model. """ super().__init__() self.agnostic_nms = agnostic_nms self.classes = classes self.max_det = max_det self.amp = amp self.imgsz = imgsz self.conf = conf self.iou = iou self.device = device self.verbose = verbose self.augment = augment self.model = YOLO(model=model) [docs] def forward(self, x, **kwargs): def to_dict(res): if len(res) == 0: return [{}] return [ { "bbox_left": r[0] - r[2] / 2, "bbox_top": r[1] - r[3] / 2, "bbox_width": r[2], "bbox_height": r[3], "conf": r[4], "class": r[5], } for r in res ] x = [_x[..., ::-1] for _x in x] results = self.model( x, agnostic_nms=kwargs.get("agnostic_nms", self.agnostic_nms), classes=kwargs.get("classes", self.classes), max_det=kwargs.get("max_det", self.max_det), imgsz=kwargs.get("imgsz", self.imgsz), conf=kwargs.get("conf", self.conf), iou=kwargs.get("iou", self.iou), device=kwargs.get("device", self.device), verbose=kwargs.get("verbose", self.verbose), task="detect", augment=kwargs.get("augment", self.augment), ) preds = [] for result in results: xywh = result.boxes.xywh.detach().cpu().numpy() conf = result.boxes.conf.detach().cpu().numpy() cls = result.boxes.cls.detach().cpu().numpy() res = np.concatenate([xywh, conf.reshape(-1, 1), cls.reshape(-1, 1)], axis=1) preds.append(to_dict(res)) return preds [docs]class YOLOv8n(YOLOv8): def __init__(self, **model_config): model_config["model"] = model_config.get("model", "yolov8n") super().__init__(model_config) [docs]class YOLOv8s(YOLOv8): def __init__(self, **model_config): model_config["model"] = model_config.get("model", "yolov8s") super().__init__(model_config) [docs]class YOLOv8m(YOLOv8): def __init__(self, **model_config): model_config["model"] = model_config.get("model", "yolov8m") super().__init__(model_config) [docs]class YOLOv8l(YOLOv8): def __init__(self, **model_config): model_config["model"] = model_config.get("model", "yolov8l") super().__init__(model_config) [docs]class YOLOv8x(YOLOv8): def __init__( self, model: str = "yolov8x", agnostic_nms: bool = False, multi_label: bool = False, classes: list[str] | None = None, max_det: int = 1000, amp: bool = False, imgsz: int = 640, conf: float = 0.25, iou: float = 0.45, device: str = "cpu", verbose: bool = False, augment: bool = False, ): super().__init__( model, agnostic_nms, multi_label, classes, max_det, amp, imgsz, conf, iou, device, verbose, augment ) ``` ``` -------------------------------- ### Video generation output Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/02_dataframe_visualization.html Example output displayed during the video generation process. ```text Writing video: 74it [00:04, 14.84it/s] ``` -------------------------------- ### MOTA score output Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/03_evaluation_metrics.html Example output dictionary returned by the mota_score function. ```python {'MOTA': 0.8, 'MOTP': 1.0, 'MODA': 0.8, 'CLR_Re': 0.8, 'CLR_Pr': 1.0, 'MTR': 0.0, 'PTR': 1.0, 'MLR': 0.0, 'sMOTA': 0.8, 'CLR_F1': 0.8888888888888888, 'FP_per_frame': 0.0, 'MOTAL': 0.8, 'MOTP_sum': 92.0, 'CLR_TP': 92, 'CLR_FN': 23, 'CLR_FP': 0, 'IDSW': 0, 'MT': 0, 'PT': 23, 'ML': 0, 'Frag': 0.0, 'CLR_Frames': 5} ``` -------------------------------- ### Get all tracklets Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Combines alive and dead tracklets from the tracker and displays the list. ```python all_tracklets = tracker.alive_tracklets + tracker.dead_tracklets all_tracklets ``` -------------------------------- ### Configure and Run Multi-Object Tracker Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Sets up the MultiObjectTracker with model specifications and runs the tracking loop over video frames. ```python import numpy as np import soccertrack from soccertrack import Camera, detection_model from soccertrack.utils import get_git_root from soccertrack.logger import show_df, tqdm, set_log_level from soccertrack.detection_model.base import Detection from soccertrack.tracking_model.tracker import MultiObjectTracker from soccertrack.tracking_model.matching import EuclideanDistance from soccertrack.metrics import mota_score, hota_score, identity_score model_spec = { "dt": 1 / 25, "order_pos": 1, "dim_pos": 2, "order_size": 0, "dim_size": 2, "q_var_pos": best_params["q_var_pos"], "r_var_pos": best_params["r_var_pos"], "q_var_size": best_params["q_var_size"], "r_var_size": best_params["r_var_size"], "p_cov_p0": best_params["p_cov_p0"], } tracker_kwargs = { "max_staleness": best_params["max_staleness"], "smooth_feature_gamma":best_params["smooth_feature_gamma"], "smooth_score_gamma": best_params["smooth_score_gamma"], } gate = best_params["gate"] tracker = MultiObjectTracker( dt = 1/25, model_spec=model_spec, tracker_kwargs=tracker_kwargs, matching_fn=EuclideanDistance(gate), ) def track(cam, tracker): for frame in (pbar := tqdm(cam.iter_frames())): # detect objects using the detection model detections = det_model(frame, augment=True).to_list() # check if detections are withing pich contour # contour = FLD(frame) # detections = filter(lambda x: cv2.pointPolygonTest(contour, (x.box[0], x.box[1]), False) > 0, detections) # use top 22 detections detections = sorted(detections, key=lambda x: x.score, reverse=True)[:22] detections = list(filter(lambda x: x.class_id == 0, detections)) # update the state of the multi-object-tracker tracker # with the list of bounding boxes tracker.step(detections=detections) return tracker root = get_git_root() model_name = "yolov5" model_repo = root / "external" / "yolov5" model_ckpt = root / "models" / "yolov5" / "yolov5x6.pt" det_model = detection_model.load(model_name, model_repo, model_ckpt) det_model.model.conf = 0.01 det_model.model.size = 6000 # dataset_path = soccertrack.datasets.get_path("top-view") csv_paths = sorted(dataset_path.glob("*.csv"))[:1] mp4_paths = sorted(dataset_path.glob("*.mp4"))[:1] scores = [] for path_to_csv, path_to_mp4 in zip(csv_paths, mp4_paths): bbdf = soccertrack.load_df(path_to_csv) # We will use this as ground truth cam = Camera(path_to_mp4) # Camera object will be used to load frames tracker = MultiObjectTracker( dt = 1/25, model_spec=model_spec, tracker_kwargs=tracker_kwargs, matching_fn=EuclideanDistance(gate), ) bbdf_pred_ft = track(cam, tracker).to_bbdf() bbdf_pred_ft.sort_index(inplace=True) bbdf = bbdf[bbdf.index>=1] mota = mota_score(bboxes_gt=bbdf, bboxes_track=bbdf_pred_ft) hota = hota_score(bboxes_gt=bbdf, bboxes_track=bbdf_pred_ft) id = identity_score(bboxes_gt=bbdf, bboxes_track=bbdf_pred_ft) scores.append({ 'MOTA': mota['MOTA'], 'HOTA': hota['HOTA'], 'DetA': hota['DetA'], 'AssA': hota['AssA'], 'IDF1': id['IDF1'], }) print(f'{path_to_mp4.name} MOTA: {mota["MOTA"]:.2f} HOTA: {hota["HOTA"]:.2f}') ``` -------------------------------- ### Prepare dataset and frames Source: https://sportslabkit.readthedocs.io/en/latest/notebooks/02_user_guide/06_tracking_the_players.html Loads the wide_view dataset, extracts the first two frames from the video, and loads the ground truth bounding boxes, adjusting the index if it starts at zero. ```python import sportslabkit as slk from sportslabkit.logger import set_log_level dataset_path = slk.datasets.get_path("wide_view") path_to_csv = sorted(dataset_path.glob("annotations/*.csv"))[0] path_to_mp4 = sorted(dataset_path.glob("videos/*.mp4"))[0] root = slk.utils.get_git_root() cam = slk.Camera(path_to_mp4) # For the sake of speed, we'll only use the first 10 frames n_frames = 2 frames = cam[:n_frames] bbdf_gt = slk.load_df(path_to_csv) # TODO: Hopefully we can get rid of this if bbdf_gt.index[0] == 0: bbdf_gt.index += 1 bbdf_gt = bbdf_gt[:n_frames] ``` -------------------------------- ### get_frame(frame_idx: int) -> numpy.ndarray Source: https://sportslabkit.readthedocs.io/en/latest/autoapi/sportslabkit/camera/index.html Gets a frame from the video at the specified index. ```APIDOC ## get_frame(frame_idx: int) -> numpy.ndarray ### Description Gets a frame from the video at the specified index. ### Method get_frame ### Parameters - **frame_idx** (int) - Required - The index of the frame to retrieve. ### Returns - **frame** (numpy.ndarray) - The frame at the given index. ```