Skip to content

Labeler

Video labeling and annotation module.

This module provides functionality for drawing and annotating video frames with labels, tracks, and detections. It includes the Labeler class for drawing on videos using OpenCV or FFmpeg backends, and utilities for extracting frames and clips from videos.

ElementType

Bases: StrEnum

Supported drawing element types.

Values
  • TXT: Text label
  • LINE: Line segment
  • BOX: Rectangle (box)
  • BBOX: Bounding box with label
  • CIRCLE: Circle or disk
  • POLYGON: Filled polygon
  • POLYLINES: Open polyline

LabelMethod

Bases: StrEnum

Supported rendering backends.

Values
  • OPENCV: use OpenCV to draw labels (default)
  • FFMPEG: use FFmpeg to draw labels with H.265 encoding for better compression
  • CHROME_SAFE: use FFmpeg to draw labels with H.264 encoding and browser-compatible settings for maximum compatibility

Encoder

Bases: StrEnum

Supported FFmpeg encoders.

Values
  • LIBX264: H.264 codec (AVC)
  • LIBX265: H.265 codec (HEVC)
  • H264_NVENC: NVIDIA GPU-accelerated H.264
  • HEVC_NVENC: NVIDIA GPU-accelerated H.265

Preset

Bases: StrEnum

Supported FFmpeg presets.

Values
  • ULTRAFAST: Fastest encoding, largest file
  • SUPERFAST: Very fast encoding
  • VERYFAST: Fast encoding
  • FASTER: Faster encoding
  • FAST: Fast encoding
  • MEDIUM: Medium speed (default for most encoders)
  • SLOW: Slow encoding
  • SLOWER: Very slow encoding
  • VERYSLOW: Slowest encoding, smallest file

TrackClipMethod

Bases: StrEnum

Track clip selection strategies.

Values
  • ALL: include all tracks (default)
  • RANDOM: randomly select a specified number of tracks, specified by random_number
  • SPECIFY: specify track ids to include, provided in track_ids

Labeler

Labeler(
    method: LabelMethod | str = LabelMethod.OPENCV,
    encoder: Encoder | str = Encoder.LIBX264,
    preset: Preset | str = Preset.MEDIUM,
    crf: int = 23,
    pix_fmt: str = "bgr24",
    compress_message: bool = False,
    nodraw_empty: bool = True,
)

A video labeler for drawing and annotating video frames.

This class provides functionality to draw labels, tracks, and detections on video files using either OpenCV or FFmpeg as the backend.

Attributes:

Name Type Description
method str

The drawing method: 'opencv', 'ffmpeg', or 'chrome_safe'.

encoder str

The video encoder to use with FFmpeg.

preset str

The encoding preset for quality/speed tradeoff.

crf int

Constant Rate Factor for compression quality.

pix_fmt str

Pixel format for video output.

compress_message bool

Whether to show compressed progress messages.

nodraw_empty bool

Whether to skip drawing empty frames.

Initialize the Labeler.

Parameters:

Name Type Description Default
method LabelMethod | str

'opencv' (default) - use opencv to draw labels 'ffmpeg' - use ffmpeg to draw labels 'chrome_safe' - use ffmpeg to draw labels with chrome compatible video format

OPENCV
encoder Encoder | str

'libx264' (default) - use libx264 encoder for ffmpeg 'libx265' - use libx265 encoder for ffmpeg 'h264_nvenc' - use h264_nvenc encoder for ffmpeg 'hevc_nvenc' - use hevc_nvenc encoder for ffmpeg

LIBX264
preset Preset | str

'medium' (default) - use medium preset for ffmpeg 'slow' - use slow preset for ffmpeg 'fast' - use fast preset for ffmpeg

MEDIUM
crf int

23 (default) - use 23 crf for ffmpeg, lower is better quality

23
pix_fmt str

Pixel format for video output. Default is 'bgr24'.

'bgr24'
compress_message bool

False (default) - show compress message in progress bar

False
nodraw_empty bool

True (default) - not draw empty frames

True
Source code in src/dnt/label/labeler.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def __init__(
    self,
    method: LabelMethod | str = LabelMethod.OPENCV,
    encoder: Encoder | str = Encoder.LIBX264,
    preset: Preset | str = Preset.MEDIUM,
    crf: int = 23,
    pix_fmt: str = "bgr24",
    compress_message: bool = False,
    nodraw_empty: bool = True,
):
    """Initialize the Labeler.

    Parameters
    ----------
    method : LabelMethod | str
        'opencv' (default) - use opencv to draw labels
        'ffmpeg' - use ffmpeg to draw labels
        'chrome_safe' - use ffmpeg to draw labels with chrome compatible video format
    encoder : Encoder | str
        'libx264' (default) - use libx264 encoder for ffmpeg
        'libx265' - use libx265 encoder for ffmpeg
        'h264_nvenc' - use h264_nvenc encoder for ffmpeg
        'hevc_nvenc' - use hevc_nvenc encoder for ffmpeg
    preset : Preset | str
        'medium' (default) - use medium preset for ffmpeg
        'slow' - use slow preset for ffmpeg
        'fast' - use fast preset for ffmpeg
    crf : int
        23 (default) - use 23 crf for ffmpeg, lower is better quality
    pix_fmt : str
        Pixel format for video output. Default is 'bgr24'.
    compress_message : bool
        False (default) - show compress message in progress bar
    nodraw_empty : bool
        True (default) - not draw empty frames

    """
    if isinstance(method, LabelMethod):
        self.method = method.value
    else:
        method_value = str(method).lower().strip()
        valid_methods = {m.value for m in LabelMethod}
        if method_value not in valid_methods:
            raise ValueError(f"Invalid method={method!r}. Choose one of {sorted(valid_methods)}.")
        self.method = method_value

    if isinstance(encoder, Encoder):
        self.encoder = encoder.value
    else:
        encoder_value = str(encoder).lower().strip()
        valid_encoders = {e.value for e in Encoder}
        if encoder_value not in valid_encoders:
            raise ValueError(f"Invalid encoder={encoder!r}. Choose one of {sorted(valid_encoders)}.")
        self.encoder = encoder_value

    if isinstance(preset, Preset):
        self.preset = preset.value
    else:
        preset_value = str(preset).lower().strip()
        valid_presets = {p.value for p in Preset}
        if preset_value not in valid_presets:
            raise ValueError(f"Invalid preset={preset!r}. Choose one of {sorted(valid_presets)}.")
        self.preset = preset_value

    self.crf = crf
    self.pix_fmt = pix_fmt
    self.compress_message = compress_message
    self.nodraw_empty = nodraw_empty

draw_shapes

draw_shapes(
    draw_file: str,
    output_file: str | None,
    shapes: list[dict] | dict,
    base_df: DataFrame | None = None,
) -> pd.DataFrame

Add shapes to a draw file in DRAW_COLUMNS format.

Parameters:

Name Type Description Default
draw_file str

Path to a draw CSV file. Used for reading existing data and as the default write target.

required
output_file str

Path to write the combined result. If None, writes to draw_file.

required
shapes list[dict] | dict

One or more shape specifications. Each dict may contain:

  • type - "line", "polyline", "circle", "rectangle", or "polygon"
  • geometry - coordinate pairs, a Shapely geometry, or a WKT string
  • color - BGR tuple, e.g. (0, 255, 0) (optional)
  • fill - whether to fill the shape (optional)
  • alpha - overlay strength 0.0-1.0; aliases: transparent, transparant (optional)
  • size - font size or radius (optional)
  • thick - line thickness (optional)
  • desc - text description (optional)
