### Install from source Source: https://github.com/talmolab/sleap-io/blob/main/README.md Install directly from the GitHub repository. ```bash pip install "sleap-io[all] @ git+https://github.com/talmolab/sleap-io.git@main" ``` -------------------------------- ### Repository Setup Commands Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Commands for cloning and installing the package dependencies using various environment managers. ```bash git clone https://github.com/talmolab/sleap-io && cd sleap-io ``` ```bash uv sync --all-extras ``` ```bash conda env create -f environment.yml && conda activate sleap-io ``` ```bash pip install -e .[dev,all] ``` -------------------------------- ### Install sleap-io in a project environment Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Standard installation commands for various package managers. ```bash pip install "sleap-io[all]" ``` ```bash uv pip install "sleap-io[all]" ``` ```bash uv add "sleap-io[all]" ``` ```bash conda install -c conda-forge sleap-io ``` -------------------------------- ### Install sleap-io Source: https://github.com/talmolab/sleap-io/blob/main/docs/index.md Install the library using pip or run it directly using uvx. ```bash pip install "sleap-io[all]" ``` ```bash uvx sleap-io show labels.slp ``` -------------------------------- ### Development setup Source: https://github.com/talmolab/sleap-io/blob/main/README.md Clone the repository and sync dependencies for development. ```bash git clone https://github.com/talmolab/sleap-io.git && cd sleap-io uv sync --all-extras ``` -------------------------------- ### Clone and sync development environment Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Initial setup for contributors. ```bash # Clone the repository git clone https://github.com/talmolab/sleap-io.git cd sleap-io # Install with development dependencies (recommended) uv sync --all-extras ``` -------------------------------- ### Minimal CLI installation Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Install the CLI tool without optional dependencies. ```bash uv tool install sleap-io # Basic installation ``` -------------------------------- ### Install video backend dependencies Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Commands to install optional video backend support. ```bash uv sync --all-extras ``` ```bash pip install -e .[all] ``` ```bash pip install -e .[opencv] ``` ```bash pip install -e .[pyav] ``` -------------------------------- ### Install sleap-io with optional extras Source: https://github.com/talmolab/sleap-io/blob/main/docs/remote.md Install the base package or include specific extras for cloud storage support, remote media, or all features. ```bash pip install sleap-io # http/https only pip install "sleap-io[cloud]" # + s3, gs/gcs, az/abfs pip install "sleap-io[pyav]" # remote media video (provides av) pip install "sleap-io[all]" # everything (cloud + pyav included) ``` -------------------------------- ### Run example scripts with uv Source: https://github.com/talmolab/sleap-io/blob/main/docs/examples.md Execute example scripts directly without manual environment management. ```bash # Run any example script directly (no install needed) uv run --with sleap-io example.py ``` -------------------------------- ### Install as CLI tool Source: https://github.com/talmolab/sleap-io/blob/main/README.md Install the package globally to use the sio command. ```bash uv tool install "sleap-io[all]" sio show labels.slp ``` -------------------------------- ### Install sleap-io from source Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Commands to install the latest development version directly from the GitHub repository. ```bash pip install "sleap-io[all]" @ git+https://github.com/talmolab/sleap-io.git@main ``` ```bash uv pip install "sleap-io[all] @ git+https://github.com/talmolab/sleap-io.git@main" ``` ```bash uv add "sleap-io[all]" --git https://github.com/talmolab/sleap-io.git --branch main ``` -------------------------------- ### Install as Python library Source: https://github.com/talmolab/sleap-io/blob/main/README.md Install the package using standard package managers. ```bash pip install "sleap-io[all]" # or: uv add "sleap-io[all]" # or: conda install -c conda-forge sleap-io ``` -------------------------------- ### Install uv Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Install the uv package manager for various environments. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` ```bash pip install uv ``` -------------------------------- ### Quick usage example Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Demonstrates loading, inspecting, converting, and saving pose data. ```python # /// script # dependencies = ["sleap-io[all]"] # /// import sleap_io as sio # Load labels from any supported format labels = sio.load_file("labels.slp") # Inspect the data print(f"Videos: {len(labels.videos)}") print(f"Labeled frames: {len(labels.labeled_frames)}") print(f"Skeleton: {labels.skeleton.node_names}") # Convert to numpy for analysis locations = labels.numpy() # shape: (frames, tracks, nodes, 2) # Save to a different format sio.save_nwb(labels, "labels.nwb") ``` -------------------------------- ### Configure video backend example Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/io-functions.md Demonstrates setting the default video plugin and checking available backends. ```python import sleap_io as sio # Set default video backend sio.set_default_video_plugin("opencv") # Check available backends backends = sio.get_available_video_backends() # ["FFMPEG", "opencv", "pyav"] # Get installation instructions print(sio.get_installation_instructions("pyav")) ``` -------------------------------- ### Run quick demo with uv Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Execute the demo script directly without manual installation. ```bash uv run quick_demo.py ``` -------------------------------- ### CLI transformation examples Source: https://github.com/talmolab/sleap-io/blob/main/docs/transforms.md Examples of CLI commands for transforming standard and package SLP files. ```bash sio transform predictions.slp --scale 0.5 -o scaled.slp # Creates: # scaled.slp # scaled.videos/original_video.transformed.mp4 ``` ```bash sio transform predictions.pkg.slp --scale 0.5 -o scaled.pkg.slp # Creates: # scaled.pkg.slp (with embedded transformed frames) ``` -------------------------------- ### Common Conversion Examples Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Examples of converting between common pose estimation formats. ```bash # Convert SLEAP to NWB sio convert labels.slp -o labels.nwb # Convert SLEAP to COCO sio convert labels.slp -o annotations.json --to coco # Convert COCO to SLEAP sio convert annotations.json -o labels.slp --from coco # Convert TrackMate spot data to SLEAP (auto-detected from headers) sio convert spots.csv -o labels.slp # Explicit TrackMate import (skips content sniffing) sio convert spots.csv -o labels.slp --from trackmate ``` -------------------------------- ### Install CLI from source Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Install the latest version of the CLI tool directly from the GitHub repository. ```bash uv tool install "sleap-io[all]" ``` ```bash uv tool install "git+https://github.com/talmolab/sleap-io.git@main" ``` -------------------------------- ### Install and use sleap-io as a global tool Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Install sleap-io globally using uv tool for regular use, enabling the sio command shortcut. ```bash # Basic install (includes video support via imageio-ffmpeg) uv tool install sleap-io # Or with faster video backends (OpenCV, PyAV) uv tool install "sleap-io[all]" # Now use the short command sio show labels.slp sio convert labels.slp -o labels.nwb ``` -------------------------------- ### Query available video backends Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/configuration-and-utility.md Lists installed video backends and retrieves installation instructions for specific plugins. ```python # List available video reading backends backends = sio.get_available_video_backends() print(backends) # ["FFMPEG", "opencv", "pyav"] # Check if specific backend is available if "opencv" in sio.get_available_video_backends(): sio.set_default_video_plugin("opencv") # Get installation instructions print(sio.get_installation_instructions("pyav")) ``` -------------------------------- ### Quick Start Development Workflow Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Commands to clone the repository, set up the environment, and run initial quality checks. ```bash # Clone and setup git clone https://github.com/talmolab/sleap-io && cd sleap-io uv sync --all-extras # Make changes on a new branch git checkout -b yourname/feature-name # Before committing - format and lint uv run ruff format sleap_io tests && uv run ruff check --fix sleap_io tests # Run tests uv run pytest tests/ # Check coverage uv run pytest -q --maxfail=1 --cov --cov-branch && rm .coverage.* && uv run coverage annotate ``` -------------------------------- ### Install sleap-io with optional extras Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Use pip to install the package with specific feature sets enabled via extras. ```bash pip install "sleap-io[opencv]" # Just OpenCV pip install "sleap-io[opencv,mat]" # Multiple extras pip install "sleap-io[all]" # Everything ``` -------------------------------- ### Install sleap-io Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/README.md Commands to install the base package or specific optional dependencies for enhanced functionality. ```bash # Basic installation pip install sleap-io # With all optional extras pip install "sleap-io[all]" # Specific extras pip install "sleap-io[opencv,polars,cloud]" ``` -------------------------------- ### Download Examples Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Common usage patterns for downloading files from different sources and handling authentication. ```bash # Into the current directory (filename taken from the URL) sio download https://example.com/labels.slp # Into a directory, or to an exact path sio download s3://my-bucket/run/video.mp4 data/ sio download https://example.com/a.slp out.slp # Authenticated source, forcing a fresh download sio download https://example.com/a.slp -H 'Authorization: Bearer ' -f ``` -------------------------------- ### Install development dependencies Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Commands to install the project with development extras using various package managers. ```bash uv sync --all-extras ``` ```bash pip install -e ".[dev]" ``` ```bash conda env create -f environment.yml ``` -------------------------------- ### Install as Python library Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Add sleap-io to a Python project and import it. ```bash pip install "sleap-io[all]" # or: uv add "sleap-io[all]" ``` ```python import sleap_io as sio labels = sio.load_file("labels.slp") ``` -------------------------------- ### Alternative development installation Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Methods for installing in editable mode using pip or conda. ```bash pip install -e ".[all]" # runtime + optional extras pip install --group dev # dev tools (pytest, ruff, mkdocs) ``` ```bash conda env create -f environment.yml conda activate sleap-io pip install -e . ``` -------------------------------- ### Embed command output example Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Example console output after running the embed command. ```text Embedded: labels.slp -> labels.pkg.slp Frames: user: 100, predictions: 50, suggestions: 25 ``` -------------------------------- ### Quick Start with SLEAP-IO Codecs Source: https://github.com/talmolab/sleap-io/blob/main/sleap_io/codecs/README.md Demonstrates loading labels and converting them to DataFrame, dictionary, and NumPy formats. ```python from sleap_io import load_file from sleap_io.codecs import to_dataframe, to_dict, to_numpy # Load labels labels = load_file("predictions.slp") # Convert to DataFrame df = to_dataframe(labels, format="points") print(df.head()) # Convert to dictionary (JSON-serializable) d = to_dict(labels) # Convert to numpy array arr = to_numpy(labels, return_confidence=True) ``` -------------------------------- ### Common split configurations Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Examples of default, three-way, and reproducible splits. ```bash # Default 80/20 train/val split sio split labels.slp -o splits/ # Three-way 70/15/15 split sio split labels.slp -o splits/ --train 0.7 --test 0.15 # Reproducible split with seed sio split labels.slp -o splits/ --seed 42 ``` -------------------------------- ### Apply transform_video Examples Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/transforms-and-merging.md Demonstrates creating a transformed video proxy and updating a Labels object to use the transformed video. ```python video = sio.load_video("original.mp4") # Create transformed proxy video_scaled = sio.transform_video(video, scale=0.5) # Read transformed frame frame = video_scaled[0] # Automatically applies transformation print(frame.shape) # (height//2, width//2, 3) # Compose labels and video transformation labels = sio.load_file("data.slp") labels_transformed = sio.transform_labels(labels, scale=0.5) video_transformed = sio.transform_video(labels.videos[0], scale=0.5) # Update labels to use transformed video labels_transformed.videos[0] = video_transformed labels_transformed.save("transformed.slp") ``` -------------------------------- ### Fraction configuration Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Examples of valid and invalid fraction combinations. ```bash # Valid: 0.7 + 0.15 + 0.15 = 1.0 sio split labels.slp -o splits/ --train 0.7 --val 0.15 --test 0.15 # Error: 0.8 + 0.15 + 0.15 = 1.1 > 1.0 sio split labels.slp -o splits/ --train 0.8 --val 0.15 --test 0.15 ``` -------------------------------- ### Execute installed CLI commands Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Common commands for the installed sio utility. ```bash sio show labels.slp sio convert -i labels.slp -o labels.nwb sio --version ``` -------------------------------- ### Creating Training Splits Example Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/transforms-and-merging.md Demonstrates using the convenience method to generate and save training splits to a directory. ```python labels = sio.load_file("data.slp") train, val, test = labels.make_training_splits( n_train=0.8, n_val=0.1, n_test=0.1, save_dir="training_splits/", seed=42 ) # Files created: # - training_splits/train.slp # - training_splits/val.slp # - training_splits/test.slp ``` -------------------------------- ### sio.get_available_video_backends() Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/configuration-and-utility.md Returns a list of available video reading backends installed in the environment. ```APIDOC ## sio.get_available_video_backends() ### Description Returns a list of strings representing the available video reading backends. ``` -------------------------------- ### Access CLI Help and Version Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Use these commands to view help documentation for specific subcommands or to verify the installed version and plugins. ```bash # Get help sio --help sio show --help sio convert --help sio export --help sio split --help sio unsplit --help sio merge --help sio embed --help sio unembed --help sio filenames --help sio download --help sio fix --help sio render --help sio trim --help sio reencode --help sio transform --help sio apply-crops --help # Check version and installed plugins sio --version ``` -------------------------------- ### Labels.render() usage examples Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/rendering.md Demonstrates various rendering configurations including presets, frame ranges, and custom styling. ```python import sleap_io as sio labels = sio.load_file("predictions.slp") # Basic rendering labels.render("output.mp4") # Fast preview (0.25x resolution, lower quality) labels.render("preview.mp4", preset="preview") # High quality (full resolution, high bitrate) labels.render("output_quality.mp4", preset="quality") # Specific frame range labels.render( "clip.mp4", start_frame=100, end_frame=500, fps=30.0 ) # Custom rendering labels.render( "custom.mp4", scale=0.5, edge_width=1, node_radius=3, color_manager="dark", markers="square" ) # With motion trails labels.render( "with_trails.mp4", trails={"length": 10, "color": [255, 0, 0]} ) ``` -------------------------------- ### Splitting Labels Examples Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/transforms-and-merging.md Demonstrates creating various dataset splits and saving the resulting Labels objects. ```python labels = sio.load_file("all_data.slp") # Default split: 80/10/10 train, val, test = labels.split(seed=42) # Custom split: 70/20/10 train, val, test = labels.split( n_train=0.7, n_val=0.2, n_test=0.1, seed=42 ) # Binary split (no test set) train, val = labels.split(n_train=0.8, n_val=0.2, n_test=None, seed=42) # Save splits train.save("split_train.slp") val.save("split_val.slp") test.save("split_test.slp") ``` -------------------------------- ### render_image() usage examples Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/rendering.md Shows how to save a frame to a file or retrieve it as a numpy array. ```python import sleap_io as sio labels = sio.load_file("predictions.slp") lf = labels[0] # First frame # Render and save sio.render_image(lf, output_path="frame.png") # Get rendered image as array img = sio.render_image(lf) print(img.shape) # (height, width, 3) ``` -------------------------------- ### Versioning format Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Standard semver versioning format and examples for the package. ```text {MAJOR}.{MINOR}.{PATCH} ``` ```text 0.0.1 0.1.10a2 ``` -------------------------------- ### Example CLI output Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md The console output generated after running a split command. ```text Split 1000 frames from: labels.slp Output directory: splits/ train.slp: 800 frames val.slp: 200 frames Random seed: 42 ``` -------------------------------- ### Merge command output example Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Sample console output showing the progress and statistics of a merge operation. ```text Loading: project.slp 500 frames, 1 videos Merging: predictions.slp Strategy: auto +1000 frames, +2500 instances Saving: merged.slp Merged 2 files: 1500 frames, 1 videos 2500 instances added ``` -------------------------------- ### Example Output for sio unsplit Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Console output showing the progress of merging files. ```text Loading: train.slp 800 frames, 1 videos Merging: val.slp +200 frames -> 1000 total Saving: merged.slp Merged 2 files: 1000 frames, 1 videos ``` -------------------------------- ### Virtual Cropping Quick Start Source: https://github.com/talmolab/sleap-io/blob/main/docs/cropping.md Demonstrates creating a cropped video view from an existing video object using coordinate slicing. ```pycon >>> import sleap_io as sio >>> >>> full = sio.load_video("tests/data/videos/centered_pair_low_quality.mp4") >>> print(full.shape) >>> >>> # A cropped view. crop = (x1, y1, x2, y2), with x2/y2 EXCLUSIVE. >>> view = full.crop((64, 64, 192, 192)) >>> print(view.shape) # cropped view >>> print(view[0].shape) # a single cropped frame >>> print(view._crop_tuple()) # (x1, y1, x2, y2) -- view.crop is not the rect >>> print(view.source_video is full) # provenance to the uncropped original ``` -------------------------------- ### General Export CLI Examples Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Common command-line patterns for exporting SLEAP labels, including filtering by frame range, track occupancy, and video selection. ```bash # Full export with all options sio export predictions.slp -o analysis.csv \ --csv-format frames \ --empty-frames \ --start 0 --end 1000 \ --include-scores \ --video-id path # Sparse export (only labeled frames) sio export predictions.slp -o sparse.csv --no-empty-frames # HDF5 with track filtering sio export predictions.slp -o filtered.h5 --min-occupancy 0.5 # Batch export all videos sio export multi_video.slp -o export.csv -v all # Memory-efficient export for large files sio export large.slp -o analysis.csv --chunk-size 10000 ``` -------------------------------- ### Basic trim usage Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Common examples for trimming labels and video files using start and end frame indices. ```bash # Trim labels and video to frames 100-1000 sio trim labels.slp --start 100 --end 1000 # -> labels.trim.slp + labels.trim.mp4 # Explicit output path sio trim labels.slp --start 100 --end 1000 -o clip.slp # Trim just a video file sio trim video.mp4 --start 100 --end 500 # -> video.trim.mp4 # Trim from start to frame 1000 sio trim labels.slp --end 1000 # Trim from frame 100 to end of video sio trim labels.slp --start 100 ``` -------------------------------- ### Documenting Python methods Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Example of a function docstring following the Google Python Style Guide, including argument and return type specifications. ```py def load_tracks(filepath: str) -> np.ndarray: """Load the tracks from a SLEAP Analysis HDF5 file. Args: filepath: Path to a SLEAP Analysis HDF5 file. Returns: The loaded tracks as a `np.ndarray` of shape `(n_tracks, n_frames, n_nodes, 2)` and dtype `float32`. Raises: ValueError: If the file does not contain a `/tracks` dataset. See also: save_tracks """ with h5py.File(filepath, "r") as f: if "tracks" not in f: raise ValueError( "The file does not contain a /tracks dataset. " "This may not have been generated by SLEAP." ) tracks = f["tracks"][:] return tracks.astype("float32") ``` -------------------------------- ### Polars output example Source: https://github.com/talmolab/sleap-io/blob/main/docs/codecs.md Example representation of a Polars DataFrame output. ```text shape: (6, 8) ┌───────────┬─────────┬───────┬───────┬───────┬─────────────┬────────────────┬───────┐ │ frame_idx ┆ node ┆ x ┆ y ┆ track ┆ track_score ┆ instance_score ┆ score │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ f64 ┆ f64 ┆ str ┆ f64 ┆ f64 ┆ f64 │ ╞═══════════╪═════════╪═══════╪═══════╪═══════╪═════════════╪════════════════╪═══════╡ │ 0 ┆ head ┆ 100.0 ┆ 200.0 ┆ fly_1 ┆ 0.98 ┆ 0.91 ┆ 0.95 │ │ 0 ┆ thorax ┆ 150.0 ┆ 250.0 ┆ fly_1 ┆ 0.98 ┆ 0.91 ┆ 0.92 │ │ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... ┆ ... │ └───────────┴─────────┴───────┴───────┴───────┴─────────────┴────────────────┴───────┘ ``` -------------------------------- ### Basic Usage of sio unsplit Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Examples of merging individual files, directories, and embedded package files. ```bash # Merge individual split files sio unsplit train.slp val.slp -o merged.slp sio unsplit train.slp val.slp test.slp -o merged.slp # Merge all .slp files in a directory sio unsplit splits/ -o merged.slp # Merge embedded package files sio unsplit train.pkg.slp val.pkg.slp -o merged.slp ``` -------------------------------- ### Run CLI commands with uvx Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Execute sleap-io commands instantly without permanent installation using uvx. ```bash # Inspect a labels file uvx sleap-io show labels.slp # Convert between formats uvx sleap-io convert labels.slp -o labels.nwb # Embed frames in output (video reading works out of the box) uvx sleap-io convert -i labels.slp -o labels.pkg.slp --embed user # Export to Ultralytics format uvx sleap-io convert -i labels.slp -o dataset/ --to ultralytics # Check version uvx sleap-io --version ``` -------------------------------- ### Restore video references Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Example of restoring original video references from an embedded package file. ```bash # Restore original video references sio unembed labels.pkg.slp -o labels.slp ``` -------------------------------- ### Render single images Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Examples for rendering specific labeled frames or video frames to PNG files. ```bash # Render labeled frame by index (0-based) sio render predictions.slp --lf 0 # -> predictions.lf=0.png sio render predictions.slp --lf 42 # -> predictions.lf=42.png # Render specific video frame by index sio render predictions.slp --frame 100 # -> predictions.video=0.frame=100.png sio render predictions.slp --frame 100 --video 1 # Explicit output path sio render predictions.slp --lf 5 -o frame.png ``` -------------------------------- ### Install Polars support Source: https://github.com/talmolab/sleap-io/blob/main/docs/codecs.md Polars is an optional dependency that must be installed separately. ```bash pip install sleap-io[polars] ``` -------------------------------- ### Cropping video examples Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/transforms-and-merging.md Demonstrates various ways to crop a video using explicit coordinates, bounding boxes, ROI objects, or centered windows. ```python video = sio.load_video("video.mp4") # Explicit crop region v_cropped = video.crop(crop=(100, 100, 500, 500)) # Bounding box v_cropped = video.crop(bbox=(100.5, 100.5, 500.7, 500.3)) # ROI with margin from shapely.geometry import Polygon roi = Polygon([(100, 100), (500, 100), (500, 500), (100, 500)]) v_cropped = video.crop(roi=roi, margin=20) # Fixed-size centered window v_centered = video.crop(center=(640, 360), size=(256, 256)) # Read cropped frame frame = v_cropped[0] print(frame.shape) # (y2-y1, x2-x1, 3) ``` -------------------------------- ### Apply transform_labels Examples Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/transforms-and-merging.md Demonstrates various geometric transformations on a Labels object, including scaling, cropping, flipping, rotation, and composition. ```python import sleap_io as sio labels = sio.load_file("predictions.slp") # Scale to half size labels_scaled = sio.transform_labels(labels, scale=0.5) # Crop to region labels_cropped = sio.transform_labels( labels, crop=(100, 100, 500, 500) ) # Flip horizontally (for left-right symmetry augmentation) labels_flipped = sio.transform_labels(labels, flip_x=True) # Rotate 45 degrees labels_rotated = sio.transform_labels(labels, rotate=45.0) # Pad with 50 pixels on all sides labels_padded = sio.transform_labels( labels, pad=(50, 50, 50, 50) ) # Compose multiple transforms labels_transformed = sio.transform_labels( labels, scale=0.5, rotate=10.0, offset=(100, 50) ) # Save transformed data labels_transformed.save("transformed.slp") ``` -------------------------------- ### Merging Labels Examples Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/transforms-and-merging.md Demonstrates merging annotation files with default and custom parameters, including history management. ```python import sleap_io as sio # Load multiple annotation sources manual = sio.load_file("manual_annotations.slp") predictions = sio.load_file("model_predictions.slp") # Merge predictions into manual annotations manual.merge(predictions) manual.save("merged.slp") # Merge with custom parameters manual.merge( predictions, match_threshold=50.0, # Allow 50-pixel spatial distance remove_duplicates=True ) # Preserve merge history manual.merge(predictions, max_merge_history=None) # Keep all history print(manual.provenance.get("merge_history", [])) ``` -------------------------------- ### Install with specific Python version Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Specify a Python version when installing the CLI tool. ```bash uv tool install "sleap-io[all]" --python 3.12 ``` -------------------------------- ### Copy labels and manage backends Source: https://github.com/talmolab/sleap-io/blob/main/docs/examples.md Creates deep copies of label objects with options to control video backend initialization. Includes a non-mutating save example. ```python import sleap_io as sio labels = sio.load_file("labels.slp") # Default: preserves each video's current open_backend setting labels_copy = labels.copy() # Prevent file handles from being created (useful for batch processing) labels_copy = labels.copy(open_videos=False) # Force all videos to auto-open when frames are accessed labels_copy = labels.copy(open_videos=True) # Filtering done separately (cleaner separation of concerns) labels_copy = labels.copy() labels_copy.remove_predictions() labels_copy.suggestions = [] ``` ```python # Original labels are NOT modified (safer) labels.save("output.pkg.slp", embed="user") assert labels.videos[0].filename != "output.pkg.slp" # Still points to original # With embed_inplace=True: original labels ARE modified (faster) labels.save("output.pkg.slp", embed="user", embed_inplace=True) ``` -------------------------------- ### Common rendering tasks Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Examples of common rendering operations including output path specification, previewing, frame selection, and background customization. ```bash # Render video with automatic output filename sio render predictions.slp # -> predictions.viz.mp4 # Render with explicit output path sio render predictions.slp -o output.mp4 # Fast preview (0.25x resolution) sio render predictions.slp --preset preview # Render a specific clip sio render predictions.slp --start 100 --end 200 # Render a single frame to PNG sio render predictions.slp --lf 0 # -> predictions.lf=0.png # Render without source video (solid background) sio render predictions.slp --background black sio render predictions.slp --background "#333" # Segmentation predictions are drawn automatically (no --overlay needed): # label_images take precedence, falling back to SegmentationMask annotations. # Works on RGB and single-channel grayscale video. sio render predictions.slp -o out.mp4 # Overlay a segmentation mask on rendered poses (explicit overlay overrides auto) sio render predictions.slp --overlay masks.tif --overlay-alpha 0.4 # Overlay-only mode: render masks on images without a labels file sio render --images frames/ --overlay masks.tif -o output.mp4 ``` -------------------------------- ### Check SLEAP-IO version and plugins Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Use this command to verify the installed version of sleap-io and check the status of core and video backend plugins. ```bash sio --version ``` -------------------------------- ### Basic Video Reencoding Examples Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Common usage patterns for reencoding individual video files with various quality and performance settings. ```bash # Reencode with default settings (medium quality, 1 keyframe/second) sio reencode video.mp4 -o video.seekable.mp4 # Higher quality encoding sio reencode video.mp4 -o output.mp4 --quality high # More frequent keyframes for faster seeking sio reencode video.mp4 -o output.mp4 --keyframe-interval 0.5 # Downsample high-speed video for preview sio reencode highspeed.mp4 -o preview.mp4 --fps 30 --quality low # Preview the ffmpeg command without executing sio reencode video.mp4 -o output.mp4 --dry-run # Force Python path (for HDF5-embedded sources or when ffmpeg unavailable) sio reencode video.mp4 -o output.mp4 --no-ffmpeg # Default output (no -o) is always {stem}.reencoded.mp4 sio reencode video.mov # -> video.reencoded.mp4 # Reencode in place: replace the input with {stem}.mp4 and delete the original sio reencode video.mov --replace # -> video.mp4 (deletes video.mov) ``` -------------------------------- ### Building the package with uv Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Commands to build the source distribution and wheel locally using uv. ```bash # Build source distribution and wheel uv build # Build artifacts will be placed in dist/ ls dist/ ``` -------------------------------- ### Install sleap-io without OpenCV Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Use this command to avoid dependency conflicts with other ML frameworks that may already provide OpenCV. ```bash pip install "sleap-io[pyav,mat]" # Skip opencv ``` -------------------------------- ### Build documentation Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Commands for serving or building the documentation site. ```bash # Serve docs locally mkdocs serve # Build static site mkdocs build ``` -------------------------------- ### Track Example Entries Source: https://github.com/talmolab/sleap-io/blob/main/docs/formats/slp.md Example of multiple track entries stored as JSON arrays. ```json [0, "mouse_1"] [0, "mouse_2"] [0, "female"] ``` -------------------------------- ### Multiple Skeletons in YAML Source: https://github.com/talmolab/sleap-io/blob/main/docs/formats/slp.md Example showing how to define multiple skeletons within a single YAML file using top-level keys. ```yaml fly: nodes: - name: head - name: thorax edges: - source: { name: head } destination: { name: thorax } symmetries: [] mouse: nodes: - name: nose - name: spine edges: - source: { name: nose } destination: { name: spine } symmetries: [] ``` -------------------------------- ### Handle Polars installation error Source: https://github.com/talmolab/sleap-io/blob/main/docs/codecs.md Error message displayed when the polars backend is requested but not installed. ```text ImportError: Polars backend requires polars to be installed ``` -------------------------------- ### Manage documentation versions Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Commands to build, deploy, and serve documentation using mike. ```bash uv run mike deploy --update-aliases 0.1.4 latest ``` ```bash uv run mike serve ``` ```bash uv run mike deploy --push --update-aliases --allow-empty 0.1.4 latest ``` -------------------------------- ### Initialize Instance3D and PredictedInstance3D Source: https://github.com/talmolab/sleap-io/blob/main/docs/model/3d.md Demonstrates creating 3D instances with skeletons and point coordinates, including confidence scores for predicted instances. ```pycon >>> import numpy as np >>> import sleap_io as sio >>> skel = sio.Skeleton(nodes=["head", "tail"], edges=[("head", "tail")]) >>> pts = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) >>> inst_3d = sio.Instance3D(points=pts, skeleton=skel) >>> print(inst_3d.n_visible, inst_3d.is_empty) >>> pred_3d = sio.PredictedInstance3D( ... points=pts, skeleton=skel, point_scores=np.array([0.9, 0.8]), ... ) >>> print(pred_3d.point_scores) ``` -------------------------------- ### Create an InstanceGroup Source: https://github.com/talmolab/sleap-io/blob/main/docs/model/3d.md Demonstrates initializing an InstanceGroup with 2D instances from multiple cameras, a 3D instance, and an identity. ```pycon >>> import numpy as np >>> import sleap_io as sio >>> skel = sio.Skeleton(nodes=["head", "tail"], edges=[("head", "tail")]) >>> cam1, cam2 = sio.Camera(name="cam1"), sio.Camera(name="cam2") >>> inst_2d_cam1 = sio.Instance.from_numpy(np.array([[10, 20], [30, 40]]), skeleton=skel) >>> inst_2d_cam2 = sio.Instance.from_numpy(np.array([[12, 22], [32, 42]]), skeleton=skel) >>> inst_3d = sio.Instance3D(points=np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), skeleton=skel) >>> mouse_a = sio.Identity(name="mouse_A") >>> group = sio.InstanceGroup( ... instance_by_camera={cam1: inst_2d_cam1, cam2: inst_2d_cam2}, ... instance_3d=inst_3d, ... identity=mouse_a, ... ) >>> print(len(group.instances), "matched instances") >>> print(group.identity.name) ``` -------------------------------- ### Verify environment Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Check the current Python path and installed package version. ```bash which python python -c "import sleap_io; print(sleap_io.__version__)" ``` -------------------------------- ### Dictionary Output Structure Source: https://github.com/talmolab/sleap-io/blob/main/docs/codecs.md Example of the JSON-serializable dictionary structure produced by to_dict(). ```json { "version": "1.0.0", "skeletons": [ { "name": "fly", "nodes": ["head", "thorax", "abdomen"], "edges": [[0, 1], [1, 2]] } ], "videos": [ {"filename": "video.mp4", "shape": [1000, 1024, 1024, 1]} ], "tracks": [ {"name": "fly_1"} ], "labeled_frames": [ { "frame_idx": 0, "video_idx": 0, "instances": [ { "type": "predicted_instance", "skeleton_idx": 0, "points": [ {"x": 100.0, "y": 200.0, "visible": true, "complete": false}, {"x": 150.0, "y": 250.0, "visible": true, "complete": false}, {"x": 200.0, "y": 300.0, "visible": true, "complete": false} ], "track_idx": 0, "score": 0.91 } ] }, { "frame_idx": 12, "video_idx": 0, "instances": [], "is_negative": true } ], "suggestions": [], "provenance": {} } ``` -------------------------------- ### Run CLI commands with uvx Source: https://github.com/talmolab/sleap-io/blob/main/README.md Execute CLI commands without a permanent installation. ```bash uvx sleap-io show labels.slp uvx sleap-io convert -i labels.slp -o labels.nwb ``` -------------------------------- ### Check video backends Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Verify available video backends via CLI or Python. ```bash sio --version # Or in Python: python -c "import sleap_io; print(sleap_io.get_available_video_backends())" ``` -------------------------------- ### Common Transformation Operations Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Examples of applying specific geometric transformations and previewing results. ```bash # Scale down 50% sio transform labels.slp --scale 0.5 -o scaled.slp # Crop to region (x1,y1,x2,y2) sio transform labels.slp --crop 100,100,500,500 -o cropped.slp # Rotate 90 degrees clockwise sio transform labels.slp --rotate 90 -o rotated.slp # Flip horizontally sio transform labels.slp --flip-horizontal -o flipped.slp # Combined transforms (applied in order: crop -> scale -> rotate -> pad -> flip) sio transform labels.slp --crop 100,100,500,500 --scale 2.0 -o zoomed.slp # Preview without processing sio transform labels.slp --scale 0.5 --dry-run # Transform raw video (no labels) sio transform video.mp4 --scale 0.5 -o video_scaled.mp4 ``` -------------------------------- ### Unembed output example Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Expected console output after successfully running the unembed command. ```text Unembedded: labels.pkg.slp -> labels.slp Restored 1 video(s) to source paths ``` -------------------------------- ### Discover available options Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md List all available colors and palettes supported by the renderer. ```bash sio render --list-colors # Show all named colors sio render --list-palettes # Show all available palettes ``` -------------------------------- ### Pin specific versions Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Examples for pinning dependencies to specific versions, commits, or tags. ```toml # Pin to version "sleap-io[all]==0.6.0" # Pin to specific commit "sleap-io[all] @ git+https://github.com/talmolab/sleap-io.git@abc1234" # Pin to tag "sleap-io[all] @ git+https://github.com/talmolab/sleap-io.git@v0.6.0" ``` -------------------------------- ### Show All File Details Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Combines skeleton, video, tracks, and provenance views for a complete summary. ```bash sio show labels.slp --all ``` -------------------------------- ### Metadata JSON Structure Source: https://github.com/talmolab/sleap-io/blob/main/docs/formats/csv.md Example of the JSON schema used for metadata sidecar files. ```json { "version": "1.0", "videos": [ { "filename": "video.mp4", "backend_metadata": {} } ], "skeletons": [ { "name": "Skeleton-0", "nodes": ["nose", "head", "neck", "tail"], "edges": [[0, 1], [1, 2], [2, 3]], "symmetries": [] } ], "tracks": ["mouse_1", "mouse_2"], "suggestions": [], "provenance": {} } ``` -------------------------------- ### Create fresh environment Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Resolve dependency conflicts by creating a new virtual environment. ```bash uv venv uv pip install "sleap-io[all]" ``` -------------------------------- ### Run CLI with optional dependencies Source: https://github.com/talmolab/sleap-io/blob/main/docs/install.md Use uvx to run commands with all optional dependencies included. ```bash # Inspect a labels file uvx sleap-io show labels.slp # Convert between formats uvx sleap-io convert -i labels.slp -o labels.nwb # Use with all optional dependencies (requires --from for extras) uvx --from "sleap-io[all]" sleap-io show labels.slp ``` -------------------------------- ### Basic sio filenames usage Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Shows the general syntax for inspection and update modes. ```bash # Inspection mode (default) sio filenames sio filenames -i # Update mode sio filenames -o [update options] ``` -------------------------------- ### Camera Metadata Class Source: https://github.com/talmolab/sleap-io/blob/main/_autodocs/types-reference.md Defines metadata for a single camera within a multi-camera setup. ```python class Camera: """Metadata for a single camera in a multi-camera setup.""" ``` -------------------------------- ### Initialize a RecordingSession Source: https://github.com/talmolab/sleap-io/blob/main/docs/model/3d.md Link cameras to specific video files to represent a synchronized multi-camera recording. ```pycon >>> import sleap_io as sio >>> import numpy as np >>> cam = sio.Camera( ... matrix=np.array([[500, 0, 320], [0, 500, 240], [0, 0, 1]], dtype="float64"), ... dist=np.zeros(5), size=(640, 480), rvec=np.zeros(3), ... tvec=np.array([0, 0, 1], dtype="float64"), name="cam_top", ... ) >>> cam2 = sio.Camera( ... matrix=np.eye(3) * 500, dist=np.zeros(5), size=(640, 480), ... rvec=np.array([0, 0.5, 0]), ... tvec=np.array([1, 0, 1], dtype="float64"), name="cam_side", ... ) >>> cg = sio.CameraGroup(cameras=[cam, cam2]) >>> vid_top = sio.Video("top_view.mp4", open_backend=False) >>> vid_side = sio.Video("side_view.mp4", open_backend=False) >>> session = sio.RecordingSession( ... camera_group=cg, ... video_by_camera={cam: vid_top, cam2: vid_side}, ... camera_by_video={vid_top: cam, vid_side: cam2}, ... ) >>> print(session.cameras) >>> print(session.videos) >>> print(session.get_camera(vid_top).name) ``` -------------------------------- ### Seed sensitivity warning Source: https://github.com/talmolab/sleap-io/blob/main/docs/cli.md Example showing how different options affect reproducibility even with the same seed. ```bash # These will produce DIFFERENT splits even with the same seed: sio split labels.slp -o run1/ --seed 42 sio split labels.slp -o run2/ --seed 42 --remove-predictions ``` -------------------------------- ### Configure video matching via strings Source: https://github.com/talmolab/sleap-io/blob/main/docs/merging.md Demonstrates common string-based configuration options for the merge method. ```python # Default: safe AUTO cascade base.merge(other, video="auto") # Exact path match only base.merge(other, video="path") # Match by filename only (ignores directory) base.merge(other, video="basename") ``` -------------------------------- ### Publishing the package with uv Source: https://github.com/talmolab/sleap-io/blob/main/CONTRIBUTING.md Commands to build and publish the package manually using uv. ```bash # Build and publish uv build uv publish ``` -------------------------------- ### Video Metadata JSON Structure Source: https://github.com/talmolab/sleap-io/blob/main/docs/formats/slp.md Example of a standard MediaVideo entry within the /videos_json dataset. ```json { "filename": "path/to/video.mp4", "backend": { "type": "MediaVideo", "shape": [1000, 480, 640, 3], "filename": "path/to/video.mp4", "grayscale": false, "bgr": true, "fps": 30.0 }, "source_video": null } ``` -------------------------------- ### Render video clip Source: https://github.com/talmolab/sleap-io/blob/main/docs/rendering.md Render a specific range of frames by defining start and end indices. ```python sio.render_video(labels, "clip.mp4", start=100, end=200) ```