swarmsort.prepare_input module

Input preparation and verification utilities for SwarmSort.

This module provides optimized conversion functions from various detection formats (YOLO v8/v11, etc.) to SwarmSort’s Detection format, along with input verification.

swarmsort.prepare_input.numpy_to_detections(boxes, confidences=None, embeddings=None, format='xyxy')[source]

Convert numpy arrays to SwarmSort Detection format.

Ultra-fast conversion for custom detection pipelines.

Parameters:
  • boxes (ndarray) – Array of bounding boxes. Shape (N, 4)

  • confidences (Optional[ndarray]) – Array of confidence scores. Shape (N,)

  • embeddings (Optional[ndarray]) – Optional embedding vectors. Shape (N, embedding_dim)

  • format (str) – Box format - ‘xyxy’, ‘xywh’, or ‘cxcywh’

Return type:

List[Detection]

Returns:

List of Detection objects

Example

>>> boxes = np.array([[100, 100, 200, 200], [300, 300, 400, 400]])
>>> confs = np.array([0.9, 0.85])
>>> detections = numpy_to_detections(boxes, confs)
swarmsort.prepare_input.prepare_detections(raw_detections, source_format='auto', **kwargs)[source]

Universal detection preparation function.

Automatically converts and verifies detections from various formats.

Parameters:
  • raw_detections (Union[List[Detection], ndarray, Any]) – Raw detection data in any supported format

  • source_format (str) – Format hint - ‘auto’, ‘yolo’, ‘numpy’, ‘detection’

  • **kwargs – Additional arguments passed to conversion functions

Return type:

List[Detection]

Returns:

List of verified Detection objects ready for tracking

Example

>>> # Auto-detect format and convert
>>> detections = prepare_detections(yolo_results)
>>> tracked = tracker.update(detections)
swarmsort.prepare_input.verify_detections(detections, image_shape=None, auto_fix=False, raise_on_error=False)[source]

Verify and optionally fix detection inputs.

Checks for common issues and can auto-fix them.

Parameters:
  • detections (List[Detection]) – List of Detection objects to verify

  • image_shape (Optional[Tuple[int, int]]) – (height, width) to check if detections are within bounds

  • auto_fix (bool) – If True, attempts to fix issues (clip coords, normalize, etc.)

  • raise_on_error (bool) – If True, raises exception on critical errors

Return type:

Tuple[List[Detection], List[str]]

Returns:

Tuple of (verified_detections, list_of_warnings)

Example

>>> detections, warnings = verify_detections(detections, image_shape=(720, 1280))
>>> if warnings:
>>>     print(f"Found {len(warnings)} issues")
swarmsort.prepare_input.yolo_to_detections(yolo_results, image_shape=None, confidence_threshold=0.0, class_filter=None, extract_embeddings=False)[source]

Convert YOLO v8/v11 detection results to SwarmSort Detection format.

Works with both stream=True and stream=False YOLO predictions.

Parameters:
  • yolo_results (Any) – YOLO results object from model.predict() or model.track() - Single Results object (one frame) - NOT a generator/list of results (use in loop for that)

  • image_shape (Optional[Tuple[int, int]]) – (height, width) of the image. If None, extracts from results

  • confidence_threshold (float) – Minimum confidence to include detection

  • class_filter (Optional[List[int]]) – List of class IDs to include. None means all classes

  • extract_embeddings (bool) – If True, attempts to extract visual features if available

Return type:

List[Detection]

Returns:

List of Detection objects ready for SwarmSort tracking

Examples

>>> from ultralytics import YOLO
>>> model = YOLO('yolov8n.pt')
>>>
>>> # Option 1: stream=False (loads all frames to memory)
>>> results = model.predict('video.mp4', stream=False)
>>> for result in results:  # Iterate over pre-loaded results
>>>     detections = yolo_to_detections(result)
>>>     tracked = tracker.update(detections)
>>>
>>> # Option 2: stream=True (memory efficient, processes one at a time)
>>> results = model.predict('video.mp4', stream=True)
>>> for result in results:  # Generator, loads one frame at a time
>>>     detections = yolo_to_detections(result)
>>>     tracked = tracker.update(detections)
swarmsort.prepare_input.yolo_to_detections_batch(yolo_results_list, confidence_threshold=0.0, class_filter=None)[source]

Convert a pre-loaded list of YOLO results to SwarmSort format.

NOTE: This is mainly useful for offline analysis where you want to process all detections first before tracking. For real-time tracking, use yolo_to_detections() in your frame loop instead.

Parameters:
  • yolo_results_list (List[Any]) – List of YOLO results (pre-loaded, not a generator)

  • confidence_threshold (float) – Minimum confidence threshold

  • class_filter (Optional[List[int]]) – Optional class filter

Return type:

List[List[Detection]]

Returns:

List of detection lists (one list per frame)

Example (offline analysis):
>>> # Load all results first (uses more memory)
>>> model = YOLO('yolov8n.pt')
>>> results = model.predict('video.mp4', stream=False)  # All frames in memory
>>> all_detections = yolo_to_detections_batch(results)
>>>
>>> # Now you can analyze detections before tracking
>>> print(f"Total detections: {sum(len(d) for d in all_detections)}")
>>>
>>> # Then track
>>> for frame_detections in all_detections:
>>>     tracked = tracker.update(frame_detections)
For real-time/streaming, just use yolo_to_detections() directly:
>>> for result in model.predict('video.mp4', stream=True):
>>>     detections = yolo_to_detections(result)
>>>     tracked = tracker.update(detections)