required
base_df DataFrame

Existing draw DataFrame to append to. If None and draw_file exists, that file is loaded instead.

None

Returns:

Type Description
DataFrame

Combined DataFrame with DRAW_COLUMNS.

Raises:

Type Description
ValueError

If a shape specification is invalid (bad type, insufficient points, or unsupported geometry).

Source code in src/dnt/label/labeler.py
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def draw_shapes(
    self,
    draw_file: str,
    output_file: str | None,
    shapes: list[dict] | dict,
    base_df: pd.DataFrame | None = None,
) -> pd.DataFrame:
    """Add shapes to a draw file in DRAW_COLUMNS format.

    Parameters
    ----------
    draw_file : str
        Path to a draw CSV file. Used for reading existing data and as the
        default write target.
    output_file : str, optional
        Path to write the combined result. If None, writes to *draw_file*.
    shapes : list[dict] | dict
        One or more shape specifications. Each dict may contain:

        - ``type`` - ``"line"``, ``"polyline"``, ``"circle"``,
          ``"rectangle"``, or ``"polygon"``
        - ``geometry`` - coordinate pairs, a Shapely geometry, or a WKT string
        - ``color`` - BGR tuple, e.g. ``(0, 255, 0)`` *(optional)*
        - ``fill`` - whether to fill the shape *(optional)*
        - ``alpha`` - overlay strength 0.0-1.0; aliases: ``transparent``,
          ``transparant`` *(optional)*
        - ``size`` - font size or radius *(optional)*
        - ``thick`` - line thickness *(optional)*
        - ``desc`` - text description *(optional)*
    base_df : pd.DataFrame, optional
        Existing draw DataFrame to append to. If None and *draw_file*
        exists, that file is loaded instead.

    Returns
    -------
    pd.DataFrame
        Combined DataFrame with DRAW_COLUMNS.

    Raises
    ------
    ValueError
        If a shape specification is invalid (bad type, insufficient points,
        or unsupported geometry).

    """
    if isinstance(shapes, dict):
        shapes = [shapes]

    if base_df is not None:
        base_df = self._ensure_draw_columns(base_df.copy())
    elif os.path.exists(draw_file):
        base_df = pd.read_csv(
            draw_file,
            dtype={"frame": int, "type": str, "size": float, "desc": str, "thick": int},
            converters={"coords": lambda x: list(literal_eval(x)), "color": lambda x: literal_eval(x)},
        )
        base_df = self._ensure_draw_columns(base_df)
    else:
        base_df = pd.DataFrame(columns=DRAW_COLUMNS)

    def _parse_geom(geom: object) -> object:
        if isinstance(geom, str):
            try:
                from shapely import wkt
            except ImportError as exc:
                raise ValueError("WKT geometry requires shapely to be installed.") from exc
            return wkt.loads(geom)
        return geom

    def _as_pairs(geom: object) -> list[tuple[float, float]]:
        if hasattr(geom, "coords"):
            return [(float(x), float(y)) for x, y in geom.coords]
        if isinstance(geom, (list, tuple, np.ndarray)):
            vals = list(geom)
            if len(vals) == 2 and all(isinstance(v, (int, float, np.integer, np.floating)) for v in vals):
                return [(float(vals[0]), float(vals[1]))]
            if len(vals) == 4 and all(isinstance(v, (int, float, np.integer, np.floating)) for v in vals):
                return [(float(vals[0]), float(vals[1])), (float(vals[2]), float(vals[3]))]
            if (
                len(vals) >= 2
                and len(vals) % 2 == 0
                and all(isinstance(v, (int, float, np.integer, np.floating)) for v in vals)
            ):
                return [(float(vals[i]), float(vals[i + 1])) for i in range(0, len(vals), 2)]
            pairs: list[tuple[float, float]] = []
            for p in vals:
                if isinstance(p, (list, tuple, np.ndarray)) and len(p) >= 2:
                    pairs.append((float(p[0]), float(p[1])))
                else:
                    raise ValueError(f"Unsupported geometry point format: {p!r}")
            return pairs
        raise ValueError(f"Unsupported geometry coordinates: {type(geom)!r}")

    default_frames = sorted(base_df["frame"].astype(int).unique().tolist()) if len(base_df) > 0 else [0]

    if not shapes:
        target_file = output_file or draw_file
        if target_file:
            base_df.to_csv(target_file, index=False)
        return base_df

    rows: list[list[object]] = []
    for idx, shape in enumerate(shapes):
        if isinstance(shape, dict):
            shape_type = str(shape.get("type", "")).lower().strip()
            geom = _parse_geom(shape.get("geometry"))
            color = self._normalize_color(shape.get("color"), _bright_color(idx))
            fill = bool(shape.get("fill", False))
            alpha = float(shape.get("alpha", shape.get("transparent", shape.get("transparant", 0.0))))
            size = float(shape.get("size", 4.0))
            thick = int(shape.get("thick", 2))
            desc = str(shape.get("desc", ""))
        else:
            geom = _parse_geom(shape)
            shape_type = ""
            color = _bright_color(idx)
            fill = False
            alpha = 0.0
            size = 4.0
            thick = 2
            desc = ""

        alpha = min(max(alpha, 0.0), 1.0)
        target_frames = default_frames

        if not shape_type:
            if hasattr(geom, "geom_type"):
                geom_type = str(geom.geom_type).lower()
                if geom_type in {"linestring", "linearring"}:
                    shape_type = "polyline"
                elif geom_type == "polygon":
                    shape_type = "polygon"
                elif geom_type == "point":
                    shape_type = "circle"
            elif isinstance(geom, (list, tuple)) and len(geom) == 4:
                shape_type = "rectangle"

        if shape_type == "line":
            coords = _as_pairs(geom)
            if len(coords) != 2:
                raise ValueError("line requires exactly 2 points.")
            elem_type = ElementType.LINE.value
        elif shape_type in {"polyline", "polylines"}:
            coords = _as_pairs(geom)
            if len(coords) < 2:
                raise ValueError("polyline requires at least 2 points.")
            elem_type = ElementType.POLYLINES.value
        elif shape_type == "circle":
            if hasattr(geom, "geom_type") and str(geom.geom_type).lower() == "point":
                coords = [(float(geom.x), float(geom.y))]
            else:
                pts = _as_pairs(geom)
                if len(pts) != 1:
                    raise ValueError("circle requires a center point.")
                coords = [pts[0]]
            elem_type = ElementType.CIRCLE.value
        elif shape_type in {"rectangle", "rect", "box"}:
            if hasattr(geom, "bounds"):
                minx, miny, maxx, maxy = geom.bounds
                coords = [(float(minx), float(miny)), (float(maxx), float(maxy))]
            else:
                pts = _as_pairs(geom)
                if len(pts) != 2:
                    raise ValueError("rectangle requires 2 corner points.")
                coords = [pts[0], pts[1]]
            elem_type = ElementType.BOX.value
        elif shape_type == "polygon":
            if hasattr(geom, "geom_type") and str(geom.geom_type).lower() == "polygon":
                coords = [(float(x), float(y)) for x, y in geom.exterior.coords]
            else:
                coords = _as_pairs(geom)
            if len(coords) < 3:
                raise ValueError("polygon requires at least 3 points.")
            if coords[0] != coords[-1]:
                coords = [*coords, coords[0]]
            elem_type = ElementType.POLYGON.value
        else:
            raise ValueError(f"Unsupported shape type: {shape_type!r}")

        for frame in target_frames:
            rows.append([frame, elem_type, coords, color, size, thick, desc, fill, alpha])

    shape_df = pd.DataFrame(rows, columns=DRAW_COLUMNS)
    out_df = pd.concat([base_df, shape_df], ignore_index=True)

    out_df.sort_values(by="frame", inplace=True)
    target_file = output_file or draw_file
    if target_file:
        out_df.to_csv(target_file, index=False)

    return out_df

