|
| 1 | +# Virtual cropping |
| 2 | + |
| 3 | +sleap-io can expose a **virtual, on-read crop** of a video — a cropped view whose |
| 4 | +frames are produced by decoding the source and slicing in memory, without copying or |
| 5 | +re-encoding any pixels on disk. It is the lazy, non-destructive counterpart of the |
| 6 | +materializing [Transforms](transforms.md) pipeline: a virtually-cropped frame is |
| 7 | +byte-identical to what baking a `Transform(crop=...)` would write. |
| 8 | + |
| 9 | +--- |
| 10 | + |
| 11 | +## Quick start |
| 12 | + |
| 13 | +```python |
| 14 | +import sleap_io as sio |
| 15 | + |
| 16 | +full = sio.load_video("session.mp4") # (1000, 1080, 1920, 3) |
| 17 | + |
| 18 | +# A cropped view. crop = (x1, y1, x2, y2), with x2/y2 EXCLUSIVE. |
| 19 | +view = full.crop((320, 200, 576, 456)) |
| 20 | +view.shape # (1000, 256, 256, 3) -- cropped |
| 21 | +view[0].shape # (256, 256, 3) -- a cropped frame |
| 22 | +view.crop # not a thing; use view._crop_tuple() -> (320, 200, 576, 456) |
| 23 | +view.source_video is full # True -- provenance to the uncropped original |
| 24 | +``` |
| 25 | + |
| 26 | +`Video.from_crop` opens a file and crops it in one call: |
| 27 | + |
| 28 | +```python |
| 29 | +view = sio.Video.from_crop("session.mp4", crop=(320, 200, 576, 456)) |
| 30 | +``` |
| 31 | + |
| 32 | +The returned object is a normal [`Video`](model/video.md): `shape`, `len()`, `grayscale`, |
| 33 | +NumPy-style indexing, and matching all report the **cropped** view. |
| 34 | + |
| 35 | +--- |
| 36 | + |
| 37 | +## The crop convention |
| 38 | + |
| 39 | +A crop is `(x1, y1, x2, y2)` in **source pixel coordinates**, with `x2`/`y2` |
| 40 | +**exclusive** — exactly the convention used by [`Transform`](transforms.md) and |
| 41 | +`crop_frame`. The cropped size is `(y2 - y1, x2 - x1)`. |
| 42 | + |
| 43 | +Coordinates may be **negative or extend past the source** — out-of-bounds regions are |
| 44 | +**padded** with `fill` (default `0`), never clamped, so the output shape is always |
| 45 | +exactly `(y2 - y1, x2 - x1)`. This makes fixed-size, centroid-following windows easy: |
| 46 | + |
| 47 | +```python |
| 48 | +# Fixed 128x128 window centered on a point (may run off the frame edge -> padded). |
| 49 | +view = full.crop(center=(cx, cy), size=(128, 128), fill=0) |
| 50 | +view.shape # (n_frames, 128, 128, 3) |
| 51 | +``` |
| 52 | + |
| 53 | +`Video.crop` accepts one region spec — an explicit `crop` rect, a `bbox=(x1,y1,x2,y2)`, |
| 54 | +an `roi` (anything exposing shapely-style `.bounds`, expanded by `margin`), or a |
| 55 | +`center`/`size` pair: |
| 56 | + |
| 57 | +```python |
| 58 | +full.crop((x1, y1, x2, y2)) # explicit rect |
| 59 | +full.crop(bbox=(x1, y1, x2, y2)) # same, named |
| 60 | +full.crop(roi=my_roi, margin=8) # axis-aligned bounds of an ROI + margin |
| 61 | +full.crop(center=(cx, cy), size=(w, h)) # fixed-size window |
| 62 | +``` |
| 63 | + |
| 64 | +--- |
| 65 | + |
| 66 | +## Coordinates |
| 67 | + |
| 68 | +A crop is a pure integer translation by `(x1, y1)`, so mapping landmark coordinates |
| 69 | +between source and cropped frames is exact and NaN-preserving: |
| 70 | + |
| 71 | +```python |
| 72 | +pts_crop = view.to_crop_coords(pts_source) # subtract (x1, y1) |
| 73 | +pts_source = view.to_source_coords(pts_crop) # add (x1, y1) |
| 74 | +``` |
| 75 | + |
| 76 | +On an uncropped video these are identity passthroughs, so the same call works |
| 77 | +regardless of whether a video happens to be cropped. The underlying functions live in |
| 78 | +`sleap_io.transform.points` as `crop_points` / `uncrop_points`. |
| 79 | + |
| 80 | +!!! note "Coordinates are never rewritten on disk" |
| 81 | + Virtual cropping never mutates stored `instance.points`. These helpers are |
| 82 | + read-time conveniences for presenting/ingesting coordinates in cropped-frame space. |
| 83 | + |
| 84 | +--- |
| 85 | + |
| 86 | +## Mosaics: many crops, one decode |
| 87 | + |
| 88 | +Multiple differently-cropped views of one physical file can share a single decoder, so |
| 89 | +the source frame is decoded once per read rather than once per tile: |
| 90 | + |
| 91 | +```python |
| 92 | +full = sio.load_video("session.mp4") |
| 93 | +tiles = [ |
| 94 | + full.crop((x, y, x + 128, y + 128)) # share_decode=True (default) |
| 95 | + for y in range(0, 1080 - 128, 128) |
| 96 | + for x in range(0, 1920 - 128, 128) |
| 97 | +] |
| 98 | +labels = sio.Labels(videos=tiles) |
| 99 | +``` |
| 100 | + |
| 101 | +Each tile reuses `full`'s backend as its inner reader. The tiles do **not** own that |
| 102 | +shared decoder, so closing one tile does not tear down its siblings; the owning source |
| 103 | +`Video` manages the decoder's lifetime. (Decoder sharing is intentionally not preserved |
| 104 | +across `pickle`/`deepcopy`/`open()` — each reconstruction rebuilds its own reader.) |
| 105 | + |
| 106 | +Two crops of the same file with **different** crops are kept distinct through merge, |
| 107 | +append, and matching; two crops with the **same** rect dedup to one view. |
| 108 | + |
| 109 | +--- |
| 110 | + |
| 111 | +## Saving & loading (SLP round-trip) |
| 112 | + |
| 113 | +Crops round-trip through `.slp` without breaking older readers: |
| 114 | + |
| 115 | +```python |
| 116 | +sio.save_file(labels, "mosaic.slp") |
| 117 | +labels2 = sio.load_file("mosaic.slp") |
| 118 | +labels2.videos[0]._crop_tuple() # (0, 0, 128, 128) -- preserved |
| 119 | +labels2.videos[0].shape # (1000, 128, 128, 3) |
| 120 | +labels2.videos[0].source_video.shape # (1000, 1080, 1920, 3) |
| 121 | +len(labels2.videos) # all tiles preserved (not collapsed) |
| 122 | +``` |
| 123 | + |
| 124 | +- The crop rects are stored in a dedicated top-level `/video_crops` dataset, written |
| 125 | + **only when a crop is present**; the `videos_json` entry describes the **uncropped |
| 126 | + source**. |
| 127 | +- An older reader that does not understand `/video_crops` simply loads the uncropped |
| 128 | + source video — a graceful, lossy degrade, never an error. |
| 129 | +- Files with no crops are byte-identical to before this feature existed (no |
| 130 | + `/video_crops`, no format-version bump). |
| 131 | + |
| 132 | +--- |
| 133 | + |
| 134 | +## Applying (baking) a crop to disk |
| 135 | + |
| 136 | +A virtual crop can be **materialized** to a real video file — the cropped pixels become |
| 137 | +physical and the crop is no longer a read-time view. This is coordinate-neutral: a virtual |
| 138 | +crop already presents cropped-frame coordinates, so baking the pixels leaves all point |
| 139 | +coordinates unchanged. |
| 140 | + |
| 141 | +`Video.apply_crop` bakes one cropped video and returns a new `Video` for the baked file, |
| 142 | +preserving provenance (`source_video` is the uncropped original): |
| 143 | + |
| 144 | +```python |
| 145 | +view = full.crop((320, 200, 576, 456)) |
| 146 | +baked = view.apply_crop("crop.mp4") |
| 147 | +baked.shape # (1000, 256, 256, 3) — cropped, now physical |
| 148 | +baked.source_video.shape # (1000, 1080, 1920, 3) — uncropped original |
| 149 | +baked._crop_tuple() # None — the crop is materialized, not virtual |
| 150 | +``` |
| 151 | + |
| 152 | +`Labels.apply_crops` bakes every virtually-cropped video in a `Labels` and rewires all |
| 153 | +references (labeled frames, ROIs, suggestions) to the baked files; uncropped videos are |
| 154 | +untouched and coordinates are unchanged: |
| 155 | + |
| 156 | +```python |
| 157 | +labels.apply_crops(video_dir="baked_videos/") # one file per tile, unique names |
| 158 | +``` |
| 159 | + |
| 160 | +From the command line, `sio apply-crops` materializes every virtual crop in an SLP, |
| 161 | +writing baked videos to a directory next to the output and updating the references: |
| 162 | + |
| 163 | +```bash |
| 164 | +sio apply-crops mosaic.slp -o baked.slp --video-dir baked_videos/ |
| 165 | +``` |
| 166 | + |
| 167 | +!!! note "`apply_crop` vs `sio transform --crop`" |
| 168 | + `apply_crop` materializes an **existing** virtual crop (no coordinate change). |
| 169 | + `sio transform --crop` applies a **new** crop and adjusts coordinates — that is the |
| 170 | + materializing [`transform_video`](transforms.md) / `transform_labels` path: |
| 171 | + |
| 172 | + ```python |
| 173 | + sio.transform_video(full, "baked.mp4", sio.Transform(crop=(320, 200, 576, 456))) |
| 174 | + ``` |
| 175 | + |
| 176 | +!!! info "Encoder padding" |
| 177 | + The H.264 encoder pads frame dimensions up to a multiple of 16 (bottom/right only, |
| 178 | + preserving the top-left content and coordinate alignment). A baked video whose cropped |
| 179 | + width/height are not multiples of 16 is padded on those edges. |
| 180 | + |
| 181 | +--- |
| 182 | + |
| 183 | +## Performance expectations |
| 184 | + |
| 185 | +The crop is applied **after** a full-frame decode for every backend except raw, |
| 186 | +sub-frame-chunked HDF5, where it can push the region read down to the storage layer: |
| 187 | + |
| 188 | +| Backend | Strategy | I/O effect | |
| 189 | +|---|---|---| |
| 190 | +| `MediaVideo` (mp4/H.264/…) | decode full frame, slice | **No decode/I/O savings** — inter-frame codecs must decode the whole frame; the slice is a free in-memory view. Saves resident array size only. | |
| 191 | +| `HDF5Video` raw rank-4, **sub-frame chunked** | hyperslab region read (`ds[i, y1:y2, x1:x2, :]`) | **Real I/O reduction** — only the overlapping chunks are read/decompressed. The one case where a crop saves disk work. | |
| 192 | +| `HDF5Video` raw rank-4, per-frame chunked | region read (whole chunk still fetched) | Modest — skips chunk reassembly, not I/O. | |
| 193 | +| `HDF5Video` embedded PNG/JPEG (`.pkg.slp`) | decode full image, slice | **No savings** — the whole image must be decoded before any spatial selection. | |
| 194 | +| `ImageVideo`, `TiffVideo`, `SeqVideo` | decode full frame, slice | **No savings** with the current decoders. | |
| 195 | + |
| 196 | +Pushdown for raw HDF5 is automatic and gated on the dataset's actual chunking; it falls |
| 197 | +back to a full decode plus slice (byte-identical) whenever it would not help. |
| 198 | + |
| 199 | +--- |
| 200 | + |
| 201 | +## Non-goals |
| 202 | + |
| 203 | +Virtual cropping is a pure translate-and-clip view. It deliberately does **not** do: |
| 204 | + |
| 205 | +- **Rotation, scale, pad, or flip on read** — those remain the domain of the |
| 206 | + materializing [`Transform`](transforms.md) pipeline. |
| 207 | +- **Decode-cost savings for compressed video** — only sub-frame-chunked raw HDF5 sees |
| 208 | + real I/O savings; everywhere else the crop is a free post-decode view. |
| 209 | +- **Lossless export through non-SLP writers** (NWB, COCO, JABS, Ultralytics) — those |
| 210 | + formats have no crop concept; exporting a cropped `Labels` through them is acceptably |
| 211 | + lossy (the cropped frame and its coordinates are emitted as-is). |
| 212 | +- **Rewriting on-disk point coordinates** — the source labels are never mutated. |
| 213 | + |
| 214 | +--- |
| 215 | + |
| 216 | +## See also |
| 217 | + |
| 218 | +- [Transforms](transforms.md): the materializing crop/scale/rotate/pad/flip pipeline. |
| 219 | +- [Video](model/video.md): the `Video` facade and its backends. |
0 commit comments