Visualization Library¶
Modular visualization components for reviewing tracking and behavior analysis results.
Components include:
- Track + label overlay on video frames
- Interactive video playback
- Egocentric crop generation
- Interaction crop generation (pair-level)
- Global embedding colored scatter plots
- Timeline plots
visualization_library ¶
Visualization library for behavior datasets.
This library provides modular visualization components: - Data loading (tracks, labels, ground truth) - Overlay preparation and frame drawing - Video streaming with overlays - Interactive video playback - Egocentric crop generation
Example usage
from mosaic.behavior.visualization_library import playback playback.play_video(dataset, group="hex", sequence="hex_3", ...)
from mosaic.behavior.visualization_library.egocentric_crop import EgocentricCrop crop_feat = EgocentricCrop(params={"target_id": 0, "crop_size": (256, 256)}) dataset.run_feature(crop_feat, sequences=["hex_3"])
EgocentricCrop ¶
Generate egocentric (animal-centered) video crops.
Centers the view on a target individual (or all individuals if target_id=None), optionally rotating to align the animal's heading with the +x axis. Can output as video file or individual frame images.
Parameters¶
target_id : Any, optional ID of the individual to center on. If None, processes ALL individuals found in the tracks data, creating separate outputs for each. center_mode : str or int How to compute the center point: - "default": mean of all pose points poseX0..N/poseY0..N (pixel coords) - "pose0" or 0: use poseX0/poseY0 (typically head/nose) - int: use specific pose point index crop_size : tuple of (int, int) Output crop dimensions as (width, height) in pixels rotate_to_heading : bool If True, rotate crop so animal's heading aligns with +x axis heading_points : tuple of (int, int) (neck_idx, tail_idx) pose point indices for heading computation. Heading points FROM tail TO neck (direction animal is facing). margin_factor : float Extra margin for rotation (1.5 = 50% larger pre-crop before rotation) center_offset_px : float Pixel offset along heading direction from computed center (default 0). Positive shifts forward (toward head). Useful for centering on specific body parts, e.g. 35 for body center in bees. body_mask : bool If True, apply elliptical body mask to isolate the focal individual. body_mask_length_px : int Length (semi-major axis) of the body mask ellipse in pixels. body_mask_width_px : int Width (semi-minor axis) of the body mask ellipse in pixels. use_clahe : bool If True, apply CLAHE (Contrast Limited Adaptive Histogram Equalization) to improve contrast in crops. clahe_clip_limit : float CLAHE clip limit parameter. clahe_tile_grid_size : int CLAHE tile grid size (both dimensions). grayscale : bool If True, convert output to single-channel grayscale. transform_keypoints : bool If True, transform pose keypoint coordinates into crop space and include them in the metadata output as poseX_crop, poseY_crop. output_mode : str Output format: - "video": single video file per individual - "frames": individual frame images per individual - "both": video + frames output_fps : float, optional Output video FPS. If None, uses source video FPS. output_root : str, optional Override output directory. If None, outputs to media/egocentric_crops/. frame_format : str Format for frame images ("png" or "jpg") background_color : int Padding color for out-of-bounds regions (0=black, 255=white)
Examples¶
Process a single individual:
crop = EgocentricCrop(params={"target_id": 0, "crop_size": (256, 256)}) dataset.run_feature(crop, sequences=["hex_3"])
Bee-style crop with body masking and CLAHE:
crop = EgocentricCrop(params={ ... "crop_size": (192, 192), ... "center_offset_px": 35.0, ... "body_mask": True, ... "use_clahe": True, ... "grayscale": True, ... "angle_col": "ANGLE", ... }) dataset.run_feature(crop, sequences=["hex_3"])
Source code in src/mosaic/behavior/visualization_library/egocentric_crop.py
bind_dataset ¶
set_scope ¶
transform ¶
Process a single sequence's tracks to generate egocentric crop video/frames.
Parameters¶
df : pd.DataFrame Tracks DataFrame for a single sequence
Returns¶
pd.DataFrame Metadata DataFrame with crop info per frame/id
Source code in src/mosaic/behavior/visualization_library/egocentric_crop.py
InteractionCropPipeline ¶
InteractionCropPipeline(inputs: Inputs = Inputs(('tracks', Result(feature='pair-interaction-filter'))), params: dict[str, object] | None = None)
Generate egocentric crop videos for detected interaction segments.
Reads interaction segments from an upstream pair-interaction-filter
result and generates per-individual cropped videos for each segment.
Optionally applies body masking, CLAHE, and grayscale conversion.
Inputs¶
This feature takes two inputs:
1. Tracks (standard trajectory data with pose keypoints)
2. A pair-interaction-filter result providing interaction segments
The pipeline iterates over the filter result's interaction segments
(grouped by id_a, id_b, interaction_id) and extracts
egocentric crops from the source video for each individual in the pair.
Output¶
Videos are written to <run_root>/ when run via the pipeline
(run_id-tagged). Returns a metadata DataFrame with one row per
generated clip:
- group, sequence, id_a, id_b, target_id, interaction_id
- start_frame, end_frame, n_frames
- video_path (filename only, relative to run_root)
Source code in src/mosaic/behavior/visualization_library/interaction_crop.py
apply ¶
Process merged tracks + interaction-filter DataFrame.
The pipeline merges both inputs on frame, so df contains track columns and filter columns (id_a, id_b, interaction_id, interaction_start, interaction_end).
Source code in src/mosaic/behavior/visualization_library/interaction_crop.py
VizGlobalColored ¶
Generic scatter plot visualization for any global embedding or feature columns.
Uses ResultColumn params for fully customizable x and y axes. For example, t-SNE coordinates, PCA components, speed vs approach distance, etc. Labels can be from any feature's parquet output (via ResultColumn) or ground truth labels (via GroundTruthLabelsSource).
Source code in src/mosaic/behavior/visualization_library/viz_global_colored.py
TimelinePlot ¶
Visualize per-frame labels as horizontal colored-bar timelines.
Params¶
source : dict
Feature reference: {"feature": "kpms-apply", "run_id": None, "pattern": "*.parquet"}
Or ground-truth labels: {"source": "labels", "kind": "CalMS21"}
label_column : str or None
Column containing the labels. Auto-detected if None.
label_columns : list[str] or None
Combine multiple binary (0/1) columns into one composite label.
The label value is the column name of the first active column,
or 0 when none are active. Overrides label_column.
Use with skip_labels=[0] to hide inactive frames.
skip_labels : list or None
Label values to not draw (rendered as white/blank space).
Example: [0] to hide "no event" frames.
symmetric_pairs : bool
If True, treat (A,B) == (B,A) for pair-level data.
palette : str
Seaborn palette name for label colors (default "tab20").
pair_palette : str
Palette for asymmetric pair role shading (default "Paired").
figsize_width : float
Width of each figure in inches.
row_height : float
Height per timeline row in inches.
min_fig_height / max_fig_height : float
Clamp figure height.
show_legend : bool
Whether to add a legend. When there are many labels the legend is
placed outside the plot area.
title_template : str
Format string for plot title; {sequence} is replaced.
dpi : int
Output resolution.
per_sequence : bool
One PNG per sequence (True) or a single combined PNG (False).
missing_label_value : int
Sentinel for unlabeled frames (rendered gray).
label_name_map : dict or None
Optional {label_id: display_name} for the legend.
Output¶
PNG file(s) in the run folder plus a single marker parquet row for indexing.
Source code in src/mosaic/behavior/visualization_library/viz_timeline.py
demo_load_visual_inputs ¶
Small wrapper to quickly inspect what load_tracks_and_labels returns.
Usage (notebook):
tracks, labels = demo_load_visual_inputs(dataset, "G1", "S1",
{"temporal-stack": None,
"behavior-xgb-pred": "
Source code in src/mosaic/behavior/visualization_library/data_loading.py
load_ground_truth_labels ¶
Load per-frame ground-truth labels for a given kind/group/sequence.
Returns a DataFrame with columns
frame, label_id, label_name (if mapping provided in the npz). For individual_pair_v1 format, also includes id1, id2 columns.
Source code in src/mosaic/behavior/visualization_library/data_loading.py
load_tracks_and_labels ¶
load_tracks_and_labels(ds, group: str, sequence: str, feature_runs: Dict[str, Optional[str]]) -> Tuple[pd.DataFrame, Dict[str, Any]]
Load a single sequence's tracks plus per-frame labels from feature/model runs.
Parameters¶
ds : Dataset Loaded Dataset instance. group, sequence : str The scope to load. feature_runs : dict[str, str | None] Mapping of feature/model storage names -> run_id. If run_id is None, the latest finished run is used.
Returns¶
tracks_df : pd.DataFrame Standard tracks for the requested (group, sequence). labels : dict { "per_id": {feature_name: {id_value: Series}}, "per_pair": {feature_name: {(id1, id2): Series}}, "raw": {feature_name: DataFrame} # full frame per feature for bespoke use } Series are indexed by frame and hold the chosen label column.
Source code in src/mosaic/behavior/visualization_library/data_loading.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
draw_frame ¶
draw_frame(image: ndarray, frame_overlay: dict, id_colors: dict, show_labels: bool = True, point_radius: int = 8, bbox_thickness: int = 2, show_individual_bboxes: bool = True, scale: Tuple[float, float] = (1.0, 1.0), color_feature: Optional[str] = None, color_mode: Optional[str] = None, pair_box_feature: Optional[str] = None, pair_box_behaviors: Optional[Iterable[Any]] = None, hide_individual_bboxes_for_pair: bool = False) -> np.ndarray
Draw pose points, bounding boxes, and labels for a single frame.
Parameters¶
image : np.ndarray (H,W,3) Video frame in BGR order. frame_overlay : dict Entry from overlay_data["per_frame"][frame]. id_colors : dict Mapping produced by prepare_overlay.
Source code in src/mosaic/behavior/visualization_library/overlay.py
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 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 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 822 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 | |
prepare_overlay ¶
prepare_overlay(tracks_df: DataFrame, labels: dict, gt_df: Optional[DataFrame] = None, kinds: Iterable[str] = ('pose', 'bbox'), color_by: Optional[str] = None, hide_unlabeled: bool = False) -> dict
Precompute lightweight per-frame overlay structures (pose keypoints, bounding boxes, labels).
Parameters¶
tracks_df : DataFrame Output of load_tracks_and_labels()[0]. labels : dict Output of load_tracks_and_labels()[1]. gt_df : DataFrame, optional Output of load_ground_truth_labels (used as global per-frame labels). kinds : Iterable[str] Overlay primitives to compute ("pose", "bbox").
Returns¶
dict with keys: frames: sorted list of frame numbers per_frame: {frame -> {"ids": {id -> info}, "global_labels": {...}}} id_colors: {id -> (B,G,R)}
Source code in src/mosaic/behavior/visualization_library/overlay.py
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 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 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 | |
build_overlay ¶
build_overlay(ds, group: str, sequence: str, feature_runs: Dict[str, Optional[str]], label_kind: Optional[str] = 'behavior', color_by: Optional[str] = None, label_maps: Optional[Dict[str, dict]] = None, hide_unlabeled: bool = False, visualization_spec: Optional[dict] = None) -> Tuple[dict, Any, Dict[str, Any]]
Build a base overlay (and optional spec layers), returning overlay/tracks/labels.
Source code in src/mosaic/behavior/visualization_library/playback.py
play_video ¶
play_video(ds, group: str, sequence: str, feature_runs: Dict[str, Optional[str]], label_kind: Optional[str] = 'behavior', color_by: Optional[str] = None, label_maps: Optional[Dict[str, dict]] = None, hide_unlabeled: bool = False, overlay_data: Optional[dict] = None, start: int = 0, end: Optional[int] = None, downscale: float = 1.0, draw_options: Optional[Dict[str, Any]] = None, show_individual_bboxes: bool = True, pair_box_feature: Optional[str] = None, pair_box_behaviors: Optional[Iterable[Any]] = None, hide_individual_bboxes_for_pair: bool = False, output_path: Optional[Path | str] = None, show_window: bool = True, window_name: Optional[str] = None, visualization_spec: Optional[dict] = None) -> Optional[Path]
Stream a video with overlays; optionally save to disk.
Parameters¶
ds : Dataset Loaded Dataset instance. group : str Group name. sequence : str Sequence name. feature_runs : dict[str, str | None] Mapping of feature/model storage names -> run_id. label_kind : str, optional Kind of labels to load (default "behavior"). color_by : str, optional Feature name to color by, or "gt" for ground-truth. label_maps : dict[str, dict], optional Optional mapping per feature to replace numeric labels with names, e.g. {"behavior-xgb-pred__from__...": {0: "attack", 1: "investigation", ...}}. hide_unlabeled : bool If True, skip drawing ids that lack labels (after any filtering/mapping). overlay_data : dict, optional Precomputed overlay from prepare_overlay(). If provided, skips rebuilding overlay (useful when you want to pre-filter labels before playback). start : int Starting frame index. end : int, optional Ending frame index. downscale : float Downscale factor (1.0 = no scaling). draw_options : dict, optional Optional frame-drawing options. Allowed keys: "show_labels", "point_radius", "bbox_thickness". You can also store defaults in overlay_data["draw_options"]. show_individual_bboxes : bool If False, skip drawing per-id bounding boxes while keeping pose points/labels. pair_box_feature : str, optional Pair-label feature to inspect when drawing union boxes. pair_box_behaviors : iterable, optional Behavior values that should trigger pair-level boxes. hide_individual_bboxes_for_pair : bool If True, do not draw per-id boxes for ids participating in selected pair boxes. output_path : Path or str, optional If provided, saves video to this path. show_window : bool If True, displays video in a window. window_name : str, optional Name for the display window. visualization_spec : dict, optional Optional spec with extra render layers and playback overrides.
Returns¶
Path or None Path to the saved video file if output_path was provided.
Keyboard Controls¶
- q or Esc: Quit
- Space: Pause/resume
- d: Step one frame (while paused)
- s: Save current frame as PNG
Source code in src/mosaic/behavior/visualization_library/playback.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 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 | |
play_video_with_spec ¶
play_video_with_spec(ds, group: str, sequence: str, feature_runs: Dict[str, Optional[str]], visualization_spec: dict, **kwargs: Any) -> Optional[Path]
Convenience wrapper: build overlay from tracks/labels + visualization_spec, then play/save.
Any explicit kwargs are forwarded to play_video and override spec playback defaults.
Source code in src/mosaic/behavior/visualization_library/playback.py
render_stream ¶
render_stream(video_paths: Union[list[Path], Path, str], overlay_data: dict, start: int = 0, end: Optional[int] = None, downscale: float = 1.0, show_individual_bboxes: bool = True, pair_box_feature: Optional[str] = None, pair_box_behaviors: Optional[Iterable[Any]] = None, hide_individual_bboxes_for_pair: bool = False, draw_options: Optional[Dict[str, Any]] = None) -> _FrameStream
Return an iterable that yields (frame_index, frame_bgr_with_overlay).
Parameters¶
video_paths : list[Path], Path, or str Path(s) to the video file(s). For multi-video sequences, pass an ordered list of Paths. A single Path/str is also accepted. overlay_data : dict Output from prepare_overlay() start : int Starting frame index end : int, optional Ending frame index (inclusive). If None, streams to end of video. downscale : float Downscale factor (1.0 = no scaling, 0.5 = half size) show_individual_bboxes : bool If False, skip drawing per-id bounding boxes while keeping pose points/labels. pair_box_feature : str, optional Pair-label feature to inspect when drawing union boxes. pair_box_behaviors : iterable, optional Behavior values that should trigger pair-level boxes. hide_individual_bboxes_for_pair : bool If True, do not draw per-id boxes for ids participating in selected pair boxes. draw_options : dict, optional Optional frame-drawing options. Allowed keys: "show_labels", "point_radius", "bbox_thickness".
Returns¶
_FrameStream Iterator yielding (frame_index, frame_bgr) tuples
Source code in src/mosaic/behavior/visualization_library/video_stream.py
apply_visualization_spec ¶
apply_visualization_spec(overlay: dict[str, Any], tracks_df: DataFrame, labels: dict[str, Any], spec: Optional[dict[str, Any]]) -> dict[str, Any]
Apply all enabled layers from a visualization spec into overlay in-place.
Source code in src/mosaic/behavior/visualization_library/visual_spec.py
list_visual_adapters ¶
normalize_visualization_spec ¶
Normalize user-provided visualization spec.