draw

draw(
    input_video: str,
    output_video: str,
    draws: DataFrame | None = None,
    draw_file: str | None = None,
    start_frame: int | None = None,
    end_frame: int | None = None,
    video_index: int | None = None,
    video_tot: int | None = None,
    verbose: bool = True,
)

Draw labels on video.

Parameters:

Name Type Description Default
input_video str

Path to raw video file.

required
output_video str

Path to output labeled video file.

required
draws DataFrame

A DataFrame containing labeling information. If None, reads from draw_file.

None
draw_file str

A txt/csv file with header: ['frame','type','coords','color','size','thick','desc','fill','alpha']

None
start_frame int

Starting frame number. If None, defaults to 0.

None
end_frame int

Ending frame number. If None, defaults to last frame.

None
video_index int

Video index for batch processing display.

None
video_tot int

Total video count for batch processing display.

None
verbose bool

Whether to show progress. Default is True.

True

Raises:

Type Description
OSError

If the input video cannot be opened.

RuntimeError

If FFmpeg fails (when using ffmpeg or chrome_safe method).

Source code in src/dnt/label/labeler.py
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
def draw(
    self,
    input_video: str,
    output_video: str,
    draws: pd.DataFrame | None = None,
    draw_file: str | None = None,
    start_frame: int | None = None,
    end_frame: int | None = None,
    video_index: int | None = None,
    video_tot: int | None = None,
    verbose: bool = True,
):
    """Draw labels on video.

    Parameters
    ----------
    input_video : str
        Path to raw video file.
    output_video : str
        Path to output labeled video file.
    draws : pd.DataFrame, optional
        A DataFrame containing labeling information. If None, reads from draw_file.
    draw_file : str, optional
        A txt/csv file with header:
        ['frame','type','coords','color','size','thick','desc','fill','alpha']
    start_frame : int, optional
        Starting frame number. If None, defaults to 0.
    end_frame : int, optional
        Ending frame number. If None, defaults to last frame.
    video_index : int, optional
        Video index for batch processing display.
    video_tot : int, optional
        Total video count for batch processing display.
    verbose : bool, optional
        Whether to show progress. Default is True.

    Raises
    ------
    OSError
        If the input video cannot be opened.
    RuntimeError
        If FFmpeg fails (when using ffmpeg or chrome_safe method).

    """
    if draws is not None:
        data = draws
    else:
        data = pd.read_csv(
            draw_file,
            dtype={"frame": int, "type": str, "size": float, "desc": str, "thick": int},
            converters={"coords": lambda x: list(literal_eval(x)), "color": lambda x: literal_eval(x)},
        )
    data = self._ensure_draw_columns(data)

    output_dir = os.path.dirname(output_video)
    if output_dir:
        os.makedirs(output_dir, exist_ok=True)

    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")

    if start_frame is None:
        start_frame = 0
    if end_frame is None:
        end_frame = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1

    tot_frames = end_frame - start_frame + 1
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    frame_to_elements = {k: g for k, g in data.groupby("frame", sort=False)}
    use_ffmpeg = self.method in {"ffmpeg", "chrome_safe"}
    process = None
    writer = None

    if self.method == "ffmpeg":
        # FFmpeg command to write H.265 encoded video
        ffmpeg_cmd = [
            "ffmpeg",
            "-y",  # Overwrite output file if it exists
            "-f",
            "rawvideo",
            "-vcodec",
            "rawvideo",
            "-pix_fmt",
            self.pix_fmt,
            "-s",
            f"{width}x{height}",
            "-r",
            str(fps),
            "-i",
            "-",  # Read input from stdin
            "-c:v",
            self.encoder,  # H.265 codec
            "-preset",
            self.preset,  # Adjust preset as needed (ultrafast, fast, medium, slow, etc.)
            "-crf",
            str(self.crf),  # Constant Rate Factor (higher = more compression, lower = better quality)
            output_video,
        ]

        # Start FFmpeg process
        process = subprocess.Popen(
            ffmpeg_cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
        )
    elif self.method == "chrome_safe":
        # FFmpeg command for browser-safe H.264 output.
        ffmpeg_cmd = [
            "ffmpeg",
            "-y",  # Overwrite output file if it exists
            "-f",
            "rawvideo",
            "-vcodec",
            "rawvideo",
            "-pix_fmt",
            self.pix_fmt,
            "-s",
            f"{width}x{height}",
            "-r",
            str(fps),
            "-i",
            "-",  # Read input from stdin
            "-c:v",
            "libx264",  # H.264 codec
            "-profile:v",
            "high",
            "-level",
            "4.0",
            "-preset",
            "medium",
            "-crf",
            "23",
            "-pix_fmt",
            "yuv420p",
            "-movflags",
            "+faststart",
            "-an",
            output_video,
        ]

        # Start FFmpeg process
        process = subprocess.Popen(
            ffmpeg_cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
        )
    else:
        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        writer = cv2.VideoWriter(output_video, fourcc, fps, (width, height))

    if verbose:
        pbar = tqdm(total=tot_frames, unit=" frames")
        if self.compress_message:
            pbar.set_description_str("Labeling")
        else:
            if video_index and video_tot:
                pbar.set_description_str(f"Labeling {video_index} of {video_tot}")
            else:
                pbar.set_description_str(f"Labeling {input_video} ")

    cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
    while cap.isOpened():
        pos_frame = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
        ret, frame = cap.read()
        if (not ret) or (pos_frame > end_frame):
            break

        elements = frame_to_elements.get(pos_frame)
        if elements is None:
            if use_ffmpeg:
                try:
                    process.stdin.write(frame.tobytes())
                except BrokenPipeError as exc:
                    ffmpeg_error = process.stderr.read().decode("utf-8", errors="replace") if process.stderr else ""
                    raise RuntimeError(
                        f"FFmpeg pipe closed early while writing frame {pos_frame}.\n{ffmpeg_error}"
                    ) from exc
            else:
                writer.write(frame)
            if verbose:
                pbar.update()
            continue

        for _, element in elements.iterrows():
            self._draw_element(
                frame,
                {
                    "type": element["type"],
                    "coords": element["coords"],
                    "color": element["color"],
                    "size": element["size"],
                    "thick": element["thick"],
                    "desc": element["desc"],
                    "fill": element["fill"],
                    "alpha": element["alpha"],
                },
            )

        if use_ffmpeg:
            try:
                process.stdin.write(frame.tobytes())
            except BrokenPipeError as exc:
                ffmpeg_error = process.stderr.read().decode("utf-8", errors="replace") if process.stderr else ""
                raise RuntimeError(
                    f"FFmpeg pipe closed early while writing frame {pos_frame}.\n{ffmpeg_error}"
                ) from exc
        else:
            writer.write(frame)

        if verbose:
            pbar.update()

    if verbose:
        pbar.close()
    # cv2.destroyAllWindows()
    cap.release()
    if use_ffmpeg:
        if process.stdin:
            process.stdin.close()
        return_code = process.wait()
        if return_code != 0:
            ffmpeg_error = process.stderr.read().decode("utf-8", errors="replace") if process.stderr else ""
            raise RuntimeError(f"FFmpeg failed with exit code {return_code}.\n{ffmpeg_error}")
    else:
        writer.release()

draw_track_clips

draw_track_clips(
    input_video: str,
    output_path: str,
    tracks: DataFrame | None = None,
    track_file: str | None = None,
    method: TrackClipMethod | str = TrackClipMethod.ALL,
    random_number: int = 10,
    track_ids: list | None = None,
    start_frame_offset: int = 0,
    end_frame_offset: int = 0,
    tail_length: int = 0,
    label_prefix: bool = False,
    label_class: bool = False,
    shapes: list[dict] | None = None,
    color: tuple[int, int, int] | str | None = None,
    fill: bool = False,
    alpha: float = 0.0,
    size: int = 1,
    thick: int = 1,
    tail_size: int | None = None,
    video_index: int | None = None,
    video_tot: int | None = None,
    verbose: bool = True,
)

Draw track clips from video.

Parameters:

Name Type Description Default
input_video str

The raw video file.

required
output_path str

The folder for outputting track clips.

required
tracks DataFrame

The dataframe of tracks. If None, reads from track_file.

None
track_file str

The track file if tracks is None.

None
method TrackClipMethod | str

'all' (default) - all tracks 'random' - random select tracks 'specify' - specify track ids

ALL
random_number int

The number of track ids if method == 'random'. Default is 10.

10
track_ids list

The list of track ids if method == 'specify'.

None
start_frame_offset int

The offset of start frame. Default is 0.

0
end_frame_offset int

The offset of end frame. Default is 0.

0
tail_length int

The tail length. Default is 0. Use -1 to draw full history since the first frame of each track.

0
label_prefix bool

If True, add the video file name as the prefix in output file names. Default is False.

False
size int

Font size. Default is 1.

1
thick int

Line thickness. Default is 1.

1
tail_size int

Radius of tail dots. If None, an auto-scaled visible radius is used.

None
label_class bool

Whether to include class in track labels. Default is False.

False
shapes list[dict]

Shape overlays to add before rendering. See draw_shapes for the expected dict format.

None
color tuple[int, int, int] | str

Clip color control: - None: default per-track color scheme - "random": random BGR color per clip - (b, g, r): fixed BGR color for all clips

None
fill bool

Whether to fill generated track boxes. Default is False.

False
alpha float

Overlay strength for fill in [0, 1]. Default is 0.0.

0.0
video_index int

Video index for batch processing display.

None
video_tot int

Total video count for batch processing display.

None
verbose bool

If True, show progress bar. Default is True.

True

Raises:

Type Description
OSError

If the input video cannot be opened.

Source code in src/dnt/label/labeler.py
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def draw_track_clips(
    self,
    input_video: str,
    output_path: str,
    tracks: pd.DataFrame | None = None,
    track_file: str | None = None,
    method: TrackClipMethod | str = TrackClipMethod.ALL,
    random_number: int = 10,
    track_ids: list | None = None,
    start_frame_offset: int = 0,
    end_frame_offset: int = 0,
    tail_length: int = 0,
    label_prefix: bool = False,
    label_class: bool = False,
    shapes: list[dict] | None = None,
    color: tuple[int, int, int] | str | None = None,
    fill: bool = False,
    alpha: float = 0.0,
    size: int = 1,
    thick: int = 1,
    tail_size: int | None = None,
    video_index: int | None = None,
    video_tot: int | None = None,
    verbose: bool = True,
):
    """Draw track clips from video.

    Parameters
    ----------
    input_video : str
        The raw video file.
    output_path : str
        The folder for outputting track clips.
    tracks : pd.DataFrame, optional
        The dataframe of tracks. If None, reads from track_file.
    track_file : str, optional
        The track file if tracks is None.
    method : TrackClipMethod | str
        'all' (default) - all tracks
        'random' - random select tracks
        'specify' - specify track ids
    random_number : int
        The number of track ids if method == 'random'. Default is 10.
    track_ids : list, optional
        The list of track ids if method == 'specify'.
    start_frame_offset : int
        The offset of start frame. Default is 0.
    end_frame_offset : int
        The offset of end frame. Default is 0.
    tail_length : int
        The tail length. Default is 0.
        Use `-1` to draw full history since the first frame of each track.
    label_prefix : bool
        If True, add the video file name as the prefix in output file names. Default is False.
    size : int
        Font size. Default is 1.
    thick : int
        Line thickness. Default is 1.
    tail_size : int, optional
        Radius of tail dots. If None, an auto-scaled visible radius is used.
    label_class : bool
        Whether to include class in track labels. Default is False.
    shapes : list[dict], optional
        Shape overlays to add before rendering. See ``draw_shapes`` for
        the expected dict format.
    color : tuple[int, int, int] | str, optional
        Clip color control:
        - None: default per-track color scheme
        - "random": random BGR color per clip
        - (b, g, r): fixed BGR color for all clips
    fill : bool
        Whether to fill generated track boxes. Default is False.
    alpha : float
        Overlay strength for fill in [0, 1]. Default is 0.0.
    video_index : int, optional
        Video index for batch processing display.
    video_tot : int, optional
        Total video count for batch processing display.
    verbose : bool
        If True, show progress bar. Default is True.

    Raises
    ------
    OSError
        If the input video cannot be opened.

    """
    if tracks is None:
        tracks = pd.read_csv(
            track_file,
            header=None,
            dtype={0: int, 1: int, 2: int, 3: int, 4: int, 5: int, 6: float, 7: int, 8: int, 9: int},
        )
    tracks.columns = TRACK_COLUMNS

    if isinstance(method, TrackClipMethod):
        track_clip_method = method.value
    else:
        track_clip_method = str(method).lower().strip()
        valid_methods = {m.value for m in TrackClipMethod}
        if track_clip_method not in valid_methods:
            raise ValueError(f"Invalid method={method!r}. Choose one of {sorted(valid_methods)}.")

    if track_clip_method == TrackClipMethod.RANDOM.value:
        track_ids = tracks["track"].unique().tolist()
        if random_number <= 0:
            random_number = 10
        random_number = min(random_number, len(track_ids))
        track_ids = random.sample(track_ids, random_number)
    elif track_clip_method == TrackClipMethod.SPECIFY.value:
        if (track_ids is None) or (len(track_ids) == 0):
            print("No tracks are provided!")
            return pd.DataFrame()
    else:
        track_ids = tracks["track"].unique().tolist()

    # pbar = tqdm(total=len(track_ids), desc='Labeling tracks ', unit='clips')
    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    cap.release()

    for id in track_ids:
        selected_tracks = tracks[tracks["track"] == id].copy()
        start_frame = max(selected_tracks["frame"].min() - start_frame_offset, 0)
        end_frame = min(
            selected_tracks["frame"].max() + end_frame_offset,
            frame_count - 1,
        )
        if label_prefix:
            out_video = os.path.join(
                output_path, os.path.splitext(os.path.basename(input_video))[0] + "_" + str(id) + ".mp4"
            )
        else:
            out_video = os.path.join(output_path, str(id) + ".mp4")

        if isinstance(color, str):
            color_mode = color.lower().strip()
            if color_mode == "random":
                clip_color = random.choice(BRIGHT_COLORS_BGR)
            elif color_mode in {"none", "default"}:
                clip_color = None
            else:
                raise ValueError("color must be None, 'random', or a BGR tuple like (0, 255, 0).")
        elif color is None:
            clip_color = None
        else:
            clip_color = self._normalize_color(color)

        self.draw_tracks(
            input_video=input_video,
            output_video=out_video,
            tracks=selected_tracks,
            color=clip_color,
            start_frame=start_frame,
            end_frame=end_frame,
            verbose=verbose,
            tail_length=tail_length,
            thick=thick,
            size=size,
            tail_size=tail_size,
            label_class=label_class,
            shapes=shapes,
            fill=fill,
            alpha=alpha,
            video_index=video_index,
            video_tot=video_tot,
        )

draw_tracks

draw_tracks(
    input_video: str,
    output_video: str,
    tracks: DataFrame | None = None,
    track_file: str | None = None,
    label_file: str | None = None,
    color: tuple[int, int, int] | None = None,
    thick: int = 2,
    size: int = 1,
    tail_length: int = 0,
    tail_size: int | None = None,
    label_class: bool = False,
    shapes: list[dict] | None = None,
    fill: bool = False,
    alpha: float = 0.0,
    start_frame: int | None = None,
    end_frame: int | None = None,
    video_index: int | None = None,
    video_tot: int | None = None,
    verbose: bool = True,
)

Draw tracks on video.

Parameters:

Name Type Description Default
input_video str

Path to raw video file.

required
output_video str

Path to output labeled video file.

required
tracks DataFrame

DataFrame containing track data. If None, reads from track_file.

None
track_file str

Path to track file if tracks is None.

None
label_file str

Path to save label output.

None
color tuple[int, int, int]

Custom color for drawing. If None, uses default colormap.

None
tail_length int

Length of tail to display. Default is 0. Use -1 to draw full history since the first frame of each track.

0
tail_size int

Radius of tail dots. If None, an auto-scaled visible radius is used.

None
thick int

Line thickness. Default is 2.

2
size int

Font size. Default is 1.

1
label_class bool

Whether to display class names. Default is False.

False
shapes list[dict]

Shape overlays to add before rendering. See draw_shapes for the expected dict format.

None
fill bool

Whether to fill generated track boxes. Default is False.

False
alpha float

Overlay strength for fill in [0, 1]. Default is 0.0.

0.0
start_frame int

Starting frame. If None, defaults to 0.

None
end_frame int

Ending frame. If None, defaults to last frame.

None
video_index int

Video index for batch processing display.

None
video_tot int

Total video count for batch processing display.

None
verbose bool

Whether to show progress. Default is True.

True

Returns:

Type Description
DataFrame

DataFrame containing generated draw elements (with DRAW_COLUMNS).

Raises:

Type Description
OSError

If the input video cannot be opened.

Source code in src/dnt/label/labeler.py
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def draw_tracks(
    self,
    input_video: str,
    output_video: str,
    tracks: pd.DataFrame | None = None,
    track_file: str | None = None,
    label_file: str | None = None,
    color: tuple[int, int, int] | None = None,
    thick: int = 2,
    size: int = 1,
    tail_length: int = 0,
    tail_size: int | None = None,
    label_class: bool = False,
    shapes: list[dict] | None = None,
    fill: bool = False,
    alpha: float = 0.0,
    start_frame: int | None = None,
    end_frame: int | None = None,
    video_index: int | None = None,
    video_tot: int | None = None,
    verbose: bool = True,
):
    """Draw tracks on video.

    Parameters
    ----------
    input_video : str
        Path to raw video file.
    output_video : str
        Path to output labeled video file.
    tracks : pd.DataFrame, optional
        DataFrame containing track data. If None, reads from track_file.
    track_file : str, optional
        Path to track file if tracks is None.
    label_file : str, optional
        Path to save label output.
    color : tuple[int, int, int], optional
        Custom color for drawing. If None, uses default colormap.
    tail_length : int
        Length of tail to display. Default is 0.
        Use `-1` to draw full history since the first frame of each track.
    tail_size : int, optional
        Radius of tail dots. If None, an auto-scaled visible radius is used.
    thick : int
        Line thickness. Default is 2.
    size : int
        Font size. Default is 1.
    label_class : bool
        Whether to display class names. Default is False.
    shapes : list[dict], optional
        Shape overlays to add before rendering. See ``draw_shapes`` for
        the expected dict format.
    fill : bool
        Whether to fill generated track boxes. Default is False.
    alpha : float
        Overlay strength for fill in [0, 1]. Default is 0.0.
    start_frame : int, optional
        Starting frame. If None, defaults to 0.
    end_frame : int, optional
        Ending frame. If None, defaults to last frame.
    video_index : int, optional
        Video index for batch processing display.
    video_tot : int, optional
        Total video count for batch processing display.
    verbose : bool
        Whether to show progress. Default is True.

    Returns
    -------
    pd.DataFrame
        DataFrame containing generated draw elements (with DRAW_COLUMNS).

    Raises
    ------
    OSError
        If the input video cannot be opened.

    """
    if tracks is None:
        tracks = pd.read_csv(
            track_file,
            header=None,
            dtype={0: int, 1: int, 2: int, 3: int, 4: int, 5: int, 6: float, 7: int, 8: int, 9: int},
        )
    tracks.columns = TRACK_COLUMNS

    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")

    if start_frame is None:
        start_frame = 0
    if end_frame is None:
        end_frame = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1

    selected_tracks = tracks.loc[(tracks["frame"] >= start_frame) & (tracks["frame"] <= end_frame)].copy()

    pbar_desc = ""
    if self.compress_message:
        pbar_desc = "Generating labels"
    else:
        if video_index and video_tot:
            pbar_desc = f"Generating labels {video_index} of {video_tot}"
        else:
            pbar_desc = f"Generating labels {input_video} "

    names = load_classes()
    pbar = tqdm(total=len(selected_tracks), unit=" frames", desc=pbar_desc, disable=not verbose)
    tail_radius = max(1, int((size) * 1)) if tail_size is None else max(1, int(tail_size))
    alpha = min(max(float(alpha), 0.0), 1.0)
    results = []
    for _, track in selected_tracks.iterrows():
        final_color = _bright_color(int(track["track"])) if color is None else color

        track_id = int(track["track"])
        cls_desc = names[int(track["cls"])] if label_class else ""
        desc = f"{track_id} {cls_desc}"
        results.append([
            track["frame"],
            ElementType.BBOX.value,
            [(track["x"], track["y"]), (track["x"] + track["w"], track["y"] + track["h"])],
            final_color,
            size,
            thick,
            desc,
            fill,
            alpha,
        ])
        if tail_length != 0:
            current_frame = int(track["frame"])
            if tail_length == -1:
                pre_boxes = tracks.loc[
                    (tracks["track"] == track["track"]) & (tracks["frame"] < current_frame)
                ].values.tolist()
            elif tail_length > 0:
                frames = [*range(current_frame - tail_length, current_frame)]
                pre_boxes = tracks.loc[
                    (tracks["frame"].isin(frames)) & (tracks["track"] == track["track"])
                ].values.tolist()
            else:
                pre_boxes = []

            if len(pre_boxes) > 0:
                for pre_box in pre_boxes:
                    xc = int(pre_box[2]) + int(pre_box[4] / 2)
                    yc = int(pre_box[3]) + int(pre_box[5] / 2)
                    results.append([
                        track["frame"],
                        ElementType.CIRCLE.value,
                        [(xc, yc)],
                        final_color,
                        tail_radius,
                        -1,
                        "",
                        fill,
                        alpha,
                    ])

        pbar.update()

    pbar.close()

    results.sort()
    results = list(results for results, _ in itertools.groupby(results))
    df = pd.DataFrame(results, columns=DRAW_COLUMNS)
    df = self._apply_shapes_with_draw_shapes(df, shapes)
    df.sort_values(by="frame", inplace=True)

    if output_video:
        self.draw(
            input_video=input_video,
            output_video=output_video,
            draws=df,
            start_frame=start_frame,
            end_frame=end_frame,
            video_index=video_index,
            video_tot=video_tot,
            verbose=verbose,
        )

    if label_file:
        df.to_csv(label_file, index=False)

    return df

draw_dets

draw_dets(
    input_video: str,
    output_video: str,
    dets: DataFrame | None = None,
    det_file: str | None = None,
    label_file: str | None = None,
    color: tuple[int, int, int] | None = None,
    thick: int = 2,
    size: int = 1,
    label_score: bool = True,
    shapes: list[dict] | None = None,
    fill: bool = False,
    alpha: float = 0.0,
    start_frame: int | None = None,
    end_frame: int | None = None,
    video_index: int | None = None,
    video_tot: int | None = None,
)

Draw detections on video.

Parameters:

Name Type Description Default
input_video str

Path to raw video file.

required
output_video str

Path to output labeled video file.

required
dets DataFrame

DataFrame containing detection data. If None, reads from det_file.

None
det_file str

Path to detection file if dets is None.

None
label_file str

Path to save label output.

None
color tuple[int, int, int]

Custom color for drawing. If None, uses default colormap.

None
thick int

Line thickness. Default is 2.

2
size int

Font size. Default is 1.

1
label_score bool

Whether to display detection scores. Default is True.

True
shapes list[dict]

Shape overlays to add before rendering. See draw_shapes for the expected dict format.

None
fill bool

Whether to fill generated detection boxes. Default is False.

False
alpha float

Overlay strength for fill in [0, 1]. Default is 0.0.

0.0
start_frame int

Starting frame. If None, defaults to 0.

None
end_frame int

Ending frame. If None, defaults to last frame.

None
video_index int

Video index for batch processing display.

None
video_tot int

Total video count for batch processing display.

None

Returns:

Type Description
DataFrame

DataFrame containing generated draw elements (with DRAW_COLUMNS).

Raises:

Type Description
OSError

If the input video cannot be opened.

Source code in src/dnt/label/labeler.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
def draw_dets(
    self,
    input_video: str,
    output_video: str,
    dets: pd.DataFrame | None = None,
    det_file: str | None = None,
    label_file: str | None = None,
    color: tuple[int, int, int] | None = None,
    thick: int = 2,
    size: int = 1,
    label_score: bool = True,
    shapes: list[dict] | None = None,
    fill: bool = False,
    alpha: float = 0.0,
    start_frame: int | None = None,
    end_frame: int | None = None,
    video_index: int | None = None,
    video_tot: int | None = None,
):
    """Draw detections on video.

    Parameters
    ----------
    input_video : str
        Path to raw video file.
    output_video : str
        Path to output labeled video file.
    dets : pd.DataFrame, optional
        DataFrame containing detection data. If None, reads from det_file.
    det_file : str, optional
        Path to detection file if dets is None.
    label_file : str, optional
        Path to save label output.
    color : tuple[int, int, int], optional
        Custom color for drawing. If None, uses default colormap.
    thick : int
        Line thickness. Default is 2.
    size : int
        Font size. Default is 1.
    label_score : bool
        Whether to display detection scores. Default is True.
    shapes : list[dict], optional
        Shape overlays to add before rendering. See ``draw_shapes`` for
        the expected dict format.
    fill : bool
        Whether to fill generated detection boxes. Default is False.
    alpha : float
        Overlay strength for fill in [0, 1]. Default is 0.0.
    start_frame : int, optional
        Starting frame. If None, defaults to 0.
    end_frame : int, optional
        Ending frame. If None, defaults to last frame.
    video_index : int, optional
        Video index for batch processing display.
    video_tot : int, optional
        Total video count for batch processing display.

    Returns
    -------
    pd.DataFrame
        DataFrame containing generated draw elements (with DRAW_COLUMNS).

    Raises
    ------
    OSError
        If the input video cannot be opened.

    """
    if dets is None:
        dets = pd.read_csv(det_file, header=None)

    names = load_classes()

    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")

    if start_frame is None:
        start_frame = 0
    if end_frame is None:
        end_frame = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1

    selected_dets = dets.loc[(dets[0] >= start_frame) & (dets[0] <= end_frame)].copy()

    pbar = tqdm(total=len(selected_dets), unit=" dets")
    if self.compress_message:
        pbar.set_description_str("Generating labels")
    else:
        if video_index and video_tot:
            pbar.set_description_str(f"Generating labels {video_index} of {video_tot}")
        else:
            pbar.set_description_str(f"Generating labels {input_video} ")

    results = []
    alpha = min(max(float(alpha), 0.0), 1.0)
    for _, det in selected_dets.iterrows():
        final_color = _bright_color(int(det[7])) if color is None else color

        desc = f"{names[int(det[7])]} {det[6]:.1f}" if label_score else str(int(det[7]))

        results.append([
            det[0],
            ElementType.BBOX.value,
            [(det[2], det[3]), (det[2] + det[4], det[3] + det[5])],
            final_color,
            size,
            thick,
            desc,
            fill,
            alpha,
        ])
        pbar.update()

    results.sort()
    results = list(results for results, _ in itertools.groupby(results))
    df = pd.DataFrame(results, columns=DRAW_COLUMNS)
    df = self._apply_shapes_with_draw_shapes(df, shapes)
    df.sort_values(by="frame", inplace=True)

    if output_video:
        self.draw(
            input_video=input_video,
            output_video=output_video,
            draws=df,
            start_frame=start_frame,
            end_frame=end_frame,
            video_index=video_index,
            video_tot=video_tot,
        )

    if label_file:
        df.to_csv(label_file, index=False)

    return df

clip

clip(
    input_video: str,
    output_video: str,
    start_frame: int | None = None,
    end_frame: int | None = None,
    method: LabelMethod | str | None = None,
)

Extract a clip from the video.

Parameters:

Name Type Description Default
input_video str

Path to input video file.

required
output_video str

Path to output clipped video file.

required
start_frame int

Starting frame. If None, defaults to 0.

None
end_frame int

Ending frame. If None, defaults to last frame.

None
method LabelMethod | str

Output backend for clipping. If None, uses the instance method. Supported: 'opencv', 'ffmpeg', 'chrome_safe'.

None

Raises:

Type Description
OSError

If the input video cannot be opened.

ValueError

If frame range is invalid or video has no frames.

RuntimeError

If FFmpeg fails (when using ffmpeg or chrome_safe method).

Source code in src/dnt/label/labeler.py
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
def clip(
    self,
    input_video: str,
    output_video: str,
    start_frame: int | None = None,
    end_frame: int | None = None,
    method: LabelMethod | str | None = None,
):
    """Extract a clip from the video.

    Parameters
    ----------
    input_video : str
        Path to input video file.
    output_video : str
        Path to output clipped video file.
    start_frame : int, optional
        Starting frame. If None, defaults to 0.
    end_frame : int, optional
        Ending frame. If None, defaults to last frame.
    method : LabelMethod | str, optional
        Output backend for clipping. If None, uses the instance method.
        Supported: 'opencv', 'ffmpeg', 'chrome_safe'.

    Raises
    ------
    OSError
        If the input video cannot be opened.
    ValueError
        If frame range is invalid or video has no frames.
    RuntimeError
        If FFmpeg fails (when using ffmpeg or chrome_safe method).

    """
    if method is None:
        clip_method = self.method
    elif isinstance(method, LabelMethod):
        clip_method = method.value
    else:
        clip_method = str(method).lower().strip()
        valid_methods = {m.value for m in LabelMethod}
        if clip_method not in valid_methods:
            raise ValueError(f"Invalid method={method!r}. Choose one of {sorted(valid_methods)}.")

    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")

    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if total_frames <= 0:
        cap.release()
        raise ValueError(f"No frames available in video: {input_video}")

    fps = cap.get(cv2.CAP_PROP_FPS)
    if fps <= 0:
        cap.release()
        raise ValueError(f"Invalid FPS ({fps}) for video: {input_video}")

    if start_frame is None:
        start_frame = 0

    if end_frame is None:
        end_frame = total_frames - 1

    start_frame = max(0, min(int(start_frame), total_frames - 1))
    end_frame = max(0, min(int(end_frame), total_frames - 1))
    if end_frame < start_frame:
        end_frame = start_frame

    tot_frames = end_frame - start_frame + 1
    fps = int(fps)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    output_dir = os.path.dirname(output_video)
    if output_dir:
        os.makedirs(output_dir, exist_ok=True)

    # Keep clip output bitrate aligned with source when possible.
    source_bitrate_bps: int | None = None
    try:
        probe = subprocess.run(
            [
                "ffprobe",
                "-v",
                "error",
                "-select_streams",
                "v:0",
                "-show_entries",
                "stream=bit_rate",
                "-of",
                "default=nokey=1:noprint_wrappers=1",
                input_video,
            ],
            check=False,
            capture_output=True,
            text=True,
        )
        if probe.returncode == 0:
            value = probe.stdout.strip()
            if value.isdigit():
                source_bitrate_bps = int(value)
    except FileNotFoundError:
        source_bitrate_bps = None

    if source_bitrate_bps is None:
        cap_bitrate_kbps = cap.get(cv2.CAP_PROP_BITRATE)
        if cap_bitrate_kbps and cap_bitrate_kbps > 0:
            source_bitrate_bps = int(cap_bitrate_kbps * 1000)

    bitrate_args: list[str] = []
    if source_bitrate_bps and source_bitrate_bps > 0:
        bitrate_args = [
            "-b:v",
            str(source_bitrate_bps),
            "-minrate",
            str(source_bitrate_bps),
            "-maxrate",
            str(source_bitrate_bps),
            "-bufsize",
            str(source_bitrate_bps * 2),
        ]

    use_ffmpeg = clip_method in {LabelMethod.FFMPEG.value, LabelMethod.CHROME_SAFE.value}
    process = None
    writer = None

    if clip_method == LabelMethod.FFMPEG.value:
        rate_control_args = bitrate_args if bitrate_args else ["-crf", str(self.crf)]
        ffmpeg_cmd = [
            "ffmpeg",
            "-y",
            "-f",
            "rawvideo",
            "-vcodec",
            "rawvideo",
            "-pix_fmt",
            self.pix_fmt,
            "-s",
            f"{width}x{height}",
            "-r",
            str(fps),
            "-i",
            "-",
            "-c:v",
            self.encoder,
            "-preset",
            self.preset,
            *rate_control_args,
            output_video,
        ]
        process = subprocess.Popen(
            ffmpeg_cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
        )
    elif clip_method == LabelMethod.CHROME_SAFE.value:
        rate_control_args = bitrate_args if bitrate_args else ["-crf", "23"]
        ffmpeg_cmd = [
            "ffmpeg",
            "-y",
            "-f",
            "rawvideo",
            "-vcodec",
            "rawvideo",
            "-pix_fmt",
            self.pix_fmt,
            "-s",
            f"{width}x{height}",
            "-r",
            str(fps),
            "-i",
            "-",
            "-c:v",
            "libx264",
            "-profile:v",
            "high",
            "-level",
            "4.0",
            "-preset",
            "medium",
            *rate_control_args,
            "-pix_fmt",
            "yuv420p",
            "-movflags",
            "+faststart",
            "-an",
            output_video,
        ]
        process = subprocess.Popen(
            ffmpeg_cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
        )
    else:
        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        writer = cv2.VideoWriter(output_video, fourcc, fps, (width, height))

    pbar = tqdm(total=tot_frames, unit=" frames")
    if self.compress_message:
        pbar.set_description_str("Cutting")
    else:
        pbar.set_description_str(f"Cutting {input_video} ")

    cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
    while cap.isOpened():
        pos_frame = int(cap.get(cv2.CAP_PROP_POS_FRAMES))
        ret, frame = cap.read()
        if (not ret) or (pos_frame > end_frame):
            break

        if use_ffmpeg:
            try:
                process.stdin.write(frame.tobytes())
            except BrokenPipeError as exc:
                ffmpeg_error = process.stderr.read().decode("utf-8", errors="replace") if process.stderr else ""
                raise RuntimeError(
                    f"FFmpeg pipe closed early while clipping frame {pos_frame}.\n{ffmpeg_error}"
                ) from exc
        else:
            writer.write(frame)

        pbar.update()

    pbar.close()
    cap.release()
    if use_ffmpeg:
        if process.stdin:
            process.stdin.close()
        return_code = process.wait()
        if return_code != 0:
            ffmpeg_error = process.stderr.read().decode("utf-8", errors="replace") if process.stderr else ""
            raise RuntimeError(f"FFmpeg failed with exit code {return_code}.\n{ffmpeg_error}")
    else:
        writer.release()

clip_by_time

clip_by_time(
    input_video: str,
    output_video: str,
    start_sec: float = 0.0,
    clip_len_sec: float | None = None,
    method: LabelMethod | str | None = None,
)

Extract a clip by time range.

Parameters:

Name Type Description Default
input_video str

Path to input video file.

required
output_video str

Path to output clipped video file.

required
start_sec float

Starting second. Negative values are treated as 0.

0.0
clip_len_sec float

Clip length in seconds. If None, clip runs to end of video.

None
method LabelMethod | str

Output backend for clipping. If None, uses the instance method. Supported: 'opencv', 'ffmpeg', 'chrome_safe'.

None

Raises:

Type Description
OSError

If the input video cannot be opened.

ValueError

If the video has no frames, FPS is invalid, or clip_len_sec <= 0.

Source code in src/dnt/label/labeler.py
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
def clip_by_time(
    self,
    input_video: str,
    output_video: str,
    start_sec: float = 0.0,
    clip_len_sec: float | None = None,
    method: LabelMethod | str | None = None,
):
    """Extract a clip by time range.

    Parameters
    ----------
    input_video : str
        Path to input video file.
    output_video : str
        Path to output clipped video file.
    start_sec : float
        Starting second. Negative values are treated as 0.
    clip_len_sec : float, optional
        Clip length in seconds. If None, clip runs to end of video.
    method : LabelMethod | str, optional
        Output backend for clipping. If None, uses the instance method.
        Supported: 'opencv', 'ffmpeg', 'chrome_safe'.

    Raises
    ------
    OSError
        If the input video cannot be opened.
    ValueError
        If the video has no frames, FPS is invalid, or clip_len_sec <= 0.

    """
    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")

    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if total_frames <= 0:
        cap.release()
        raise ValueError(f"No frames available in video: {input_video}")

    fps = cap.get(cv2.CAP_PROP_FPS)
    if fps <= 0:
        cap.release()
        raise ValueError(f"Invalid FPS ({fps}) for video: {input_video}")

    start_frame = int(max(0.0, start_sec) * fps)
    if clip_len_sec is None:
        end_frame = total_frames - 1
    else:
        if clip_len_sec <= 0:
            cap.release()
            raise ValueError(f"clip_len_sec must be > 0, got {clip_len_sec}.")
        clip_len_frames = max(1, round(clip_len_sec * fps))
        end_frame = start_frame + clip_len_frames - 1

    cap.release()

    self.clip(
        input_video=input_video,
        output_video=output_video,
        start_frame=start_frame,
        end_frame=end_frame,
        method=method,
    )

export_frames staticmethod

export_frames(
    input_video: str,
    frames: list[int],
    output_path: str,
    prefix: str | None = None,
)

Extract specific frames from video.

Parameters:

Name Type Description Default
input_video str

Path to input video file.

required
frames list[int]

List of frame numbers to extract.

required
output_path str

Path to output directory for extracted frames.

required
prefix str

Prefix to add to output filenames. If None, no prefix is used.

None

Raises:

Type Description
OSError

If the input video cannot be opened.

Source code in src/dnt/label/labeler.py
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
@staticmethod
def export_frames(input_video: str, frames: list[int], output_path: str, prefix: str | None = None):
    """Extract specific frames from video.

    Parameters
    ----------
    input_video : str
        Path to input video file.
    frames : list[int]
        List of frame numbers to extract.
    output_path : str
        Path to output directory for extracted frames.
    prefix : str, optional
        Prefix to add to output filenames. If None, no prefix is used.

    Raises
    ------
    OSError
        If the input video cannot be opened.

    """
    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")

    pbar = tqdm(total=len(frames), unit=" frames")
    pbar.set_description_str("Extracting frame")

    for frame in frames:
        cap.set(cv2.CAP_PROP_POS_FRAMES, frame)
        ret, frame_read = cap.read()

        if prefix is None:
            frame_file = os.path.join(output_path, str(frame) + ".jpg")
        else:
            frame_file = os.path.join(output_path, prefix + "-" + str(frame) + ".jpg")

        if ret:
            cv2.imwrite(frame_file, frame_read)
        else:
            break

        pbar.update()

    pbar.close()
    cap.release()

    print(f"Writing frames to {output_path}")

export_track_frames staticmethod

export_track_frames(
    input_video: str,
    tracks: DataFrame,
    output_path: str,
    bbox: bool = True,
    prefix: str | None = None,
    thick: int = 2,
)

Extract frames for each track from video.

Parameters:

Name Type Description Default
input_video str

Path to input video file.

required
tracks DataFrame

DataFrame containing track data with TRACK_COLUMNS.

required
output_path str

Path to output directory for extracted frames.

required
bbox bool

Whether to draw bounding boxes. Default is True.

True
prefix str

Prefix to add to output filenames. If None, no prefix is used.

None
thick int

Line thickness for bounding boxes. Default is 2.

2

Raises:

Type Description
OSError

If the input video cannot be opened.

Exception

If tracks DataFrame has invalid format.

Source code in src/dnt/label/labeler.py
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
@staticmethod
def export_track_frames(
    input_video: str,
    tracks: pd.DataFrame,
    output_path: str,
    bbox: bool = True,
    prefix: str | None = None,
    thick: int = 2,
):
    """Extract frames for each track from video.

    Parameters
    ----------
    input_video : str
        Path to input video file.
    tracks : pd.DataFrame
        DataFrame containing track data with TRACK_COLUMNS.
    output_path : str
        Path to output directory for extracted frames.
    bbox : bool
        Whether to draw bounding boxes. Default is True.
    prefix : str, optional
        Prefix to add to output filenames. If None, no prefix is used.
    thick : int
        Line thickness for bounding boxes. Default is 2.

    Raises
    ------
    OSError
        If the input video cannot be opened.
    Exception
        If tracks DataFrame has invalid format.

    """
    if (tracks is None) or (len(tracks.columns) < 10):
        raise ValueError("Invalid tracks: DataFrame must have at least 10 columns.")
    tracks.columns = TRACK_COLUMNS
    ids = tracks["track"].unique()
    os.makedirs(output_path, exist_ok=True)

    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")

    pbar = tqdm(total=len(ids), unit=" frame")
    for id in ids:
        pbar.set_description_str("Extracting track: " + str(id))
        selected = tracks[tracks["track"] == id]
        if len(selected) > 0:
            for _, track in selected.iterrows():
                frame = track["frame"]
                cap.set(cv2.CAP_PROP_POS_FRAMES, frame)
                ret, img = cap.read()

                if ret:
                    if bbox:
                        x1 = track["x"]
                        y1 = track["y"]
                        x2 = track["x"] + track["w"]
                        y2 = track["y"] + track["h"]
                        final_color = _bright_color(int(id))
                        cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), final_color, thick)

                        if prefix is None:
                            frame_file = os.path.join(output_path, str(id) + "_" + str(frame) + ".jpg")
                        else:
                            frame_file = os.path.join(
                                output_path, prefix + "-" + str(id) + "_" + str(frame) + ".jpg"
                            )

                        cv2.imwrite(frame_file, img)
                else:
                    break

            pbar.update()

    pbar.close()
    cap.release()

    print(f"Writing frames to {output_path}")

time2frame staticmethod

time2frame(input_video: str, time: float)

Convert time in seconds to frame number.

Parameters:

Name Type Description Default
input_video str

Path to input video file.

required
time float

Time in seconds.

required

Returns:

Type Description
int

Frame number corresponding to the given time.

Raises:

Type Description
OSError

If the input video cannot be opened.

Source code in src/dnt/label/labeler.py
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
@staticmethod
def time2frame(input_video: str, time: float):
    """Convert time in seconds to frame number.

    Parameters
    ----------
    input_video : str
        Path to input video file.
    time : float
        Time in seconds.

    Returns
    -------
    int
        Frame number corresponding to the given time.

    Raises
    ------
    OSError
        If the input video cannot be opened.

    """
    cap = cv2.VideoCapture(input_video)
    if not cap.isOpened():
        raise OSError("Couldn't open webcam or video")

    video_fps = int(cap.get(cv2.CAP_PROP_FPS))  # original fps
    frame = int(video_fps * time)
    cap.release()
    return frame