Update code and model card
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +1 -2
- code/README.md +38 -50
- code/agt/completion/flux_fill.py +3 -32
- code/agt/completion/handoff.py +0 -8
- code/agt/completion/reliability.py +2 -30
- code/agt/data/__init__.py +0 -1
- code/agt/data/camera.py +0 -3
- code/agt/data/clips.py +0 -20
- code/agt/data/compose.py +2 -18
- code/agt/data/grid.py +0 -15
- code/agt/data/labels.py +1 -7
- code/agt/data/protocol.py +6 -29
- code/agt/data/reader.py +0 -6
- code/agt/data/scene.py +2 -27
- code/agt/data/store.py +6 -61
- code/agt/data/video.py +1 -14
- code/agt/dataset/__init__.py +0 -1
- code/agt/dataset/build_scenes.py +1 -10
- code/agt/dataset/export.py +0 -15
- code/agt/dataset/lidar_depth.py +13 -64
- code/agt/dataset/scene_store.py +0 -38
- code/agt/dataset/sky.py +5 -24
- code/agt/dataset/video.py +0 -10
- code/agt/dataset/visibility.py +3 -30
- code/agt/dataset/waymo.py +7 -62
- code/agt/eval/__init__.py +0 -1
- code/agt/eval/depth.py +3 -36
- code/agt/eval/hole.py +1 -11
- code/agt/eval/labels.py +0 -15
- code/agt/eval/method_dir.py +0 -28
- code/agt/eval/output_grid.py +0 -13
- code/agt/eval/regional.py +1 -9
- code/agt/eval/regions.py +1 -7
- code/agt/eval/rgb.py +1 -22
- code/agt/eval/scorer.py +0 -17
- code/agt/eval/summary.py +1 -8
- code/agt/masks/__init__.py +0 -1
- code/agt/masks/io.py +0 -15
- code/agt/masks/pipeline.py +2 -25
- code/agt/masks/postprocess.py +2 -25
- code/agt/masks/proposals.py +0 -21
- code/agt/masks/sam3_proposer.py +0 -7
- code/agt/masks/sheets.py +1 -11
- code/agt/masks/verifiers/__init__.py +0 -17
- code/agt/masks/verifiers/qwen.py +1 -20
- code/agt/masks/verify.py +1 -11
- code/agt/model/build.py +0 -4
- code/agt/model/gating.py +0 -4
- code/agt/model/mask_attention.py +0 -14
- code/agt/model/runtime.py +0 -11
README.md
CHANGED
|
@@ -29,7 +29,7 @@ pass, and generates only what no frame observes.
|
|
| 29 |
| File | Content | Size |
|
| 30 |
|---|---|---|
|
| 31 |
| `agt_reconstruction.safetensors` | feed-forward reconstruction model | 4.9 GB |
|
| 32 |
-
| `agt_completion_lora.safetensors` | LoRA
|
| 33 |
| `code/` | inference, evaluation and benchmark rebuild code | |
|
| 34 |
|
| 35 |
## Usage
|
|
@@ -38,7 +38,6 @@ pass, and generates only what no frame observes.
|
|
| 38 |
hf download MRBSTUDIO/AGT --local-dir AGT-release
|
| 39 |
cd AGT-release/code
|
| 40 |
mkdir -p checkpoints && mv ../*.safetensors checkpoints/
|
| 41 |
-
# then follow code/README.md: installation, the TAPIP3D checkpoint, and the demo
|
| 42 |
```
|
| 43 |
|
| 44 |
FLUX.1-Fill-dev, SegFormer-B5, TAPIP3D, SAM 3 and Qwen3.5 are loaded from their official sources, see
|
|
|
|
| 29 |
| File | Content | Size |
|
| 30 |
|---|---|---|
|
| 31 |
| `agt_reconstruction.safetensors` | feed-forward reconstruction model | 4.9 GB |
|
| 32 |
+
| `agt_completion_lora.safetensors` | LoRA of FLUX.1 Fill used in the generative completion | 0.7 GB |
|
| 33 |
| `code/` | inference, evaluation and benchmark rebuild code | |
|
| 34 |
|
| 35 |
## Usage
|
|
|
|
| 38 |
hf download MRBSTUDIO/AGT --local-dir AGT-release
|
| 39 |
cd AGT-release/code
|
| 40 |
mkdir -p checkpoints && mv ../*.safetensors checkpoints/
|
|
|
|
| 41 |
```
|
| 42 |
|
| 43 |
FLUX.1-Fill-dev, SegFormer-B5, TAPIP3D, SAM 3 and Qwen3.5 are loaded from their official sources, see
|
code/README.md
CHANGED
|
@@ -29,12 +29,12 @@
|
|
| 29 |
AGT reconstructs a complete 4D Gaussian scene from a driving video whose every frame is partly hidden by the hood,
|
| 30 |
the dashboard, windshield reflections or watermarks.
|
| 31 |
|
| 32 |
-
- **
|
| 33 |
-
feed-forward model
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
- **AmodalDrive.** The model is trained on AmodalDrive, a paired dataset that composites occluder layers separated
|
| 39 |
from in-the-wild dashcam videos onto clean driving scenes.
|
| 40 |
|
|
@@ -44,17 +44,12 @@ the dashboard, windshield reflections or watermarks.
|
|
| 44 |
|
| 45 |
## Installation
|
| 46 |
|
| 47 |
-
Tested on Linux with CUDA 12 and one NVIDIA H200. The full chain peaks at about 36 GB of GPU memory in the
|
| 48 |
-
completion step. Reconstruction alone needs about 8 GB with 4 input frames and 17 GB with 20.
|
| 49 |
-
|
| 50 |
```bash
|
| 51 |
git clone https://github.com/MRBXCD/AGT.git
|
| 52 |
cd AGT
|
| 53 |
```
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
**Main environment** (reconstruction, refinement, evaluation):
|
| 58 |
|
| 59 |
```bash
|
| 60 |
conda create -n agt python=3.10 -y
|
|
@@ -65,7 +60,7 @@ pip install --no-build-isolation --no-binary gsplat gsplat==1.5.3
|
|
| 65 |
pip install --no-build-isolation third_party/dggt/third_party/pointops2
|
| 66 |
```
|
| 67 |
|
| 68 |
-
**Completion environment** (
|
| 69 |
|
| 70 |
```bash
|
| 71 |
conda create -n agt-completion python=3.12 -y
|
|
@@ -79,7 +74,7 @@ pip install -r requirements-completion.txt
|
|
| 79 |
|
| 80 |
- **Mask generation for your own clips**: SAM 3 and the Qwen3.5 verifier each run in their own environment. Install
|
| 81 |
SAM 3 by following its repository, and install `requirements-masks.txt` for the verifier. The verifier runs
|
| 82 |
-
`Qwen/Qwen3.5-35B-A3B` locally with vLLM
|
| 83 |
- **Benchmark rebuild**: `requirements-rebuild.txt` and a static build of ffmpeg 7.0.2.
|
| 84 |
|
| 85 |
</details>
|
|
@@ -97,20 +92,10 @@ mv checkpoints/tapip3d_final.pth checkpoints/tracking_model.pth
|
|
| 97 |
| File | Content | Size |
|
| 98 |
|---|---|---|
|
| 99 |
| `agt_reconstruction.safetensors` | feed-forward reconstruction model | 4.9 GB |
|
| 100 |
-
| `agt_completion_lora.safetensors` | LoRA
|
| 101 |
|
| 102 |
FLUX.1-Fill-dev and SegFormer are loaded from the Hugging Face Hub, or from local copies given with `--flux` and
|
| 103 |
-
`--segformer`.
|
| 104 |
-
downloads the CoTracker3 feature encoder used inside TAPIP3D through `torch.hub` and the LPIPS network weights
|
| 105 |
-
through torchvision, both cached under `$TORCH_HOME`.
|
| 106 |
-
|
| 107 |
-
| Model | Used for | Source |
|
| 108 |
-
|---|---|---|
|
| 109 |
-
| FLUX.1-Fill-dev | frame-0 completion | [black-forest-labs/FLUX.1-Fill-dev](https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev) |
|
| 110 |
-
| SegFormer-B5 Cityscapes | sky masks | [nvidia/segformer-b5-finetuned-cityscapes-1024-1024](https://huggingface.co/nvidia/segformer-b5-finetuned-cityscapes-1024-1024) |
|
| 111 |
-
| TAPIP3D | tracking of dynamic objects | [zbww/tapip3d](https://huggingface.co/zbww/tapip3d) |
|
| 112 |
-
| SAM 3 | occluder proposals for new clips | [facebookresearch/sam3](https://github.com/facebookresearch/sam3) |
|
| 113 |
-
| Qwen3.5 | occluder verification for new clips | [Qwen/Qwen3.5-35B-A3B](https://huggingface.co/Qwen/Qwen3.5-35B-A3B) |
|
| 114 |
|
| 115 |
## Demo
|
| 116 |
|
|
@@ -126,33 +111,40 @@ python inference.py \
|
|
| 126 |
--completion-python "$(conda run -n agt-completion which python)"
|
| 127 |
```
|
| 128 |
|
| 129 |
-
Add `--reconstruction-only` to
|
| 130 |
Outputs are rendered at 518x294.
|
| 131 |
|
| 132 |
## Inference on your own video
|
| 133 |
|
|
|
|
|
|
|
| 134 |
```bash
|
| 135 |
-
# 1. Cut a 20-frame clip from the video.
|
| 136 |
python tools/prepare_clip.py --video drive.mp4 --start 12 --out work/export
|
|
|
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
python tools/make_masks.py --export work/export --out work/masks --stage verify # verifier environment (requirements-masks.txt)
|
| 141 |
-
python tools/make_masks.py --export work/export --out work/masks --stage finish # main environment (CPU)
|
| 142 |
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
python inference.py --export work/export --mask-dir work/masks --out outputs/my_clip \
|
| 145 |
--completion-python "$(conda run -n agt-completion which python)"
|
| 146 |
```
|
| 147 |
|
| 148 |
-
The output directory holds the rendered frames, depth and opacity of every clip
|
| 149 |
-
intermediate reliability maps.
|
| 150 |
|
| 151 |
## Evaluation
|
| 152 |
|
| 153 |
Build the benchmark first, see [Dataset](#dataset). Both commands use the precomputed occluder masks of AmodalDrive.
|
| 154 |
|
| 155 |
-
**
|
| 156 |
|
| 157 |
```bash
|
| 158 |
python -m agt.recon.reconstruct render --inputs AmodalDrive/exports/test --out outputs/test_feedforward \
|
|
@@ -161,7 +153,7 @@ python eval/score.py --config configs/eval/test_waymo.json --data-root AmodalDri
|
|
| 161 |
--export AmodalDrive/exports/test --method outputs/test_feedforward --out scores/test_feedforward
|
| 162 |
```
|
| 163 |
|
| 164 |
-
**
|
| 165 |
|
| 166 |
```bash
|
| 167 |
python inference.py --export AmodalDrive/exports/test --masks dataset --data-root AmodalDrive \
|
|
@@ -170,8 +162,8 @@ python eval/score.py --config configs/eval/test_waymo.json --data-root AmodalDri
|
|
| 170 |
--export AmodalDrive/exports/test --method outputs/test_full/final --out scores/test_full --tables A1 A2 B
|
| 171 |
```
|
| 172 |
|
| 173 |
-
`--clips ID ...` restricts `inference.py` to a subset of the export.
|
| 174 |
-
|
| 175 |
|
| 176 |
## Dataset
|
| 177 |
|
|
@@ -183,20 +175,16 @@ hf download MRBSTUDIO/AmodalDrive --repo-type dataset --local-dir AmodalDrive
|
|
| 183 |
```
|
| 184 |
|
| 185 |
Download the [Waymo Open Dataset](https://waymo.com/open/) v2.0.1, then run the scripts below to build the composed
|
| 186 |
-
validation and test data
|
|
|
|
| 187 |
|
| 188 |
```bash
|
| 189 |
-
# Scene preprocessing.
|
| 190 |
python tools/build_waymo_scenes.py --data-root AmodalDrive --waymo-root WAYMO --split val --split test \
|
| 191 |
--ffmpeg /path/to/ffmpeg --ffprobe /path/to/ffprobe
|
| 192 |
-
|
| 193 |
-
# Labels used by the scorer.
|
| 194 |
python tools/make_labels.py depth --data-root AmodalDrive --waymo-root WAYMO --split val --split test
|
| 195 |
python tools/make_labels.py sky --data-root AmodalDrive --waymo-root WAYMO --split val --split test
|
| 196 |
python tools/make_labels.py visibility --data-root AmodalDrive --dggt-checkpoint checkpoints/model_latest_waymo.pt \
|
| 197 |
--split val --split test
|
| 198 |
-
|
| 199 |
-
# Composition and clip export.
|
| 200 |
python tools/export_clips.py --data-root AmodalDrive --split val --out AmodalDrive/exports/val
|
| 201 |
python tools/export_clips.py --data-root AmodalDrive --split test --protocol full --out AmodalDrive/exports/test
|
| 202 |
```
|
|
@@ -209,20 +197,20 @@ python tools/export_clips.py --data-root AmodalDrive --split test --protocol ful
|
|
| 209 |
|
| 210 |
```text
|
| 211 |
AGT/
|
| 212 |
-
├── inference.py runs
|
| 213 |
├── agt/
|
| 214 |
│ ├── masks/ occluder mask generation with a pluggable verifier
|
| 215 |
│ ├── prepare/ clip export from a video
|
| 216 |
-
│ ├── model/ model construction
|
| 217 |
│ ├── recon/ feed-forward reconstruction and rendering
|
| 218 |
-
│ ├── completion/
|
| 219 |
-
│ ├── refine/
|
| 220 |
│ ├── data/ AmodalDrive reader with on-the-fly composition
|
| 221 |
│ ├── dataset/ scene preprocessing and label generation
|
| 222 |
│ └── eval/ scorer
|
| 223 |
├── eval/score.py scoring entry
|
| 224 |
├── tools/ clip preparation, mask generation, benchmark rebuild
|
| 225 |
-
├── configs/ model, completion,
|
| 226 |
└── third_party/dggt/ the DGGT files used by this code
|
| 227 |
```
|
| 228 |
|
|
|
|
| 29 |
AGT reconstructs a complete 4D Gaussian scene from a driving video whose every frame is partly hidden by the hood,
|
| 30 |
the dashboard, windshield reflections or watermarks.
|
| 31 |
|
| 32 |
+
- **Amodal geometry recovery.** The occluder mask masks the occluder tokens in the attention layers, so that the
|
| 33 |
+
feed-forward model recovers cameras, depth and motion from the obstructed frames in a single pass.
|
| 34 |
+
- **Observed appearance reconstruction.** The observability of every pixel is computed from this geometry, and
|
| 35 |
+
appearance is reconstructed only in the observed regions.
|
| 36 |
+
- **Generative completion.** The unobserved regions are filled by an image diffusion model and optimized into the
|
| 37 |
+
Gaussian scene.
|
| 38 |
- **AmodalDrive.** The model is trained on AmodalDrive, a paired dataset that composites occluder layers separated
|
| 39 |
from in-the-wild dashcam videos onto clean driving scenes.
|
| 40 |
|
|
|
|
| 44 |
|
| 45 |
## Installation
|
| 46 |
|
|
|
|
|
|
|
|
|
|
| 47 |
```bash
|
| 48 |
git clone https://github.com/MRBXCD/AGT.git
|
| 49 |
cd AGT
|
| 50 |
```
|
| 51 |
|
| 52 |
+
**Main environment** (reconstruction, scene optimization, evaluation):
|
|
|
|
|
|
|
| 53 |
|
| 54 |
```bash
|
| 55 |
conda create -n agt python=3.10 -y
|
|
|
|
| 60 |
pip install --no-build-isolation third_party/dggt/third_party/pointops2
|
| 61 |
```
|
| 62 |
|
| 63 |
+
**Completion environment** (generative completion):
|
| 64 |
|
| 65 |
```bash
|
| 66 |
conda create -n agt-completion python=3.12 -y
|
|
|
|
| 74 |
|
| 75 |
- **Mask generation for your own clips**: SAM 3 and the Qwen3.5 verifier each run in their own environment. Install
|
| 76 |
SAM 3 by following its repository, and install `requirements-masks.txt` for the verifier. The verifier runs
|
| 77 |
+
`Qwen/Qwen3.5-35B-A3B` locally with vLLM.
|
| 78 |
- **Benchmark rebuild**: `requirements-rebuild.txt` and a static build of ffmpeg 7.0.2.
|
| 79 |
|
| 80 |
</details>
|
|
|
|
| 92 |
| File | Content | Size |
|
| 93 |
|---|---|---|
|
| 94 |
| `agt_reconstruction.safetensors` | feed-forward reconstruction model | 4.9 GB |
|
| 95 |
+
| `agt_completion_lora.safetensors` | LoRA of FLUX.1 Fill used in the generative completion | 0.7 GB |
|
| 96 |
|
| 97 |
FLUX.1-Fill-dev and SegFormer are loaded from the Hugging Face Hub, or from local copies given with `--flux` and
|
| 98 |
+
`--segformer`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
## Demo
|
| 101 |
|
|
|
|
| 111 |
--completion-python "$(conda run -n agt-completion which python)"
|
| 112 |
```
|
| 113 |
|
| 114 |
+
Add `--reconstruction-only` to run AGT without generative completion; this needs only the main environment.
|
| 115 |
Outputs are rendered at 518x294.
|
| 116 |
|
| 117 |
## Inference on your own video
|
| 118 |
|
| 119 |
+
Cut a 20-frame clip from the video:
|
| 120 |
+
|
| 121 |
```bash
|
|
|
|
| 122 |
python tools/prepare_clip.py --video drive.mp4 --start 12 --out work/export
|
| 123 |
+
```
|
| 124 |
|
| 125 |
+
Generate its occluder mask. SAM 3 proposes regions in the SAM 3 environment, Qwen3.5 verifies them in the verifier
|
| 126 |
+
environment, and the frames vote in the main environment:
|
|
|
|
|
|
|
| 127 |
|
| 128 |
+
```bash
|
| 129 |
+
python tools/make_masks.py --export work/export --out work/masks --stage propose
|
| 130 |
+
python tools/make_masks.py --export work/export --out work/masks --stage verify
|
| 131 |
+
python tools/make_masks.py --export work/export --out work/masks --stage finish
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
Run AGT:
|
| 135 |
+
|
| 136 |
+
```bash
|
| 137 |
python inference.py --export work/export --mask-dir work/masks --out outputs/my_clip \
|
| 138 |
--completion-python "$(conda run -n agt-completion which python)"
|
| 139 |
```
|
| 140 |
|
| 141 |
+
The output directory holds the rendered frames, depth and opacity of every clip.
|
|
|
|
| 142 |
|
| 143 |
## Evaluation
|
| 144 |
|
| 145 |
Build the benchmark first, see [Dataset](#dataset). Both commands use the precomputed occluder masks of AmodalDrive.
|
| 146 |
|
| 147 |
+
**AGT without completion** (colour, depth and region metrics):
|
| 148 |
|
| 149 |
```bash
|
| 150 |
python -m agt.recon.reconstruct render --inputs AmodalDrive/exports/test --out outputs/test_feedforward \
|
|
|
|
| 153 |
--export AmodalDrive/exports/test --method outputs/test_feedforward --out scores/test_feedforward
|
| 154 |
```
|
| 155 |
|
| 156 |
+
**AGT** (the method directory is `<out>/final`):
|
| 157 |
|
| 158 |
```bash
|
| 159 |
python inference.py --export AmodalDrive/exports/test --masks dataset --data-root AmodalDrive \
|
|
|
|
| 162 |
--export AmodalDrive/exports/test --method outputs/test_full/final --out scores/test_full --tables A1 A2 B
|
| 163 |
```
|
| 164 |
|
| 165 |
+
`--clips ID ...` restricts `inference.py` to a subset of the export. AGT is scored on the colour and region tables
|
| 166 |
+
(`--tables A1 A2 B`). `configs/eval/val_waymo.json` scores the validation export (`--split val`).
|
| 167 |
|
| 168 |
## Dataset
|
| 169 |
|
|
|
|
| 175 |
```
|
| 176 |
|
| 177 |
Download the [Waymo Open Dataset](https://waymo.com/open/) v2.0.1, then run the scripts below to build the composed
|
| 178 |
+
validation and test data. They preprocess the scenes, compute the labels used by the scorer, and compose and export
|
| 179 |
+
the clips.
|
| 180 |
|
| 181 |
```bash
|
|
|
|
| 182 |
python tools/build_waymo_scenes.py --data-root AmodalDrive --waymo-root WAYMO --split val --split test \
|
| 183 |
--ffmpeg /path/to/ffmpeg --ffprobe /path/to/ffprobe
|
|
|
|
|
|
|
| 184 |
python tools/make_labels.py depth --data-root AmodalDrive --waymo-root WAYMO --split val --split test
|
| 185 |
python tools/make_labels.py sky --data-root AmodalDrive --waymo-root WAYMO --split val --split test
|
| 186 |
python tools/make_labels.py visibility --data-root AmodalDrive --dggt-checkpoint checkpoints/model_latest_waymo.pt \
|
| 187 |
--split val --split test
|
|
|
|
|
|
|
| 188 |
python tools/export_clips.py --data-root AmodalDrive --split val --out AmodalDrive/exports/val
|
| 189 |
python tools/export_clips.py --data-root AmodalDrive --split test --protocol full --out AmodalDrive/exports/test
|
| 190 |
```
|
|
|
|
| 197 |
|
| 198 |
```text
|
| 199 |
AGT/
|
| 200 |
+
├── inference.py runs AGT on an example case, a new clip or a benchmark export
|
| 201 |
├── agt/
|
| 202 |
│ ├── masks/ occluder mask generation with a pluggable verifier
|
| 203 |
│ ├── prepare/ clip export from a video
|
| 204 |
+
│ ├── model/ model construction, masked attention and observability
|
| 205 |
│ ├── recon/ feed-forward reconstruction and rendering
|
| 206 |
+
│ ├── completion/ render completion
|
| 207 |
+
│ ├── refine/ scene optimization
|
| 208 |
│ ├── data/ AmodalDrive reader with on-the-fly composition
|
| 209 |
│ ├── dataset/ scene preprocessing and label generation
|
| 210 |
│ └── eval/ scorer
|
| 211 |
├── eval/score.py scoring entry
|
| 212 |
├── tools/ clip preparation, mask generation, benchmark rebuild
|
| 213 |
+
├── configs/ model, completion, scene optimization, mask, dataset and evaluation settings
|
| 214 |
└── third_party/dggt/ the DGGT files used by this code
|
| 215 |
```
|
| 216 |
|
code/agt/completion/flux_fill.py
CHANGED
|
@@ -1,21 +1,3 @@
|
|
| 1 |
-
"""Frame-0 completion: FLUX.1 Fill [dev] with the AGT LoRA fills the repair mask of the first rendered frame.
|
| 2 |
-
|
| 3 |
-
Inputs per clip: the first-pass render of frame 0 (frames.npz 'rgb'[0]) and the repair mask of frame 0 at tau
|
| 4 |
-
(agt.completion.reliability). No ground truth is read.
|
| 5 |
-
- resolution (no stretching): 294x518 -> PIL LANCZOS x2 to 588x1036 -> edge padding right / bottom to 592x1040
|
| 6 |
-
(FLUX needs multiples of 16: VAE x8 and 2x2 packing); the mask goes x2 nearest (pixel repeat) + the same padding.
|
| 7 |
-
The output is cropped back to 588x1036 and resized to 294x518 with PIL LANCZOS.
|
| 8 |
-
- the image and mask go to diffusers FluxFillPipeline as PIL images (mask 255 = fill); the pipeline's own
|
| 9 |
-
preprocessing, masked-image latents and channel concatenation are used unchanged.
|
| 10 |
-
- sampling: the FluxFillPipeline defaults (strength 1.0, 50 steps, guidance scale 30, max_sequence_length 512),
|
| 11 |
-
fixed seed on a CPU generator, the fixed prompt of configs/completion.json encoded once per run.
|
| 12 |
-
- LoRA: rank / alpha / target modules from the safetensors metadata, attached with peft LoraConfig
|
| 13 |
-
(init 'gaussian') + transformer.add_adapter, then the tensors are copied in.
|
| 14 |
-
Output <out>/<clip>.npz (agt.completion.handoff, positions [0]): rgb = the whole generated frame, mask = the repair mask.
|
| 15 |
-
|
| 16 |
-
python -m agt.completion.flux_fill --pass1 <first pass> --rel <reliability> --out <dir> \\
|
| 17 |
-
--base <FLUX.1-Fill-dev dir or hub id> --lora checkpoints/agt_completion_lora.safetensors
|
| 18 |
-
"""
|
| 19 |
from __future__ import annotations
|
| 20 |
|
| 21 |
import argparse
|
|
@@ -31,8 +13,8 @@ from .reliability import load_repair_mask
|
|
| 31 |
CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json'
|
| 32 |
GRID_HW = (294, 518)
|
| 33 |
SCALE = 2
|
| 34 |
-
UP_HW = (GRID_HW[0] * SCALE, GRID_HW[1] * SCALE)
|
| 35 |
-
MODEL_HW = (592, 1040)
|
| 36 |
|
| 37 |
|
| 38 |
def to_u8(rgb01):
|
|
@@ -40,7 +22,6 @@ def to_u8(rgb01):
|
|
| 40 |
|
| 41 |
|
| 42 |
def up2_rgb(frame_u8):
|
| 43 |
-
"""uint8 [294,518,3] -> uint8 [588,1036,3], PIL LANCZOS x2."""
|
| 44 |
from PIL import Image
|
| 45 |
f = np.asarray(frame_u8)
|
| 46 |
assert f.dtype == np.uint8 and f.shape[:2] == GRID_HW, f.shape
|
|
@@ -48,14 +29,12 @@ def up2_rgb(frame_u8):
|
|
| 48 |
|
| 49 |
|
| 50 |
def up2_mask(mask):
|
| 51 |
-
"""bool [294,518] -> bool [588,1036], x2 nearest (pixel repeat)."""
|
| 52 |
m = np.asarray(mask, bool)
|
| 53 |
assert m.shape == GRID_HW, m.shape
|
| 54 |
return np.repeat(np.repeat(m, SCALE, 0), SCALE, 1)
|
| 55 |
|
| 56 |
|
| 57 |
def pad_edge(a, hw=MODEL_HW):
|
| 58 |
-
"""Edge padding right / bottom to hw."""
|
| 59 |
a = np.asarray(a)
|
| 60 |
ph, pw = hw[0] - a.shape[0], hw[1] - a.shape[1]
|
| 61 |
assert ph >= 0 and pw >= 0, (a.shape, hw)
|
|
@@ -63,14 +42,12 @@ def pad_edge(a, hw=MODEL_HW):
|
|
| 63 |
|
| 64 |
|
| 65 |
def crop_pad(a, hw=UP_HW):
|
| 66 |
-
"""Inverse of pad_edge."""
|
| 67 |
a = np.asarray(a)
|
| 68 |
assert a.shape[:2] == MODEL_HW, a.shape
|
| 69 |
return a[:hw[0], :hw[1]]
|
| 70 |
|
| 71 |
|
| 72 |
def to_model(frame_u8, mask=None):
|
| 73 |
-
"""Frame u8 + repair mask -> model input (uint8 [592,1040,3], bool [592,1040] | None)."""
|
| 74 |
img = pad_edge(up2_rgb(frame_u8))
|
| 75 |
m = None if mask is None else pad_edge(up2_mask(mask))
|
| 76 |
assert img.shape == (*MODEL_HW, 3) and (m is None or m.shape == MODEL_HW)
|
|
@@ -78,7 +55,6 @@ def to_model(frame_u8, mask=None):
|
|
| 78 |
|
| 79 |
|
| 80 |
def from_model(gen_u8):
|
| 81 |
-
"""Generated uint8 [592,1040,3] -> crop the padding -> LANCZOS to uint8 [294,518,3]."""
|
| 82 |
from PIL import Image
|
| 83 |
g = crop_pad(np.asarray(gen_u8))
|
| 84 |
assert g.dtype == np.uint8 and g.shape == (*UP_HW, 3), g.shape
|
|
@@ -88,7 +64,6 @@ def from_model(gen_u8):
|
|
| 88 |
|
| 89 |
|
| 90 |
def to_pil(img_u8, mask=None):
|
| 91 |
-
"""FluxFillPipeline image / mask_image: PIL RGB and PIL L (255 = fill); already at the model size."""
|
| 92 |
from PIL import Image
|
| 93 |
im = Image.fromarray(np.asarray(img_u8, np.uint8))
|
| 94 |
return im if mask is None else (im, Image.fromarray(np.where(np.asarray(mask, bool), 255, 0).astype(np.uint8), mode='L'))
|
|
@@ -102,7 +77,6 @@ def attach_lora(transformer, rank, alpha, targets, init='gaussian', dropout=0.0)
|
|
| 102 |
|
| 103 |
|
| 104 |
def load_lora(transformer, path):
|
| 105 |
-
"""LoRA safetensors (keys = transformer parameter names, float32) -> attached and copied in (same key set)."""
|
| 106 |
from safetensors import safe_open
|
| 107 |
from safetensors.torch import load_file
|
| 108 |
with safe_open(str(path), 'pt') as f:
|
|
@@ -129,7 +103,6 @@ def load_pipeline(base, device, dtype_name='bfloat16', lora=None, revision=None)
|
|
| 129 |
|
| 130 |
|
| 131 |
def encode_prompt(pipe, prompt, device, max_sequence_length=512):
|
| 132 |
-
"""FluxFillPipeline.encode_prompt (CLIP pooled + T5, prompt_2 = None) -> (prompt_embeds, pooled_prompt_embeds)."""
|
| 133 |
import torch
|
| 134 |
with torch.no_grad():
|
| 135 |
pe, ppe, _ = pipe.encode_prompt(prompt=prompt, prompt_2=None, device=device, num_images_per_prompt=1,
|
|
@@ -138,7 +111,6 @@ def encode_prompt(pipe, prompt, device, max_sequence_length=512):
|
|
| 138 |
|
| 139 |
|
| 140 |
def generate(pipe, img_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling):
|
| 141 |
-
"""Model-size input (uint8 [H,W,3] + bool [H,W]) -> generated uint8 [H,W,3]."""
|
| 142 |
import torch
|
| 143 |
im, m = to_pil(img_u8, mask)
|
| 144 |
h, w = np.asarray(img_u8).shape[:2]
|
|
@@ -152,14 +124,13 @@ def generate(pipe, img_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling):
|
|
| 152 |
|
| 153 |
|
| 154 |
def fix_frame(pipe, frame_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling):
|
| 155 |
-
"""294x518 frame + mask -> generated whole frame uint8 [294,518,3]."""
|
| 156 |
img, m = to_model(frame_u8, mask)
|
| 157 |
return from_model(generate(pipe, img, m, prompt_embeds, pooled_prompt_embeds, sampling))
|
| 158 |
|
| 159 |
|
| 160 |
def main(argv=None):
|
| 161 |
import torch
|
| 162 |
-
p = argparse.ArgumentParser(prog='agt.completion.flux_fill'
|
| 163 |
p.add_argument('--pass1', required=True, help='first-pass output directory')
|
| 164 |
p.add_argument('--rel', required=True, help='reliability maps (agt.completion.reliability)')
|
| 165 |
p.add_argument('--out', required=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import argparse
|
|
|
|
| 13 |
CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json'
|
| 14 |
GRID_HW = (294, 518)
|
| 15 |
SCALE = 2
|
| 16 |
+
UP_HW = (GRID_HW[0] * SCALE, GRID_HW[1] * SCALE)
|
| 17 |
+
MODEL_HW = (592, 1040)
|
| 18 |
|
| 19 |
|
| 20 |
def to_u8(rgb01):
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
def up2_rgb(frame_u8):
|
|
|
|
| 25 |
from PIL import Image
|
| 26 |
f = np.asarray(frame_u8)
|
| 27 |
assert f.dtype == np.uint8 and f.shape[:2] == GRID_HW, f.shape
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
def up2_mask(mask):
|
|
|
|
| 32 |
m = np.asarray(mask, bool)
|
| 33 |
assert m.shape == GRID_HW, m.shape
|
| 34 |
return np.repeat(np.repeat(m, SCALE, 0), SCALE, 1)
|
| 35 |
|
| 36 |
|
| 37 |
def pad_edge(a, hw=MODEL_HW):
|
|
|
|
| 38 |
a = np.asarray(a)
|
| 39 |
ph, pw = hw[0] - a.shape[0], hw[1] - a.shape[1]
|
| 40 |
assert ph >= 0 and pw >= 0, (a.shape, hw)
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
def crop_pad(a, hw=UP_HW):
|
|
|
|
| 45 |
a = np.asarray(a)
|
| 46 |
assert a.shape[:2] == MODEL_HW, a.shape
|
| 47 |
return a[:hw[0], :hw[1]]
|
| 48 |
|
| 49 |
|
| 50 |
def to_model(frame_u8, mask=None):
|
|
|
|
| 51 |
img = pad_edge(up2_rgb(frame_u8))
|
| 52 |
m = None if mask is None else pad_edge(up2_mask(mask))
|
| 53 |
assert img.shape == (*MODEL_HW, 3) and (m is None or m.shape == MODEL_HW)
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
def from_model(gen_u8):
|
|
|
|
| 58 |
from PIL import Image
|
| 59 |
g = crop_pad(np.asarray(gen_u8))
|
| 60 |
assert g.dtype == np.uint8 and g.shape == (*UP_HW, 3), g.shape
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
def to_pil(img_u8, mask=None):
|
|
|
|
| 67 |
from PIL import Image
|
| 68 |
im = Image.fromarray(np.asarray(img_u8, np.uint8))
|
| 69 |
return im if mask is None else (im, Image.fromarray(np.where(np.asarray(mask, bool), 255, 0).astype(np.uint8), mode='L'))
|
|
|
|
| 77 |
|
| 78 |
|
| 79 |
def load_lora(transformer, path):
|
|
|
|
| 80 |
from safetensors import safe_open
|
| 81 |
from safetensors.torch import load_file
|
| 82 |
with safe_open(str(path), 'pt') as f:
|
|
|
|
| 103 |
|
| 104 |
|
| 105 |
def encode_prompt(pipe, prompt, device, max_sequence_length=512):
|
|
|
|
| 106 |
import torch
|
| 107 |
with torch.no_grad():
|
| 108 |
pe, ppe, _ = pipe.encode_prompt(prompt=prompt, prompt_2=None, device=device, num_images_per_prompt=1,
|
|
|
|
| 111 |
|
| 112 |
|
| 113 |
def generate(pipe, img_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling):
|
|
|
|
| 114 |
import torch
|
| 115 |
im, m = to_pil(img_u8, mask)
|
| 116 |
h, w = np.asarray(img_u8).shape[:2]
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
def fix_frame(pipe, frame_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling):
|
|
|
|
| 127 |
img, m = to_model(frame_u8, mask)
|
| 128 |
return from_model(generate(pipe, img, m, prompt_embeds, pooled_prompt_embeds, sampling))
|
| 129 |
|
| 130 |
|
| 131 |
def main(argv=None):
|
| 132 |
import torch
|
| 133 |
+
p = argparse.ArgumentParser(prog='agt.completion.flux_fill')
|
| 134 |
p.add_argument('--pass1', required=True, help='first-pass output directory')
|
| 135 |
p.add_argument('--rel', required=True, help='reliability maps (agt.completion.reliability)')
|
| 136 |
p.add_argument('--out', required=True)
|
code/agt/completion/handoff.py
CHANGED
|
@@ -1,10 +1,3 @@
|
|
| 1 |
-
"""Hand-off files between the completion and refinement steps.
|
| 2 |
-
|
| 3 |
-
<dir>/<clip>.npz: rgb float32 (n,294,518,3) in [0, 1], mask bool (n,294,518) = repair mask of each frame,
|
| 4 |
-
positions int64 (n,), meta = JSON string. The frame-0 completion writes positions [0] (rgb = the whole generated
|
| 5 |
-
frame, not pasted back into the mask); the refinement writes its renders of the input frames (positions = the input
|
| 6 |
-
frames of the first pass).
|
| 7 |
-
"""
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
import json
|
|
@@ -28,7 +21,6 @@ def write_handoff(path, rgb, mask, positions, meta):
|
|
| 28 |
|
| 29 |
|
| 30 |
def load_handoff(path, positions):
|
| 31 |
-
"""-> (rgb (n,H,W,3) float32, mask (n,H,W) bool, meta); positions must match."""
|
| 32 |
with np.load(path, allow_pickle=False) as h:
|
| 33 |
rgb, mask, pos = h['rgb'].astype(np.float32), h['mask'].astype(bool), h['positions'].tolist()
|
| 34 |
meta = json.loads(str(h['meta']))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
def load_handoff(path, positions):
|
|
|
|
| 24 |
with np.load(path, allow_pickle=False) as h:
|
| 25 |
rgb, mask, pos = h['rgb'].astype(np.float32), h['mask'].astype(bool), h['positions'].tolist()
|
| 26 |
meta = json.loads(str(h['meta']))
|
code/agt/completion/reliability.py
CHANGED
|
@@ -1,23 +1,3 @@
|
|
| 1 |
-
"""Reliability map of a first-pass render: the pixels of the rendered frames that no input frame supports.
|
| 2 |
-
|
| 3 |
-
Per clip, from the first-pass outputs of agt.recon.reconstruct (depth.npz, render_cameras.npz and render_sky.npz,
|
| 4 |
-
written with --export-render-cameras --export-render-sky) and the occluder mask of that pass:
|
| 5 |
-
- observation count n: every pixel of every rendered frame is unprojected with its rendered depth and projected into
|
| 6 |
-
each input frame; it counts once when it lands inside the image and outside that frame's occluder mask
|
| 7 |
-
(agt.model.visibility.visibility_camera on the full frame; a frame is never its own source). Input frames add a
|
| 8 |
-
self term of 1 outside their mask. With more than 8 input frames the sources go in groups of 8 and the counts add.
|
| 9 |
-
- U = (n == 0) and not (rendered sky outside the occluder mask): the sky is rendered by the sky model and has no
|
| 10 |
-
geometry; inside the occluder mask a "sky" label is the segmentation mistaking the smooth rendered occluder.
|
| 11 |
-
- holes: accumulated opacity alpha < tau and not sky (DGGT trains alpha towards 1 - sky, train.py:199).
|
| 12 |
-
- repair mask (per tau) = U or holes; ledger 0 = kept, 1 = unobserved (U), 2 = hole observed at least once.
|
| 13 |
-
Coordinates as in visibility_camera: depth = camera z, pixel i at the continuous coordinate i.
|
| 14 |
-
|
| 15 |
-
Output <out>/<clip>/reliability.npz: n, alpha, sky, depth_valid, U, holes, repair_mask, ledger (per tau), taus,
|
| 16 |
-
positions, context_positions.
|
| 17 |
-
|
| 18 |
-
python -m agt.completion.reliability --pass1 <first pass> --inputs <export> --out <dir> \\
|
| 19 |
-
--masks dataset --data-root <AmodalDrive root> # the mask options of the first pass
|
| 20 |
-
"""
|
| 21 |
from __future__ import annotations
|
| 22 |
|
| 23 |
import argparse
|
|
@@ -27,21 +7,17 @@ from pathlib import Path
|
|
| 27 |
import numpy as np
|
| 28 |
|
| 29 |
EXPORT_CONTEXT = [0, 5, 10, 15]
|
| 30 |
-
MAX_SOURCES = 8
|
| 31 |
LEDGER = {'S': 0, 'G': 1, 'R': 2}
|
| 32 |
CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json'
|
| 33 |
|
| 34 |
|
| 35 |
def source_chunks(sources):
|
| 36 |
-
"""Sources in groups of at most 8 (one group = a single call)."""
|
| 37 |
sources = list(sources)
|
| 38 |
return [sources[i:i + MAX_SOURCES] for i in range(0, len(sources), MAX_SOURCES)]
|
| 39 |
|
| 40 |
|
| 41 |
def observation_count(depth, K, c2w, mask, context_positions, *, device='cpu'):
|
| 42 |
-
"""depth (T,H,W) camera z; K (T,3,3); c2w (T,4,4); mask (T,H,W) bool occluder mask (source alpha).
|
| 43 |
-
|
| 44 |
-
Returns n uint8 (T,H,W) = count over the other input frames + self term; valid bool (T,H,W) (finite depth > 0)."""
|
| 45 |
import torch
|
| 46 |
from ..model.visibility import visibility_camera
|
| 47 |
depth = torch.as_tensor(np.asarray(depth), dtype=torch.float64, device=device)
|
|
@@ -63,8 +39,6 @@ def observation_count(depth, K, c2w, mask, context_positions, *, device='cpu'):
|
|
| 63 |
|
| 64 |
|
| 65 |
def compose(n, alpha, sky, taus, mask):
|
| 66 |
-
"""n (T,H,W); alpha (T,H,W) accumulated opacity; sky (T,H,W) bool; mask (H,W) occluder mask.
|
| 67 |
-
Returns U and holes / repair_mask / ledger of shape (len(taus),T,H,W)."""
|
| 68 |
n, alpha, sky = np.asarray(n), np.asarray(alpha, np.float32), np.asarray(sky, bool)
|
| 69 |
U = (n == 0) & ~(sky & ~np.broadcast_to(np.asarray(mask, bool), sky.shape))
|
| 70 |
holes = np.stack([(alpha < tau) & ~sky for tau in taus])
|
|
@@ -76,7 +50,6 @@ def compose(n, alpha, sky, taus, mask):
|
|
| 76 |
|
| 77 |
|
| 78 |
def load_pass1(pass1, cid):
|
| 79 |
-
"""First-pass exports of one clip: depth / alpha, render cameras, rendered sky."""
|
| 80 |
d = Path(pass1) / cid
|
| 81 |
with np.load(d / 'depth.npz') as f:
|
| 82 |
depth, alpha = f['depth'].astype(np.float32), f['alpha'].astype(np.float32)
|
|
@@ -113,7 +86,6 @@ def write_clip(out, cid, arrays):
|
|
| 113 |
|
| 114 |
|
| 115 |
def load_repair_mask(rel, cid, tau):
|
| 116 |
-
"""repair_mask (T,H,W) bool of one clip at tau."""
|
| 117 |
with np.load(Path(rel) / cid / 'reliability.npz', allow_pickle=False) as h:
|
| 118 |
taus = [round(float(x), 6) for x in h['taus']]
|
| 119 |
return h['repair_mask'][taus.index(round(float(tau), 6))].astype(bool)
|
|
@@ -121,7 +93,7 @@ def load_repair_mask(rel, cid, tau):
|
|
| 121 |
|
| 122 |
def main(argv=None):
|
| 123 |
from ..recon.reconstruct import open_masks
|
| 124 |
-
p = argparse.ArgumentParser(prog='agt.completion.reliability'
|
| 125 |
p.add_argument('--pass1', required=True, help='first-pass output directory (reconstruct with '
|
| 126 |
'--export-render-cameras --export-render-sky)')
|
| 127 |
p.add_argument('--inputs', required=True, help='clip export of the first pass')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import argparse
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
|
| 9 |
EXPORT_CONTEXT = [0, 5, 10, 15]
|
| 10 |
+
MAX_SOURCES = 8
|
| 11 |
LEDGER = {'S': 0, 'G': 1, 'R': 2}
|
| 12 |
CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json'
|
| 13 |
|
| 14 |
|
| 15 |
def source_chunks(sources):
|
|
|
|
| 16 |
sources = list(sources)
|
| 17 |
return [sources[i:i + MAX_SOURCES] for i in range(0, len(sources), MAX_SOURCES)]
|
| 18 |
|
| 19 |
|
| 20 |
def observation_count(depth, K, c2w, mask, context_positions, *, device='cpu'):
|
|
|
|
|
|
|
|
|
|
| 21 |
import torch
|
| 22 |
from ..model.visibility import visibility_camera
|
| 23 |
depth = torch.as_tensor(np.asarray(depth), dtype=torch.float64, device=device)
|
|
|
|
| 39 |
|
| 40 |
|
| 41 |
def compose(n, alpha, sky, taus, mask):
|
|
|
|
|
|
|
| 42 |
n, alpha, sky = np.asarray(n), np.asarray(alpha, np.float32), np.asarray(sky, bool)
|
| 43 |
U = (n == 0) & ~(sky & ~np.broadcast_to(np.asarray(mask, bool), sky.shape))
|
| 44 |
holes = np.stack([(alpha < tau) & ~sky for tau in taus])
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
def load_pass1(pass1, cid):
|
|
|
|
| 53 |
d = Path(pass1) / cid
|
| 54 |
with np.load(d / 'depth.npz') as f:
|
| 55 |
depth, alpha = f['depth'].astype(np.float32), f['alpha'].astype(np.float32)
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
def load_repair_mask(rel, cid, tau):
|
|
|
|
| 89 |
with np.load(Path(rel) / cid / 'reliability.npz', allow_pickle=False) as h:
|
| 90 |
taus = [round(float(x), 6) for x in h['taus']]
|
| 91 |
return h['repair_mask'][taus.index(round(float(tau), 6))].astype(bool)
|
|
|
|
| 93 |
|
| 94 |
def main(argv=None):
|
| 95 |
from ..recon.reconstruct import open_masks
|
| 96 |
+
p = argparse.ArgumentParser(prog='agt.completion.reliability')
|
| 97 |
p.add_argument('--pass1', required=True, help='first-pass output directory (reconstruct with '
|
| 98 |
'--export-render-cameras --export-render-sky)')
|
| 99 |
p.add_argument('--inputs', required=True, help='clip export of the first pass')
|
code/agt/data/__init__.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
"""Data access: clip protocol, scene index over a data root, clip reader with read-time occluder composition."""
|
| 2 |
from .protocol import ClipProtocol
|
| 3 |
from .reader import ClipReader, open_reader
|
| 4 |
|
|
|
|
|
|
|
| 1 |
from .protocol import ClipProtocol
|
| 2 |
from .reader import ClipReader, open_reader
|
| 3 |
|
code/agt/data/camera.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
"""Pinhole geometry in integer pixel coordinates; arrays use column-vector poses."""
|
| 2 |
from dataclasses import dataclass
|
| 3 |
|
| 4 |
import numpy as np
|
|
@@ -29,7 +28,6 @@ class PinholeCamera:
|
|
| 29 |
if calibration_profile == NUREC_PINHOLE_PROFILE:
|
| 30 |
if value.get('camera_id') != 'pinhole_front_v1':
|
| 31 |
raise ValueError('NuRec pinhole profile requires pinhole_front_v1')
|
| 32 |
-
# NuRec render samples are at x+0.5, y+0.5: convert once to integer pixel centres.
|
| 33 |
principal = principal - .5
|
| 34 |
elif calibration_profile != DECLARED_INTEGER_PROFILE:
|
| 35 |
raise ValueError(f'Unsupported calibration profile: {calibration_profile}')
|
|
@@ -55,7 +53,6 @@ class PinholeCamera:
|
|
| 55 |
|
| 56 |
|
| 57 |
def exposure_midpoint(frame):
|
| 58 |
-
"""Camera-to-world pose at the exposure midpoint: translation mean, rotation Slerp at 0.5."""
|
| 59 |
poses = np.asarray([frame['pose_start_camera_to_world'], frame['pose_end_camera_to_world']], dtype=np.float64)
|
| 60 |
if poses.shape != (2, 4, 4) or not np.isfinite(poses).all():
|
| 61 |
raise ValueError('Invalid camera poses')
|
|
|
|
|
|
|
| 1 |
from dataclasses import dataclass
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 28 |
if calibration_profile == NUREC_PINHOLE_PROFILE:
|
| 29 |
if value.get('camera_id') != 'pinhole_front_v1':
|
| 30 |
raise ValueError('NuRec pinhole profile requires pinhole_front_v1')
|
|
|
|
| 31 |
principal = principal - .5
|
| 32 |
elif calibration_profile != DECLARED_INTEGER_PROFILE:
|
| 33 |
raise ValueError(f'Unsupported calibration profile: {calibration_profile}')
|
|
|
|
| 53 |
|
| 54 |
|
| 55 |
def exposure_midpoint(frame):
|
|
|
|
| 56 |
poses = np.asarray([frame['pose_start_camera_to_world'], frame['pose_end_camera_to_world']], dtype=np.float64)
|
| 57 |
if poses.shape != (2, 4, 4) or not np.isfinite(poses).all():
|
| 58 |
raise ValueError('Invalid camera poses')
|
code/agt/data/clips.py
CHANGED
|
@@ -1,12 +1,3 @@
|
|
| 1 |
-
"""(protocol, scene record) -> clip records: frame numbers derived from timestamps, roles, times.
|
| 2 |
-
|
| 3 |
-
Frame selection: every sample time takes the frame whose exposure midpoint is nearest (a tie goes to the earlier
|
| 4 |
-
frame). The selection tolerance is half the scene's mean frame period unless the data declares a tolerance for the
|
| 5 |
-
scene's source (eval_sets/<version>.frame_selection.json; nuScenes 50 ms). The tolerance only decides whether a
|
| 6 |
-
window is accepted; it never changes which frame a sample takes. A window is unusable when a sample has no frame
|
| 7 |
-
within the tolerance or when two samples take the same frame; such a window is dropped (never repaired) and
|
| 8 |
-
recorded.
|
| 9 |
-
"""
|
| 10 |
from __future__ import annotations
|
| 11 |
|
| 12 |
import numpy as np
|
|
@@ -18,8 +9,6 @@ RULE_SAME_FRAME = 'same_frame_picked_twice'
|
|
| 18 |
|
| 19 |
|
| 20 |
class FrameSelectionError(ValueError):
|
| 21 |
-
"""A window's samples cannot be mapped to frames; `rules` names every violated rule."""
|
| 22 |
-
|
| 23 |
def __init__(self, message, *, rules=(), max_error_us=float('nan'), tolerance_us=float('nan')):
|
| 24 |
super().__init__(message)
|
| 25 |
self.rules, self.max_error_us, self.tolerance_us = tuple(rules), float(max_error_us), float(tolerance_us)
|
|
@@ -38,7 +27,6 @@ def frame_times(frames_meta) -> dict:
|
|
| 38 |
|
| 39 |
|
| 40 |
def nearest_frames(tau_us: np.ndarray, targets_us) -> tuple:
|
| 41 |
-
"""(pick, error_us): the nearest exposure midpoint per target, ties to the earlier frame; no checks."""
|
| 42 |
targets = np.asarray(targets_us, dtype=np.float64)
|
| 43 |
right = np.clip(np.searchsorted(tau_us, targets), 1, len(tau_us) - 1)
|
| 44 |
left = right - 1
|
|
@@ -47,13 +35,10 @@ def nearest_frames(tau_us: np.ndarray, targets_us) -> tuple:
|
|
| 47 |
|
| 48 |
|
| 49 |
def selection_tolerance_us(period_us: float, tolerance_us: float | None = None) -> float:
|
| 50 |
-
"""The data's declared tolerance, else half the scene's mean frame period."""
|
| 51 |
return float(period_us) / 2 if tolerance_us is None else float(tolerance_us)
|
| 52 |
|
| 53 |
|
| 54 |
def select_frames(tau_us: np.ndarray, targets_us, period_us: float, tolerance_us: float | None = None) -> tuple:
|
| 55 |
-
"""Nearest exposure midpoint per target; every target must be within the tolerance and no two targets may take
|
| 56 |
-
the same frame. Raises FrameSelectionError naming every violation."""
|
| 57 |
tol = selection_tolerance_us(period_us, tolerance_us)
|
| 58 |
targets = np.asarray(targets_us, dtype=np.float64)
|
| 59 |
pick, error = nearest_frames(tau_us, targets)
|
|
@@ -73,11 +58,6 @@ def select_frames(tau_us: np.ndarray, targets_us, period_us: float, tolerance_us
|
|
| 73 |
|
| 74 |
def build_clips(protocol: ClipProtocol, record, frames_meta, *, sample_id: str | None = None,
|
| 75 |
skipped: list | None = None, tolerance_us: float | None = None) -> list:
|
| 76 |
-
"""`record` is a SceneRecord; `sample_id` defaults to its scene_id.
|
| 77 |
-
|
| 78 |
-
tolerance_us: the selection tolerance the data declares for the record's source (None: half the scene's mean
|
| 79 |
-
frame period). skipped=None: an unusable window raises; with a list, such a window is left out and recorded
|
| 80 |
-
there: {sample_id, scene_id, source_id, window_start_s, reason, rules, max_error_us, tolerance_us}."""
|
| 81 |
T = int(record.frame_count)
|
| 82 |
if len(frames_meta) != T:
|
| 83 |
raise ValueError(f'{record.scene_id}: frames.jsonl has {len(frames_meta)} rows, record says {T}')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
class FrameSelectionError(ValueError):
|
|
|
|
|
|
|
| 12 |
def __init__(self, message, *, rules=(), max_error_us=float('nan'), tolerance_us=float('nan')):
|
| 13 |
super().__init__(message)
|
| 14 |
self.rules, self.max_error_us, self.tolerance_us = tuple(rules), float(max_error_us), float(tolerance_us)
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
def nearest_frames(tau_us: np.ndarray, targets_us) -> tuple:
|
|
|
|
| 30 |
targets = np.asarray(targets_us, dtype=np.float64)
|
| 31 |
right = np.clip(np.searchsorted(tau_us, targets), 1, len(tau_us) - 1)
|
| 32 |
left = right - 1
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
def selection_tolerance_us(period_us: float, tolerance_us: float | None = None) -> float:
|
|
|
|
| 38 |
return float(period_us) / 2 if tolerance_us is None else float(tolerance_us)
|
| 39 |
|
| 40 |
|
| 41 |
def select_frames(tau_us: np.ndarray, targets_us, period_us: float, tolerance_us: float | None = None) -> tuple:
|
|
|
|
|
|
|
| 42 |
tol = selection_tolerance_us(period_us, tolerance_us)
|
| 43 |
targets = np.asarray(targets_us, dtype=np.float64)
|
| 44 |
pick, error = nearest_frames(tau_us, targets)
|
|
|
|
| 58 |
|
| 59 |
def build_clips(protocol: ClipProtocol, record, frames_meta, *, sample_id: str | None = None,
|
| 60 |
skipped: list | None = None, tolerance_us: float | None = None) -> list:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
T = int(record.frame_count)
|
| 62 |
if len(frames_meta) != T:
|
| 63 |
raise ValueError(f'{record.scene_id}: frames.jsonl has {len(frames_meta)} rows, record says {T}')
|
code/agt/data/compose.py
CHANGED
|
@@ -1,10 +1,3 @@
|
|
| 1 |
-
"""Read-time composition of an occluder layer onto clean frames (float32 display space).
|
| 2 |
-
|
| 3 |
-
Day (lighting profile adaptation 'none'): compose_batch(clean, idx, layers, lighting=None).
|
| 4 |
-
Night ('night_appearance_v1'): adapt_layers(layers, roles, scene_stats, profile) once per scene re-exposes the
|
| 5 |
-
static layers to the scene (configs/dataset/lighting/<profile>.yaml), then compose_batch(clean, idx, adapted, lighting).
|
| 6 |
-
All maths of the adaptation in approximately linear light (display^2.2).
|
| 7 |
-
"""
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
import math
|
|
@@ -21,9 +14,7 @@ GAMMA = 2.2
|
|
| 21 |
LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32)
|
| 22 |
|
| 23 |
|
| 24 |
-
# ---- composition --------------------------------------------------------------------------
|
| 25 |
def to_uint8(image: np.ndarray) -> np.ndarray:
|
| 26 |
-
"""floor(clip(x, 0, 1) * 255 + 0.5)."""
|
| 27 |
return np.ascontiguousarray(
|
| 28 |
np.floor(np.clip(image, 0.0, 1.0) * 255.0 + 0.5), dtype=np.uint8
|
| 29 |
)
|
|
@@ -45,8 +36,6 @@ def compose_hybrid(clean: np.ndarray, alpha: np.ndarray, obs: np.ndarray, solid_
|
|
| 45 |
|
| 46 |
def compose_batch(clean_frames: np.ndarray, frame_indices: np.ndarray, layers: dict[str, np.ndarray],
|
| 47 |
lighting: dict | None = None) -> np.ndarray:
|
| 48 |
-
"""Compose a batch of clean frames [T,H,W,3] with prepared layers. `lighting` is the parameters block of an
|
| 49 |
-
adapting profile (night_appearance_v1) or None for the day chain."""
|
| 50 |
if clean_frames.ndim != 4 or clean_frames.shape[0] != len(frame_indices):
|
| 51 |
raise ValueError('clean_frames must be [T,H,W,3] with one index per frame')
|
| 52 |
if clean_frames.shape[1:] != layers['solid_rgb'].shape:
|
|
@@ -66,7 +55,6 @@ def compose_batch(clean_frames: np.ndarray, frame_indices: np.ndarray, layers: d
|
|
| 66 |
return np.stack([night_frame(frames[i], int(frame_indices[i]), layers, lighting) for i in range(len(frame_indices))])
|
| 67 |
|
| 68 |
|
| 69 |
-
# ---- lighting profiles --------------------------------------------------------------------
|
| 70 |
def _number(value: Any, field: str, low: float, high: float) -> float:
|
| 71 |
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not low <= value <= high:
|
| 72 |
raise ValueError(f'{field}: expected a finite number in [{low}, {high}]')
|
|
@@ -74,7 +62,6 @@ def _number(value: Any, field: str, low: float, high: float) -> float:
|
|
| 74 |
|
| 75 |
|
| 76 |
def load_lighting_profile(profile_id: str, directory=LIGHTING_DIR) -> dict[str, Any]:
|
| 77 |
-
"""Strictly validated lighting profile <directory>/<profile_id>.yaml."""
|
| 78 |
import yaml
|
| 79 |
if not isinstance(profile_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]+', profile_id):
|
| 80 |
raise ValueError('lighting profile_id: expected a safe, nonempty identifier')
|
|
@@ -138,7 +125,6 @@ def luminance(x: np.ndarray) -> np.ndarray:
|
|
| 138 |
|
| 139 |
def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray], scene_stats: dict[str, Any],
|
| 140 |
profile: dict[str, Any]) -> tuple[dict[str, np.ndarray], dict[str, Any]]:
|
| 141 |
-
"""Night re-exposure of the static layers to the target scene (scene_stats.json of the clean scene)."""
|
| 142 |
if is_identity(profile):
|
| 143 |
raise ValueError('adapt_layers is only defined for adapting profiles')
|
| 144 |
solid_cfg = profile['solid']
|
|
@@ -150,7 +136,7 @@ def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray
|
|
| 150 |
assigned = np.zeros(solid_mask.shape, bool)
|
| 151 |
gains: dict[str, Any] = {}
|
| 152 |
low, high = solid_cfg['gain_clip']
|
| 153 |
-
for role in ROLES:
|
| 154 |
mask = role_masks.get(role)
|
| 155 |
if mask is None:
|
| 156 |
continue
|
|
@@ -162,7 +148,7 @@ def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray
|
|
| 162 |
gains[role] = {'pixels': int(selected.sum()), 'day_mean_luminance': day_mean, 'gain': gain}
|
| 163 |
gain_map[selected] = gain
|
| 164 |
assigned |= selected
|
| 165 |
-
rest = solid_mask & ~assigned
|
| 166 |
if rest.any():
|
| 167 |
day_mean = float(max(lum[rest].mean(), 1e-6))
|
| 168 |
gain = float(np.clip(solid_cfg['target_over_scene_mean']['dashboard'] * scene_mean / day_mean, low, high))
|
|
@@ -186,14 +172,12 @@ def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray
|
|
| 186 |
|
| 187 |
|
| 188 |
def frame_noise(shape: tuple[int, ...], sigma: float, seed: int, frame_index: int) -> np.ndarray:
|
| 189 |
-
"""Zero-mean Gaussian noise that depends only on (seed, frame index)."""
|
| 190 |
if sigma <= 0:
|
| 191 |
return np.zeros(shape, np.float32)
|
| 192 |
return np.random.default_rng([int(seed), int(frame_index)]).normal(0.0, sigma, shape).astype(np.float32)
|
| 193 |
|
| 194 |
|
| 195 |
def night_frame(clean: np.ndarray, frame_index: int, layers: dict[str, np.ndarray], parameters: dict[str, Any]) -> np.ndarray:
|
| 196 |
-
"""One frame with the per-frame terms of night_appearance_v1 (clean and layers in display domain)."""
|
| 197 |
from scipy.ndimage import gaussian_filter
|
| 198 |
clean_lin = lin(clean)
|
| 199 |
reflection = parameters['hood_reflection']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import math
|
|
|
|
| 14 |
LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32)
|
| 15 |
|
| 16 |
|
|
|
|
| 17 |
def to_uint8(image: np.ndarray) -> np.ndarray:
|
|
|
|
| 18 |
return np.ascontiguousarray(
|
| 19 |
np.floor(np.clip(image, 0.0, 1.0) * 255.0 + 0.5), dtype=np.uint8
|
| 20 |
)
|
|
|
|
| 36 |
|
| 37 |
def compose_batch(clean_frames: np.ndarray, frame_indices: np.ndarray, layers: dict[str, np.ndarray],
|
| 38 |
lighting: dict | None = None) -> np.ndarray:
|
|
|
|
|
|
|
| 39 |
if clean_frames.ndim != 4 or clean_frames.shape[0] != len(frame_indices):
|
| 40 |
raise ValueError('clean_frames must be [T,H,W,3] with one index per frame')
|
| 41 |
if clean_frames.shape[1:] != layers['solid_rgb'].shape:
|
|
|
|
| 55 |
return np.stack([night_frame(frames[i], int(frame_indices[i]), layers, lighting) for i in range(len(frame_indices))])
|
| 56 |
|
| 57 |
|
|
|
|
| 58 |
def _number(value: Any, field: str, low: float, high: float) -> float:
|
| 59 |
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not low <= value <= high:
|
| 60 |
raise ValueError(f'{field}: expected a finite number in [{low}, {high}]')
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
def load_lighting_profile(profile_id: str, directory=LIGHTING_DIR) -> dict[str, Any]:
|
|
|
|
| 65 |
import yaml
|
| 66 |
if not isinstance(profile_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]+', profile_id):
|
| 67 |
raise ValueError('lighting profile_id: expected a safe, nonempty identifier')
|
|
|
|
| 125 |
|
| 126 |
def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray], scene_stats: dict[str, Any],
|
| 127 |
profile: dict[str, Any]) -> tuple[dict[str, np.ndarray], dict[str, Any]]:
|
|
|
|
| 128 |
if is_identity(profile):
|
| 129 |
raise ValueError('adapt_layers is only defined for adapting profiles')
|
| 130 |
solid_cfg = profile['solid']
|
|
|
|
| 136 |
assigned = np.zeros(solid_mask.shape, bool)
|
| 137 |
gains: dict[str, Any] = {}
|
| 138 |
low, high = solid_cfg['gain_clip']
|
| 139 |
+
for role in ROLES:
|
| 140 |
mask = role_masks.get(role)
|
| 141 |
if mask is None:
|
| 142 |
continue
|
|
|
|
| 148 |
gains[role] = {'pixels': int(selected.sum()), 'day_mean_luminance': day_mean, 'gain': gain}
|
| 149 |
gain_map[selected] = gain
|
| 150 |
assigned |= selected
|
| 151 |
+
rest = solid_mask & ~assigned
|
| 152 |
if rest.any():
|
| 153 |
day_mean = float(max(lum[rest].mean(), 1e-6))
|
| 154 |
gain = float(np.clip(solid_cfg['target_over_scene_mean']['dashboard'] * scene_mean / day_mean, low, high))
|
|
|
|
| 172 |
|
| 173 |
|
| 174 |
def frame_noise(shape: tuple[int, ...], sigma: float, seed: int, frame_index: int) -> np.ndarray:
|
|
|
|
| 175 |
if sigma <= 0:
|
| 176 |
return np.zeros(shape, np.float32)
|
| 177 |
return np.random.default_rng([int(seed), int(frame_index)]).normal(0.0, sigma, shape).astype(np.float32)
|
| 178 |
|
| 179 |
|
| 180 |
def night_frame(clean: np.ndarray, frame_index: int, layers: dict[str, np.ndarray], parameters: dict[str, Any]) -> np.ndarray:
|
|
|
|
| 181 |
from scipy.ndimage import gaussian_filter
|
| 182 |
clean_lin = lin(clean)
|
| 183 |
reflection = parameters['hood_reflection']
|
code/agt/data/grid.py
CHANGED
|
@@ -1,11 +1,3 @@
|
|
| 1 |
-
"""Scoring grid and the one resampling function.
|
| 2 |
-
|
| 3 |
-
``resize_float`` is the single resampler for GT frames, labels and method outputs: torch
|
| 4 |
-
``F.interpolate(mode='bilinear', antialias=True, align_corners=False)`` on CPU float32. RGB is u8/255 -> resize ->
|
| 5 |
-
floor(clip(x, 0, 1) * 255 + 0.5); binary masks are resized as float32 and thresholded at >= 0.5; continuous layers
|
| 6 |
-
are resized as is. The output is bitwise stable across thread counts and batch sizes within one torch build, but
|
| 7 |
-
not across torch builds (last ulp). Data stored on the grid (518x294) is never resampled.
|
| 8 |
-
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
import numpy as np
|
|
@@ -18,7 +10,6 @@ DIRECT = 'direct_anisotropic_full_frame'
|
|
| 18 |
|
| 19 |
|
| 20 |
def resize_float(values: np.ndarray, width: int, height: int, *, batched: bool = False) -> np.ndarray:
|
| 21 |
-
"""Resampler on CPU float32. Layouts: HxW, HxWxC (batched=False); NxHxW, NxHxWxC (batched=True)."""
|
| 22 |
import torch
|
| 23 |
import torch.nn.functional as F
|
| 24 |
x = np.asarray(values)
|
|
@@ -40,8 +31,6 @@ def resize_float(values: np.ndarray, width: int, height: int, *, batched: bool =
|
|
| 40 |
|
| 41 |
|
| 42 |
class ScoringGrid:
|
| 43 |
-
"""Grid spec from the protocol -> camera + array resampling for that grid."""
|
| 44 |
-
|
| 45 |
def __init__(self, spec: dict | None = None):
|
| 46 |
self.spec = dict(spec or GRID_518x294)
|
| 47 |
self.width, self.height = int(self.spec['width']), int(self.spec['height'])
|
|
@@ -55,25 +44,21 @@ class ScoringGrid:
|
|
| 55 |
return f'g{self.height}'
|
| 56 |
|
| 57 |
def camera(self, native: PinholeCamera) -> PinholeCamera:
|
| 58 |
-
"""fx' = fx*sx, cx' = (cx + 0.5) * sx - 0.5 (pixel centres at integers), same in y."""
|
| 59 |
sx, sy = self.width / native.width, self.height / native.height
|
| 60 |
return PinholeCamera(self.width, self.height, native.fx * sx, native.fy * sy,
|
| 61 |
(native.cx + .5) * sx - .5, (native.cy + .5) * sy - .5)
|
| 62 |
|
| 63 |
def continuous(self, layer: np.ndarray, *, batched: bool = False) -> np.ndarray:
|
| 64 |
-
"""HxW / HxWxC (or NxHxW / NxHxWxC with batched=True) float layer -> grid float32."""
|
| 65 |
layer = np.asarray(layer, dtype=np.float32)
|
| 66 |
return resize_float(layer, self.width, self.height, batched=batched)
|
| 67 |
|
| 68 |
def rgb(self, frames_u8: np.ndarray) -> np.ndarray:
|
| 69 |
-
"""(N,)H,W,3 uint8 native RGB -> grid uint8 RGB."""
|
| 70 |
frames = np.asarray(frames_u8)
|
| 71 |
if frames.dtype != np.uint8 or frames.shape[-1] != 3 or frames.ndim not in (3, 4):
|
| 72 |
raise ValueError('Expected uint8 RGB (N,)HxWx3')
|
| 73 |
return to_uint8(self.continuous(frames.astype(np.float32) / 255, batched=frames.ndim == 4))
|
| 74 |
|
| 75 |
def mask(self, mask: np.ndarray) -> np.ndarray:
|
| 76 |
-
"""(N,)HxW binary -> grid uint8 {0,1} (resize as float32, >= threshold)."""
|
| 77 |
mask = np.asarray(mask)
|
| 78 |
if mask.ndim not in (2, 3) or not np.isin(mask, (0, 1)).all():
|
| 79 |
raise ValueError('Expected a binary (N,)HxW mask')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
def resize_float(values: np.ndarray, width: int, height: int, *, batched: bool = False) -> np.ndarray:
|
|
|
|
| 13 |
import torch
|
| 14 |
import torch.nn.functional as F
|
| 15 |
x = np.asarray(values)
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
class ScoringGrid:
|
|
|
|
|
|
|
| 34 |
def __init__(self, spec: dict | None = None):
|
| 35 |
self.spec = dict(spec or GRID_518x294)
|
| 36 |
self.width, self.height = int(self.spec['width']), int(self.spec['height'])
|
|
|
|
| 44 |
return f'g{self.height}'
|
| 45 |
|
| 46 |
def camera(self, native: PinholeCamera) -> PinholeCamera:
|
|
|
|
| 47 |
sx, sy = self.width / native.width, self.height / native.height
|
| 48 |
return PinholeCamera(self.width, self.height, native.fx * sx, native.fy * sy,
|
| 49 |
(native.cx + .5) * sx - .5, (native.cy + .5) * sy - .5)
|
| 50 |
|
| 51 |
def continuous(self, layer: np.ndarray, *, batched: bool = False) -> np.ndarray:
|
|
|
|
| 52 |
layer = np.asarray(layer, dtype=np.float32)
|
| 53 |
return resize_float(layer, self.width, self.height, batched=batched)
|
| 54 |
|
| 55 |
def rgb(self, frames_u8: np.ndarray) -> np.ndarray:
|
|
|
|
| 56 |
frames = np.asarray(frames_u8)
|
| 57 |
if frames.dtype != np.uint8 or frames.shape[-1] != 3 or frames.ndim not in (3, 4):
|
| 58 |
raise ValueError('Expected uint8 RGB (N,)HxWx3')
|
| 59 |
return to_uint8(self.continuous(frames.astype(np.float32) / 255, batched=frames.ndim == 4))
|
| 60 |
|
| 61 |
def mask(self, mask: np.ndarray) -> np.ndarray:
|
|
|
|
| 62 |
mask = np.asarray(mask)
|
| 63 |
if mask.ndim not in (2, 3) or not np.isin(mask, (0, 1)).all():
|
| 64 |
raise ValueError('Expected a binary (N,)HxW mask')
|
code/agt/data/labels.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
"""Per-frame clean-scene label stores (labels/<version>/<source>/<scene>/<file>.h5), read by frame number with
|
| 2 |
-
frame / time alignment checks. Labels are validated, never rescaled."""
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import numpy as np
|
|
@@ -20,7 +18,7 @@ class FrameLabels:
|
|
| 20 |
|
| 21 |
def read(self, scene_id: str, indices, frame_count: int, timestamps_start_us=None) -> dict:
|
| 22 |
import h5py
|
| 23 |
-
self.labels.require(scene_id)
|
| 24 |
path = self.labels.path(scene_id)
|
| 25 |
if not path.is_file():
|
| 26 |
raise FileNotFoundError(f'{self.labels.name} labels missing for {scene_id}: {path}')
|
|
@@ -52,15 +50,11 @@ class FrameLabels:
|
|
| 52 |
|
| 53 |
|
| 54 |
class MotionStore(FrameLabels):
|
| 55 |
-
"""labels/motion_v2/<source>/<scene>/masks.h5 `motion_mask`."""
|
| 56 |
-
|
| 57 |
def __init__(self, root):
|
| 58 |
super().__init__(root, name='motion', layers=('motion_mask',))
|
| 59 |
|
| 60 |
|
| 61 |
class CleanSkyStore(FrameLabels):
|
| 62 |
-
"""labels/sky_v1/<source>/<scene>/sky.h5 `sky`: uint8 sky probability of the clean frames (>= 128 is sky)."""
|
| 63 |
-
|
| 64 |
def __init__(self, root):
|
| 65 |
super().__init__(root, name='sky', layers=('sky',))
|
| 66 |
if self.labels.version != 1:
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 18 |
|
| 19 |
def read(self, scene_id: str, indices, frame_count: int, timestamps_start_us=None) -> dict:
|
| 20 |
import h5py
|
| 21 |
+
self.labels.require(scene_id)
|
| 22 |
path = self.labels.path(scene_id)
|
| 23 |
if not path.is_file():
|
| 24 |
raise FileNotFoundError(f'{self.labels.name} labels missing for {scene_id}: {path}')
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
class MotionStore(FrameLabels):
|
|
|
|
|
|
|
| 53 |
def __init__(self, root):
|
| 54 |
super().__init__(root, name='motion', layers=('motion_mask',))
|
| 55 |
|
| 56 |
|
| 57 |
class CleanSkyStore(FrameLabels):
|
|
|
|
|
|
|
| 58 |
def __init__(self, root):
|
| 59 |
super().__init__(root, name='sky', layers=('sky',))
|
| 60 |
if self.labels.version != 1:
|
code/agt/data/protocol.py
CHANGED
|
@@ -1,13 +1,3 @@
|
|
| 1 |
-
"""Clip protocol: which instants of a scene form a clip, and what each one is for.
|
| 2 |
-
|
| 3 |
-
Everything is written in seconds and Hz; frame numbers are derived per scene from its timestamps (nearest exposure
|
| 4 |
-
midpoint) and stored in the clip record. On 30 fps data this gives 60-frame windows, sample stride 3 and context
|
| 5 |
-
offsets 0/15/30/45. The selection tolerance is a data-side parameter (eval_sets/<version>.frame_selection.json,
|
| 6 |
-
see agt.data.store.frame_selection); the protocol JSON is unchanged by it.
|
| 7 |
-
|
| 8 |
-
The protocol is a small JSON object. ``protocol_id`` = sha256 of its canonical JSON (sorted keys, no whitespace,
|
| 9 |
-
UTF-8).
|
| 10 |
-
"""
|
| 11 |
from __future__ import annotations
|
| 12 |
|
| 13 |
from dataclasses import dataclass, field, fields
|
|
@@ -18,8 +8,6 @@ from pathlib import Path
|
|
| 18 |
SCHEMA = 'clip_protocol_v1'
|
| 19 |
PROTOCOL_DIR = Path(__file__).resolve().parent / 'protocols'
|
| 20 |
|
| 21 |
-
# The scoring grid is the native frame resized as a whole (anisotropic, no crop), with one resampling function for
|
| 22 |
-
# GT, labels and method outputs.
|
| 23 |
GRID_518x294 = {
|
| 24 |
'width': 518,
|
| 25 |
'height': 294,
|
|
@@ -47,24 +35,20 @@ class ClipProtocol:
|
|
| 47 |
name: str = 'clips'
|
| 48 |
version: str = '1'
|
| 49 |
schema: str = SCHEMA
|
| 50 |
-
# ---- frame protocol ----
|
| 51 |
window_s: float = 2.0
|
| 52 |
sample_hz: float = 10.0
|
| 53 |
context_s: tuple = (0.0, 0.5, 1.0, 1.5)
|
| 54 |
-
# ---- windows ----
|
| 55 |
window_mode: str = 'full'
|
| 56 |
-
window_starts_s: tuple | None = None
|
| 57 |
-
full_first_s: float = 0.0
|
| 58 |
-
partial_starts_s: tuple = (0.0, 9.0)
|
| 59 |
partial_last_s: float = 17.97
|
| 60 |
duration_rule: str = 'T = frame_count * mean_frame_period; window fits if start + window_s <= T + period/2'
|
| 61 |
frame_selection: str = 'nearest_exposure_midpoint_within_half_mean_frame_period'
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
pose_reference: str = 'first_context_frame' # c2w[first context] = I
|
| 66 |
t_norm: str = '(t - t_context_first) / (t_context_last - t_context_first)'
|
| 67 |
-
# ---- scoring grid ----
|
| 68 |
grid: dict = field(default_factory=lambda: dict(GRID_518x294))
|
| 69 |
|
| 70 |
def __post_init__(self):
|
|
@@ -98,7 +82,6 @@ class ClipProtocol:
|
|
| 98 |
if key not in self.grid:
|
| 99 |
raise ValueError('grid needs ' + key)
|
| 100 |
|
| 101 |
-
# ---- sampling lattice ----------------------------------------------
|
| 102 |
def n_samples(self) -> int:
|
| 103 |
return int(round(self.window_s * self.sample_hz))
|
| 104 |
|
|
@@ -109,7 +92,6 @@ class ClipProtocol:
|
|
| 109 |
return tuple(_us(c) for c in self.context_s)
|
| 110 |
|
| 111 |
def roles(self) -> tuple:
|
| 112 |
-
"""Role of each sample, in sample order."""
|
| 113 |
ctx = self.context_us()
|
| 114 |
first, last = ctx[0], ctx[-1]
|
| 115 |
out = []
|
|
@@ -125,15 +107,12 @@ class ClipProtocol:
|
|
| 125 |
return tuple(out)
|
| 126 |
|
| 127 |
def frame_set_positions(self, which: str) -> list:
|
| 128 |
-
"""Sample positions of a frame set: heldout = interp + extrap, recon = context."""
|
| 129 |
roles = self.roles()
|
| 130 |
wanted = {'heldout': (ROLE_INTERP, ROLE_EXTRAP), 'interp': (ROLE_INTERP,),
|
| 131 |
'extrap': (ROLE_EXTRAP,), 'recon': (ROLE_CONTEXT,)}[which]
|
| 132 |
return [i for i, r in enumerate(roles) if r in wanted]
|
| 133 |
|
| 134 |
-
# ---- windows ---------------------------------------------------------
|
| 135 |
def window_starts_us(self, duration_us: float, period_us: float) -> list:
|
| 136 |
-
"""Window start times (us, scene time with frame 0 at 0) for a scene of the given duration."""
|
| 137 |
W = _us(self.window_s)
|
| 138 |
tol = period_us / 2
|
| 139 |
|
|
@@ -157,7 +136,6 @@ class ClipProtocol:
|
|
| 157 |
raise ValueError(f'windows {bad or "none"} do not fit a {duration_us/US:.4f} s scene')
|
| 158 |
return starts
|
| 159 |
|
| 160 |
-
# ---- identity --------------------------------------------------------
|
| 161 |
def to_dict(self) -> dict:
|
| 162 |
d = {f.name: getattr(self, f.name) for f in fields(self)}
|
| 163 |
for key in ('context_s', 'partial_starts_s', 'window_starts_s'):
|
|
@@ -191,7 +169,6 @@ class ClipProtocol:
|
|
| 191 |
|
| 192 |
@classmethod
|
| 193 |
def load(cls, name_or_path='partial') -> 'ClipProtocol':
|
| 194 |
-
"""A protocol by name ('partial': 3 windows per scene; 'full': consecutive windows) or a JSON file."""
|
| 195 |
path = Path(name_or_path)
|
| 196 |
if not str(name_or_path).endswith('.json'):
|
| 197 |
path = PROTOCOL_DIR / f'{name_or_path}.json'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from dataclasses import dataclass, field, fields
|
|
|
|
| 8 |
SCHEMA = 'clip_protocol_v1'
|
| 9 |
PROTOCOL_DIR = Path(__file__).resolve().parent / 'protocols'
|
| 10 |
|
|
|
|
|
|
|
| 11 |
GRID_518x294 = {
|
| 12 |
'width': 518,
|
| 13 |
'height': 294,
|
|
|
|
| 35 |
name: str = 'clips'
|
| 36 |
version: str = '1'
|
| 37 |
schema: str = SCHEMA
|
|
|
|
| 38 |
window_s: float = 2.0
|
| 39 |
sample_hz: float = 10.0
|
| 40 |
context_s: tuple = (0.0, 0.5, 1.0, 1.5)
|
|
|
|
| 41 |
window_mode: str = 'full'
|
| 42 |
+
window_starts_s: tuple | None = None
|
| 43 |
+
full_first_s: float = 0.0
|
| 44 |
+
partial_starts_s: tuple = (0.0, 9.0)
|
| 45 |
partial_last_s: float = 17.97
|
| 46 |
duration_rule: str = 'T = frame_count * mean_frame_period; window fits if start + window_s <= T + period/2'
|
| 47 |
frame_selection: str = 'nearest_exposure_midpoint_within_half_mean_frame_period'
|
| 48 |
+
frame_time: str = 'exposure_midpoint'
|
| 49 |
+
pose_time: str = 'exposure_midpoint'
|
| 50 |
+
pose_reference: str = 'first_context_frame'
|
|
|
|
| 51 |
t_norm: str = '(t - t_context_first) / (t_context_last - t_context_first)'
|
|
|
|
| 52 |
grid: dict = field(default_factory=lambda: dict(GRID_518x294))
|
| 53 |
|
| 54 |
def __post_init__(self):
|
|
|
|
| 82 |
if key not in self.grid:
|
| 83 |
raise ValueError('grid needs ' + key)
|
| 84 |
|
|
|
|
| 85 |
def n_samples(self) -> int:
|
| 86 |
return int(round(self.window_s * self.sample_hz))
|
| 87 |
|
|
|
|
| 92 |
return tuple(_us(c) for c in self.context_s)
|
| 93 |
|
| 94 |
def roles(self) -> tuple:
|
|
|
|
| 95 |
ctx = self.context_us()
|
| 96 |
first, last = ctx[0], ctx[-1]
|
| 97 |
out = []
|
|
|
|
| 107 |
return tuple(out)
|
| 108 |
|
| 109 |
def frame_set_positions(self, which: str) -> list:
|
|
|
|
| 110 |
roles = self.roles()
|
| 111 |
wanted = {'heldout': (ROLE_INTERP, ROLE_EXTRAP), 'interp': (ROLE_INTERP,),
|
| 112 |
'extrap': (ROLE_EXTRAP,), 'recon': (ROLE_CONTEXT,)}[which]
|
| 113 |
return [i for i, r in enumerate(roles) if r in wanted]
|
| 114 |
|
|
|
|
| 115 |
def window_starts_us(self, duration_us: float, period_us: float) -> list:
|
|
|
|
| 116 |
W = _us(self.window_s)
|
| 117 |
tol = period_us / 2
|
| 118 |
|
|
|
|
| 136 |
raise ValueError(f'windows {bad or "none"} do not fit a {duration_us/US:.4f} s scene')
|
| 137 |
return starts
|
| 138 |
|
|
|
|
| 139 |
def to_dict(self) -> dict:
|
| 140 |
d = {f.name: getattr(self, f.name) for f in fields(self)}
|
| 141 |
for key in ('context_s', 'partial_starts_s', 'window_starts_s'):
|
|
|
|
| 169 |
|
| 170 |
@classmethod
|
| 171 |
def load(cls, name_or_path='partial') -> 'ClipProtocol':
|
|
|
|
| 172 |
path = Path(name_or_path)
|
| 173 |
if not str(name_or_path).endswith('.json'):
|
| 174 |
path = PROTOCOL_DIR / f'{name_or_path}.json'
|
code/agt/data/reader.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
"""ClipReader: protocol x scene index -> clip list, and clip -> the arrays the scorer and the export read."""
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
from collections import OrderedDict
|
|
@@ -45,19 +44,15 @@ class ClipReader:
|
|
| 45 |
return clips
|
| 46 |
|
| 47 |
def skipped_windows(self) -> list:
|
| 48 |
-
"""Windows left out (never repaired) because a sample had no frame within the source's selection tolerance or
|
| 49 |
-
two samples took the same frame."""
|
| 50 |
self.clips()
|
| 51 |
return [w for sample_id in sorted(self._skipped) for w in self._skipped[sample_id]]
|
| 52 |
|
| 53 |
def clips(self) -> list:
|
| 54 |
-
"""Deterministic enumeration: samples in sample-key order, windows in time order."""
|
| 55 |
if self._clips is None:
|
| 56 |
self._clips = [c for record in self.index for c in self.clips_for(self.index.sample_id(record))]
|
| 57 |
return list(self._clips)
|
| 58 |
|
| 59 |
def load(self, clip: dict, *, rgb=RGB_KINDS) -> dict:
|
| 60 |
-
"""Arrays in protocol sample order: rgb_clean / rgb_dirty (uint8 on the grid), poses, times, roles, cameras."""
|
| 61 |
src = self.source(clip['sample_id'])
|
| 62 |
idx = [int(i) for i in clip['frame_indices']]
|
| 63 |
out = {'frame_indices': np.asarray(idx, dtype=np.int64),
|
|
@@ -92,6 +87,5 @@ class ClipReader:
|
|
| 92 |
|
| 93 |
def open_reader(data_root, split: str, protocol: ClipProtocol, *, map_version: str = 'v2', sources=None,
|
| 94 |
time_of_day: str = 'both', **kwargs) -> ClipReader:
|
| 95 |
-
"""ClipReader of one split of a data root (scene store rebuilt locally + the released metadata)."""
|
| 96 |
index = SceneIndex.from_data_root(data_root, split, map_version=map_version, sources=sources, time_of_day=time_of_day)
|
| 97 |
return ClipReader(index, protocol, **kwargs)
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from collections import OrderedDict
|
|
|
|
| 44 |
return clips
|
| 45 |
|
| 46 |
def skipped_windows(self) -> list:
|
|
|
|
|
|
|
| 47 |
self.clips()
|
| 48 |
return [w for sample_id in sorted(self._skipped) for w in self._skipped[sample_id]]
|
| 49 |
|
| 50 |
def clips(self) -> list:
|
|
|
|
| 51 |
if self._clips is None:
|
| 52 |
self._clips = [c for record in self.index for c in self.clips_for(self.index.sample_id(record))]
|
| 53 |
return list(self._clips)
|
| 54 |
|
| 55 |
def load(self, clip: dict, *, rgb=RGB_KINDS) -> dict:
|
|
|
|
| 56 |
src = self.source(clip['sample_id'])
|
| 57 |
idx = [int(i) for i in clip['frame_indices']]
|
| 58 |
out = {'frame_indices': np.asarray(idx, dtype=np.int64),
|
|
|
|
| 87 |
|
| 88 |
def open_reader(data_root, split: str, protocol: ClipProtocol, *, map_version: str = 'v2', sources=None,
|
| 89 |
time_of_day: str = 'both', **kwargs) -> ClipReader:
|
|
|
|
| 90 |
index = SceneIndex.from_data_root(data_root, split, map_version=map_version, sources=sources, time_of_day=time_of_day)
|
| 91 |
return ClipReader(index, protocol, **kwargs)
|
code/agt/data/scene.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
"""Scene records (where things are), scene index (which samples), label sets and scene sources (how to read one
|
| 2 |
-
sample on the protocol's grid)."""
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
from dataclasses import dataclass, field
|
|
@@ -22,18 +20,14 @@ def read_jsonl(path):
|
|
| 22 |
|
| 23 |
|
| 24 |
def native_camera(camera_json: dict, dataset_id: str) -> tuple:
|
| 25 |
-
"""Principal point as declared (NuRec cameras: pixel-edge convention converted to integer centres)."""
|
| 26 |
profile = DATASET_CAMERA_PROFILES.get(dataset_id, DECLARED_INTEGER_PROFILE)
|
| 27 |
return PinholeCamera.from_json(camera_json, calibration_profile=profile), profile
|
| 28 |
|
| 29 |
|
| 30 |
-
# ---- label sets ------------------------------------------------------------------------------
|
| 31 |
LABEL_MANIFEST = 'label_manifest.json'
|
| 32 |
|
| 33 |
|
| 34 |
class LabelSet:
|
| 35 |
-
"""Per-scene label files under one root, described by its label_manifest.json (name, version, grid, layers)."""
|
| 36 |
-
|
| 37 |
def __init__(self, root, manifest: dict):
|
| 38 |
self.root, self.manifest = Path(root), manifest
|
| 39 |
self.name, self.version = manifest['name'], int(manifest['version'])
|
|
@@ -57,21 +51,18 @@ class LabelSet:
|
|
| 57 |
|
| 58 |
@property
|
| 59 |
def unavailable(self) -> dict:
|
| 60 |
-
"""{scene_id: entry} of the root's unavailable.json (scenes this label set cannot have; {} without one)."""
|
| 61 |
if self._unavailable is None:
|
| 62 |
from .store import read_unavailable
|
| 63 |
self._unavailable = read_unavailable(self.root)
|
| 64 |
return self._unavailable
|
| 65 |
|
| 66 |
def require(self, scene_id: str):
|
| 67 |
-
"""Raise store.LabelsUnavailable when the root lists the scene as unavailable (no labels, never zeros)."""
|
| 68 |
if scene_id in self.unavailable:
|
| 69 |
from .store import unavailable_error
|
| 70 |
source = self.manifest.get('source_id', self.root.name)
|
| 71 |
raise unavailable_error(self.name, self.root.parent.name, source, [scene_id], self.unavailable, self.root)
|
| 72 |
|
| 73 |
|
| 74 |
-
# ---- records and index -----------------------------------------------------------------------
|
| 75 |
@dataclass
|
| 76 |
class SceneRecord:
|
| 77 |
dataset_id: str
|
|
@@ -79,13 +70,13 @@ class SceneRecord:
|
|
| 79 |
camera_id: str
|
| 80 |
variant_id: str
|
| 81 |
frame_count: int
|
| 82 |
-
files: dict
|
| 83 |
time_of_day: str = 'unknown'
|
| 84 |
group: str = 'unknown'
|
| 85 |
template_id: str = ''
|
| 86 |
source_id: str | None = None
|
| 87 |
fps: float | None = None
|
| 88 |
-
resolution: tuple | None = None
|
| 89 |
split: str | None = None
|
| 90 |
official_split: str | None = None
|
| 91 |
map_version: str | None = None
|
|
@@ -104,8 +95,6 @@ class SceneRecord:
|
|
| 104 |
|
| 105 |
@classmethod
|
| 106 |
def from_rows(cls, scene_row: dict, eval_row: dict, map_row: dict, data_root, template_file: str) -> 'SceneRecord':
|
| 107 |
-
"""One sample: scene-store row (where the clean scene is) + split row + map row (which layer, which lighting
|
| 108 |
-
profile, which noise seed). The obstructed frames are composed at read time."""
|
| 109 |
root = Path(data_root)
|
| 110 |
files = {'clean': str(root / scene_row['files']['rgb']['relative_path'])}
|
| 111 |
for key in ('camera', 'frames', 'scene_stats'):
|
|
@@ -125,8 +114,6 @@ class SceneRecord:
|
|
| 125 |
|
| 126 |
|
| 127 |
class SceneIndex:
|
| 128 |
-
"""Ordered samples of one split (one sample per scene)."""
|
| 129 |
-
|
| 130 |
def __init__(self, records, *, eval_set_id: str, info: dict | None = None):
|
| 131 |
self.records = sorted(records, key=lambda r: r.sample_key)
|
| 132 |
keys = [r.sample_key for r in self.records]
|
|
@@ -149,8 +136,6 @@ class SceneIndex:
|
|
| 149 |
return '__'.join(record.sample_key[1:])
|
| 150 |
|
| 151 |
def selection_tolerance_us(self, record: SceneRecord) -> float | None:
|
| 152 |
-
"""Frame-selection tolerance the data declares for the record's source; None = half the scene's mean frame
|
| 153 |
-
period."""
|
| 154 |
block = self.info.get('frame_selection')
|
| 155 |
if block is None:
|
| 156 |
return None
|
|
@@ -165,23 +150,17 @@ class SceneIndex:
|
|
| 165 |
@classmethod
|
| 166 |
def from_data_root(cls, root, split: str, *, map_version: str = 'v2', sources=None,
|
| 167 |
time_of_day: str = 'both') -> 'SceneIndex':
|
| 168 |
-
"""scenes/manifest.jsonl x eval_sets/<eval>/<split>.jsonl x maps/<map_version>/<split>.jsonl; sources: subset
|
| 169 |
-
of the map's enabled sources (None = all); time_of_day: 'day' (= day + dawn) | 'night' | 'both'."""
|
| 170 |
from .store import build_records
|
| 171 |
records, info = build_records(root, split, map_version=map_version, sources=sources, time_of_day=time_of_day)
|
| 172 |
return cls(records, eval_set_id=f"amodaldrive_map_{map_version}_{split}", info=info)
|
| 173 |
|
| 174 |
|
| 175 |
-
# ---- one sample ------------------------------------------------------------------------------
|
| 176 |
class SceneSource:
|
| 177 |
-
"""One sample, opened once: camera, timing, poses, RGB on demand."""
|
| 178 |
-
|
| 179 |
def __init__(self, record: SceneRecord, grid: ScoringGrid, *, thread_count=2, thread_type=None):
|
| 180 |
self.record, self.grid = record, grid
|
| 181 |
self.thread_count, self.thread_type = thread_count, thread_type
|
| 182 |
clean_dir = record.clean_dir
|
| 183 |
self.camera, self.calibration_profile = native_camera(read_json(clean_dir / 'camera.json'), record.dataset_id)
|
| 184 |
-
# The stored video is on the grid (518x294); a camera.json at another resolution is mapped to the grid.
|
| 185 |
self.stored_size = tuple(int(v) for v in record.resolution)
|
| 186 |
same = (self.camera.width, self.camera.height) == (grid.width, grid.height)
|
| 187 |
self.grid_camera = self.camera if same else grid.camera(self.camera)
|
|
@@ -206,7 +185,6 @@ class SceneSource:
|
|
| 206 |
return self._video
|
| 207 |
|
| 208 |
def rgb(self, kind: str, indices) -> np.ndarray:
|
| 209 |
-
"""(N, 294, 518, 3) uint8 in the order of `indices`; 'dirty' = compose(clean) with the map row's layer."""
|
| 210 |
indices = [int(i) for i in indices]
|
| 211 |
if kind == 'dirty':
|
| 212 |
return self.compose(self.rgb('clean', indices), indices)
|
|
@@ -220,19 +198,16 @@ class SceneSource:
|
|
| 220 |
return out
|
| 221 |
|
| 222 |
def template(self):
|
| 223 |
-
"""store.PreparedTemplate of this scene's map row (day layers, or night-adapted layers + parameters)."""
|
| 224 |
if self._template is None:
|
| 225 |
from .store import prepared_template
|
| 226 |
self._template = prepared_template(self.record)
|
| 227 |
return self._template
|
| 228 |
|
| 229 |
def compose(self, clean_u8, indices) -> np.ndarray:
|
| 230 |
-
"""uint8 obstructed frames from uint8 clean frames at absolute `indices`."""
|
| 231 |
from .store import compose
|
| 232 |
return compose(clean_u8, indices, self.template())
|
| 233 |
|
| 234 |
def poses(self, indices, *, reference: int) -> np.ndarray:
|
| 235 |
-
"""Exposure-midpoint camera-to-world poses relative to frame `reference`."""
|
| 236 |
indices = [int(i) for i in indices]
|
| 237 |
poses = np.stack([exposure_midpoint(self.frames_meta[i]) for i in indices])
|
| 238 |
if int(reference) == indices[0]:
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from dataclasses import dataclass, field
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
def native_camera(camera_json: dict, dataset_id: str) -> tuple:
|
|
|
|
| 23 |
profile = DATASET_CAMERA_PROFILES.get(dataset_id, DECLARED_INTEGER_PROFILE)
|
| 24 |
return PinholeCamera.from_json(camera_json, calibration_profile=profile), profile
|
| 25 |
|
| 26 |
|
|
|
|
| 27 |
LABEL_MANIFEST = 'label_manifest.json'
|
| 28 |
|
| 29 |
|
| 30 |
class LabelSet:
|
|
|
|
|
|
|
| 31 |
def __init__(self, root, manifest: dict):
|
| 32 |
self.root, self.manifest = Path(root), manifest
|
| 33 |
self.name, self.version = manifest['name'], int(manifest['version'])
|
|
|
|
| 51 |
|
| 52 |
@property
|
| 53 |
def unavailable(self) -> dict:
|
|
|
|
| 54 |
if self._unavailable is None:
|
| 55 |
from .store import read_unavailable
|
| 56 |
self._unavailable = read_unavailable(self.root)
|
| 57 |
return self._unavailable
|
| 58 |
|
| 59 |
def require(self, scene_id: str):
|
|
|
|
| 60 |
if scene_id in self.unavailable:
|
| 61 |
from .store import unavailable_error
|
| 62 |
source = self.manifest.get('source_id', self.root.name)
|
| 63 |
raise unavailable_error(self.name, self.root.parent.name, source, [scene_id], self.unavailable, self.root)
|
| 64 |
|
| 65 |
|
|
|
|
| 66 |
@dataclass
|
| 67 |
class SceneRecord:
|
| 68 |
dataset_id: str
|
|
|
|
| 70 |
camera_id: str
|
| 71 |
variant_id: str
|
| 72 |
frame_count: int
|
| 73 |
+
files: dict
|
| 74 |
time_of_day: str = 'unknown'
|
| 75 |
group: str = 'unknown'
|
| 76 |
template_id: str = ''
|
| 77 |
source_id: str | None = None
|
| 78 |
fps: float | None = None
|
| 79 |
+
resolution: tuple | None = None
|
| 80 |
split: str | None = None
|
| 81 |
official_split: str | None = None
|
| 82 |
map_version: str | None = None
|
|
|
|
| 95 |
|
| 96 |
@classmethod
|
| 97 |
def from_rows(cls, scene_row: dict, eval_row: dict, map_row: dict, data_root, template_file: str) -> 'SceneRecord':
|
|
|
|
|
|
|
| 98 |
root = Path(data_root)
|
| 99 |
files = {'clean': str(root / scene_row['files']['rgb']['relative_path'])}
|
| 100 |
for key in ('camera', 'frames', 'scene_stats'):
|
|
|
|
| 114 |
|
| 115 |
|
| 116 |
class SceneIndex:
|
|
|
|
|
|
|
| 117 |
def __init__(self, records, *, eval_set_id: str, info: dict | None = None):
|
| 118 |
self.records = sorted(records, key=lambda r: r.sample_key)
|
| 119 |
keys = [r.sample_key for r in self.records]
|
|
|
|
| 136 |
return '__'.join(record.sample_key[1:])
|
| 137 |
|
| 138 |
def selection_tolerance_us(self, record: SceneRecord) -> float | None:
|
|
|
|
|
|
|
| 139 |
block = self.info.get('frame_selection')
|
| 140 |
if block is None:
|
| 141 |
return None
|
|
|
|
| 150 |
@classmethod
|
| 151 |
def from_data_root(cls, root, split: str, *, map_version: str = 'v2', sources=None,
|
| 152 |
time_of_day: str = 'both') -> 'SceneIndex':
|
|
|
|
|
|
|
| 153 |
from .store import build_records
|
| 154 |
records, info = build_records(root, split, map_version=map_version, sources=sources, time_of_day=time_of_day)
|
| 155 |
return cls(records, eval_set_id=f"amodaldrive_map_{map_version}_{split}", info=info)
|
| 156 |
|
| 157 |
|
|
|
|
| 158 |
class SceneSource:
|
|
|
|
|
|
|
| 159 |
def __init__(self, record: SceneRecord, grid: ScoringGrid, *, thread_count=2, thread_type=None):
|
| 160 |
self.record, self.grid = record, grid
|
| 161 |
self.thread_count, self.thread_type = thread_count, thread_type
|
| 162 |
clean_dir = record.clean_dir
|
| 163 |
self.camera, self.calibration_profile = native_camera(read_json(clean_dir / 'camera.json'), record.dataset_id)
|
|
|
|
| 164 |
self.stored_size = tuple(int(v) for v in record.resolution)
|
| 165 |
same = (self.camera.width, self.camera.height) == (grid.width, grid.height)
|
| 166 |
self.grid_camera = self.camera if same else grid.camera(self.camera)
|
|
|
|
| 185 |
return self._video
|
| 186 |
|
| 187 |
def rgb(self, kind: str, indices) -> np.ndarray:
|
|
|
|
| 188 |
indices = [int(i) for i in indices]
|
| 189 |
if kind == 'dirty':
|
| 190 |
return self.compose(self.rgb('clean', indices), indices)
|
|
|
|
| 198 |
return out
|
| 199 |
|
| 200 |
def template(self):
|
|
|
|
| 201 |
if self._template is None:
|
| 202 |
from .store import prepared_template
|
| 203 |
self._template = prepared_template(self.record)
|
| 204 |
return self._template
|
| 205 |
|
| 206 |
def compose(self, clean_u8, indices) -> np.ndarray:
|
|
|
|
| 207 |
from .store import compose
|
| 208 |
return compose(clean_u8, indices, self.template())
|
| 209 |
|
| 210 |
def poses(self, indices, *, reference: int) -> np.ndarray:
|
|
|
|
| 211 |
indices = [int(i) for i in indices]
|
| 212 |
poses = np.stack([exposure_midpoint(self.frames_meta[i]) for i in indices])
|
| 213 |
if int(reference) == indices[0]:
|
code/agt/data/store.py
CHANGED
|
@@ -1,26 +1,3 @@
|
|
| 1 |
-
"""Data root: scene store + occluder-layer pool + pairing map, joined into SceneRecords; layer loading and the
|
| 2 |
-
read-time composition used by SceneSource.
|
| 3 |
-
|
| 4 |
-
Layout (all paths relative to the data root):
|
| 5 |
-
scenes/manifest.jsonl one row per rebuilt scene (source_id, dataset_id, fps, frame_count, ...)
|
| 6 |
-
scenes/<source>/<scene>/{rgb.mp4 518x294, frames.jsonl, camera.json, scene_stats.json}
|
| 7 |
-
eval_sets/<version>/<split>.jsonl the split rows (scene_id, source_id, split, ...)
|
| 8 |
-
eval_sets/<version>.frame_selection.json frame-selection tolerance per source
|
| 9 |
-
maps/<map version>/{<split>.jsonl, map.json} one row per (source, scene): template_id, lighting_profile, noise_seed
|
| 10 |
-
templates/pool.json template_id -> layer file (data-root relative) + partition
|
| 11 |
-
templates/layers/<tid>/layers_518x294.h5 8 static layers + roles/<role> masks
|
| 12 |
-
masks/ground_truth|predicted/<source>/<scene>/mask.h5 occluder masks
|
| 13 |
-
labels/<label version>/<source>/... clean-scene labels rebuilt locally (gt_visibility_v2,
|
| 14 |
-
lidar_dggt_single_v2, sky_v1, motion_v2)
|
| 15 |
-
|
| 16 |
-
Read-time composition:
|
| 17 |
-
day (lighting profile adaptation 'none'): compose_batch(clean, idx, layers, lighting=None)
|
| 18 |
-
night (adaptation 'night_appearance_v1'): adapted, meta = adapt_layers(layers, roles, scene_stats, profile) once
|
| 19 |
-
per scene; compose_batch(clean, idx, adapted, lighting=parameters)
|
| 20 |
-
with clean = decoded uint8 / 255 (float32) and the result quantised by to_uint8. `parameters` is the profile's
|
| 21 |
-
parameter block with solid.noise_seed replaced by the map row's noise_seed (unused when the profile has no frame
|
| 22 |
-
noise, as night_v2).
|
| 23 |
-
"""
|
| 24 |
from __future__ import annotations
|
| 25 |
|
| 26 |
from collections import OrderedDict
|
|
@@ -58,11 +35,7 @@ def _check(condition, message):
|
|
| 58 |
raise ValueError(message)
|
| 59 |
|
| 60 |
|
| 61 |
-
# ---- occluder layers ------------------------------------------------------------------------
|
| 62 |
def load_template_layers(data: bytes, *, source: str = '<bytes>') -> tuple:
|
| 63 |
-
"""layers_518x294.h5 -> (layers, roles, attrs) with the layer checks: names, shape, dtype, finite, [0, 1], solid
|
| 64 |
-
pixels opaque, effective_alpha == blend + (1 - blend) * alpha bitwise, bottom forced inside the solid mask. Arrays are
|
| 65 |
-
returned read-only (shared by every sample of the process)."""
|
| 66 |
import h5py
|
| 67 |
width, height = TEMPLATE_SIZE_WH
|
| 68 |
binary = {'solid_mask_hard', 'bottom_forced_mask', 'hole_filled_mask'}
|
|
@@ -106,8 +79,6 @@ def load_template_layers(data: bytes, *, source: str = '<bytes>') -> tuple:
|
|
| 106 |
|
| 107 |
|
| 108 |
class LRU:
|
| 109 |
-
"""Small per-process LRU cache."""
|
| 110 |
-
|
| 111 |
def __init__(self, capacity: int):
|
| 112 |
self.capacity = max(1, int(capacity))
|
| 113 |
self.items = OrderedDict()
|
|
@@ -129,7 +100,6 @@ _PROFILES = {}
|
|
| 129 |
|
| 130 |
|
| 131 |
def template_layers(path) -> tuple:
|
| 132 |
-
"""(layers, roles, attrs) of one layer file (cached per process)."""
|
| 133 |
return TEMPLATES.get(str(path), lambda: load_template_layers(Path(path).read_bytes(), source=str(path)))
|
| 134 |
|
| 135 |
|
|
@@ -141,7 +111,6 @@ def lighting_profile(profile_id: str) -> dict:
|
|
| 141 |
|
| 142 |
|
| 143 |
def row_parameters(parameters: dict, noise_seed: int) -> dict:
|
| 144 |
-
"""The profile's parameter block with solid.noise_seed replaced by the map row's noise seed (new dicts)."""
|
| 145 |
if isinstance(noise_seed, bool) or not isinstance(noise_seed, (int, np.integer)) or noise_seed < 0:
|
| 146 |
raise ValueError(f'noise_seed must be a nonnegative integer, got {noise_seed!r}')
|
| 147 |
return {**parameters, 'solid': {**parameters['solid'], 'noise_seed': int(noise_seed)}}
|
|
@@ -149,15 +118,12 @@ def row_parameters(parameters: dict, noise_seed: int) -> dict:
|
|
| 149 |
|
| 150 |
@dataclass(frozen=True)
|
| 151 |
class PreparedTemplate:
|
| 152 |
-
"""The layers a scene composes with (day: the layer file's; night: adapt_layers output) and the lighting block."""
|
| 153 |
layers: dict
|
| 154 |
roles: dict
|
| 155 |
parameters: dict | None
|
| 156 |
|
| 157 |
|
| 158 |
def prepared_template(record) -> PreparedTemplate:
|
| 159 |
-
"""Layers for one record (cached per process): day = the stored layers; night = adapt_layers once per
|
| 160 |
-
(layer file, scene, profile, noise seed)."""
|
| 161 |
layers, roles, _ = template_layers(record.files['template_layers'])
|
| 162 |
profile = lighting_profile(record.lighting_profile)
|
| 163 |
expected = 'none' if record.group == 'day' else 'night_appearance_v1'
|
|
@@ -179,7 +145,6 @@ def prepared_template(record) -> PreparedTemplate:
|
|
| 179 |
|
| 180 |
|
| 181 |
def compose(clean_u8: np.ndarray, indices, prepared: PreparedTemplate) -> np.ndarray:
|
| 182 |
-
"""(N, 294, 518, 3) uint8 clean at absolute frame numbers -> uint8 obstructed frames."""
|
| 183 |
from .compose import compose_batch, to_uint8
|
| 184 |
clean = np.asarray(clean_u8)
|
| 185 |
if clean.dtype != np.uint8 or clean.ndim != 4 or clean.shape[0] != len(indices):
|
|
@@ -189,14 +154,12 @@ def compose(clean_u8: np.ndarray, indices, prepared: PreparedTemplate) -> np.nda
|
|
| 189 |
lighting=prepared.parameters))
|
| 190 |
|
| 191 |
|
| 192 |
-
# ---- labels per source ----------------------------------------------------------------------
|
| 193 |
class MissingLabels(FileNotFoundError):
|
| 194 |
pass
|
| 195 |
|
| 196 |
|
| 197 |
class LabelsUnavailable(MissingLabels):
|
| 198 |
-
|
| 199 |
-
of the Waymo test scenes, whose 3D boxes are not published). Never replaced by zeros."""
|
| 200 |
|
| 201 |
|
| 202 |
UNAVAILABLE = 'unavailable.json'
|
|
@@ -207,7 +170,6 @@ def label_root(data_root, version: str, source_id: str) -> Path:
|
|
| 207 |
|
| 208 |
|
| 209 |
def read_unavailable(root) -> dict:
|
| 210 |
-
"""{scene_id: entry} of <label root>/unavailable.json ({} without one)."""
|
| 211 |
path = Path(root) / UNAVAILABLE
|
| 212 |
if not path.is_file():
|
| 213 |
return {}
|
|
@@ -226,28 +188,20 @@ def unavailable_error(name: str, version: str, source: str, scenes, entries: dic
|
|
| 226 |
f'{scenes[:5]}): {"; ".join(reasons)}; listed in {Path(root) / UNAVAILABLE}')
|
| 227 |
|
| 228 |
|
| 229 |
-
# ---- frame selection ------------------------------------------------------------------------
|
| 230 |
FRAME_SELECTION_SUFFIX = '.frame_selection.json'
|
| 231 |
SELECTION_SCENE_MEAN = 'half_scene_mean_frame_period'
|
| 232 |
SELECTION_LONGEST_REGULAR = 'half_longest_regular_interval'
|
| 233 |
FRAME_SELECTION_PARAMETERS = {
|
| 234 |
'interval': 'exposure midpoint (timestamp_start_us + timestamp_end_us) / 2 of frame k+1 minus that of frame k',
|
| 235 |
-
'bin_us': 10_000,
|
| 236 |
-
'regular_share': 0.05,
|
| 237 |
-
'dropout_periods': 1.5,
|
| 238 |
-
'cadence_tolerance': 0.01,
|
| 239 |
-
'long_interval_rounding_us': 1_000,
|
| 240 |
}
|
| 241 |
-
# Rule: pool the exposure-midpoint intervals of every scene of a source, round each to the nearest 10 ms; a value
|
| 242 |
-
# holding at least 5 % of the intervals is frequent. With the nominal period P = 1 / fps, a frequent value of at
|
| 243 |
-
# least 1.5 P is a dropped-frame interval; the other frequent values are the regular intervals, whose mean must be
|
| 244 |
-
# within 1 % of P. Two or more regular intervals with that mean (nuScenes front camera: 50 and 100 ms):
|
| 245 |
-
# tolerance = half the longest (median of its intervals in whole ms). Otherwise (evenly spaced frames, e.g. Waymo):
|
| 246 |
-
# tolerance = half the scene's mean frame period.
|
| 247 |
|
| 248 |
|
| 249 |
def selection_from_histogram(histogram: dict, medians: dict, means: dict, fps, parameters: dict) -> dict:
|
| 250 |
-
"""Selection and tolerance of a source from its interval histogram {value_ms: count} and the nominal fps."""
|
| 251 |
total = sum(int(k) for k in histogram.values())
|
| 252 |
_check(total > 0, 'empty interval histogram')
|
| 253 |
_check(fps is not None and float(fps) > 0, f'nominal fps {fps!r} is not positive')
|
|
@@ -270,8 +224,6 @@ def selection_from_histogram(histogram: dict, medians: dict, means: dict, fps, p
|
|
| 270 |
|
| 271 |
|
| 272 |
def frame_selection(root, eval_path: str, sources) -> dict:
|
| 273 |
-
"""{source: {'selection', 'tolerance_us'}} from eval_sets/<version>.frame_selection.json (tolerance None = half
|
| 274 |
-
the scene's mean frame period; also used for every source when the file is absent)."""
|
| 275 |
path = Path(root) / (str(eval_path).rstrip('/') + FRAME_SELECTION_SUFFIX)
|
| 276 |
if not path.is_file():
|
| 277 |
return {s: {'selection': SELECTION_SCENE_MEAN, 'tolerance_us': None} for s in sources}
|
|
@@ -290,10 +242,7 @@ def frame_selection(root, eval_path: str, sources) -> dict:
|
|
| 290 |
return out
|
| 291 |
|
| 292 |
|
| 293 |
-
# ---- index building -------------------------------------------------------------------------
|
| 294 |
def manifest_records(root, source_id: str, scene_ids=None) -> list:
|
| 295 |
-
"""Clean-only SceneRecords of every scenes/manifest.jsonl row of one source, sorted by scene_id (label generators:
|
| 296 |
-
a label set covers all scenes of a source; no split, map or layer is involved; rgb('dirty') is not available)."""
|
| 297 |
from .scene import SceneRecord
|
| 298 |
root = Path(root)
|
| 299 |
rows = [r for r in read_jsonl(root / SCENE_MANIFEST) if r['source_id'] == source_id]
|
|
@@ -320,10 +269,6 @@ def manifest_records(root, source_id: str, scene_ids=None) -> list:
|
|
| 320 |
|
| 321 |
|
| 322 |
def build_records(root, split: str, *, map_version: str = 'v2', sources=None, time_of_day: str = 'both') -> tuple:
|
| 323 |
-
"""(records, info) of one split: scenes/manifest.jsonl x eval_sets/<eval>/<split>.jsonl x
|
| 324 |
-
maps/<map_version>/<split>.jsonl (the eval version and the layer pool come from map.json). Every scene of the
|
| 325 |
-
split (for the selected sources) must have exactly one map row (and vice versa) and a scene-store row; rows are
|
| 326 |
-
cross-checked field by field."""
|
| 327 |
from .scene import SceneRecord
|
| 328 |
root = Path(root)
|
| 329 |
if time_of_day not in TIME_OF_DAY_FILTERS:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from collections import OrderedDict
|
|
|
|
| 35 |
raise ValueError(message)
|
| 36 |
|
| 37 |
|
|
|
|
| 38 |
def load_template_layers(data: bytes, *, source: str = '<bytes>') -> tuple:
|
|
|
|
|
|
|
|
|
|
| 39 |
import h5py
|
| 40 |
width, height = TEMPLATE_SIZE_WH
|
| 41 |
binary = {'solid_mask_hard', 'bottom_forced_mask', 'hole_filled_mask'}
|
|
|
|
| 79 |
|
| 80 |
|
| 81 |
class LRU:
|
|
|
|
|
|
|
| 82 |
def __init__(self, capacity: int):
|
| 83 |
self.capacity = max(1, int(capacity))
|
| 84 |
self.items = OrderedDict()
|
|
|
|
| 100 |
|
| 101 |
|
| 102 |
def template_layers(path) -> tuple:
|
|
|
|
| 103 |
return TEMPLATES.get(str(path), lambda: load_template_layers(Path(path).read_bytes(), source=str(path)))
|
| 104 |
|
| 105 |
|
|
|
|
| 111 |
|
| 112 |
|
| 113 |
def row_parameters(parameters: dict, noise_seed: int) -> dict:
|
|
|
|
| 114 |
if isinstance(noise_seed, bool) or not isinstance(noise_seed, (int, np.integer)) or noise_seed < 0:
|
| 115 |
raise ValueError(f'noise_seed must be a nonnegative integer, got {noise_seed!r}')
|
| 116 |
return {**parameters, 'solid': {**parameters['solid'], 'noise_seed': int(noise_seed)}}
|
|
|
|
| 118 |
|
| 119 |
@dataclass(frozen=True)
|
| 120 |
class PreparedTemplate:
|
|
|
|
| 121 |
layers: dict
|
| 122 |
roles: dict
|
| 123 |
parameters: dict | None
|
| 124 |
|
| 125 |
|
| 126 |
def prepared_template(record) -> PreparedTemplate:
|
|
|
|
|
|
|
| 127 |
layers, roles, _ = template_layers(record.files['template_layers'])
|
| 128 |
profile = lighting_profile(record.lighting_profile)
|
| 129 |
expected = 'none' if record.group == 'day' else 'night_appearance_v1'
|
|
|
|
| 145 |
|
| 146 |
|
| 147 |
def compose(clean_u8: np.ndarray, indices, prepared: PreparedTemplate) -> np.ndarray:
|
|
|
|
| 148 |
from .compose import compose_batch, to_uint8
|
| 149 |
clean = np.asarray(clean_u8)
|
| 150 |
if clean.dtype != np.uint8 or clean.ndim != 4 or clean.shape[0] != len(indices):
|
|
|
|
| 154 |
lighting=prepared.parameters))
|
| 155 |
|
| 156 |
|
|
|
|
| 157 |
class MissingLabels(FileNotFoundError):
|
| 158 |
pass
|
| 159 |
|
| 160 |
|
| 161 |
class LabelsUnavailable(MissingLabels):
|
| 162 |
+
pass
|
|
|
|
| 163 |
|
| 164 |
|
| 165 |
UNAVAILABLE = 'unavailable.json'
|
|
|
|
| 170 |
|
| 171 |
|
| 172 |
def read_unavailable(root) -> dict:
|
|
|
|
| 173 |
path = Path(root) / UNAVAILABLE
|
| 174 |
if not path.is_file():
|
| 175 |
return {}
|
|
|
|
| 188 |
f'{scenes[:5]}): {"; ".join(reasons)}; listed in {Path(root) / UNAVAILABLE}')
|
| 189 |
|
| 190 |
|
|
|
|
| 191 |
FRAME_SELECTION_SUFFIX = '.frame_selection.json'
|
| 192 |
SELECTION_SCENE_MEAN = 'half_scene_mean_frame_period'
|
| 193 |
SELECTION_LONGEST_REGULAR = 'half_longest_regular_interval'
|
| 194 |
FRAME_SELECTION_PARAMETERS = {
|
| 195 |
'interval': 'exposure midpoint (timestamp_start_us + timestamp_end_us) / 2 of frame k+1 minus that of frame k',
|
| 196 |
+
'bin_us': 10_000,
|
| 197 |
+
'regular_share': 0.05,
|
| 198 |
+
'dropout_periods': 1.5,
|
| 199 |
+
'cadence_tolerance': 0.01,
|
| 200 |
+
'long_interval_rounding_us': 1_000,
|
| 201 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
|
| 204 |
def selection_from_histogram(histogram: dict, medians: dict, means: dict, fps, parameters: dict) -> dict:
|
|
|
|
| 205 |
total = sum(int(k) for k in histogram.values())
|
| 206 |
_check(total > 0, 'empty interval histogram')
|
| 207 |
_check(fps is not None and float(fps) > 0, f'nominal fps {fps!r} is not positive')
|
|
|
|
| 224 |
|
| 225 |
|
| 226 |
def frame_selection(root, eval_path: str, sources) -> dict:
|
|
|
|
|
|
|
| 227 |
path = Path(root) / (str(eval_path).rstrip('/') + FRAME_SELECTION_SUFFIX)
|
| 228 |
if not path.is_file():
|
| 229 |
return {s: {'selection': SELECTION_SCENE_MEAN, 'tolerance_us': None} for s in sources}
|
|
|
|
| 242 |
return out
|
| 243 |
|
| 244 |
|
|
|
|
| 245 |
def manifest_records(root, source_id: str, scene_ids=None) -> list:
|
|
|
|
|
|
|
| 246 |
from .scene import SceneRecord
|
| 247 |
root = Path(root)
|
| 248 |
rows = [r for r in read_jsonl(root / SCENE_MANIFEST) if r['source_id'] == source_id]
|
|
|
|
| 269 |
|
| 270 |
|
| 271 |
def build_records(root, split: str, *, map_version: str = 'v2', sources=None, time_of_day: str = 'both') -> tuple:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
from .scene import SceneRecord
|
| 273 |
root = Path(root)
|
| 274 |
if time_of_day not in TIME_OF_DAY_FILTERS:
|
code/agt/data/video.py
CHANGED
|
@@ -1,11 +1,3 @@
|
|
| 1 |
-
"""One frame-fetch function: seek to the keyframe at or before the first wanted frame, then decode forward and keep
|
| 2 |
-
what was asked.
|
| 3 |
-
|
| 4 |
-
The scene videos are HEVC open-GOP (IDR at 0, CRA every 30 frames with RASL leading pictures) and mp4 indexes packets
|
| 5 |
-
by dts, so a naive pts seek can land on the next CRA and lose the wanted frame. Here frame identity comes from packet
|
| 6 |
-
pts, the seek goes to the keyframe packet's dts, and a landing that misses a wanted frame steps back one keyframe and
|
| 7 |
-
retries (reaching 0 = full sequential decode). Pixel values are bitwise those of a sequential decode.
|
| 8 |
-
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
from pathlib import Path
|
|
@@ -14,8 +6,6 @@ import numpy as np
|
|
| 14 |
|
| 15 |
|
| 16 |
class VideoSource:
|
| 17 |
-
"""Lazy container; pts index built once per file by demuxing (no decode)."""
|
| 18 |
-
|
| 19 |
def __init__(self, path, *, thread_count=2, thread_type=None, expected_frames=None):
|
| 20 |
self.path = Path(path)
|
| 21 |
if not self.path.is_file():
|
|
@@ -53,7 +43,7 @@ class VideoSource:
|
|
| 53 |
try:
|
| 54 |
pts, dts, key = [], [], []
|
| 55 |
for packet in container.demux(stream):
|
| 56 |
-
if packet.pts is None:
|
| 57 |
continue
|
| 58 |
pts.append(int(packet.pts)); key.append(bool(packet.is_keyframe))
|
| 59 |
dts.append(int(packet.dts) if packet.dts is not None else int(packet.pts))
|
|
@@ -76,7 +66,6 @@ class VideoSource:
|
|
| 76 |
self._ensure_index(); return int(len(self._pts))
|
| 77 |
|
| 78 |
def decode_native(self, indices, *, allow_seek=True) -> dict:
|
| 79 |
-
"""{absolute_frame_index: HxWx3 uint8 rgb24} for the requested indices."""
|
| 80 |
wanted = sorted({int(i) for i in indices})
|
| 81 |
if not wanted:
|
| 82 |
raise ValueError('Empty frame selection')
|
|
@@ -87,7 +76,6 @@ class VideoSource:
|
|
| 87 |
self._container, self._stream = self._open()
|
| 88 |
container, stream = self._container, self._stream
|
| 89 |
keyframes = np.flatnonzero(self._keyframe)
|
| 90 |
-
# Keyframe at or before the first wanted frame, in display order; seek to that packet's dts.
|
| 91 |
k = int(keyframes[np.searchsorted(keyframes, wanted[0], side='right') - 1]) if allow_seek else 0
|
| 92 |
while True:
|
| 93 |
container.seek(int(self._dts[k]), backward=True, any_frame=False, stream=stream)
|
|
@@ -106,6 +94,5 @@ class VideoSource:
|
|
| 106 |
return out
|
| 107 |
if k == 0:
|
| 108 |
raise ValueError(f'{self.path}: missing frames {sorted(wanted_set - set(out))} even from the start')
|
| 109 |
-
# Landed after the first wanted frame or pictures were dropped: step back one keyframe and retry.
|
| 110 |
k = int(keyframes[np.searchsorted(keyframes, k, side='left') - 1])
|
| 111 |
self.close(); self._container, self._stream = self._open(); container, stream = self._container, self._stream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from pathlib import Path
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
class VideoSource:
|
|
|
|
|
|
|
| 9 |
def __init__(self, path, *, thread_count=2, thread_type=None, expected_frames=None):
|
| 10 |
self.path = Path(path)
|
| 11 |
if not self.path.is_file():
|
|
|
|
| 43 |
try:
|
| 44 |
pts, dts, key = [], [], []
|
| 45 |
for packet in container.demux(stream):
|
| 46 |
+
if packet.pts is None:
|
| 47 |
continue
|
| 48 |
pts.append(int(packet.pts)); key.append(bool(packet.is_keyframe))
|
| 49 |
dts.append(int(packet.dts) if packet.dts is not None else int(packet.pts))
|
|
|
|
| 66 |
self._ensure_index(); return int(len(self._pts))
|
| 67 |
|
| 68 |
def decode_native(self, indices, *, allow_seek=True) -> dict:
|
|
|
|
| 69 |
wanted = sorted({int(i) for i in indices})
|
| 70 |
if not wanted:
|
| 71 |
raise ValueError('Empty frame selection')
|
|
|
|
| 76 |
self._container, self._stream = self._open()
|
| 77 |
container, stream = self._container, self._stream
|
| 78 |
keyframes = np.flatnonzero(self._keyframe)
|
|
|
|
| 79 |
k = int(keyframes[np.searchsorted(keyframes, wanted[0], side='right') - 1]) if allow_seek else 0
|
| 80 |
while True:
|
| 81 |
container.seek(int(self._dts[k]), backward=True, any_frame=False, stream=stream)
|
|
|
|
| 94 |
return out
|
| 95 |
if k == 0:
|
| 96 |
raise ValueError(f'{self.path}: missing frames {sorted(wanted_set - set(out))} even from the start')
|
|
|
|
| 97 |
k = int(keyframes[np.searchsorted(keyframes, k, side='left') - 1])
|
| 98 |
self.close(); self._container, self._stream = self._open(); container, stream = self._container, self._stream
|
code/agt/dataset/__init__.py
CHANGED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
"""Rebuild of the Waymo scene store, the Waymo-derived labels and the clip exports from a local Waymo download."""
|
|
|
|
|
|
code/agt/dataset/build_scenes.py
CHANGED
|
@@ -1,10 +1,3 @@
|
|
| 1 |
-
"""Build the Waymo part of the scene store from a local Waymo Open Dataset v2.0.1 download.
|
| 2 |
-
|
| 3 |
-
Per segment: scenes/waymo/<segment>/{rgb.mp4 518x294 HEVC crf 14, frames.jsonl, camera.json, scene_stats.json} and one
|
| 4 |
-
row in scenes/manifest.jsonl. Image rule: JPEG 1920x1280 -> rows [100, 1180) -> PIL BICUBIC 518x294 -> libx265
|
| 5 |
-
(yuv420p, GOP 30, crf 14). A segment whose manifest row has the current transcode identity and whose files match the
|
| 6 |
-
row's sha256 is skipped.
|
| 7 |
-
"""
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
import collections
|
|
@@ -34,7 +27,6 @@ def current_identity(ffmpeg: str, ffprobe: str) -> dict:
|
|
| 34 |
|
| 35 |
|
| 36 |
def split_segments(data_root: Path, split: str) -> list[tuple[str, str]]:
|
| 37 |
-
"""(official Waymo split, segment) of every Waymo scene of eval_sets/v2/<split>.jsonl."""
|
| 38 |
rows = [json.loads(line) for line in (Path(data_root) / "eval_sets/v2" / f"{split}.jsonl").read_text().splitlines()
|
| 39 |
if line.strip()]
|
| 40 |
return [(r["origin_split"], r["scene_id"]) for r in rows if r["source_id"] == SOURCE_ID]
|
|
@@ -70,13 +62,12 @@ def convert_segment(task: dict) -> dict:
|
|
| 70 |
size=waymo.SIZE, native_size=waymo.NATIVE_SIZE, transcode=task["identity"], provenance=provenance,
|
| 71 |
extra={"official_split": split, "location": data.stats["location"], "weather": data.stats["weather"]})
|
| 72 |
return {"status": "converted", "scene_id": segment, "row": row, "seconds": time.time() - started}
|
| 73 |
-
except Exception:
|
| 74 |
return {"status": "failed", "scene_id": segment, "error": traceback.format_exc(), "seconds": time.time() - started}
|
| 75 |
|
| 76 |
|
| 77 |
def build(out: Path, raw: Path, segments: list[tuple[str, str]], *, ffmpeg: str = "ffmpeg", ffprobe: str = "ffprobe",
|
| 78 |
workers: int = 3) -> int:
|
| 79 |
-
"""Convert (split, segment) pairs into the scene store of ``out``; returns the number of failed segments."""
|
| 80 |
started = time.time()
|
| 81 |
out, raw = Path(out).resolve(), Path(raw).resolve()
|
| 82 |
identity = current_identity(ffmpeg, ffprobe)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import collections
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
def split_segments(data_root: Path, split: str) -> list[tuple[str, str]]:
|
|
|
|
| 30 |
rows = [json.loads(line) for line in (Path(data_root) / "eval_sets/v2" / f"{split}.jsonl").read_text().splitlines()
|
| 31 |
if line.strip()]
|
| 32 |
return [(r["origin_split"], r["scene_id"]) for r in rows if r["source_id"] == SOURCE_ID]
|
|
|
|
| 62 |
size=waymo.SIZE, native_size=waymo.NATIVE_SIZE, transcode=task["identity"], provenance=provenance,
|
| 63 |
extra={"official_split": split, "location": data.stats["location"], "weather": data.stats["weather"]})
|
| 64 |
return {"status": "converted", "scene_id": segment, "row": row, "seconds": time.time() - started}
|
| 65 |
+
except Exception:
|
| 66 |
return {"status": "failed", "scene_id": segment, "error": traceback.format_exc(), "seconds": time.time() - started}
|
| 67 |
|
| 68 |
|
| 69 |
def build(out: Path, raw: Path, segments: list[tuple[str, str]], *, ffmpeg: str = "ffmpeg", ffprobe: str = "ffprobe",
|
| 70 |
workers: int = 3) -> int:
|
|
|
|
| 71 |
started = time.time()
|
| 72 |
out, raw = Path(out).resolve(), Path(raw).resolve()
|
| 73 |
identity = current_identity(ffmpeg, ffprobe)
|
code/agt/dataset/export.py
CHANGED
|
@@ -1,17 +1,3 @@
|
|
| 1 |
-
"""Method-independent inputs of every clip of one split (the files the inference code reads).
|
| 2 |
-
|
| 3 |
-
Per clip (protocol sample order k = 0..19):
|
| 4 |
-
|
| 5 |
-
<out>/<clip_id>/frame_<k:02d>.png obstructed frame (clean frame composed with the scene's occluder layer at read
|
| 6 |
-
time), 518x294 uint8, lossless PNG
|
| 7 |
-
<out>/<clip_id>/clip.json roles, keyframe flags, frame indices, timestamps (exposure midpoint and start,
|
| 8 |
-
us), t_norm, c2w (20 x 4 x 4, exposure midpoint, relative to the first context
|
| 9 |
-
frame), native camera and grid camera
|
| 10 |
-
<out>/manifest.json eval set, protocol, per-clip sha256
|
| 11 |
-
|
| 12 |
-
Held-out frames are exported too; a method that may only see the input frames uses the roles in clip.json. Clean
|
| 13 |
-
frames are never exported. The clips are the ones the scorer reads (agt.data.reader.open_reader, same protocol).
|
| 14 |
-
"""
|
| 15 |
from __future__ import annotations
|
| 16 |
|
| 17 |
from concurrent.futures import ProcessPoolExecutor
|
|
@@ -91,7 +77,6 @@ def _export_sample(job):
|
|
| 91 |
|
| 92 |
|
| 93 |
def default_out(data_root, eval_set: str, protocol, sources, time_of_day) -> Path:
|
| 94 |
-
"""<data_root>/exports/<eval_set>/<sources>__<time>/<protocol id[:12]>."""
|
| 95 |
return Path(data_root) / 'exports' / eval_set / f"{'+'.join(sources)}__{time_of_day}" / protocol.short_id
|
| 96 |
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from concurrent.futures import ProcessPoolExecutor
|
|
|
|
| 77 |
|
| 78 |
|
| 79 |
def default_out(data_root, eval_set: str, protocol, sources, time_of_day) -> Path:
|
|
|
|
| 80 |
return Path(data_root) / 'exports' / eval_set / f"{'+'.join(sources)}__{time_of_day}" / protocol.short_id
|
| 81 |
|
| 82 |
|
code/agt/dataset/lidar_depth.py
CHANGED
|
@@ -1,21 +1,3 @@
|
|
| 1 |
-
"""lidar_dggt_single_v2: single-scan LiDAR depth labels of the Waymo scenes, a line-by-line port of the DGGT recipe.
|
| 2 |
-
|
| 3 |
-
Reference: xiaomi-research/dggt@a3276d2 datasets/waymo/waymo_preprocess_.py
|
| 4 |
-
L333-424 range image -> points; first return; TOP points ego-compensated with the per-pixel range-image pose
|
| 5 |
-
and brought to the vehicle frame of the frame pose (other lasers: no pixel pose, vehicle frame as stored)
|
| 6 |
-
L686-736 save_lidar: ri_index=0 (first return) of every laser, concatenated
|
| 7 |
-
L740-806 depth_flows_4: K scaled by ORIGINAL_SIZE / target (downsample 4), points_2d = K @ world_to_cam @ p,
|
| 8 |
-
uv = xy / (z + 1e-6), keep 0 <= u < w, 0 <= v < h, z > 0, integer index = astype(int32) (floor),
|
| 9 |
-
np.add.at sum and count, depth = sum / count, 0 where count == 0, float32
|
| 10 |
-
datasets/dataset.py L14-34 resize_flow: F.interpolate(mode="nearest") from the quarter grid to the model input size.
|
| 11 |
-
|
| 12 |
-
Per frame of frames.jsonl: the scan of the same frame (lidar rows with key.frame_timestamp_micros = the camera row),
|
| 13 |
-
first return of the 5 lasers, the exposure-midpoint camera of frames.jsonl, the 480x270 quarter grid of the 1920x1080
|
| 14 |
-
crop (pixel-edge K: Waymo intrinsics are corner-origin, c_v - 100 for the crop), mean camera z per cell, 0 = no point.
|
| 15 |
-
No range cap, no percentile clipping, no hole filling, no z-buffer, no valid-cell threshold.
|
| 16 |
-
|
| 17 |
-
Output: labels/lidar_dggt_single_v2/waymo/<scene>/{depth.h5, complete.json} and labels/lidar_dggt_single_v2/label_manifest.json.
|
| 18 |
-
"""
|
| 19 |
from __future__ import annotations
|
| 20 |
|
| 21 |
import concurrent.futures
|
|
@@ -40,13 +22,13 @@ LABEL_NAME = 'lidar_depth'
|
|
| 40 |
LABEL_DIR = Path('labels') / RECIPE_ID
|
| 41 |
FILE = 'depth.h5'
|
| 42 |
SOURCE = 'waymo'
|
| 43 |
-
DOWNSAMPLE = 4
|
| 44 |
-
TRAIN_GRID = (518, 294)
|
| 45 |
SOURCE_SIZE = (1920, 1080)
|
| 46 |
WAYMO_CROP_TOP = 100
|
| 47 |
-
WAYMO_TOP = 1
|
| 48 |
-
WAYMO_LASERS = (1, 2, 3, 4, 5)
|
| 49 |
-
WAYMO_SPIN_US = 100_000
|
| 50 |
DGGT_COMMIT = 'a3276d2bbe4cbb03bcc117830b1836110a27adeb'
|
| 51 |
DGGT_REFERENCE = (f'xiaomi-research/dggt@{DGGT_COMMIT} datasets/waymo/waymo_preprocess_.py L333-424, L686-736, '
|
| 52 |
'L740-806; datasets/dataset.py L14-34 (resize_flow)')
|
|
@@ -56,13 +38,11 @@ COMPONENTS = ('lidar', 'lidar_pose', 'lidar_calibration', 'vehicle_pose')
|
|
| 56 |
|
| 57 |
|
| 58 |
def label_grid() -> tuple[int, int]:
|
| 59 |
-
"""(w, h) = source size // 4 (DGGT ORIGINAL_SIZE // downsample_factor)."""
|
| 60 |
width, height = SOURCE_SIZE
|
| 61 |
return width // DOWNSAMPLE, height // DOWNSAMPLE
|
| 62 |
|
| 63 |
|
| 64 |
def recipe() -> dict[str, Any]:
|
| 65 |
-
"""Everything that decides the label values (recorded in every scene's complete.json)."""
|
| 66 |
width, height = label_grid()
|
| 67 |
rules = {
|
| 68 |
'recipe_id': RECIPE_ID, 'source': SOURCE, 'reference': DGGT_REFERENCE,
|
|
@@ -85,7 +65,6 @@ def recipe() -> dict[str, Any]:
|
|
| 85 |
return {**rules, 'sha256': hashlib.sha256(json.dumps(rules, sort_keys=True).encode()).hexdigest()}
|
| 86 |
|
| 87 |
|
| 88 |
-
# ---- geometry ------------------------------------------------------------------------------------------------------
|
| 89 |
def exposure_mid_us(frame: dict) -> float:
|
| 90 |
return (int(frame['timestamp_start_us']) + int(frame['timestamp_end_us'])) / 2
|
| 91 |
|
|
@@ -95,7 +74,6 @@ def edge_matrix(fx: float, fy: float, cx_edge: float, cy_edge: float) -> np.ndar
|
|
| 95 |
|
| 96 |
|
| 97 |
def scale_to_grid(K_edge: np.ndarray, source_size: tuple[int, int], grid: tuple[int, int]) -> np.ndarray:
|
| 98 |
-
"""DGGT L779-782 on a pixel-edge K: K[0,0] /= W/w, K[1,1] /= H/h, K[0,2] /= W/w, K[1,2] /= H/h."""
|
| 99 |
K = np.array(K_edge, np.float64)
|
| 100 |
(W, H), (w, h) = source_size, grid
|
| 101 |
K[0, 0] /= W / w
|
|
@@ -107,30 +85,24 @@ def scale_to_grid(K_edge: np.ndarray, source_size: tuple[int, int], grid: tuple[
|
|
| 107 |
|
| 108 |
def grid_matrix_from_centres(fx: float, fy: float, cx: float, cy: float, size: tuple[int, int],
|
| 109 |
grid: tuple[int, int]) -> np.ndarray:
|
| 110 |
-
"""Integer-pixel-centre pinhole on an image of `size` -> pixel-edge K on `grid` (c_edge = c + 0.5, then scale)."""
|
| 111 |
return scale_to_grid(edge_matrix(fx, fy, cx + .5, cy + .5), size, grid)
|
| 112 |
|
| 113 |
|
| 114 |
def to_camera(points_world: np.ndarray, camera_to_world: np.ndarray) -> np.ndarray:
|
| 115 |
-
"""World -> camera (scipy Rotation of the pose rotation, inverse applied to p - t)."""
|
| 116 |
pose = np.asarray(camera_to_world, np.float64)
|
| 117 |
return Rotation.from_matrix(pose[:3, :3]).inv().apply(np.asarray(points_world, np.float64) - pose[:3, 3])
|
| 118 |
|
| 119 |
|
| 120 |
def transform(matrix: np.ndarray, points: np.ndarray) -> np.ndarray:
|
| 121 |
-
"""4x4 column-vector transform of (N, 3) points."""
|
| 122 |
matrix = np.asarray(matrix, np.float64)
|
| 123 |
return np.asarray(points, np.float64) @ matrix[:3, :3].T + matrix[:3, 3]
|
| 124 |
|
| 125 |
|
| 126 |
def project_mean_z(xyz, K_edge, width, height):
|
| 127 |
-
"""DGGT rule: positive z, in-frame floor bins, arithmetic mean z per bin, empty = 0.
|
| 128 |
-
|
| 129 |
-
-> depth (H,W) float32, counts (H,W) uint32, number of projected points."""
|
| 130 |
order = np.flatnonzero(np.isfinite(xyz).all(1) & (xyz[:, 2] > 0))
|
| 131 |
good = xyz[order]
|
| 132 |
projected = good @ K_edge.T
|
| 133 |
-
uv = projected[:, :2] / (projected[:, 2:3] + 1e-6)
|
| 134 |
inside = (uv[:, 0] >= 0) & (uv[:, 0] < width) & (uv[:, 1] >= 0) & (uv[:, 1] < height)
|
| 135 |
pix = uv[inside].astype(np.int32)
|
| 136 |
z = projected[inside, 2]
|
|
@@ -144,11 +116,11 @@ def project_mean_z(xyz, K_edge, width, height):
|
|
| 144 |
|
| 145 |
@dataclass
|
| 146 |
class FrameLabel:
|
| 147 |
-
depth: np.ndarray
|
| 148 |
-
scan_mid_us: float
|
| 149 |
-
scan_id: int
|
| 150 |
-
points_scan: int
|
| 151 |
-
points_in_grid: int
|
| 152 |
extra: dict[str, Any] = field(default_factory=dict)
|
| 153 |
|
| 154 |
|
|
@@ -156,10 +128,7 @@ def empty_label(grid: tuple[int, int], **extra) -> FrameLabel:
|
|
| 156 |
return FrameLabel(np.zeros((grid[1], grid[0]), np.float32), float('nan'), -1, 0, 0, dict(extra))
|
| 157 |
|
| 158 |
|
| 159 |
-
# ---- Waymo range images --------------------------------------------------------------------------------------------
|
| 160 |
def waymo_inclination(values, minimum: float, maximum: float, height: int) -> np.ndarray:
|
| 161 |
-
"""Row inclinations of a range image, row 0 first: beam_inclinations or compute_inclination(min, max)
|
| 162 |
-
((0.5 + i) / H * (max - min) + min), then reversed (DGGT tf.reverse)."""
|
| 163 |
if values is None or len(values) == 0:
|
| 164 |
values = (.5 + np.arange(height, dtype=np.float64)) / height * (maximum - minimum) + minimum
|
| 165 |
values = np.asarray(values, np.float64)
|
|
@@ -169,14 +138,12 @@ def waymo_inclination(values, minimum: float, maximum: float, height: int) -> np
|
|
| 169 |
|
| 170 |
|
| 171 |
def waymo_azimuth(extrinsic: np.ndarray, width: int) -> np.ndarray:
|
| 172 |
-
"""range_image_utils.compute_range_image_polar: column azimuth in the sensor frame."""
|
| 173 |
az_correction = np.arctan2(extrinsic[1, 0], extrinsic[0, 0])
|
| 174 |
ratios = (np.arange(width, 0, -1, dtype=np.float64) - .5) / width
|
| 175 |
return (ratios * 2. - 1.) * np.pi - az_correction
|
| 176 |
|
| 177 |
|
| 178 |
def rotation_rpy(roll, pitch, yaw) -> np.ndarray:
|
| 179 |
-
"""transform_utils.get_rotation_matrix: Rz(yaw) Ry(pitch) Rx(roll), broadcast over leading axes."""
|
| 180 |
cr, sr, cp, sp, cy, sy = np.cos(roll), np.sin(roll), np.cos(pitch), np.sin(pitch), np.cos(yaw), np.sin(yaw)
|
| 181 |
out = np.empty(np.shape(roll) + (3, 3), np.float64)
|
| 182 |
out[..., 0, 0] = cy * cp
|
|
@@ -193,11 +160,6 @@ def rotation_rpy(roll, pitch, yaw) -> np.ndarray:
|
|
| 193 |
|
| 194 |
def waymo_range_image_points(ranges: np.ndarray, extrinsic: np.ndarray, inclination: np.ndarray,
|
| 195 |
pixel_pose: np.ndarray | None = None, frame_pose: np.ndarray | None = None):
|
| 196 |
-
"""DGGT extract_point_cloud_from_range_image + gather on range > 0.
|
| 197 |
-
|
| 198 |
-
ranges (H, W) channel 0 of range_image_return1; pixel_pose (H, W, 6) roll, pitch, yaw, x, y, z (TOP only) with
|
| 199 |
-
frame_pose (world_from_vehicle of the frame). -> (points (N, 3) in the vehicle frame of frame_pose, mask (H, W)).
|
| 200 |
-
"""
|
| 201 |
ranges = np.asarray(ranges, np.float64)
|
| 202 |
height, width = ranges.shape
|
| 203 |
mask = ranges > 0
|
|
@@ -223,8 +185,6 @@ def waymo_component(raw: Path, split: str, component: str, segment: str) -> Path
|
|
| 223 |
|
| 224 |
|
| 225 |
def waymo_grid_matrix(camera: dict, grid: tuple[int, int]) -> np.ndarray:
|
| 226 |
-
"""DGGT K on the 480x270 grid from Waymo's native corner-origin intrinsics (crop: c_v - 100), checked against the
|
| 227 |
-
518x294 integer-centre camera.json (same edges, other scale)."""
|
| 228 |
c = camera['calibration']
|
| 229 |
native = c['native']
|
| 230 |
if tuple(native['resolution']) != (1920, 1280) or c['crop']['rows_removed_top'] != WAYMO_CROP_TOP:
|
|
@@ -242,8 +202,6 @@ def waymo_grid_matrix(camera: dict, grid: tuple[int, int]) -> np.ndarray:
|
|
| 242 |
|
| 243 |
|
| 244 |
class WaymoScene:
|
| 245 |
-
"""One segment: v2.0.1 lidar / lidar_pose / lidar_calibration / vehicle_pose; frames.jsonl + camera.json of the
|
| 246 |
-
scene store. Frames are labelled in frames.jsonl order; lidar rows are streamed row group by row group."""
|
| 247 |
extra_fields = {'lasers': np.int8}
|
| 248 |
|
| 249 |
def __init__(self, raw: Path, scene_dir: Path):
|
|
@@ -280,7 +238,6 @@ class WaymoScene:
|
|
| 280 |
table['key.frame_timestamp_micros'], table['[VehiclePoseComponent].world_from_vehicle.transform'])}
|
| 281 |
|
| 282 |
def frame_points(self, ranges: dict[int, np.ndarray], top_pose: np.ndarray, timestamp: int) -> np.ndarray:
|
| 283 |
-
"""First-return points of all lasers (DGGT laser order) in the vehicle frame of the frame pose."""
|
| 284 |
frame_pose = self.vehicle_pose[timestamp]
|
| 285 |
out = []
|
| 286 |
for laser in WAYMO_LASERS:
|
|
@@ -295,11 +252,9 @@ class WaymoScene:
|
|
| 295 |
return np.concatenate(out)
|
| 296 |
|
| 297 |
def local_points(self, vehicle_points: np.ndarray, timestamp: int) -> np.ndarray:
|
| 298 |
-
"""Vehicle frame of the frame pose -> the scene-store world (local = vehicle frame of frame 0)."""
|
| 299 |
return transform(self.local_from_global @ self.vehicle_pose[timestamp], vehicle_points)
|
| 300 |
|
| 301 |
def iter_scans(self, wanted: set[int]):
|
| 302 |
-
"""Yield (timestamp, {laser: range image (H, W, 4)}, TOP pose (H, W, 6)) for the frames in `wanted`."""
|
| 303 |
import pyarrow.parquet as pq
|
| 304 |
pr, lr = '[LiDARPoseComponent].range_image_return1.', '[LiDARComponent].range_image_return1.'
|
| 305 |
poses = {}
|
|
@@ -331,11 +286,10 @@ class WaymoScene:
|
|
| 331 |
if len(pending[t]) == len(WAYMO_LASERS) and t in poses:
|
| 332 |
yield t, pending.pop(t), poses.pop(t)
|
| 333 |
del table
|
| 334 |
-
for t, images in pending.items():
|
| 335 |
yield t, images, poses.get(t)
|
| 336 |
|
| 337 |
def label_all(self, frames: list[dict]) -> list[FrameLabel]:
|
| 338 |
-
"""Every frames.jsonl row; a frame without its 5 range images, TOP pose or vehicle pose gets an empty label."""
|
| 339 |
by_stamp = {int(f['frame_timestamp_us']): i for i, f in enumerate(frames)}
|
| 340 |
if len(by_stamp) != len(frames):
|
| 341 |
raise ValueError(f'{self.segment}: repeated frame timestamps')
|
|
@@ -353,10 +307,8 @@ class WaymoScene:
|
|
| 353 |
return [o if o is not None else empty_label(self.grid, lasers=0) for o in out]
|
| 354 |
|
| 355 |
|
| 356 |
-
# ---- storage ---------------------------------------------------------------------------------------------------------
|
| 357 |
def write_depth_h5(path: Path, *, depth: np.ndarray, frame_indices, timestamp_mid_us, scan_mid_us, scan_id,
|
| 358 |
points_scan, points_in_grid, K_grid: np.ndarray, extra: dict[str, np.ndarray], attrs: dict) -> str:
|
| 359 |
-
"""One scene -> depth.h5 (atomic); returns its sha256. depth (T, h, w) float32 gzip, one chunk per frame."""
|
| 360 |
import h5py
|
| 361 |
depth = np.asarray(depth, np.float32)
|
| 362 |
frame_indices = np.asarray(frame_indices, np.int64)
|
|
@@ -401,7 +353,6 @@ def summarise(depth: np.ndarray, offsets_us: np.ndarray, missing: int) -> dict:
|
|
| 401 |
|
| 402 |
|
| 403 |
def label_scene(data_root: Path, raw: Path, scene: str) -> dict:
|
| 404 |
-
"""One scene -> depth.h5 + complete.json; skipped when complete.json names the same recipe and depth.h5 matches it."""
|
| 405 |
started = time.monotonic()
|
| 406 |
data_root = Path(data_root)
|
| 407 |
rules = recipe()
|
|
@@ -443,12 +394,11 @@ def label_scene(data_root: Path, raw: Path, scene: str) -> dict:
|
|
| 443 |
'summary': summary, 'seconds': round(time.monotonic() - started, 1)}
|
| 444 |
store.atomic_text(marker, json.dumps(record, indent=1, sort_keys=True) + '\n')
|
| 445 |
return {'scene': scene, 'status': 'written', **summary, 'seconds': record['seconds']}
|
| 446 |
-
except Exception as exc:
|
| 447 |
return {'scene': scene, 'status': 'failed', 'error': repr(exc), 'traceback': traceback.format_exc()}
|
| 448 |
|
| 449 |
|
| 450 |
def write_manifest(data_root: Path) -> Path:
|
| 451 |
-
"""labels/lidar_dggt_single_v2/label_manifest.json (the block the readers check: name, label_id, grid)."""
|
| 452 |
width, height = label_grid()
|
| 453 |
path = Path(data_root) / LABEL_DIR / 'label_manifest.json'
|
| 454 |
manifest = {'schema': 'amodaldrive_label_manifest_v1', 'name': LABEL_NAME, 'label_id': RECIPE_ID, 'file': FILE,
|
|
@@ -461,7 +411,6 @@ def write_manifest(data_root: Path) -> Path:
|
|
| 461 |
|
| 462 |
|
| 463 |
def generate(data_root: Path, raw: Path, scenes: list[str], workers: int = 4) -> int:
|
| 464 |
-
"""Label every scene (spawned worker processes); returns the number of failed scenes."""
|
| 465 |
write_manifest(data_root)
|
| 466 |
failed = 0
|
| 467 |
with concurrent.futures.ProcessPoolExecutor(max_workers=max(1, min(workers, len(scenes) or 1)),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import concurrent.futures
|
|
|
|
| 22 |
LABEL_DIR = Path('labels') / RECIPE_ID
|
| 23 |
FILE = 'depth.h5'
|
| 24 |
SOURCE = 'waymo'
|
| 25 |
+
DOWNSAMPLE = 4
|
| 26 |
+
TRAIN_GRID = (518, 294)
|
| 27 |
SOURCE_SIZE = (1920, 1080)
|
| 28 |
WAYMO_CROP_TOP = 100
|
| 29 |
+
WAYMO_TOP = 1
|
| 30 |
+
WAYMO_LASERS = (1, 2, 3, 4, 5)
|
| 31 |
+
WAYMO_SPIN_US = 100_000
|
| 32 |
DGGT_COMMIT = 'a3276d2bbe4cbb03bcc117830b1836110a27adeb'
|
| 33 |
DGGT_REFERENCE = (f'xiaomi-research/dggt@{DGGT_COMMIT} datasets/waymo/waymo_preprocess_.py L333-424, L686-736, '
|
| 34 |
'L740-806; datasets/dataset.py L14-34 (resize_flow)')
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
def label_grid() -> tuple[int, int]:
|
|
|
|
| 41 |
width, height = SOURCE_SIZE
|
| 42 |
return width // DOWNSAMPLE, height // DOWNSAMPLE
|
| 43 |
|
| 44 |
|
| 45 |
def recipe() -> dict[str, Any]:
|
|
|
|
| 46 |
width, height = label_grid()
|
| 47 |
rules = {
|
| 48 |
'recipe_id': RECIPE_ID, 'source': SOURCE, 'reference': DGGT_REFERENCE,
|
|
|
|
| 65 |
return {**rules, 'sha256': hashlib.sha256(json.dumps(rules, sort_keys=True).encode()).hexdigest()}
|
| 66 |
|
| 67 |
|
|
|
|
| 68 |
def exposure_mid_us(frame: dict) -> float:
|
| 69 |
return (int(frame['timestamp_start_us']) + int(frame['timestamp_end_us'])) / 2
|
| 70 |
|
|
|
|
| 74 |
|
| 75 |
|
| 76 |
def scale_to_grid(K_edge: np.ndarray, source_size: tuple[int, int], grid: tuple[int, int]) -> np.ndarray:
|
|
|
|
| 77 |
K = np.array(K_edge, np.float64)
|
| 78 |
(W, H), (w, h) = source_size, grid
|
| 79 |
K[0, 0] /= W / w
|
|
|
|
| 85 |
|
| 86 |
def grid_matrix_from_centres(fx: float, fy: float, cx: float, cy: float, size: tuple[int, int],
|
| 87 |
grid: tuple[int, int]) -> np.ndarray:
|
|
|
|
| 88 |
return scale_to_grid(edge_matrix(fx, fy, cx + .5, cy + .5), size, grid)
|
| 89 |
|
| 90 |
|
| 91 |
def to_camera(points_world: np.ndarray, camera_to_world: np.ndarray) -> np.ndarray:
|
|
|
|
| 92 |
pose = np.asarray(camera_to_world, np.float64)
|
| 93 |
return Rotation.from_matrix(pose[:3, :3]).inv().apply(np.asarray(points_world, np.float64) - pose[:3, 3])
|
| 94 |
|
| 95 |
|
| 96 |
def transform(matrix: np.ndarray, points: np.ndarray) -> np.ndarray:
|
|
|
|
| 97 |
matrix = np.asarray(matrix, np.float64)
|
| 98 |
return np.asarray(points, np.float64) @ matrix[:3, :3].T + matrix[:3, 3]
|
| 99 |
|
| 100 |
|
| 101 |
def project_mean_z(xyz, K_edge, width, height):
|
|
|
|
|
|
|
|
|
|
| 102 |
order = np.flatnonzero(np.isfinite(xyz).all(1) & (xyz[:, 2] > 0))
|
| 103 |
good = xyz[order]
|
| 104 |
projected = good @ K_edge.T
|
| 105 |
+
uv = projected[:, :2] / (projected[:, 2:3] + 1e-6)
|
| 106 |
inside = (uv[:, 0] >= 0) & (uv[:, 0] < width) & (uv[:, 1] >= 0) & (uv[:, 1] < height)
|
| 107 |
pix = uv[inside].astype(np.int32)
|
| 108 |
z = projected[inside, 2]
|
|
|
|
| 116 |
|
| 117 |
@dataclass
|
| 118 |
class FrameLabel:
|
| 119 |
+
depth: np.ndarray
|
| 120 |
+
scan_mid_us: float
|
| 121 |
+
scan_id: int
|
| 122 |
+
points_scan: int
|
| 123 |
+
points_in_grid: int
|
| 124 |
extra: dict[str, Any] = field(default_factory=dict)
|
| 125 |
|
| 126 |
|
|
|
|
| 128 |
return FrameLabel(np.zeros((grid[1], grid[0]), np.float32), float('nan'), -1, 0, 0, dict(extra))
|
| 129 |
|
| 130 |
|
|
|
|
| 131 |
def waymo_inclination(values, minimum: float, maximum: float, height: int) -> np.ndarray:
|
|
|
|
|
|
|
| 132 |
if values is None or len(values) == 0:
|
| 133 |
values = (.5 + np.arange(height, dtype=np.float64)) / height * (maximum - minimum) + minimum
|
| 134 |
values = np.asarray(values, np.float64)
|
|
|
|
| 138 |
|
| 139 |
|
| 140 |
def waymo_azimuth(extrinsic: np.ndarray, width: int) -> np.ndarray:
|
|
|
|
| 141 |
az_correction = np.arctan2(extrinsic[1, 0], extrinsic[0, 0])
|
| 142 |
ratios = (np.arange(width, 0, -1, dtype=np.float64) - .5) / width
|
| 143 |
return (ratios * 2. - 1.) * np.pi - az_correction
|
| 144 |
|
| 145 |
|
| 146 |
def rotation_rpy(roll, pitch, yaw) -> np.ndarray:
|
|
|
|
| 147 |
cr, sr, cp, sp, cy, sy = np.cos(roll), np.sin(roll), np.cos(pitch), np.sin(pitch), np.cos(yaw), np.sin(yaw)
|
| 148 |
out = np.empty(np.shape(roll) + (3, 3), np.float64)
|
| 149 |
out[..., 0, 0] = cy * cp
|
|
|
|
| 160 |
|
| 161 |
def waymo_range_image_points(ranges: np.ndarray, extrinsic: np.ndarray, inclination: np.ndarray,
|
| 162 |
pixel_pose: np.ndarray | None = None, frame_pose: np.ndarray | None = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
ranges = np.asarray(ranges, np.float64)
|
| 164 |
height, width = ranges.shape
|
| 165 |
mask = ranges > 0
|
|
|
|
| 185 |
|
| 186 |
|
| 187 |
def waymo_grid_matrix(camera: dict, grid: tuple[int, int]) -> np.ndarray:
|
|
|
|
|
|
|
| 188 |
c = camera['calibration']
|
| 189 |
native = c['native']
|
| 190 |
if tuple(native['resolution']) != (1920, 1280) or c['crop']['rows_removed_top'] != WAYMO_CROP_TOP:
|
|
|
|
| 202 |
|
| 203 |
|
| 204 |
class WaymoScene:
|
|
|
|
|
|
|
| 205 |
extra_fields = {'lasers': np.int8}
|
| 206 |
|
| 207 |
def __init__(self, raw: Path, scene_dir: Path):
|
|
|
|
| 238 |
table['key.frame_timestamp_micros'], table['[VehiclePoseComponent].world_from_vehicle.transform'])}
|
| 239 |
|
| 240 |
def frame_points(self, ranges: dict[int, np.ndarray], top_pose: np.ndarray, timestamp: int) -> np.ndarray:
|
|
|
|
| 241 |
frame_pose = self.vehicle_pose[timestamp]
|
| 242 |
out = []
|
| 243 |
for laser in WAYMO_LASERS:
|
|
|
|
| 252 |
return np.concatenate(out)
|
| 253 |
|
| 254 |
def local_points(self, vehicle_points: np.ndarray, timestamp: int) -> np.ndarray:
|
|
|
|
| 255 |
return transform(self.local_from_global @ self.vehicle_pose[timestamp], vehicle_points)
|
| 256 |
|
| 257 |
def iter_scans(self, wanted: set[int]):
|
|
|
|
| 258 |
import pyarrow.parquet as pq
|
| 259 |
pr, lr = '[LiDARPoseComponent].range_image_return1.', '[LiDARComponent].range_image_return1.'
|
| 260 |
poses = {}
|
|
|
|
| 286 |
if len(pending[t]) == len(WAYMO_LASERS) and t in poses:
|
| 287 |
yield t, pending.pop(t), poses.pop(t)
|
| 288 |
del table
|
| 289 |
+
for t, images in pending.items():
|
| 290 |
yield t, images, poses.get(t)
|
| 291 |
|
| 292 |
def label_all(self, frames: list[dict]) -> list[FrameLabel]:
|
|
|
|
| 293 |
by_stamp = {int(f['frame_timestamp_us']): i for i, f in enumerate(frames)}
|
| 294 |
if len(by_stamp) != len(frames):
|
| 295 |
raise ValueError(f'{self.segment}: repeated frame timestamps')
|
|
|
|
| 307 |
return [o if o is not None else empty_label(self.grid, lasers=0) for o in out]
|
| 308 |
|
| 309 |
|
|
|
|
| 310 |
def write_depth_h5(path: Path, *, depth: np.ndarray, frame_indices, timestamp_mid_us, scan_mid_us, scan_id,
|
| 311 |
points_scan, points_in_grid, K_grid: np.ndarray, extra: dict[str, np.ndarray], attrs: dict) -> str:
|
|
|
|
| 312 |
import h5py
|
| 313 |
depth = np.asarray(depth, np.float32)
|
| 314 |
frame_indices = np.asarray(frame_indices, np.int64)
|
|
|
|
| 353 |
|
| 354 |
|
| 355 |
def label_scene(data_root: Path, raw: Path, scene: str) -> dict:
|
|
|
|
| 356 |
started = time.monotonic()
|
| 357 |
data_root = Path(data_root)
|
| 358 |
rules = recipe()
|
|
|
|
| 394 |
'summary': summary, 'seconds': round(time.monotonic() - started, 1)}
|
| 395 |
store.atomic_text(marker, json.dumps(record, indent=1, sort_keys=True) + '\n')
|
| 396 |
return {'scene': scene, 'status': 'written', **summary, 'seconds': record['seconds']}
|
| 397 |
+
except Exception as exc:
|
| 398 |
return {'scene': scene, 'status': 'failed', 'error': repr(exc), 'traceback': traceback.format_exc()}
|
| 399 |
|
| 400 |
|
| 401 |
def write_manifest(data_root: Path) -> Path:
|
|
|
|
| 402 |
width, height = label_grid()
|
| 403 |
path = Path(data_root) / LABEL_DIR / 'label_manifest.json'
|
| 404 |
manifest = {'schema': 'amodaldrive_label_manifest_v1', 'name': LABEL_NAME, 'label_id': RECIPE_ID, 'file': FILE,
|
|
|
|
| 411 |
|
| 412 |
|
| 413 |
def generate(data_root: Path, raw: Path, scenes: list[str], workers: int = 4) -> int:
|
|
|
|
| 414 |
write_manifest(data_root)
|
| 415 |
failed = 0
|
| 416 |
with concurrent.futures.ProcessPoolExecutor(max_workers=max(1, min(workers, len(scenes) or 1)),
|
code/agt/dataset/scene_store.py
CHANGED
|
@@ -1,13 +1,3 @@
|
|
| 1 |
-
"""Writer of the scene store: ``<data_root>/scenes/<source_id>/<scene_id>/`` and ``scenes/manifest.jsonl``.
|
| 2 |
-
|
| 3 |
-
One scene directory holds ``rgb.mp4`` (clean frames at 518x294, HEVC) and the metadata files of the source
|
| 4 |
-
(``frames.jsonl``, ``camera.json``, ``scene_stats.json``). Every scene has one row in ``scenes/manifest.jsonl``.
|
| 5 |
-
|
| 6 |
-
Frame rule: PIL RGB ``Image.resize((518, 294), Image.Resampling.BICUBIC)`` (height ``round(h * 518 / w / 14) * 14``,
|
| 7 |
-
the DGGT image loader, datasets/dataset.py:60-136), then libx265 yuv420p with a fixed keyframe interval
|
| 8 |
-
(``keyint = min-keyint = GOP``, ``scenecut=0``, x265's default open GOP).
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
from __future__ import annotations
|
| 12 |
|
| 13 |
import contextlib
|
|
@@ -35,7 +25,6 @@ IDENTITY_SCHEMA = "amodaldrive_transcode_identity_v1"
|
|
| 35 |
VIDEO_NAME = "rgb.mp4"
|
| 36 |
MANIFEST_NAME = "manifest.jsonl"
|
| 37 |
|
| 38 |
-
# scene statistics: linear light (display^2.2) of the upper 60 % rows of 24 evenly spaced frames, Rec.709 luma
|
| 39 |
GAMMA = 2.2
|
| 40 |
LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32)
|
| 41 |
SCENE_ROWS_FRACTION = 0.6
|
|
@@ -50,7 +39,6 @@ def luminance(x: np.ndarray) -> np.ndarray:
|
|
| 50 |
return x @ LUMA
|
| 51 |
|
| 52 |
|
| 53 |
-
# ---- small helpers ---------------------------------------------------------------------------------------
|
| 54 |
def sha256_file(path: Path | str, chunk: int = 1 << 20) -> str:
|
| 55 |
digest = hashlib.sha256()
|
| 56 |
with open(path, "rb") as stream:
|
|
@@ -72,13 +60,11 @@ def utc_now() -> str:
|
|
| 72 |
|
| 73 |
|
| 74 |
def group_of(time_of_day: str) -> str:
|
| 75 |
-
"""Day and dawn are the day group, every other time of day is night."""
|
| 76 |
return "day" if time_of_day in ("day", "dawn") else "night"
|
| 77 |
|
| 78 |
|
| 79 |
@contextlib.contextmanager
|
| 80 |
def locked(path: Path) -> Iterator[None]:
|
| 81 |
-
"""Exclusive advisory lock on the hidden sibling ``.<name>.lock``."""
|
| 82 |
lock_path = path.with_name(f".{path.name}.lock")
|
| 83 |
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
| 84 |
with open(lock_path, "a") as handle:
|
|
@@ -90,7 +76,6 @@ def locked(path: Path) -> Iterator[None]:
|
|
| 90 |
|
| 91 |
|
| 92 |
def atomic_text(path: Path, text: str) -> None:
|
| 93 |
-
"""mkstemp, fsync, replace; mode 0666 & ~umask."""
|
| 94 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 95 |
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
| 96 |
try:
|
|
@@ -106,14 +91,11 @@ def atomic_text(path: Path, text: str) -> None:
|
|
| 106 |
os.chmod(path, 0o666 & ~mask)
|
| 107 |
|
| 108 |
|
| 109 |
-
# ---- frames: resize ----------------------------------------------------------------------------------------
|
| 110 |
def resize_size(width: int, height: int, target_width: int = TARGET_WIDTH, multiple: int = PATCH_MULTIPLE) -> tuple[int, int]:
|
| 111 |
-
"""Width ``target_width``, height rounded to a multiple of ``multiple`` (DGGT datasets/dataset.py:89-91)."""
|
| 112 |
return int(target_width), round(height * (target_width / width) / multiple) * multiple
|
| 113 |
|
| 114 |
|
| 115 |
def pil_resize(frame: np.ndarray, size: tuple[int, int]) -> np.ndarray:
|
| 116 |
-
"""One HxWx3 uint8 frame through PIL BICUBIC to ``size`` (uint8, before ToTensor)."""
|
| 117 |
from PIL import Image
|
| 118 |
frame = np.asarray(frame)
|
| 119 |
if frame.dtype != np.uint8 or frame.ndim != 3 or frame.shape[-1] != 3:
|
|
@@ -132,7 +114,6 @@ def resize_identity(native_size: tuple[int, int], size: tuple[int, int], crop: A
|
|
| 132 |
"reference": "DGGT datasets/dataset.py:60-136 image loader (before ToTensor)"}
|
| 133 |
|
| 134 |
|
| 135 |
-
# ---- encoder identity --------------------------------------------------------------------------------------
|
| 136 |
@functools.lru_cache(maxsize=None)
|
| 137 |
def _tool_version(binary: str) -> str:
|
| 138 |
result = subprocess.run([binary, "-version"], capture_output=True, text=True, check=True)
|
|
@@ -154,7 +135,6 @@ FRAME_RATE_RULE = "video_fps = 1e6 / median start-timestamp interval of frames.j
|
|
| 154 |
|
| 155 |
def transcode_identity(*, ffmpeg: str, ffprobe: str, config: VideoConfig, native_size: tuple[int, int],
|
| 156 |
size: tuple[int, int], decoder: dict[str, Any], crop: Any = "none") -> dict[str, Any]:
|
| 157 |
-
"""Tools, versions and parameters that decide the stored pixels (recorded in every manifest row)."""
|
| 158 |
arguments = encoder_command("<ffmpeg>", "<rgb.mp4>.partial", size[0], size[1], 1.0, config)
|
| 159 |
arguments[arguments.index("-r") + 1] = "<video_fps:.9f>"
|
| 160 |
identity = {"schema": IDENTITY_SCHEMA, "decoder": decoder, "resize": resize_identity(native_size, size, crop),
|
|
@@ -165,10 +145,7 @@ def transcode_identity(*, ffmpeg: str, ffprobe: str, config: VideoConfig, native
|
|
| 165 |
return identity
|
| 166 |
|
| 167 |
|
| 168 |
-
# ---- one scene ---------------------------------------------------------------------------------------------
|
| 169 |
def write_metadata(destination: Path, name: str, content: bytes) -> dict[str, Any]:
|
| 170 |
-
"""One generated metadata file of a scene directory, written through ``<name>.partial`` and an atomic replace.
|
| 171 |
-
Returns ``{"sha256", "bytes"}``."""
|
| 172 |
if name == VIDEO_NAME or Path(name).name != name:
|
| 173 |
raise ValueError(f"invalid metadata file name {name!r}")
|
| 174 |
destination.mkdir(parents=True, exist_ok=True)
|
|
@@ -190,12 +167,6 @@ def write_metadata(destination: Path, name: str, content: bytes) -> dict[str, An
|
|
| 190 |
|
| 191 |
def write_scene(destination: Path, frames: Iterable[np.ndarray], *, size: tuple[int, int], fps: float, frame_count: int,
|
| 192 |
metadata: dict[str, bytes], ffmpeg: str, ffprobe: str, config: VideoConfig) -> dict[str, Any]:
|
| 193 |
-
"""Write ``rgb.mp4`` from ``frames`` (already at ``size``) and the ``metadata`` files into ``destination``.
|
| 194 |
-
|
| 195 |
-
A previous ``rgb.mp4`` is removed first; the encoder publishes the new one only after ffmpeg succeeds, then
|
| 196 |
-
``validate_video`` checks codec, pixel format, size, frame count and rate.
|
| 197 |
-
Returns ``{"files": {name: {"sha256", "bytes"}}, "video": <validate_video result>}``.
|
| 198 |
-
"""
|
| 199 |
width, height = (int(v) for v in size)
|
| 200 |
destination.mkdir(parents=True, exist_ok=True)
|
| 201 |
files: dict[str, dict[str, Any]] = {}
|
|
@@ -223,7 +194,6 @@ def scene_row(*, data_root: Path, destination: Path, written: dict[str, Any], so
|
|
| 223 |
dataset_id: str, camera_id: str, fps: int | float, video_fps: float, frame_count: int, time_of_day: str,
|
| 224 |
size: tuple[int, int], native_size: tuple[int, int], transcode: dict[str, Any],
|
| 225 |
provenance: dict[str, Any], extra: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 226 |
-
"""Manifest row of one written scene; file keys are the stems (rgb.mp4 -> rgb), paths relative to the data root."""
|
| 227 |
files = {}
|
| 228 |
for name, info in sorted(written["files"].items()):
|
| 229 |
key = "rgb" if name == VIDEO_NAME else Path(name).stem
|
|
@@ -243,7 +213,6 @@ def scene_row(*, data_root: Path, destination: Path, written: dict[str, Any], so
|
|
| 243 |
|
| 244 |
|
| 245 |
def scene_complete(data_root: Path, row: dict[str, Any] | None, *, identity: dict[str, Any]) -> bool:
|
| 246 |
-
"""A scene is done when its row has the current transcode identity and every listed file matches its sha256."""
|
| 247 |
if row is None or row.get("transcode", {}).get("identity_sha256") != identity["identity_sha256"]:
|
| 248 |
return False
|
| 249 |
for info in row["files"].values():
|
|
@@ -253,10 +222,7 @@ def scene_complete(data_root: Path, row: dict[str, Any] | None, *, identity: dic
|
|
| 253 |
return True
|
| 254 |
|
| 255 |
|
| 256 |
-
# ---- scene statistics -------------------------------------------------------------------------------------------
|
| 257 |
def scene_statistics_from_frames(frames: Iterable[np.ndarray], indices: Iterable[int], frame_count: int) -> dict[str, Any]:
|
| 258 |
-
"""Linear-light statistics of the sampled uint8 clean frames (uint8 / 255 is the display-domain value): upper
|
| 259 |
-
``SCENE_ROWS_FRACTION`` rows, mean / median / p99 luminance, mean RGB, white-balance gain."""
|
| 260 |
indices = [int(i) for i in indices]
|
| 261 |
stack = [np.asarray(f) for f in frames]
|
| 262 |
if len(stack) != len(indices) or not stack:
|
|
@@ -277,12 +243,10 @@ def scene_statistics_from_frames(frames: Iterable[np.ndarray], indices: Iterable
|
|
| 277 |
|
| 278 |
|
| 279 |
def sampled_frame_indices(frame_count: int) -> list[int]:
|
| 280 |
-
"""The 24 evenly spaced frames the scene statistics sample."""
|
| 281 |
return [int(i) for i in np.unique(np.linspace(0, frame_count - 1, min(SCENE_SAMPLE_FRAMES, frame_count)).round().astype(int))]
|
| 282 |
|
| 283 |
|
| 284 |
def scene_statistics_from_video(path: Path, frame_count: int) -> dict[str, Any]:
|
| 285 |
-
"""Scene statistics of a stored clean ``rgb.mp4`` (decoded as the readers decode it, PyAV rgb24)."""
|
| 286 |
indices = sampled_frame_indices(frame_count)
|
| 287 |
wanted = set(indices)
|
| 288 |
frames = [f for i, f in enumerate(decode_frames(path, expected_frames=frame_count)) if i in wanted]
|
|
@@ -291,7 +255,6 @@ def scene_statistics_from_video(path: Path, frame_count: int) -> dict[str, Any]:
|
|
| 291 |
return stats
|
| 292 |
|
| 293 |
|
| 294 |
-
# ---- manifest ---------------------------------------------------------------------------------------------------
|
| 295 |
def read_manifest(path: Path) -> list[dict[str, Any]]:
|
| 296 |
if not path.is_file():
|
| 297 |
return []
|
|
@@ -299,7 +262,6 @@ def read_manifest(path: Path) -> list[dict[str, Any]]:
|
|
| 299 |
|
| 300 |
|
| 301 |
def merge_manifest(path: Path, rows: Iterable[dict[str, Any]]) -> dict[str, int]:
|
| 302 |
-
"""Insert or replace rows keyed by (source_id, scene_id); other rows are kept. Rewritten sorted, atomically."""
|
| 303 |
rows = list(rows)
|
| 304 |
keys = [(r["source_id"], r["scene_id"]) for r in rows]
|
| 305 |
if len(set(keys)) != len(keys):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import contextlib
|
|
|
|
| 25 |
VIDEO_NAME = "rgb.mp4"
|
| 26 |
MANIFEST_NAME = "manifest.jsonl"
|
| 27 |
|
|
|
|
| 28 |
GAMMA = 2.2
|
| 29 |
LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32)
|
| 30 |
SCENE_ROWS_FRACTION = 0.6
|
|
|
|
| 39 |
return x @ LUMA
|
| 40 |
|
| 41 |
|
|
|
|
| 42 |
def sha256_file(path: Path | str, chunk: int = 1 << 20) -> str:
|
| 43 |
digest = hashlib.sha256()
|
| 44 |
with open(path, "rb") as stream:
|
|
|
|
| 60 |
|
| 61 |
|
| 62 |
def group_of(time_of_day: str) -> str:
|
|
|
|
| 63 |
return "day" if time_of_day in ("day", "dawn") else "night"
|
| 64 |
|
| 65 |
|
| 66 |
@contextlib.contextmanager
|
| 67 |
def locked(path: Path) -> Iterator[None]:
|
|
|
|
| 68 |
lock_path = path.with_name(f".{path.name}.lock")
|
| 69 |
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
| 70 |
with open(lock_path, "a") as handle:
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
def atomic_text(path: Path, text: str) -> None:
|
|
|
|
| 79 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
|
| 81 |
try:
|
|
|
|
| 91 |
os.chmod(path, 0o666 & ~mask)
|
| 92 |
|
| 93 |
|
|
|
|
| 94 |
def resize_size(width: int, height: int, target_width: int = TARGET_WIDTH, multiple: int = PATCH_MULTIPLE) -> tuple[int, int]:
|
|
|
|
| 95 |
return int(target_width), round(height * (target_width / width) / multiple) * multiple
|
| 96 |
|
| 97 |
|
| 98 |
def pil_resize(frame: np.ndarray, size: tuple[int, int]) -> np.ndarray:
|
|
|
|
| 99 |
from PIL import Image
|
| 100 |
frame = np.asarray(frame)
|
| 101 |
if frame.dtype != np.uint8 or frame.ndim != 3 or frame.shape[-1] != 3:
|
|
|
|
| 114 |
"reference": "DGGT datasets/dataset.py:60-136 image loader (before ToTensor)"}
|
| 115 |
|
| 116 |
|
|
|
|
| 117 |
@functools.lru_cache(maxsize=None)
|
| 118 |
def _tool_version(binary: str) -> str:
|
| 119 |
result = subprocess.run([binary, "-version"], capture_output=True, text=True, check=True)
|
|
|
|
| 135 |
|
| 136 |
def transcode_identity(*, ffmpeg: str, ffprobe: str, config: VideoConfig, native_size: tuple[int, int],
|
| 137 |
size: tuple[int, int], decoder: dict[str, Any], crop: Any = "none") -> dict[str, Any]:
|
|
|
|
| 138 |
arguments = encoder_command("<ffmpeg>", "<rgb.mp4>.partial", size[0], size[1], 1.0, config)
|
| 139 |
arguments[arguments.index("-r") + 1] = "<video_fps:.9f>"
|
| 140 |
identity = {"schema": IDENTITY_SCHEMA, "decoder": decoder, "resize": resize_identity(native_size, size, crop),
|
|
|
|
| 145 |
return identity
|
| 146 |
|
| 147 |
|
|
|
|
| 148 |
def write_metadata(destination: Path, name: str, content: bytes) -> dict[str, Any]:
|
|
|
|
|
|
|
| 149 |
if name == VIDEO_NAME or Path(name).name != name:
|
| 150 |
raise ValueError(f"invalid metadata file name {name!r}")
|
| 151 |
destination.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 167 |
|
| 168 |
def write_scene(destination: Path, frames: Iterable[np.ndarray], *, size: tuple[int, int], fps: float, frame_count: int,
|
| 169 |
metadata: dict[str, bytes], ffmpeg: str, ffprobe: str, config: VideoConfig) -> dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
width, height = (int(v) for v in size)
|
| 171 |
destination.mkdir(parents=True, exist_ok=True)
|
| 172 |
files: dict[str, dict[str, Any]] = {}
|
|
|
|
| 194 |
dataset_id: str, camera_id: str, fps: int | float, video_fps: float, frame_count: int, time_of_day: str,
|
| 195 |
size: tuple[int, int], native_size: tuple[int, int], transcode: dict[str, Any],
|
| 196 |
provenance: dict[str, Any], extra: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
|
|
| 197 |
files = {}
|
| 198 |
for name, info in sorted(written["files"].items()):
|
| 199 |
key = "rgb" if name == VIDEO_NAME else Path(name).stem
|
|
|
|
| 213 |
|
| 214 |
|
| 215 |
def scene_complete(data_root: Path, row: dict[str, Any] | None, *, identity: dict[str, Any]) -> bool:
|
|
|
|
| 216 |
if row is None or row.get("transcode", {}).get("identity_sha256") != identity["identity_sha256"]:
|
| 217 |
return False
|
| 218 |
for info in row["files"].values():
|
|
|
|
| 222 |
return True
|
| 223 |
|
| 224 |
|
|
|
|
| 225 |
def scene_statistics_from_frames(frames: Iterable[np.ndarray], indices: Iterable[int], frame_count: int) -> dict[str, Any]:
|
|
|
|
|
|
|
| 226 |
indices = [int(i) for i in indices]
|
| 227 |
stack = [np.asarray(f) for f in frames]
|
| 228 |
if len(stack) != len(indices) or not stack:
|
|
|
|
| 243 |
|
| 244 |
|
| 245 |
def sampled_frame_indices(frame_count: int) -> list[int]:
|
|
|
|
| 246 |
return [int(i) for i in np.unique(np.linspace(0, frame_count - 1, min(SCENE_SAMPLE_FRAMES, frame_count)).round().astype(int))]
|
| 247 |
|
| 248 |
|
| 249 |
def scene_statistics_from_video(path: Path, frame_count: int) -> dict[str, Any]:
|
|
|
|
| 250 |
indices = sampled_frame_indices(frame_count)
|
| 251 |
wanted = set(indices)
|
| 252 |
frames = [f for i, f in enumerate(decode_frames(path, expected_frames=frame_count)) if i in wanted]
|
|
|
|
| 255 |
return stats
|
| 256 |
|
| 257 |
|
|
|
|
| 258 |
def read_manifest(path: Path) -> list[dict[str, Any]]:
|
| 259 |
if not path.is_file():
|
| 260 |
return []
|
|
|
|
| 262 |
|
| 263 |
|
| 264 |
def merge_manifest(path: Path, rows: Iterable[dict[str, Any]]) -> dict[str, int]:
|
|
|
|
| 265 |
rows = list(rows)
|
| 266 |
keys = [(r["source_id"], r["scene_id"]) for r in rows]
|
| 267 |
if len(set(keys)) != len(keys):
|
code/agt/dataset/sky.py
CHANGED
|
@@ -1,13 +1,3 @@
|
|
| 1 |
-
"""sky_v1: SegFormer-B5 Cityscapes sky of every clean Waymo frame, on the 518x294 grid (GPU).
|
| 2 |
-
|
| 3 |
-
Rule (DGGT datasets/tools/extract_masks.py:99-132 + datasets/dataset.py:60-136): segment each native frame the scene
|
| 4 |
-
store was converted from (Waymo FRONT JPEG, PIL RGB 1920x1280, rows [100, 1180)), sky = Cityscapes trainId 10, then
|
| 5 |
-
the native binary sky * 255 through PIL BICUBIC to 518x294 (uint8, edges keep intermediate values 1..254). Segmentation as
|
| 6 |
-
DGGT datasets/tools/extract_masks_hf.py (nvidia/segformer-b5-finetuned-cityscapes-1024-1024, keep-ratio resize to
|
| 7 |
-
(2048, 1024), slide inference with crop 1024 and stride 768), fp32, both TF32 switches off.
|
| 8 |
-
|
| 9 |
-
Output: labels/sky_v1/waymo/<scene>/{sky.h5, complete.json} and labels/sky_v1/waymo/label_manifest.json.
|
| 10 |
-
"""
|
| 11 |
from __future__ import annotations
|
| 12 |
|
| 13 |
import io
|
|
@@ -22,7 +12,7 @@ from . import scene_store as store
|
|
| 22 |
|
| 23 |
SEGFORMER = 'nvidia/segformer-b5-finetuned-cityscapes-1024-1024'
|
| 24 |
SEGFORMER_REVISION = '2c6f153e4c23c229e2fa2b188eb250607e030cd8'
|
| 25 |
-
SKY_LABEL = 10
|
| 26 |
GRID = (518, 294)
|
| 27 |
FILE = 'sky.h5'
|
| 28 |
LABEL_DIR = Path('labels') / 'sky_v1'
|
|
@@ -40,14 +30,13 @@ MANIFEST = {
|
|
| 40 |
'PIL RGB 1920x1280, rows [100, 1180))'},
|
| 41 |
}
|
| 42 |
|
| 43 |
-
# ---- DGGT datasets/tools/extract_masks_hf.py (slide inference of the mmseg SegFormer config) ------------------------
|
| 44 |
SEMANTIC_CLASSES = [
|
| 45 |
'road', 'sidewalk', 'building', 'wall', 'fence', 'pole',
|
| 46 |
'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',
|
| 47 |
'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',
|
| 48 |
'bicycle'
|
| 49 |
]
|
| 50 |
-
IMG_SCALE = (2048, 1024)
|
| 51 |
CROP = (1024, 1024)
|
| 52 |
STRIDE = (768, 768)
|
| 53 |
|
|
@@ -60,7 +49,6 @@ def _check_labels(model):
|
|
| 60 |
|
| 61 |
|
| 62 |
def _resize_keep_ratio(img):
|
| 63 |
-
"""mmcv.rescale_size with img_scale=(2048, 1024), keep_ratio=True."""
|
| 64 |
h, w = img.shape[:2]
|
| 65 |
long_edge, short_edge = max(IMG_SCALE), min(IMG_SCALE)
|
| 66 |
scale = min(long_edge / max(h, w), short_edge / min(h, w))
|
|
@@ -68,7 +56,6 @@ def _resize_keep_ratio(img):
|
|
| 68 |
|
| 69 |
|
| 70 |
def slide_inference(model, img_bgr, device, dtype):
|
| 71 |
-
"""mmseg EncoderDecoder.slide_inference for this config -> (H, W) uint8 trainIds."""
|
| 72 |
import torch
|
| 73 |
import torch.nn.functional as F
|
| 74 |
mean = torch.tensor([123.675, 116.28, 103.53]).view(1, 3, 1, 1)
|
|
@@ -76,7 +63,7 @@ def slide_inference(model, img_bgr, device, dtype):
|
|
| 76 |
orig_h, orig_w = img_bgr.shape[:2]
|
| 77 |
new_w, new_h = _resize_keep_ratio(img_bgr)
|
| 78 |
|
| 79 |
-
x = torch.from_numpy(img_bgr[..., ::-1].copy()).permute(2, 0, 1)[None].float()
|
| 80 |
x = F.interpolate(x, size=(new_h, new_w), mode="bilinear", align_corners=False)
|
| 81 |
x = ((x - mean) / std).to(device=device, dtype=dtype)
|
| 82 |
|
|
@@ -93,7 +80,7 @@ def slide_inference(model, img_bgr, device, dtype):
|
|
| 93 |
y2 = min(r * sh + ch, new_h); x2 = min(c * sw + cw, new_w)
|
| 94 |
y1 = max(y2 - ch, 0); x1 = max(x2 - cw, 0)
|
| 95 |
crop = x[:, :, y1:y2, x1:x2]
|
| 96 |
-
out = model(pixel_values=crop).logits
|
| 97 |
out = F.interpolate(out.float(), size=crop.shape[2:],
|
| 98 |
mode="bilinear", align_corners=False)
|
| 99 |
logits[:, :, y1:y2, x1:x2] += out
|
|
@@ -117,8 +104,6 @@ def precision(matmul: bool, cudnn: bool):
|
|
| 117 |
|
| 118 |
|
| 119 |
class Segmenter:
|
| 120 |
-
"""SegFormer-B5 Cityscapes, loaded once (``segformer`` = a local snapshot directory or the hub id)."""
|
| 121 |
-
|
| 122 |
def __init__(self, segformer: str = SEGFORMER, revision: str | None = SEGFORMER_REVISION):
|
| 123 |
import torch
|
| 124 |
from transformers import SegformerForSemanticSegmentation
|
|
@@ -131,7 +116,6 @@ class Segmenter:
|
|
| 131 |
self.torch = torch
|
| 132 |
|
| 133 |
def native(self, frame_rgb: np.ndarray) -> np.ndarray:
|
| 134 |
-
"""(H, W, 3) uint8 RGB -> native binary sky (bool)."""
|
| 135 |
torch = self.torch
|
| 136 |
with precision(matmul=False, cudnn=False), torch.inference_mode():
|
| 137 |
labels = slide_inference(self.model, frame_rgb[..., ::-1].copy(), 'cuda', torch.float32)
|
|
@@ -139,13 +123,11 @@ class Segmenter:
|
|
| 139 |
|
| 140 |
|
| 141 |
def bicubic_sky(binary: np.ndarray) -> np.ndarray:
|
| 142 |
-
"""Native binary -> (294, 518) uint8 BICUBIC value (PIL 'L' mode)."""
|
| 143 |
from PIL import Image
|
| 144 |
return np.asarray(Image.fromarray(binary.astype(np.uint8) * 255).resize(GRID, Image.Resampling.BICUBIC))
|
| 145 |
|
| 146 |
|
| 147 |
def waymo_native_frames(raw: Path, camera_json: dict, frames: list):
|
| 148 |
-
"""Yield (frame index, RGB uint8 1080x1920x3) for every frames.jsonl row, matched by key.frame_timestamp_micros."""
|
| 149 |
import pyarrow.parquet as pq
|
| 150 |
from PIL import Image
|
| 151 |
segment, split = camera_json['source']['segment'], camera_json['source']['split']
|
|
@@ -181,7 +163,6 @@ def write_manifest(data_root: Path) -> Path:
|
|
| 181 |
|
| 182 |
|
| 183 |
def label_scene(seg: Segmenter, data_root: Path, raw: Path, scene: str) -> dict:
|
| 184 |
-
"""Every native frame -> Segmenter -> bicubic_sky() -> labels/sky_v1/waymo/<scene>/{sky.h5, complete.json}."""
|
| 185 |
import h5py
|
| 186 |
started = time.time()
|
| 187 |
data_root = Path(data_root)
|
|
@@ -232,7 +213,7 @@ def generate(data_root: Path, raw: Path, scenes: list[str], *, segformer: str =
|
|
| 232 |
for scene in scenes:
|
| 233 |
try:
|
| 234 |
result = label_scene(seg, data_root, raw, scene)
|
| 235 |
-
except Exception as error:
|
| 236 |
failed += 1
|
| 237 |
result = {'scene': scene, 'status': 'failed', 'error': f'{type(error).__name__}: {error}'}
|
| 238 |
print(json.dumps(result), flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import io
|
|
|
|
| 12 |
|
| 13 |
SEGFORMER = 'nvidia/segformer-b5-finetuned-cityscapes-1024-1024'
|
| 14 |
SEGFORMER_REVISION = '2c6f153e4c23c229e2fa2b188eb250607e030cd8'
|
| 15 |
+
SKY_LABEL = 10
|
| 16 |
GRID = (518, 294)
|
| 17 |
FILE = 'sky.h5'
|
| 18 |
LABEL_DIR = Path('labels') / 'sky_v1'
|
|
|
|
| 30 |
'PIL RGB 1920x1280, rows [100, 1180))'},
|
| 31 |
}
|
| 32 |
|
|
|
|
| 33 |
SEMANTIC_CLASSES = [
|
| 34 |
'road', 'sidewalk', 'building', 'wall', 'fence', 'pole',
|
| 35 |
'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',
|
| 36 |
'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',
|
| 37 |
'bicycle'
|
| 38 |
]
|
| 39 |
+
IMG_SCALE = (2048, 1024)
|
| 40 |
CROP = (1024, 1024)
|
| 41 |
STRIDE = (768, 768)
|
| 42 |
|
|
|
|
| 49 |
|
| 50 |
|
| 51 |
def _resize_keep_ratio(img):
|
|
|
|
| 52 |
h, w = img.shape[:2]
|
| 53 |
long_edge, short_edge = max(IMG_SCALE), min(IMG_SCALE)
|
| 54 |
scale = min(long_edge / max(h, w), short_edge / min(h, w))
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
def slide_inference(model, img_bgr, device, dtype):
|
|
|
|
| 59 |
import torch
|
| 60 |
import torch.nn.functional as F
|
| 61 |
mean = torch.tensor([123.675, 116.28, 103.53]).view(1, 3, 1, 1)
|
|
|
|
| 63 |
orig_h, orig_w = img_bgr.shape[:2]
|
| 64 |
new_w, new_h = _resize_keep_ratio(img_bgr)
|
| 65 |
|
| 66 |
+
x = torch.from_numpy(img_bgr[..., ::-1].copy()).permute(2, 0, 1)[None].float()
|
| 67 |
x = F.interpolate(x, size=(new_h, new_w), mode="bilinear", align_corners=False)
|
| 68 |
x = ((x - mean) / std).to(device=device, dtype=dtype)
|
| 69 |
|
|
|
|
| 80 |
y2 = min(r * sh + ch, new_h); x2 = min(c * sw + cw, new_w)
|
| 81 |
y1 = max(y2 - ch, 0); x1 = max(x2 - cw, 0)
|
| 82 |
crop = x[:, :, y1:y2, x1:x2]
|
| 83 |
+
out = model(pixel_values=crop).logits
|
| 84 |
out = F.interpolate(out.float(), size=crop.shape[2:],
|
| 85 |
mode="bilinear", align_corners=False)
|
| 86 |
logits[:, :, y1:y2, x1:x2] += out
|
|
|
|
| 104 |
|
| 105 |
|
| 106 |
class Segmenter:
|
|
|
|
|
|
|
| 107 |
def __init__(self, segformer: str = SEGFORMER, revision: str | None = SEGFORMER_REVISION):
|
| 108 |
import torch
|
| 109 |
from transformers import SegformerForSemanticSegmentation
|
|
|
|
| 116 |
self.torch = torch
|
| 117 |
|
| 118 |
def native(self, frame_rgb: np.ndarray) -> np.ndarray:
|
|
|
|
| 119 |
torch = self.torch
|
| 120 |
with precision(matmul=False, cudnn=False), torch.inference_mode():
|
| 121 |
labels = slide_inference(self.model, frame_rgb[..., ::-1].copy(), 'cuda', torch.float32)
|
|
|
|
| 123 |
|
| 124 |
|
| 125 |
def bicubic_sky(binary: np.ndarray) -> np.ndarray:
|
|
|
|
| 126 |
from PIL import Image
|
| 127 |
return np.asarray(Image.fromarray(binary.astype(np.uint8) * 255).resize(GRID, Image.Resampling.BICUBIC))
|
| 128 |
|
| 129 |
|
| 130 |
def waymo_native_frames(raw: Path, camera_json: dict, frames: list):
|
|
|
|
| 131 |
import pyarrow.parquet as pq
|
| 132 |
from PIL import Image
|
| 133 |
segment, split = camera_json['source']['segment'], camera_json['source']['split']
|
|
|
|
| 163 |
|
| 164 |
|
| 165 |
def label_scene(seg: Segmenter, data_root: Path, raw: Path, scene: str) -> dict:
|
|
|
|
| 166 |
import h5py
|
| 167 |
started = time.time()
|
| 168 |
data_root = Path(data_root)
|
|
|
|
| 213 |
for scene in scenes:
|
| 214 |
try:
|
| 215 |
result = label_scene(seg, data_root, raw, scene)
|
| 216 |
+
except Exception as error:
|
| 217 |
failed += 1
|
| 218 |
result = {'scene': scene, 'status': 'failed', 'error': f'{type(error).__name__}: {error}'}
|
| 219 |
print(json.dumps(result), flush=True)
|
code/agt/dataset/video.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
"""HEVC encoding of the clean scene videos, the ffprobe check of a written video, and sequential decoding."""
|
| 2 |
-
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import json
|
|
@@ -28,7 +26,6 @@ class VideoConfig:
|
|
| 28 |
|
| 29 |
def encoder_command(ffmpeg: str, output: Path | str, width: int, height: int, fps: float,
|
| 30 |
config: VideoConfig = VideoConfig()) -> list[str]:
|
| 31 |
-
"""The ffmpeg argument list VideoEncoder runs (rgb24 on stdin -> HEVC mp4 at `output`)."""
|
| 32 |
return [
|
| 33 |
ffmpeg, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
|
| 34 |
"-s:v", f"{width}x{height}", "-r", f"{fps:.9f}", "-i", "-", "-an",
|
|
@@ -40,8 +37,6 @@ def encoder_command(ffmpeg: str, output: Path | str, width: int, height: int, fp
|
|
| 40 |
|
| 41 |
|
| 42 |
class VideoEncoder:
|
| 43 |
-
"""One RGB24 stream written to `<destination>.partial`, renamed to the destination only when ffmpeg succeeds."""
|
| 44 |
-
|
| 45 |
def __init__(self, ffmpeg: str, destination: Path, width: int, height: int, fps: float, config: VideoConfig = VideoConfig()) -> None:
|
| 46 |
if width <= 0 or height <= 0 or width % 2 or height % 2:
|
| 47 |
raise ValueError("HEVC yuv420p requires positive even width and height")
|
|
@@ -119,7 +114,6 @@ class VideoEncoder:
|
|
| 119 |
|
| 120 |
def validate_video(path: Path, *, width: int, height: int, count: int, fps: float, ffprobe: str = "ffprobe",
|
| 121 |
pixel_format: str = "yuv420p") -> dict[str, Any]:
|
| 122 |
-
"""ffprobe (counting frames) checks codec, pixel format, size, frame count, rate, start time and duration."""
|
| 123 |
result = subprocess.run(
|
| 124 |
[ffprobe, "-v", "error", "-select_streams", "v:0", "-count_frames", "-show_streams", "-of", "json", str(path)],
|
| 125 |
text=True, capture_output=True, check=False,
|
|
@@ -147,10 +141,6 @@ def validate_video(path: Path, *, width: int, height: int, count: int, fps: floa
|
|
| 147 |
|
| 148 |
def decode_frames(path: Path | str, *, thread_count: int = 2, thread_type: str | None = None,
|
| 149 |
expected_frames: int | None = None) -> Iterator[np.ndarray]:
|
| 150 |
-
"""Every frame of `path` in display order as HxWx3 uint8 rgb24, decoded once from the start.
|
| 151 |
-
|
| 152 |
-
The k-th yielded frame must carry the k-th smallest packet pts, so a dropped or reordered picture raises.
|
| 153 |
-
"""
|
| 154 |
import av
|
| 155 |
with av.open(str(path)) as container:
|
| 156 |
stream = container.streams.video[0]
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 26 |
|
| 27 |
def encoder_command(ffmpeg: str, output: Path | str, width: int, height: int, fps: float,
|
| 28 |
config: VideoConfig = VideoConfig()) -> list[str]:
|
|
|
|
| 29 |
return [
|
| 30 |
ffmpeg, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
|
| 31 |
"-s:v", f"{width}x{height}", "-r", f"{fps:.9f}", "-i", "-", "-an",
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
class VideoEncoder:
|
|
|
|
|
|
|
| 40 |
def __init__(self, ffmpeg: str, destination: Path, width: int, height: int, fps: float, config: VideoConfig = VideoConfig()) -> None:
|
| 41 |
if width <= 0 or height <= 0 or width % 2 or height % 2:
|
| 42 |
raise ValueError("HEVC yuv420p requires positive even width and height")
|
|
|
|
| 114 |
|
| 115 |
def validate_video(path: Path, *, width: int, height: int, count: int, fps: float, ffprobe: str = "ffprobe",
|
| 116 |
pixel_format: str = "yuv420p") -> dict[str, Any]:
|
|
|
|
| 117 |
result = subprocess.run(
|
| 118 |
[ffprobe, "-v", "error", "-select_streams", "v:0", "-count_frames", "-show_streams", "-of", "json", str(path)],
|
| 119 |
text=True, capture_output=True, check=False,
|
|
|
|
| 141 |
|
| 142 |
def decode_frames(path: Path | str, *, thread_count: int = 2, thread_type: str | None = None,
|
| 143 |
expected_frames: int | None = None) -> Iterator[np.ndarray]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
import av
|
| 145 |
with av.open(str(path)) as container:
|
| 146 |
stream = container.streams.video[0]
|
code/agt/dataset/visibility.py
CHANGED
|
@@ -1,20 +1,3 @@
|
|
| 1 |
-
"""gt_visibility_v2: camera-occluder visibility of every scene frame from every frame within +-OFFSET_RADIUS (GPU).
|
| 2 |
-
|
| 3 |
-
Per scene:
|
| 4 |
-
1. depth the released DGGT Waymo model (xiaomi-research/dggt model_latest_waymo) on the clean 518x294 frames in
|
| 5 |
-
blocks of 16 consecutive frames (the last block shifted back to a full 16; a frame keeps the depth of
|
| 6 |
-
the first block that covers it), camera z.
|
| 7 |
-
2. scale per frame, metric scale a_f = median(LiDAR / depth) over the clear pixels (effective_alpha < 0.05 of the
|
| 8 |
-
scene's occluder layer, outside solid_mask_hard, not sky, depth > 0, 0 < LiDAR <= 75 m); a frame with
|
| 9 |
-
fewer than 50 such pixels takes the scene median ratio. LiDAR = labels/lidar_dggt_single_v2 (nearest to
|
| 10 |
-
518x294), sky = labels/sky_v1 >= 127.5.
|
| 11 |
-
3. cameras K of the 518x294 camera.json, exposure-midpoint camera_to_world relative to frame 0.
|
| 12 |
-
4. bits for target frame t and source frame j = t + offset: a pixel of t, unprojected with its metric depth and
|
| 13 |
-
projected into j, lands inside the image and outside j's occluder mask (masks/ground_truth, alpha < 0.1).
|
| 14 |
-
Scene self-occlusion is not modelled. Stored packed: strict[t, offset, ceil(H*W/8)] (little bit order).
|
| 15 |
-
|
| 16 |
-
Output: labels/gt_visibility_v2/waymo/<scene>.h5 and labels/gt_visibility_v2/label_manifest.json.
|
| 17 |
-
"""
|
| 18 |
from __future__ import annotations
|
| 19 |
|
| 20 |
from datetime import datetime, timezone
|
|
@@ -33,12 +16,12 @@ SCHEMA = 'gt_visibility_fullframe_v2'
|
|
| 33 |
SEMANTICS = 'camera-occluder only; scene self-occlusion not modelled'
|
| 34 |
RECIPE = 'camera_only_v2'
|
| 35 |
SOURCE_POLICY = 'occluder_policy_hard_v1'
|
| 36 |
-
OFFSET_RADIUS = 20
|
| 37 |
TOLERANCES = {.05: 'strict'}
|
| 38 |
SOURCE = 'waymo'
|
| 39 |
DGGT_CHECKPOINT = 'https://huggingface.co/xiaomi-research/dggt/resolve/main/model_latest_waymo.pt'
|
| 40 |
DGGT_UNUSED_HEADS = ('point_head', 'semantic_head')
|
| 41 |
-
DGGT_PRECISION = {'matmul': False, 'cudnn': True}
|
| 42 |
SEED = 20260929
|
| 43 |
|
| 44 |
|
|
@@ -56,7 +39,6 @@ def med(x):
|
|
| 56 |
|
| 57 |
|
| 58 |
def metric_depth(D, L, alpha, solid, sky):
|
| 59 |
-
"""Per-frame LiDAR scale of the DGGT reference depth; solid is the layer's solid_mask_hard."""
|
| 60 |
Z_MAX, MIN_PX = 75.0, 50
|
| 61 |
clear = ((alpha < .05) & ~solid) & ~sky & (D > 0)
|
| 62 |
valid = clear & (L > 0) & (L <= Z_MAX)
|
|
@@ -80,8 +62,6 @@ def blocks16(frame_count):
|
|
| 80 |
|
| 81 |
|
| 82 |
def pil_resize_tensor(frames_u8, width: int = 518, multiple: int = 14):
|
| 83 |
-
"""DGGT datasets/dataset.py:60-136 image rule on decoded uint8 frames: PIL BICUBIC to width 518, height
|
| 84 |
-
round(h * 518 / w / 14) * 14, torchvision ToTensor; (N, 3, H, W) float32."""
|
| 85 |
import torch
|
| 86 |
from PIL import Image
|
| 87 |
from torchvision import transforms as TF
|
|
@@ -102,7 +82,6 @@ def pil_resize_tensor(frames_u8, width: int = 518, multiple: int = 14):
|
|
| 102 |
|
| 103 |
|
| 104 |
def load_dggt(checkpoint, device='cuda'):
|
| 105 |
-
"""The released DGGT Waymo model (strict load), unused heads dropped, frozen, eval mode."""
|
| 106 |
import torch
|
| 107 |
from agt.model.build import add_dggt_to_path
|
| 108 |
add_dggt_to_path()
|
|
@@ -120,7 +99,6 @@ def load_dggt(checkpoint, device='cuda'):
|
|
| 120 |
|
| 121 |
|
| 122 |
def canonical_depth(model, clean, *, device='cuda'):
|
| 123 |
-
"""DGGT reference depth of every frame; overlapping frames keep the first block's output."""
|
| 124 |
import torch
|
| 125 |
from .sky import precision
|
| 126 |
count = len(clean)
|
|
@@ -142,7 +120,6 @@ def canonical_depth(model, clean, *, device='cuda'):
|
|
| 142 |
|
| 143 |
|
| 144 |
def lidar_depth(data_root, record, frames, timestamps_mid_us, *, shape=(294, 518)):
|
| 145 |
-
"""labels/lidar_dggt_single_v2 of the frames, nearest (floor) to `shape`; (depth, labelled)."""
|
| 146 |
import h5py
|
| 147 |
path = Path(data_root) / 'labels/lidar_dggt_single_v2' / record.source_id / record.scene_id / 'depth.h5'
|
| 148 |
frames = [int(f) for f in frames]
|
|
@@ -166,7 +143,6 @@ def lidar_depth(data_root, record, frames, timestamps_mid_us, *, shape=(294, 518
|
|
| 166 |
|
| 167 |
|
| 168 |
def scene_geometry(record, data_root, model):
|
| 169 |
-
"""(metric depth, K, c2w, scales, owners, seconds) of one scene record (agt.data.store.build_records)."""
|
| 170 |
from agt.data.grid import ScoringGrid
|
| 171 |
from agt.data.labels import CleanSkyStore
|
| 172 |
from agt.data.scene import SceneSource
|
|
@@ -194,8 +170,6 @@ def scene_geometry(record, data_root, model):
|
|
| 194 |
|
| 195 |
|
| 196 |
def pair_bits(depth, K, c2w, occluder, *, offsets, device='cuda'):
|
| 197 |
-
"""Packed camera-occluder visibility of every (target, source = target + offset) pair; uint8 bit0, the spatial
|
| 198 |
-
axis packed over all pixels."""
|
| 199 |
import torch
|
| 200 |
from agt.model.visibility import visibility_camera
|
| 201 |
offsets = tuple(offsets)
|
|
@@ -254,7 +228,6 @@ def manifest(offsets) -> dict:
|
|
| 254 |
|
| 255 |
|
| 256 |
def generate(data_root, records, checkpoint) -> int:
|
| 257 |
-
"""Visibility files of the given records (agt.data SceneRecords with their map rows); returns failures."""
|
| 258 |
import torch
|
| 259 |
from agt.eval.labels import PolicyLabels
|
| 260 |
data_root = Path(data_root)
|
|
@@ -289,7 +262,7 @@ def generate(data_root, records, checkpoint) -> int:
|
|
| 289 |
timings=dict(forward_seconds=forward_seconds, pair_seconds=time.perf_counter() - pairs_started))
|
| 290 |
row = {'scene': record.scene_id, 'status': 'written', 'frames': record.frame_count,
|
| 291 |
'seconds': round(time.perf_counter() - started, 1)}
|
| 292 |
-
except Exception as error:
|
| 293 |
failed += 1
|
| 294 |
row = {'scene': record.scene_id, 'status': 'failed', 'error': f'{type(error).__name__}: {error}'}
|
| 295 |
print(json.dumps(row), flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from datetime import datetime, timezone
|
|
|
|
| 16 |
SEMANTICS = 'camera-occluder only; scene self-occlusion not modelled'
|
| 17 |
RECIPE = 'camera_only_v2'
|
| 18 |
SOURCE_POLICY = 'occluder_policy_hard_v1'
|
| 19 |
+
OFFSET_RADIUS = 20
|
| 20 |
TOLERANCES = {.05: 'strict'}
|
| 21 |
SOURCE = 'waymo'
|
| 22 |
DGGT_CHECKPOINT = 'https://huggingface.co/xiaomi-research/dggt/resolve/main/model_latest_waymo.pt'
|
| 23 |
DGGT_UNUSED_HEADS = ('point_head', 'semantic_head')
|
| 24 |
+
DGGT_PRECISION = {'matmul': False, 'cudnn': True}
|
| 25 |
SEED = 20260929
|
| 26 |
|
| 27 |
|
|
|
|
| 39 |
|
| 40 |
|
| 41 |
def metric_depth(D, L, alpha, solid, sky):
|
|
|
|
| 42 |
Z_MAX, MIN_PX = 75.0, 50
|
| 43 |
clear = ((alpha < .05) & ~solid) & ~sky & (D > 0)
|
| 44 |
valid = clear & (L > 0) & (L <= Z_MAX)
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
def pil_resize_tensor(frames_u8, width: int = 518, multiple: int = 14):
|
|
|
|
|
|
|
| 65 |
import torch
|
| 66 |
from PIL import Image
|
| 67 |
from torchvision import transforms as TF
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
def load_dggt(checkpoint, device='cuda'):
|
|
|
|
| 85 |
import torch
|
| 86 |
from agt.model.build import add_dggt_to_path
|
| 87 |
add_dggt_to_path()
|
|
|
|
| 99 |
|
| 100 |
|
| 101 |
def canonical_depth(model, clean, *, device='cuda'):
|
|
|
|
| 102 |
import torch
|
| 103 |
from .sky import precision
|
| 104 |
count = len(clean)
|
|
|
|
| 120 |
|
| 121 |
|
| 122 |
def lidar_depth(data_root, record, frames, timestamps_mid_us, *, shape=(294, 518)):
|
|
|
|
| 123 |
import h5py
|
| 124 |
path = Path(data_root) / 'labels/lidar_dggt_single_v2' / record.source_id / record.scene_id / 'depth.h5'
|
| 125 |
frames = [int(f) for f in frames]
|
|
|
|
| 143 |
|
| 144 |
|
| 145 |
def scene_geometry(record, data_root, model):
|
|
|
|
| 146 |
from agt.data.grid import ScoringGrid
|
| 147 |
from agt.data.labels import CleanSkyStore
|
| 148 |
from agt.data.scene import SceneSource
|
|
|
|
| 170 |
|
| 171 |
|
| 172 |
def pair_bits(depth, K, c2w, occluder, *, offsets, device='cuda'):
|
|
|
|
|
|
|
| 173 |
import torch
|
| 174 |
from agt.model.visibility import visibility_camera
|
| 175 |
offsets = tuple(offsets)
|
|
|
|
| 228 |
|
| 229 |
|
| 230 |
def generate(data_root, records, checkpoint) -> int:
|
|
|
|
| 231 |
import torch
|
| 232 |
from agt.eval.labels import PolicyLabels
|
| 233 |
data_root = Path(data_root)
|
|
|
|
| 262 |
timings=dict(forward_seconds=forward_seconds, pair_seconds=time.perf_counter() - pairs_started))
|
| 263 |
row = {'scene': record.scene_id, 'status': 'written', 'frames': record.frame_count,
|
| 264 |
'seconds': round(time.perf_counter() - started, 1)}
|
| 265 |
+
except Exception as error:
|
| 266 |
failed += 1
|
| 267 |
row = {'scene': record.scene_id, 'status': 'failed', 'error': f'{type(error).__name__}: {error}'}
|
| 268 |
print(json.dumps(row), flush=True)
|
code/agt/dataset/waymo.py
CHANGED
|
@@ -1,41 +1,3 @@
|
|
| 1 |
-
"""Waymo Open Dataset v2.0.1 FRONT camera as a scene source.
|
| 2 |
-
|
| 3 |
-
Input: ``<raw>/<split>/<component>/<segment>.parquet`` (the layout of the official v2.0.1 bucket), split in
|
| 4 |
-
validation / testing / testing_location (the official splits of the evaluation scenes). Every file is opened on its own with ``pyarrow.parquet.ParquetFile``.
|
| 5 |
-
Output per segment (written by ``scene_store``): ``rgb.mp4`` 518x294, ``frames.jsonl``, ``camera.json``,
|
| 6 |
-
``scene_stats.json``.
|
| 7 |
-
|
| 8 |
-
Columns used (see ``COLUMNS``):
|
| 9 |
-
camera_image key.segment_context_name, key.frame_timestamp_micros, key.camera_name,
|
| 10 |
-
[CameraImageComponent].image (JPEG), .pose.transform (4x4 row-major world_from_vehicle),
|
| 11 |
-
.velocity.linear_velocity.{x,y,z} (m/s, world frame), .velocity.angular_velocity.{x,y,z}
|
| 12 |
-
(rad/s, vehicle frame), .pose_timestamp (s), .rolling_shutter_params.{shutter,
|
| 13 |
-
camera_trigger_time, camera_readout_done_time} (s)
|
| 14 |
-
camera_calibration key.camera_name, [CameraCalibrationComponent].intrinsic.{f_u,f_v,c_u,c_v,k1,k2,p1,p2,k3},
|
| 15 |
-
.extrinsic.transform (4x4 row-major vehicle_from_camera, Waymo camera axes), .width, .height,
|
| 16 |
-
.rolling_shutter_direction
|
| 17 |
-
stats key.segment_context_name, [StatsComponent].time_of_day, .location, .weather
|
| 18 |
-
|
| 19 |
-
Conventions:
|
| 20 |
-
image PIL JPEG decode to RGB uint8 1920x1280, rows [100, 1180) kept (1920x1080, 16:9), then
|
| 21 |
-
``scene_store.pil_resize`` to 518x294 (PIL BICUBIC).
|
| 22 |
-
pixels Waymo image coordinates have their origin at the top-left corner of the top-left pixel. camera.json
|
| 23 |
-
uses integer pixel centres: c_int = c - 0.5; crop: v - 100; PIL scaling maps centres as
|
| 24 |
-
u' = (u + 0.5) * s - 0.5. Hence fx = f_u*sx, fy = f_v*sy, cx = c_u*sx - 0.5, cy = (c_v - 100)*sy - 0.5,
|
| 25 |
-
sx = 518/1920, sy = 294/1080.
|
| 26 |
-
distortion k1, k2, p1, p2, k3 (OpenCV order) are recorded in camera.json and NOT applied.
|
| 27 |
-
axes Waymo camera frame: x forward, y left, z up. camera.json / frames.jsonl use OpenCV axes (x right, y down,
|
| 28 |
-
z forward): camera_to_vehicle = extrinsic @ AXES_WAYMO_FROM_OPENCV.
|
| 29 |
-
poses [CameraImageComponent].pose is world_from_vehicle at pose_timestamp; the per-frame velocity extrapolates it:
|
| 30 |
-
r(t) = r + v dt with v in the world frame, R(t) = R exp([w]x dt) with w in the vehicle frame (the form of
|
| 31 |
-
the official camera_model.cc).
|
| 32 |
-
world ``local`` = the vehicle frame of frame 0 at its pose_timestamp; camera.json stores world_from_local.
|
| 33 |
-
time rolling shutter by columns or rows (rolling_shutter_direction 1..4) or global (5). Readout line k of L
|
| 34 |
-
has its exposure centre at trigger + shutter/2 + readout * k/(L-1), readout = readout_done - trigger -
|
| 35 |
-
shutter. timestamp_start_us / timestamp_end_us = the first / last visible line in readout order (the
|
| 36 |
-
row crop shortens row-wise readouts only); pose_start / pose_end_camera_to_world at those times.
|
| 37 |
-
"""
|
| 38 |
-
|
| 39 |
from __future__ import annotations
|
| 40 |
|
| 41 |
import io
|
|
@@ -52,21 +14,21 @@ SOURCE_ID = "waymo"
|
|
| 52 |
DATASET_ID = "waymo_front_crop169_v1"
|
| 53 |
CAMERA_ID = "front_crop169_v1"
|
| 54 |
SOURCE_CAMERA = "FRONT"
|
| 55 |
-
FRONT = 1
|
| 56 |
OFFICIAL_SPLITS = ("validation", "testing", "testing_location")
|
| 57 |
NATIVE_SIZE = (1920, 1280)
|
| 58 |
CROP_TOP, CROP_BOTTOM = 100, 100
|
| 59 |
-
CROPPED_SIZE = (NATIVE_SIZE[0], NATIVE_SIZE[1] - CROP_TOP - CROP_BOTTOM)
|
| 60 |
-
SIZE = store.resize_size(*CROPPED_SIZE)
|
| 61 |
NOMINAL_FPS = 10
|
| 62 |
TIME_OF_DAY = {"Day": "day", "Dawn/Dusk": "dawn", "Night": "night"}
|
| 63 |
ROLLING_SHUTTER = {1: "top_to_bottom", 2: "left_to_right", 3: "bottom_to_top", 4: "right_to_left", 5: "global"}
|
| 64 |
-
PRINCIPAL_POINT_OFFSET = -0.5
|
| 65 |
AXES_WAYMO_FROM_OPENCV = np.array([[0.0, 0.0, 1.0, 0.0],
|
| 66 |
[-1.0, 0.0, 0.0, 0.0],
|
| 67 |
[0.0, -1.0, 0.0, 0.0],
|
| 68 |
[0.0, 0.0, 0.0, 1.0]])
|
| 69 |
-
COMPONENTS = ("camera_image", "camera_calibration", "stats")
|
| 70 |
|
| 71 |
CI, CC, SC = "[CameraImageComponent].", "[CameraCalibrationComponent].", "[StatsComponent]."
|
| 72 |
COLUMNS = {
|
|
@@ -87,7 +49,6 @@ COLUMNS = {
|
|
| 87 |
"stats": {"segment": "key.segment_context_name", "time_of_day": SC + "time_of_day", "location": SC + "location",
|
| 88 |
"weather": SC + "weather"},
|
| 89 |
}
|
| 90 |
-
# The "conversion" block written into every camera.json (part of its bytes; kept unchanged).
|
| 91 |
CAMERA_JSON_CONVERSION = {
|
| 92 |
"version": "waymo_front_metadata_v1",
|
| 93 |
"principal_point": "integer pixel centres: c - 0.5 (Waymo corner origin), v - 100 (crop), u' = (u + 0.5) * s - 0.5",
|
|
@@ -102,13 +63,11 @@ CAMERA_JSON_CONVERSION = {
|
|
| 102 |
}
|
| 103 |
|
| 104 |
|
| 105 |
-
# ---- files ---------------------------------------------------------------------------------------------------
|
| 106 |
def component_path(raw: Path, split: str, component: str, segment: str) -> Path:
|
| 107 |
return Path(raw) / split / component / f"{segment}.parquet"
|
| 108 |
|
| 109 |
|
| 110 |
def find_split(raw: Path, segment: str) -> str:
|
| 111 |
-
"""The official split whose camera_image folder holds the segment."""
|
| 112 |
found = [s for s in OFFICIAL_SPLITS if component_path(raw, s, "camera_image", segment).is_file()]
|
| 113 |
if len(found) != 1:
|
| 114 |
raise FileNotFoundError(f"{segment}: camera_image parquet found in {found or 'no'} split of {raw}")
|
|
@@ -116,7 +75,6 @@ def find_split(raw: Path, segment: str) -> str:
|
|
| 116 |
|
| 117 |
|
| 118 |
def read_columns(path: Path, columns: Iterable[str]) -> dict[str, list]:
|
| 119 |
-
"""Named columns of one parquet file."""
|
| 120 |
import pyarrow.parquet as pq
|
| 121 |
handle = pq.ParquetFile(str(path))
|
| 122 |
names = {f.name for f in handle.schema_arrow}
|
|
@@ -127,15 +85,14 @@ def read_columns(path: Path, columns: Iterable[str]) -> dict[str, list]:
|
|
| 127 |
return handle.read(columns=columns).to_pydict()
|
| 128 |
|
| 129 |
|
| 130 |
-
# ---- one segment ---------------------------------------------------------------------------------------------------
|
| 131 |
@dataclass
|
| 132 |
class WaymoSegment:
|
| 133 |
split: str
|
| 134 |
segment: str
|
| 135 |
-
frames: list[dict[str, Any]]
|
| 136 |
calibration: dict[str, Any]
|
| 137 |
stats: dict[str, Any]
|
| 138 |
-
other_cameras: int = 0
|
| 139 |
paths: dict[str, str] = field(default_factory=dict)
|
| 140 |
|
| 141 |
@property
|
|
@@ -196,9 +153,7 @@ def read_segment(raw: Path, split: str, segment: str, *, images: bool = True) ->
|
|
| 196 |
paths={c: str(p) for c, p in paths.items()})
|
| 197 |
|
| 198 |
|
| 199 |
-
# ---- pixels ---------------------------------------------------------------------------------------------------------
|
| 200 |
def decode_jpeg(data: bytes) -> np.ndarray:
|
| 201 |
-
"""HxWx3 uint8 RGB of one Waymo JPEG (PIL / libjpeg-turbo, full decode, no draft mode)."""
|
| 202 |
from PIL import Image
|
| 203 |
with Image.open(io.BytesIO(data)) as image:
|
| 204 |
if image.format != "JPEG":
|
|
@@ -208,7 +163,6 @@ def decode_jpeg(data: bytes) -> np.ndarray:
|
|
| 208 |
|
| 209 |
|
| 210 |
def crop_rows(frame: np.ndarray, top: int = CROP_TOP, bottom: int = CROP_BOTTOM) -> np.ndarray:
|
| 211 |
-
"""Drop ``top`` rows at the top and ``bottom`` rows at the bottom (C-contiguous copy)."""
|
| 212 |
frame = np.asarray(frame)
|
| 213 |
if frame.shape[:2] != (NATIVE_SIZE[1], NATIVE_SIZE[0]):
|
| 214 |
raise ValueError(f"camera image is {frame.shape}, expected {NATIVE_SIZE[1]}x{NATIVE_SIZE[0]}")
|
|
@@ -216,7 +170,6 @@ def crop_rows(frame: np.ndarray, top: int = CROP_TOP, bottom: int = CROP_BOTTOM)
|
|
| 216 |
|
| 217 |
|
| 218 |
def clean_frame(data: bytes, size: tuple[int, int] = SIZE) -> np.ndarray:
|
| 219 |
-
"""JPEG -> RGB 1920x1280 -> rows [100, 1180) -> PIL BICUBIC 518x294 (uint8)."""
|
| 220 |
return store.pil_resize(crop_rows(decode_jpeg(data)), size)
|
| 221 |
|
| 222 |
|
|
@@ -238,26 +191,22 @@ def crop_identity() -> dict[str, Any]:
|
|
| 238 |
"input_size": list(NATIVE_SIZE), "output_size": list(CROPPED_SIZE), "rule": "frame[100:1180, :]"}
|
| 239 |
|
| 240 |
|
| 241 |
-
# ---- camera model -------------------------------------------------------------------------------------------------
|
| 242 |
def scale_factors(size: tuple[int, int] = SIZE) -> tuple[float, float]:
|
| 243 |
return size[0] / CROPPED_SIZE[0], size[1] / CROPPED_SIZE[1]
|
| 244 |
|
| 245 |
|
| 246 |
def crop_scale_intrinsics(f_u: float, f_v: float, c_u: float, c_v: float, size: tuple[int, int] = SIZE,
|
| 247 |
principal_offset: float = PRINCIPAL_POINT_OFFSET) -> dict[str, float]:
|
| 248 |
-
"""Native Waymo intrinsics -> pinhole on the stored grid, integer pixel centres."""
|
| 249 |
sx, sy = scale_factors(size)
|
| 250 |
cx_int, cy_int = c_u + principal_offset, c_v + principal_offset - CROP_TOP
|
| 251 |
return {"fx": f_u * sx, "fy": f_v * sy, "cx": (cx_int + 0.5) * sx - 0.5, "cy": (cy_int + 0.5) * sy - 0.5}
|
| 252 |
|
| 253 |
|
| 254 |
def camera_to_vehicle(extrinsic: np.ndarray) -> np.ndarray:
|
| 255 |
-
"""OpenCV-axes camera -> vehicle from Waymo's vehicle_from_camera extrinsic (camera x forward, y left, z up)."""
|
| 256 |
return np.asarray(extrinsic, np.float64).reshape(4, 4) @ AXES_WAYMO_FROM_OPENCV
|
| 257 |
|
| 258 |
|
| 259 |
def vehicle_pose_at(pose: np.ndarray, linear: Iterable[float], angular: Iterable[float], dt: float) -> np.ndarray:
|
| 260 |
-
"""world_from_vehicle at pose time + dt: r + v dt (v in the world frame), R exp([w]x dt) (w in the vehicle frame)."""
|
| 261 |
from scipy.spatial.transform import Rotation
|
| 262 |
pose = np.asarray(pose, np.float64).reshape(4, 4)
|
| 263 |
out = np.eye(4)
|
|
@@ -267,7 +216,6 @@ def vehicle_pose_at(pose: np.ndarray, linear: Iterable[float], angular: Iterable
|
|
| 267 |
|
| 268 |
|
| 269 |
def readout_line_times(trigger: float, readout_done: float, shutter: float, direction: int) -> tuple[float, float, float]:
|
| 270 |
-
"""(first visible line, image centre, last visible line) exposure-centre times in seconds."""
|
| 271 |
first_centre = trigger + shutter / 2.0
|
| 272 |
readout = readout_done - trigger - shutter
|
| 273 |
if readout < 0 or shutter < 0:
|
|
@@ -290,7 +238,6 @@ def to_us(seconds: float) -> int:
|
|
| 290 |
|
| 291 |
|
| 292 |
def frame_records(segment: WaymoSegment) -> tuple[list[dict[str, Any]], np.ndarray]:
|
| 293 |
-
"""frames.jsonl rows (camera_to_world in the local world, OpenCV axes) and world_from_local."""
|
| 294 |
calibration = segment.calibration
|
| 295 |
direction = int(calibration["rolling_shutter_direction"])
|
| 296 |
cam_to_vehicle = camera_to_vehicle(calibration["extrinsic"])
|
|
@@ -320,8 +267,6 @@ def frame_records(segment: WaymoSegment) -> tuple[list[dict[str, Any]], np.ndarr
|
|
| 320 |
|
| 321 |
|
| 322 |
def timing_summary(starts_us: Iterable[int]) -> dict[str, Any]:
|
| 323 |
-
"""Frame-rate facts of the real start timestamps (1 % interval jitter, 0.1 frame drift bounds are reported,
|
| 324 |
-
not enforced: Waymo segments keep dropped frames as gaps)."""
|
| 325 |
starts = np.asarray(list(starts_us), np.int64)
|
| 326 |
if len(starts) < 2 or np.any(np.diff(starts) <= 0):
|
| 327 |
raise ValueError("start timestamps must be strictly increasing")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import io
|
|
|
|
| 14 |
DATASET_ID = "waymo_front_crop169_v1"
|
| 15 |
CAMERA_ID = "front_crop169_v1"
|
| 16 |
SOURCE_CAMERA = "FRONT"
|
| 17 |
+
FRONT = 1
|
| 18 |
OFFICIAL_SPLITS = ("validation", "testing", "testing_location")
|
| 19 |
NATIVE_SIZE = (1920, 1280)
|
| 20 |
CROP_TOP, CROP_BOTTOM = 100, 100
|
| 21 |
+
CROPPED_SIZE = (NATIVE_SIZE[0], NATIVE_SIZE[1] - CROP_TOP - CROP_BOTTOM)
|
| 22 |
+
SIZE = store.resize_size(*CROPPED_SIZE)
|
| 23 |
NOMINAL_FPS = 10
|
| 24 |
TIME_OF_DAY = {"Day": "day", "Dawn/Dusk": "dawn", "Night": "night"}
|
| 25 |
ROLLING_SHUTTER = {1: "top_to_bottom", 2: "left_to_right", 3: "bottom_to_top", 4: "right_to_left", 5: "global"}
|
| 26 |
+
PRINCIPAL_POINT_OFFSET = -0.5
|
| 27 |
AXES_WAYMO_FROM_OPENCV = np.array([[0.0, 0.0, 1.0, 0.0],
|
| 28 |
[-1.0, 0.0, 0.0, 0.0],
|
| 29 |
[0.0, -1.0, 0.0, 0.0],
|
| 30 |
[0.0, 0.0, 0.0, 1.0]])
|
| 31 |
+
COMPONENTS = ("camera_image", "camera_calibration", "stats")
|
| 32 |
|
| 33 |
CI, CC, SC = "[CameraImageComponent].", "[CameraCalibrationComponent].", "[StatsComponent]."
|
| 34 |
COLUMNS = {
|
|
|
|
| 49 |
"stats": {"segment": "key.segment_context_name", "time_of_day": SC + "time_of_day", "location": SC + "location",
|
| 50 |
"weather": SC + "weather"},
|
| 51 |
}
|
|
|
|
| 52 |
CAMERA_JSON_CONVERSION = {
|
| 53 |
"version": "waymo_front_metadata_v1",
|
| 54 |
"principal_point": "integer pixel centres: c - 0.5 (Waymo corner origin), v - 100 (crop), u' = (u + 0.5) * s - 0.5",
|
|
|
|
| 63 |
}
|
| 64 |
|
| 65 |
|
|
|
|
| 66 |
def component_path(raw: Path, split: str, component: str, segment: str) -> Path:
|
| 67 |
return Path(raw) / split / component / f"{segment}.parquet"
|
| 68 |
|
| 69 |
|
| 70 |
def find_split(raw: Path, segment: str) -> str:
|
|
|
|
| 71 |
found = [s for s in OFFICIAL_SPLITS if component_path(raw, s, "camera_image", segment).is_file()]
|
| 72 |
if len(found) != 1:
|
| 73 |
raise FileNotFoundError(f"{segment}: camera_image parquet found in {found or 'no'} split of {raw}")
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
def read_columns(path: Path, columns: Iterable[str]) -> dict[str, list]:
|
|
|
|
| 78 |
import pyarrow.parquet as pq
|
| 79 |
handle = pq.ParquetFile(str(path))
|
| 80 |
names = {f.name for f in handle.schema_arrow}
|
|
|
|
| 85 |
return handle.read(columns=columns).to_pydict()
|
| 86 |
|
| 87 |
|
|
|
|
| 88 |
@dataclass
|
| 89 |
class WaymoSegment:
|
| 90 |
split: str
|
| 91 |
segment: str
|
| 92 |
+
frames: list[dict[str, Any]]
|
| 93 |
calibration: dict[str, Any]
|
| 94 |
stats: dict[str, Any]
|
| 95 |
+
other_cameras: int = 0
|
| 96 |
paths: dict[str, str] = field(default_factory=dict)
|
| 97 |
|
| 98 |
@property
|
|
|
|
| 153 |
paths={c: str(p) for c, p in paths.items()})
|
| 154 |
|
| 155 |
|
|
|
|
| 156 |
def decode_jpeg(data: bytes) -> np.ndarray:
|
|
|
|
| 157 |
from PIL import Image
|
| 158 |
with Image.open(io.BytesIO(data)) as image:
|
| 159 |
if image.format != "JPEG":
|
|
|
|
| 163 |
|
| 164 |
|
| 165 |
def crop_rows(frame: np.ndarray, top: int = CROP_TOP, bottom: int = CROP_BOTTOM) -> np.ndarray:
|
|
|
|
| 166 |
frame = np.asarray(frame)
|
| 167 |
if frame.shape[:2] != (NATIVE_SIZE[1], NATIVE_SIZE[0]):
|
| 168 |
raise ValueError(f"camera image is {frame.shape}, expected {NATIVE_SIZE[1]}x{NATIVE_SIZE[0]}")
|
|
|
|
| 170 |
|
| 171 |
|
| 172 |
def clean_frame(data: bytes, size: tuple[int, int] = SIZE) -> np.ndarray:
|
|
|
|
| 173 |
return store.pil_resize(crop_rows(decode_jpeg(data)), size)
|
| 174 |
|
| 175 |
|
|
|
|
| 191 |
"input_size": list(NATIVE_SIZE), "output_size": list(CROPPED_SIZE), "rule": "frame[100:1180, :]"}
|
| 192 |
|
| 193 |
|
|
|
|
| 194 |
def scale_factors(size: tuple[int, int] = SIZE) -> tuple[float, float]:
|
| 195 |
return size[0] / CROPPED_SIZE[0], size[1] / CROPPED_SIZE[1]
|
| 196 |
|
| 197 |
|
| 198 |
def crop_scale_intrinsics(f_u: float, f_v: float, c_u: float, c_v: float, size: tuple[int, int] = SIZE,
|
| 199 |
principal_offset: float = PRINCIPAL_POINT_OFFSET) -> dict[str, float]:
|
|
|
|
| 200 |
sx, sy = scale_factors(size)
|
| 201 |
cx_int, cy_int = c_u + principal_offset, c_v + principal_offset - CROP_TOP
|
| 202 |
return {"fx": f_u * sx, "fy": f_v * sy, "cx": (cx_int + 0.5) * sx - 0.5, "cy": (cy_int + 0.5) * sy - 0.5}
|
| 203 |
|
| 204 |
|
| 205 |
def camera_to_vehicle(extrinsic: np.ndarray) -> np.ndarray:
|
|
|
|
| 206 |
return np.asarray(extrinsic, np.float64).reshape(4, 4) @ AXES_WAYMO_FROM_OPENCV
|
| 207 |
|
| 208 |
|
| 209 |
def vehicle_pose_at(pose: np.ndarray, linear: Iterable[float], angular: Iterable[float], dt: float) -> np.ndarray:
|
|
|
|
| 210 |
from scipy.spatial.transform import Rotation
|
| 211 |
pose = np.asarray(pose, np.float64).reshape(4, 4)
|
| 212 |
out = np.eye(4)
|
|
|
|
| 216 |
|
| 217 |
|
| 218 |
def readout_line_times(trigger: float, readout_done: float, shutter: float, direction: int) -> tuple[float, float, float]:
|
|
|
|
| 219 |
first_centre = trigger + shutter / 2.0
|
| 220 |
readout = readout_done - trigger - shutter
|
| 221 |
if readout < 0 or shutter < 0:
|
|
|
|
| 238 |
|
| 239 |
|
| 240 |
def frame_records(segment: WaymoSegment) -> tuple[list[dict[str, Any]], np.ndarray]:
|
|
|
|
| 241 |
calibration = segment.calibration
|
| 242 |
direction = int(calibration["rolling_shutter_direction"])
|
| 243 |
cam_to_vehicle = camera_to_vehicle(calibration["extrinsic"])
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
def timing_summary(starts_us: Iterable[int]) -> dict[str, Any]:
|
|
|
|
|
|
|
| 270 |
starts = np.asarray(list(starts_us), np.int64)
|
| 271 |
if len(starts) < 2 or np.any(np.diff(starts) <= 0):
|
| 272 |
raise ValueError("start timestamps must be strictly increasing")
|
code/agt/eval/__init__.py
CHANGED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
"""Scoring of method directories: whole-frame, regional, hole and depth metrics."""
|
|
|
|
|
|
code/agt/eval/depth.py
CHANGED
|
@@ -1,25 +1,3 @@
|
|
| 1 |
-
"""Depth metrics against single-scan LiDAR: per-frame affine D-RMSE and AbsRel, and the LiDAR label reader.
|
| 2 |
-
|
| 3 |
-
Per frame, on the 518x294 scoring grid:
|
| 4 |
-
|
| 5 |
-
V = valid & isfinite(gt) & gt > 0 & gt <= Z_MAX_M & ~sky (decided by GT only)
|
| 6 |
-
M = {u in V : pred(u) not finite, or alpha(u) not finite, or alpha(u) <= eps} (missing prediction)
|
| 7 |
-
(a, b) = argmin sum_{V\\M} (a * pred + b - gt)^2 float64 lstsq on [pred, 1], prediction -> GT
|
| 8 |
-
D-RMSE = sqrt((sum_{V\\M} (a * pred + b - gt)^2 + sum_M (gt - mean(gt_V))^2) / |V|)
|
| 9 |
-
AbsRel = mean over V\\M of |a * pred + b - gt| / gt
|
| 10 |
-
|
| 11 |
-
Holes of the GT never enter the fit or the denominator; M stays in V with the no-information residual, so a fully
|
| 12 |
-
missing frame scores the GT standard deviation of V. Coefficient signs are not constrained (as DGGT's lstsq). A
|
| 13 |
-
degenerate fit (fewer than 2 pixels in V\\M, or rank < 2) uses the least-squares constant on V\\M. One fit per frame
|
| 14 |
-
is shared by the whole frame and every region.
|
| 15 |
-
|
| 16 |
-
Evaluable frames (GT side): |scan midpoint - RGB exposure midpoint| <= 50 ms and the label's native cells behind V
|
| 17 |
-
>= 2000. Aggregation: frame -> mean over the evaluable frames of a frame set in a clip -> equal-weight clip mean.
|
| 18 |
-
|
| 19 |
-
Labels (labels/lidar_dggt_single_v2/<source>/<scene>/depth.h5): 'depth' on the source's quarter grid (Waymo
|
| 20 |
-
480x270), 0 = no point, upsampled to 518x294 by DGGT's floor-nearest rule (datasets/dataset.py resize_flow); sky from
|
| 21 |
-
labels/sky_v1/<source>/<scene>/sky.h5 'sky' (uint8, >= 128 is sky).
|
| 22 |
-
"""
|
| 23 |
from __future__ import annotations
|
| 24 |
|
| 25 |
from pathlib import Path
|
|
@@ -27,7 +5,7 @@ from pathlib import Path
|
|
| 27 |
import numpy as np
|
| 28 |
|
| 29 |
Z_MAX_M = 75.0
|
| 30 |
-
SKY_THRESHOLD = 128
|
| 31 |
MAX_TIME_OFFSET_MS = 50.0
|
| 32 |
MIN_NATIVE_CELLS = 2000
|
| 33 |
GRID = (518, 294)
|
|
@@ -35,9 +13,7 @@ DEPTH_FILE = 'depth.h5'
|
|
| 35 |
SKY_FILE = 'sky.h5'
|
| 36 |
|
| 37 |
|
| 38 |
-
# ---- metrics ----------------------------------------------------------------------------------
|
| 39 |
def eval_mask(gt, valid, sky=None, z_max=Z_MAX_M):
|
| 40 |
-
"""V from the GT side only. sky: bool mask (True = sky) or None (no exclusion)."""
|
| 41 |
gt = np.asarray(gt)
|
| 42 |
mask = np.asarray(valid, bool) & np.isfinite(gt)
|
| 43 |
with np.errstate(invalid='ignore'):
|
|
@@ -48,7 +24,6 @@ def eval_mask(gt, valid, sky=None, z_max=Z_MAX_M):
|
|
| 48 |
|
| 49 |
|
| 50 |
def missing_mask(pred, alpha, eps):
|
| 51 |
-
"""Missing prediction (per pixel): non-finite depth, or non-finite / <= eps accumulated alpha."""
|
| 52 |
missing = ~np.isfinite(pred)
|
| 53 |
if alpha is not None:
|
| 54 |
alpha = np.asarray(alpha, np.float64)
|
|
@@ -58,7 +33,6 @@ def missing_mask(pred, alpha, eps):
|
|
| 58 |
|
| 59 |
|
| 60 |
def frame_drmse(pred, gt, mask, *, alpha=None, eps):
|
| 61 |
-
"""One frame. pred / gt / alpha: (H, W) on the scoring grid; mask: V. pred may be None (all of V missing)."""
|
| 62 |
mask = np.asarray(mask, bool)
|
| 63 |
n = int(mask.sum())
|
| 64 |
if n == 0:
|
|
@@ -99,7 +73,6 @@ def frame_drmse(pred, gt, mask, *, alpha=None, eps):
|
|
| 99 |
|
| 100 |
|
| 101 |
def frame_metrics(pred, gt, mask, *, alpha=None, eps, regions=None):
|
| 102 |
-
"""One fit shared by the whole frame, all regions, D-RMSE and AbsRel."""
|
| 103 |
mask = np.asarray(mask, bool)
|
| 104 |
fit = frame_drmse(pred, gt, mask, alpha=alpha, eps=eps)
|
| 105 |
gt = np.asarray(gt, np.float64)
|
|
@@ -116,7 +89,7 @@ def frame_metrics(pred, gt, mask, *, alpha=None, eps, regions=None):
|
|
| 116 |
n, n_pred = int(valid.sum()), int(present.sum())
|
| 117 |
value = float(np.sqrt(squared[valid].mean())) if n else None
|
| 118 |
if name == 'full':
|
| 119 |
-
value = fit['value']
|
| 120 |
out[name] = dict(drmse=value, absrel=float(relative[present].mean()) if n_pred else None,
|
| 121 |
n_valid=n, n_pred=n_pred, n_missing=int((valid & missing).sum()))
|
| 122 |
return dict(fit=fit, regions=out)
|
|
@@ -137,9 +110,7 @@ def aggregate(frames, positions):
|
|
| 137 |
return out
|
| 138 |
|
| 139 |
|
| 140 |
-
# ---- labels -----------------------------------------------------------------------------------
|
| 141 |
def upsample_index(src: int, dst: int) -> np.ndarray:
|
| 142 |
-
"""torch F.interpolate(mode='nearest') / cv2.INTER_NEAREST source index for each target index."""
|
| 143 |
return np.minimum(np.floor(np.arange(dst) * (src / dst)).astype(np.int64), src - 1)
|
| 144 |
|
| 145 |
|
|
@@ -149,7 +120,6 @@ def upsample_nearest(quarter: np.ndarray, width=GRID[0], height=GRID[1]) -> np.n
|
|
| 149 |
|
| 150 |
|
| 151 |
def native_cells_in_v(V, native_shape) -> int:
|
| 152 |
-
"""Number of native quarter-grid cells behind the 518x294 mask V (the floor-nearest source cell of each pixel)."""
|
| 153 |
h, w = native_shape
|
| 154 |
iy, ix = upsample_index(h, V.shape[-2]), upsample_index(w, V.shape[-1])
|
| 155 |
return int(len(np.unique((iy[:, None] * w + ix[None, :])[V])))
|
|
@@ -165,8 +135,6 @@ def frame_reasons(offset_us, cells) -> list:
|
|
| 165 |
|
| 166 |
|
| 167 |
class DepthLabels:
|
| 168 |
-
"""LiDAR depth labels (labels/lidar_dggt_single_v2) + clean sky (labels/sky_v1) of one or more sources."""
|
| 169 |
-
|
| 170 |
def __init__(self, root, sky_root, sources):
|
| 171 |
self.root, self.sky_root = Path(root), Path(sky_root)
|
| 172 |
self.sources = tuple(sources)
|
|
@@ -194,10 +162,9 @@ class DepthLabels:
|
|
| 194 |
def _rows(f, indices):
|
| 195 |
stored = f['frame_indices'][:]
|
| 196 |
lookup = {int(k): i for i, k in enumerate(stored)}
|
| 197 |
-
return [lookup[int(i)] for i in indices]
|
| 198 |
|
| 199 |
def read(self, scene_id, indices) -> dict:
|
| 200 |
-
"""-> native depth (n, h, w), depth_z_m / valid / eval_valid / sky (n, 294, 518), scan offset (n,) us."""
|
| 201 |
import h5py
|
| 202 |
indices = [int(i) for i in indices]
|
| 203 |
with h5py.File(self.path(scene_id), 'r') as f:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from pathlib import Path
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
|
| 7 |
Z_MAX_M = 75.0
|
| 8 |
+
SKY_THRESHOLD = 128
|
| 9 |
MAX_TIME_OFFSET_MS = 50.0
|
| 10 |
MIN_NATIVE_CELLS = 2000
|
| 11 |
GRID = (518, 294)
|
|
|
|
| 13 |
SKY_FILE = 'sky.h5'
|
| 14 |
|
| 15 |
|
|
|
|
| 16 |
def eval_mask(gt, valid, sky=None, z_max=Z_MAX_M):
|
|
|
|
| 17 |
gt = np.asarray(gt)
|
| 18 |
mask = np.asarray(valid, bool) & np.isfinite(gt)
|
| 19 |
with np.errstate(invalid='ignore'):
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
def missing_mask(pred, alpha, eps):
|
|
|
|
| 27 |
missing = ~np.isfinite(pred)
|
| 28 |
if alpha is not None:
|
| 29 |
alpha = np.asarray(alpha, np.float64)
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
def frame_drmse(pred, gt, mask, *, alpha=None, eps):
|
|
|
|
| 36 |
mask = np.asarray(mask, bool)
|
| 37 |
n = int(mask.sum())
|
| 38 |
if n == 0:
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
def frame_metrics(pred, gt, mask, *, alpha=None, eps, regions=None):
|
|
|
|
| 76 |
mask = np.asarray(mask, bool)
|
| 77 |
fit = frame_drmse(pred, gt, mask, alpha=alpha, eps=eps)
|
| 78 |
gt = np.asarray(gt, np.float64)
|
|
|
|
| 89 |
n, n_pred = int(valid.sum()), int(present.sum())
|
| 90 |
value = float(np.sqrt(squared[valid].mean())) if n else None
|
| 91 |
if name == 'full':
|
| 92 |
+
value = fit['value']
|
| 93 |
out[name] = dict(drmse=value, absrel=float(relative[present].mean()) if n_pred else None,
|
| 94 |
n_valid=n, n_pred=n_pred, n_missing=int((valid & missing).sum()))
|
| 95 |
return dict(fit=fit, regions=out)
|
|
|
|
| 110 |
return out
|
| 111 |
|
| 112 |
|
|
|
|
| 113 |
def upsample_index(src: int, dst: int) -> np.ndarray:
|
|
|
|
| 114 |
return np.minimum(np.floor(np.arange(dst) * (src / dst)).astype(np.int64), src - 1)
|
| 115 |
|
| 116 |
|
|
|
|
| 120 |
|
| 121 |
|
| 122 |
def native_cells_in_v(V, native_shape) -> int:
|
|
|
|
| 123 |
h, w = native_shape
|
| 124 |
iy, ix = upsample_index(h, V.shape[-2]), upsample_index(w, V.shape[-1])
|
| 125 |
return int(len(np.unique((iy[:, None] * w + ix[None, :])[V])))
|
|
|
|
| 135 |
|
| 136 |
|
| 137 |
class DepthLabels:
|
|
|
|
|
|
|
| 138 |
def __init__(self, root, sky_root, sources):
|
| 139 |
self.root, self.sky_root = Path(root), Path(sky_root)
|
| 140 |
self.sources = tuple(sources)
|
|
|
|
| 162 |
def _rows(f, indices):
|
| 163 |
stored = f['frame_indices'][:]
|
| 164 |
lookup = {int(k): i for i, k in enumerate(stored)}
|
| 165 |
+
return [lookup[int(i)] for i in indices]
|
| 166 |
|
| 167 |
def read(self, scene_id, indices) -> dict:
|
|
|
|
| 168 |
import h5py
|
| 169 |
indices = [int(i) for i in indices]
|
| 170 |
with h5py.File(self.path(scene_id), 'r') as f:
|
code/agt/eval/hole.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
"""Hole (U region) metrics: LPIPS over U, DISTS on GT-fixed context boxes of U components, seam gradient residual,
|
| 2 |
-
opacity / coverage statistics of optional method maps, and collection KID / FID over the boxes."""
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import math
|
|
@@ -27,7 +25,6 @@ def component_boxes(mask, expansion=.1):
|
|
| 27 |
|
| 28 |
|
| 29 |
def seam_residual(pred, gt, U):
|
| 30 |
-
"""GT-referenced gradient mismatch on horizontal/vertical edges crossing U."""
|
| 31 |
total, count = 0., 0
|
| 32 |
for axis in (0, 1):
|
| 33 |
a = [slice(None)] * 2
|
|
@@ -50,11 +47,6 @@ def coverage(pred, truth, domain):
|
|
| 50 |
|
| 51 |
|
| 52 |
def frechet_distance(fake, real):
|
| 53 |
-
"""FID between two (N,2048) Inception feature sets, float64 on CPU.
|
| 54 |
-
|
| 55 |
-
Mirrors torchmetrics 1.9.0 FrechetInceptionDistance.update/compute (feature sums and sum of outer products in
|
| 56 |
-
float64, unbiased covariance), then calls torchmetrics' own _compute_fid. Deterministic, no subsampling.
|
| 57 |
-
"""
|
| 58 |
import torch
|
| 59 |
from torchmetrics.image.fid import _compute_fid
|
| 60 |
stats = []
|
|
@@ -73,7 +65,7 @@ class HoleScorer:
|
|
| 73 |
self.device = region_scorer.device
|
| 74 |
self.enable_dists, self.enable_kid, self.enable_fid = dists, kid, fid
|
| 75 |
self._dists, self._kid = None, None
|
| 76 |
-
self.features = {}
|
| 77 |
|
| 78 |
def dists(self, pred, gt):
|
| 79 |
import torch
|
|
@@ -117,7 +109,6 @@ class HoleScorer:
|
|
| 117 |
required=MIN_COLLECTION_BOXES)
|
| 118 |
metric = self.kid()
|
| 119 |
metric.reset()
|
| 120 |
-
# Torchmetrics' default polynomial MMD estimator and default subset sampling, fixed seed.
|
| 121 |
metric.fake_features = [p.to(self.device) for p, _ in pairs]
|
| 122 |
metric.real_features = [g.to(self.device) for _, g in pairs]
|
| 123 |
with torch.random.fork_rng(devices=[]):
|
|
@@ -126,7 +117,6 @@ class HoleScorer:
|
|
| 126 |
return dict(value=float(value), std=float(std), n_boxes=len(pairs), status='ok')
|
| 127 |
|
| 128 |
def collection_fid(self, keys):
|
| 129 |
-
"""Collection FID on the same box features and minimum box count as KID."""
|
| 130 |
import torch
|
| 131 |
pairs = [pair for key in keys for pair in self.features.get(key, [])]
|
| 132 |
if len(pairs) < MIN_COLLECTION_BOXES:
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import math
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
def seam_residual(pred, gt, U):
|
|
|
|
| 28 |
total, count = 0., 0
|
| 29 |
for axis in (0, 1):
|
| 30 |
a = [slice(None)] * 2
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
def frechet_distance(fake, real):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
import torch
|
| 51 |
from torchmetrics.image.fid import _compute_fid
|
| 52 |
stats = []
|
|
|
|
| 65 |
self.device = region_scorer.device
|
| 66 |
self.enable_dists, self.enable_kid, self.enable_fid = dists, kid, fid
|
| 67 |
self._dists, self._kid = None, None
|
| 68 |
+
self.features = {}
|
| 69 |
|
| 70 |
def dists(self, pred, gt):
|
| 71 |
import torch
|
|
|
|
| 109 |
required=MIN_COLLECTION_BOXES)
|
| 110 |
metric = self.kid()
|
| 111 |
metric.reset()
|
|
|
|
| 112 |
metric.fake_features = [p.to(self.device) for p, _ in pairs]
|
| 113 |
metric.real_features = [g.to(self.device) for _, g in pairs]
|
| 114 |
with torch.random.fork_rng(devices=[]):
|
|
|
|
| 117 |
return dict(value=float(value), std=float(std), n_boxes=len(pairs), status='ok')
|
| 118 |
|
| 119 |
def collection_fid(self, keys):
|
|
|
|
| 120 |
import torch
|
| 121 |
pairs = [pair for key in keys for pair in self.features.get(key, [])]
|
| 122 |
if len(pairs) < MIN_COLLECTION_BOXES:
|
code/agt/eval/labels.py
CHANGED
|
@@ -1,14 +1,3 @@
|
|
| 1 |
-
"""Read-only scoring mask and GT visibility, independent of the method's input masks.
|
| 2 |
-
|
| 3 |
-
Scoring mask: masks/<folder>/<source>/<scene>/mask.h5 (default folder ground_truth, dataset occluder_policy_hard),
|
| 4 |
-
uint8 0/1 on 294x518, static across frames (2D) or frame-indexed (3D with frame_indices). Never resized, dilated or
|
| 5 |
-
substituted.
|
| 6 |
-
|
| 7 |
-
GT visibility V (labels/gt_visibility_v2/<source>/<scene>.h5): for every scene frame and every native-frame offset,
|
| 8 |
-
the packed bits `strict[frame, offset]` mark the pixels of that frame that are visible in the frame at that offset
|
| 9 |
-
(camera occluder only). V of a target frame = union over the four input frames of the clip (an input frame itself
|
| 10 |
-
contributes everything outside its occluder mask).
|
| 11 |
-
"""
|
| 12 |
from __future__ import annotations
|
| 13 |
|
| 14 |
from pathlib import Path
|
|
@@ -48,8 +37,6 @@ def checked_binary(array, shape):
|
|
| 48 |
|
| 49 |
|
| 50 |
class PolicyLabels:
|
| 51 |
-
"""Occluder masks of masks/<folder>/<source>/<scene>/mask.h5, read by native frame index."""
|
| 52 |
-
|
| 53 |
def __init__(self, data_root, folder=GT_FOLDER, dataset=GT_DATASET):
|
| 54 |
self.root = Path(data_root) / 'masks' / folder
|
| 55 |
self.folder, self.dataset = folder, dataset
|
|
@@ -77,8 +64,6 @@ class PolicyLabels:
|
|
| 77 |
|
| 78 |
|
| 79 |
class MaskProvider:
|
| 80 |
-
"""Scoring mask of a clip, (20, 294, 518) bool."""
|
| 81 |
-
|
| 82 |
def __init__(self, data_root, folder=GT_FOLDER):
|
| 83 |
self.reader = PolicyLabels(data_root, folder)
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from pathlib import Path
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
class PolicyLabels:
|
|
|
|
|
|
|
| 40 |
def __init__(self, data_root, folder=GT_FOLDER, dataset=GT_DATASET):
|
| 41 |
self.root = Path(data_root) / 'masks' / folder
|
| 42 |
self.folder, self.dataset = folder, dataset
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
class MaskProvider:
|
|
|
|
|
|
|
| 67 |
def __init__(self, data_root, folder=GT_FOLDER):
|
| 68 |
self.reader = PolicyLabels(data_root, folder)
|
| 69 |
|
code/agt/eval/method_dir.py
CHANGED
|
@@ -1,25 +1,3 @@
|
|
| 1 |
-
"""Reader of a method directory: the renders a method's own pipeline wrote for one exported clip set.
|
| 2 |
-
|
| 3 |
-
Layout (protocol sample positions k in 0..19, native resolution of the method):
|
| 4 |
-
|
| 5 |
-
<root>/meta.json native_resolution [W, H]; positions (optional, ascending, default 0..19);
|
| 6 |
-
files {clip_id: {"format": "npz" | "png"}}
|
| 7 |
-
<root>/<clip_id>/frames.npz 'rgb': (len(positions), H, W, 3) uint8, float16 or float32 in [0, 1]
|
| 8 |
-
or <root>/<clip_id>/frame_<k:02d>.png
|
| 9 |
-
<root>/depth_meta.json (optional) semantics 'normalized_expected_camera_z', native_resolution,
|
| 10 |
-
positions, files {clip_id: ...}
|
| 11 |
-
<root>/<clip_id>/depth.npz 'depth': (len(positions), H, W) normalized expected camera z of the final
|
| 12 |
-
Gaussian scene (sum(w z) / sum(w)) in the method's own units; 'alpha': the
|
| 13 |
-
accumulated opacity sum(w) of the same render. Non-finite = no depth.
|
| 14 |
-
<root>/<clip_id>/input_depth.npz (optional, with input_depth.json) 'depth': (4, H, W) float16 depth-head
|
| 15 |
-
camera z at the four input frames 0/5/10/15
|
| 16 |
-
<root>/<clip_id>/ab_maps.npz (optional) 'opacity' (16, 294, 518) accumulated opacity at positions 0..15,
|
| 17 |
-
'online_v' (4, 294, 518) the method's own visibility at the input frames,
|
| 18 |
-
'positions' = 0..15, 'context_positions' = 0/5/10/15
|
| 19 |
-
|
| 20 |
-
A method may deliver a subset of the 20 samples (extrapolated frames 16..19 are not scored); every scored sample
|
| 21 |
-
(interp + recon, 0..15) is required.
|
| 22 |
-
"""
|
| 23 |
from __future__ import annotations
|
| 24 |
|
| 25 |
import json
|
|
@@ -38,7 +16,6 @@ def png_name(k: int) -> str:
|
|
| 38 |
|
| 39 |
|
| 40 |
def check_positions(positions) -> list:
|
| 41 |
-
"""Protocol positions of the delivered samples: unique, ascending, within 0..FRAMES-1."""
|
| 42 |
positions = list(range(FRAMES)) if positions is None else [int(k) for k in positions]
|
| 43 |
if not positions or positions != sorted(set(positions)) or positions[0] < 0 or positions[-1] >= FRAMES:
|
| 44 |
raise ValueError(f'Bad positions {positions}: need ascending unique values in 0..{FRAMES - 1}')
|
|
@@ -46,7 +23,6 @@ def check_positions(positions) -> list:
|
|
| 46 |
|
| 47 |
|
| 48 |
def select_scored(output, n_samples, scored_positions):
|
| 49 |
-
"""A method's output -> its renders at the scored protocol positions, in that order."""
|
| 50 |
rgb = output['rgb']
|
| 51 |
positions = [int(p) for p in output.get('positions', range(n_samples))]
|
| 52 |
if len(positions) != len(rgb) or len(set(positions)) != len(positions):
|
|
@@ -84,7 +60,6 @@ class MethodDirectory:
|
|
| 84 |
self.has_input_depth = any(self.root.glob('*/input_depth.json'))
|
| 85 |
|
| 86 |
def predict(self, clip: dict) -> dict:
|
| 87 |
-
"""-> {'rgb': (n, H, W, 3), 'positions': [...]} in protocol order."""
|
| 88 |
entry = self.meta['files'].get(clip['clip_id'])
|
| 89 |
if entry is None:
|
| 90 |
raise ValueError(f'{self.root}: no renders for {clip["clip_id"]}')
|
|
@@ -102,7 +77,6 @@ class MethodDirectory:
|
|
| 102 |
return {'rgb': rgb, 'positions': self.positions}
|
| 103 |
|
| 104 |
def predict_depth(self, clip: dict) -> dict | None:
|
| 105 |
-
"""-> {'depth', 'alpha', 'positions'} (native resolution) or None when the clip has no depth file."""
|
| 106 |
if clip['clip_id'] not in self.depth['files']:
|
| 107 |
return None
|
| 108 |
path = self.root / clip['clip_id'] / 'depth.npz'
|
|
@@ -114,7 +88,6 @@ class MethodDirectory:
|
|
| 114 |
return {'depth': depth, 'alpha': alpha, 'positions': positions}
|
| 115 |
|
| 116 |
def input_depth(self, clip_id: str):
|
| 117 |
-
"""(4, H, W) float16 depth-head depth at the input frames, or None when the clip has none."""
|
| 118 |
root = self.root / clip_id
|
| 119 |
if not (root / 'input_depth.json').is_file():
|
| 120 |
return None
|
|
@@ -127,7 +100,6 @@ class MethodDirectory:
|
|
| 127 |
return depth
|
| 128 |
|
| 129 |
def aux(self, clip, *, pass_number=1):
|
| 130 |
-
"""Optional opacity / visibility maps of the clip (ab_maps.npz) -> list of {kind, pass, positions, array}."""
|
| 131 |
path = self.root / clip['clip_id'] / 'ab_maps.npz'
|
| 132 |
if not path.is_file():
|
| 133 |
return [], dict(status='N/A', reason='method supplied no auxiliary maps')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
def check_positions(positions) -> list:
|
|
|
|
| 19 |
positions = list(range(FRAMES)) if positions is None else [int(k) for k in positions]
|
| 20 |
if not positions or positions != sorted(set(positions)) or positions[0] < 0 or positions[-1] >= FRAMES:
|
| 21 |
raise ValueError(f'Bad positions {positions}: need ascending unique values in 0..{FRAMES - 1}')
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
def select_scored(output, n_samples, scored_positions):
|
|
|
|
| 26 |
rgb = output['rgb']
|
| 27 |
positions = [int(p) for p in output.get('positions', range(n_samples))]
|
| 28 |
if len(positions) != len(rgb) or len(set(positions)) != len(positions):
|
|
|
|
| 60 |
self.has_input_depth = any(self.root.glob('*/input_depth.json'))
|
| 61 |
|
| 62 |
def predict(self, clip: dict) -> dict:
|
|
|
|
| 63 |
entry = self.meta['files'].get(clip['clip_id'])
|
| 64 |
if entry is None:
|
| 65 |
raise ValueError(f'{self.root}: no renders for {clip["clip_id"]}')
|
|
|
|
| 77 |
return {'rgb': rgb, 'positions': self.positions}
|
| 78 |
|
| 79 |
def predict_depth(self, clip: dict) -> dict | None:
|
|
|
|
| 80 |
if clip['clip_id'] not in self.depth['files']:
|
| 81 |
return None
|
| 82 |
path = self.root / clip['clip_id'] / 'depth.npz'
|
|
|
|
| 88 |
return {'depth': depth, 'alpha': alpha, 'positions': positions}
|
| 89 |
|
| 90 |
def input_depth(self, clip_id: str):
|
|
|
|
| 91 |
root = self.root / clip_id
|
| 92 |
if not (root / 'input_depth.json').is_file():
|
| 93 |
return None
|
|
|
|
| 100 |
return depth
|
| 101 |
|
| 102 |
def aux(self, clip, *, pass_number=1):
|
|
|
|
| 103 |
path = self.root / clip['clip_id'] / 'ab_maps.npz'
|
| 104 |
if not path.is_file():
|
| 105 |
return [], dict(status='N/A', reason='method supplied no auxiliary maps')
|
code/agt/eval/output_grid.py
CHANGED
|
@@ -1,10 +1,3 @@
|
|
| 1 |
-
"""A method's native renders -> the scoring grid.
|
| 2 |
-
|
| 3 |
-
Every method renders at its own native resolution; the scorer resizes the result to the scoring grid (518x294) with
|
| 4 |
-
the same function that produced the GT and the labels (agt.data.grid). The result stays float32 and is not
|
| 5 |
-
quantized; the metric clamps it to [0, 1]. uint8 renders become u8 / 255. An output already on the grid is not
|
| 6 |
-
resampled. Depth uses the same full-frame geometry with centre-aligned nearest sampling.
|
| 7 |
-
"""
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
import numpy as np
|
|
@@ -13,7 +6,6 @@ from agt.data.grid import ScoringGrid
|
|
| 13 |
|
| 14 |
|
| 15 |
def to_scoring_grid(frames, grid: ScoringGrid) -> np.ndarray:
|
| 16 |
-
"""(N,H,W,3) uint8 or float in [0,1] covering the whole source frame -> (N,h,w,3) float32 on the grid."""
|
| 17 |
frames = np.asarray(frames)
|
| 18 |
if frames.ndim != 4 or frames.shape[-1] != 3:
|
| 19 |
raise ValueError(f'Expected (N,H,W,3) renders, got {frames.shape}')
|
|
@@ -29,15 +21,10 @@ def to_scoring_grid(frames, grid: ScoringGrid) -> np.ndarray:
|
|
| 29 |
|
| 30 |
|
| 31 |
def nearest_index(src: int, dst: int) -> np.ndarray:
|
| 32 |
-
"""Centre-aligned nearest source index of every target index (the source pixel containing the target pixel
|
| 33 |
-
centre under the full-frame scaling of `grid.continuous`, align_corners=False)."""
|
| 34 |
return np.minimum(np.floor((np.arange(dst) + .5) * (src / dst)).astype(np.int64), src - 1)
|
| 35 |
|
| 36 |
|
| 37 |
def depth_to_scoring_grid(depth, alpha, grid: ScoringGrid):
|
| 38 |
-
"""(N,H,W) predicted depth and accumulated alpha -> (N,h,w) float32 on the grid with nearest sampling, so no depth
|
| 39 |
-
is invented between foreground and background. Non-finite values pass through (scored as missing). alpha may be
|
| 40 |
-
None (only non-finite depth counts as missing)."""
|
| 41 |
depth = np.asarray(depth)
|
| 42 |
if depth.ndim != 3 or depth.dtype not in (np.float16, np.float32, np.float64):
|
| 43 |
raise ValueError(f'Expected float (N,H,W) depth, got {depth.dtype} {depth.shape}')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
def to_scoring_grid(frames, grid: ScoringGrid) -> np.ndarray:
|
|
|
|
| 9 |
frames = np.asarray(frames)
|
| 10 |
if frames.ndim != 4 or frames.shape[-1] != 3:
|
| 11 |
raise ValueError(f'Expected (N,H,W,3) renders, got {frames.shape}')
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
def nearest_index(src: int, dst: int) -> np.ndarray:
|
|
|
|
|
|
|
| 24 |
return np.minimum(np.floor((np.arange(dst) + .5) * (src / dst)).astype(np.int64), src - 1)
|
| 25 |
|
| 26 |
|
| 27 |
def depth_to_scoring_grid(depth, alpha, grid: ScoringGrid):
|
|
|
|
|
|
|
|
|
|
| 28 |
depth = np.asarray(depth)
|
| 29 |
if depth.ndim != 3 or depth.dtype not in (np.float16, np.float32, np.float64):
|
| 30 |
raise ValueError(f'Expected float (N,H,W) depth, got {depth.dtype} {depth.shape}')
|
code/agt/eval/regional.py
CHANGED
|
@@ -1,7 +1,3 @@
|
|
| 1 |
-
"""Regional PSNR / SSIM / LPIPS: Splatt3R calculate_loss / compute_ssim reduction, with channel and target-axis
|
| 2 |
-
fixes (btsmart/splatt3r bda1dd07, main.py:188-236 and utils/compute_ssim.py). Uses the whole-frame skimage
|
| 3 |
-
defaults, AlexNet LPIPS and GT conversion. RGB MSE averages channels before spatial reduction.
|
| 4 |
-
"""
|
| 5 |
from __future__ import annotations
|
| 6 |
|
| 7 |
import math
|
|
@@ -22,7 +18,6 @@ def weighted_mean(values, weight):
|
|
| 22 |
|
| 23 |
|
| 24 |
def pixel_errors(pred, gt):
|
| 25 |
-
"""NHWC or HWC float32 difference, float64 squared / channel mean."""
|
| 26 |
pred, gt = np.clip(np.asarray(pred, np.float32), 0, 1), np.clip(np.asarray(gt, np.float32), 0, 1)
|
| 27 |
if pred.shape != gt.shape or pred.ndim not in (3, 4) or pred.shape[-1] != 3:
|
| 28 |
raise ValueError('regional RGB expects matching HWC / NHWC three-channel arrays')
|
|
@@ -37,10 +32,9 @@ def psnr(mse):
|
|
| 37 |
|
| 38 |
def ssim_map(pred, gt):
|
| 39 |
from skimage.metrics import structural_similarity
|
| 40 |
-
# Splatt3R full=True; HWC as the whole-frame SSIM.
|
| 41 |
_, values = structural_similarity(pred, gt, channel_axis=2, data_range=1., full=True,
|
| 42 |
win_size=7, gaussian_weights=False, sigma=1.5, use_sample_covariance=True)
|
| 43 |
-
return values.mean(axis=-1)
|
| 44 |
|
| 45 |
|
| 46 |
def aggregate_region(frames, positions, *, min_pixels=MIN_PIXELS):
|
|
@@ -89,7 +83,6 @@ class RegionScorer:
|
|
| 89 |
|
| 90 |
def lpips_map(self, pred, gt, mask, *, blackout=True, net='alex'):
|
| 91 |
import torch
|
| 92 |
-
# Splatt3R: multiply mask in [0,1], then LPIPS(normalize=True) applies *2-1; masked spatial mean.
|
| 93 |
p = torch.from_numpy(np.ascontiguousarray(pred.transpose(2, 0, 1))).to(self.device)[None]
|
| 94 |
g = torch.from_numpy(np.ascontiguousarray(gt.transpose(2, 0, 1))).to(self.device)[None]
|
| 95 |
w = torch.as_tensor(mask.copy(), dtype=p.dtype, device=self.device)[None, None]
|
|
@@ -108,7 +101,6 @@ class RegionScorer:
|
|
| 108 |
for p, g, m, err in zip(pred, gt, mask, se):
|
| 109 |
pixels = int(m.sum())
|
| 110 |
f = dict(pixels=pixels, sse=float(err[m].sum(dtype=np.float64)), ssim=None, lpips=None)
|
| 111 |
-
# Even sub-threshold individual frames contribute to a scorable pooled clip.
|
| 112 |
if pixels:
|
| 113 |
pm, gm = p * m[..., None], g * m[..., None]
|
| 114 |
f['ssim'] = float(ssim_map(pm, gm)[m].mean(dtype=np.float64))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import math
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
def pixel_errors(pred, gt):
|
|
|
|
| 21 |
pred, gt = np.clip(np.asarray(pred, np.float32), 0, 1), np.clip(np.asarray(gt, np.float32), 0, 1)
|
| 22 |
if pred.shape != gt.shape or pred.ndim not in (3, 4) or pred.shape[-1] != 3:
|
| 23 |
raise ValueError('regional RGB expects matching HWC / NHWC three-channel arrays')
|
|
|
|
| 32 |
|
| 33 |
def ssim_map(pred, gt):
|
| 34 |
from skimage.metrics import structural_similarity
|
|
|
|
| 35 |
_, values = structural_similarity(pred, gt, channel_axis=2, data_range=1., full=True,
|
| 36 |
win_size=7, gaussian_weights=False, sigma=1.5, use_sample_covariance=True)
|
| 37 |
+
return values.mean(axis=-1)
|
| 38 |
|
| 39 |
|
| 40 |
def aggregate_region(frames, positions, *, min_pixels=MIN_PIXELS):
|
|
|
|
| 83 |
|
| 84 |
def lpips_map(self, pred, gt, mask, *, blackout=True, net='alex'):
|
| 85 |
import torch
|
|
|
|
| 86 |
p = torch.from_numpy(np.ascontiguousarray(pred.transpose(2, 0, 1))).to(self.device)[None]
|
| 87 |
g = torch.from_numpy(np.ascontiguousarray(gt.transpose(2, 0, 1))).to(self.device)[None]
|
| 88 |
w = torch.as_tensor(mask.copy(), dtype=p.dtype, device=self.device)[None, None]
|
|
|
|
| 101 |
for p, g, m, err in zip(pred, gt, mask, se):
|
| 102 |
pixels = int(m.sum())
|
| 103 |
f = dict(pixels=pixels, sse=float(err[m].sum(dtype=np.float64)), ssim=None, lpips=None)
|
|
|
|
| 104 |
if pixels:
|
| 105 |
pm, gm = p * m[..., None], g * m[..., None]
|
| 106 |
f['ssim'] = float(ssim_map(pm, gm)[m].mean(dtype=np.float64))
|
code/agt/eval/regions.py
CHANGED
|
@@ -1,9 +1,3 @@
|
|
| 1 |
-
"""Primary region partition of each scored frame and the overlapping diagnostic bits.
|
| 2 |
-
|
| 3 |
-
scene = outside the occluder mask, observed = inside the mask and visible from an input frame, U = inside the mask
|
| 4 |
-
and never visible (the hole); a band of +-width pixels around the mask edge (void) is excluded from all three.
|
| 5 |
-
S = scene + observed.
|
| 6 |
-
"""
|
| 7 |
from dataclasses import dataclass
|
| 8 |
|
| 9 |
import numpy as np
|
|
@@ -32,7 +26,7 @@ def partition(mask, visible, *, width=3, sky=None, motion=None, alpha=None, dept
|
|
| 32 |
E = ~void
|
| 33 |
masks = dict(scene=E & ~mask, observed=E & mask & visible, U=E & mask & ~visible,
|
| 34 |
E=E, S=E & (~mask | visible), void=void)
|
| 35 |
-
labels = np.zeros(mask.shape, np.uint8)
|
| 36 |
for value, key in enumerate(PRIMARY, 1):
|
| 37 |
labels[masks[key]] = value
|
| 38 |
cross = void.astype(np.uint8) * CROSS_BITS['band']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from dataclasses import dataclass
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 26 |
E = ~void
|
| 27 |
masks = dict(scene=E & ~mask, observed=E & mask & visible, U=E & mask & ~visible,
|
| 28 |
E=E, S=E & (~mask | visible), void=void)
|
| 29 |
+
labels = np.zeros(mask.shape, np.uint8)
|
| 30 |
for value, key in enumerate(PRIMARY, 1):
|
| 31 |
labels[masks[key]] = value
|
| 32 |
cross = void.astype(np.uint8) * CROSS_BITS['band']
|
code/agt/eval/rgb.py
CHANGED
|
@@ -1,15 +1,3 @@
|
|
| 1 |
-
"""Whole-frame PSNR / SSIM / LPIPS exactly as the feed-forward baselines compute them.
|
| 2 |
-
|
| 3 |
-
`frame_metrics` is DGGT's `compute_metrics` (inference.py:38-51) without the final average: both images clamped to
|
| 4 |
-
[0, 1]; per frame, float32 HWC numpy into skimage `peak_signal_noise_ratio(data_range=1.0)` and
|
| 5 |
-
skimage `structural_similarity(channel_axis=2, data_range=1.0)` (library defaults: 7x7 uniform window, sample
|
| 6 |
-
covariance, reflect padding, 3 px border cropped from the mean; the same call as STORM engine_storm.py:126-131), and
|
| 7 |
-
`lpips.LPIPS(net='alex')` (v0.1) on x*2-1, batch of one.
|
| 8 |
-
|
| 9 |
-
Predictions stay float (not quantized); GT is the decoded uint8 / 255. Scored frame sets: interp (12 interpolated
|
| 10 |
-
frames, main) and recon (4 input frames). Frame -> clip: mean over the frames of a frame set. Clip -> split:
|
| 11 |
-
equal-weight mean, as DGGT inference.py:51 and :392-394.
|
| 12 |
-
"""
|
| 13 |
import math
|
| 14 |
|
| 15 |
import numpy as np
|
|
@@ -27,7 +15,6 @@ def number(value):
|
|
| 27 |
|
| 28 |
|
| 29 |
def mean(values):
|
| 30 |
-
"""DGGT's average (sum / len, inference.py:51 and :392-394)."""
|
| 31 |
values = [number(v) for v in values]
|
| 32 |
return sum(values) / len(values)
|
| 33 |
|
|
@@ -37,7 +24,6 @@ def aggregate_frames(values):
|
|
| 37 |
|
| 38 |
|
| 39 |
def frame_metrics(img1, img2, loss_fn=None, metrics=METRICS):
|
| 40 |
-
"""DGGT compute_metrics per frame. img1 = prediction, img2 = GT: NCHW float torch tensors."""
|
| 41 |
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
|
| 42 |
img1 = img1.clamp(0, 1)
|
| 43 |
img2 = img2.clamp(0, 1)
|
|
@@ -46,7 +32,7 @@ def frame_metrics(img1, img2, loss_fn=None, metrics=METRICS):
|
|
| 46 |
im1 = img1[i].cpu().permute(1, 2, 0).numpy()
|
| 47 |
im2 = img2[i].cpu().permute(1, 2, 0).numpy()
|
| 48 |
if 'rgb_psnr' in out:
|
| 49 |
-
with np.errstate(divide='ignore'):
|
| 50 |
out['rgb_psnr'].append(float(peak_signal_noise_ratio(im1, im2, data_range=1.0)))
|
| 51 |
if 'rgb_ssim' in out:
|
| 52 |
out['rgb_ssim'].append(float(structural_similarity(im1, im2, channel_axis=2, data_range=1.0)))
|
|
@@ -56,7 +42,6 @@ def frame_metrics(img1, img2, loss_fn=None, metrics=METRICS):
|
|
| 56 |
|
| 57 |
|
| 58 |
def gt_float(gt_u8):
|
| 59 |
-
"""Decoded uint8 GT -> float32 [0, 1] (u8 / 255 in float32, as torchvision ToTensor)."""
|
| 60 |
gt_u8 = np.asarray(gt_u8)
|
| 61 |
if gt_u8.dtype != np.uint8:
|
| 62 |
raise ValueError('GT must be the decoded uint8 frames')
|
|
@@ -76,8 +61,6 @@ class RGBScorer:
|
|
| 76 |
return self.loss_fn
|
| 77 |
|
| 78 |
def frames(self, pred, gt_u8, metrics=METRICS):
|
| 79 |
-
"""pred: (N,H,W,3) float in [0,1] on the scoring grid; gt_u8: (N,H,W,3) uint8.
|
| 80 |
-
Returns metric -> per-frame values in protocol order."""
|
| 81 |
import torch
|
| 82 |
pred = np.asarray(pred)
|
| 83 |
if pred.dtype not in (np.float32, np.float64) or pred.ndim != 4 or pred.shape[-1] != 3:
|
|
@@ -89,16 +72,12 @@ class RGBScorer:
|
|
| 89 |
unknown = set(metrics) - set(METRICS)
|
| 90 |
if unknown:
|
| 91 |
raise ValueError(f'Unsupported RGB metric: {sorted(unknown)}')
|
| 92 |
-
# Same memory layouts as DGGT: rendered = renders(N,H,W,3).permute(0,3,1,2) (an NHWC buffer), target =
|
| 93 |
-
# ToTensor output (NCHW buffer). skimage's float64 MSE sum follows the layout, so this keeps PSNR
|
| 94 |
-
# bit-identical to DGGT.
|
| 95 |
img1 = torch.from_numpy(np.ascontiguousarray(pred, dtype=np.float32)).permute(0, 3, 1, 2).to(self.device)
|
| 96 |
img2 = torch.from_numpy(np.ascontiguousarray(gt_float(gt_u8).transpose(0, 3, 1, 2))).to(self.device)
|
| 97 |
with torch.inference_mode():
|
| 98 |
return frame_metrics(img1, img2, self.lpips() if 'rgb_lpips' in metrics else None, metrics)
|
| 99 |
|
| 100 |
def score(self, pred, gt_u8, frame_sets, metrics=METRICS):
|
| 101 |
-
"""-> {'frames': metric -> per-frame values, metric: {frame_set: aggregate}}."""
|
| 102 |
per_frame = self.frames(pred, gt_u8, metrics)
|
| 103 |
result = {'frames': {m: [scalar(v) for v in values] for m, values in per_frame.items()}}
|
| 104 |
for m in metrics:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import math
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
def mean(values):
|
|
|
|
| 18 |
values = [number(v) for v in values]
|
| 19 |
return sum(values) / len(values)
|
| 20 |
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
def frame_metrics(img1, img2, loss_fn=None, metrics=METRICS):
|
|
|
|
| 27 |
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
|
| 28 |
img1 = img1.clamp(0, 1)
|
| 29 |
img2 = img2.clamp(0, 1)
|
|
|
|
| 32 |
im1 = img1[i].cpu().permute(1, 2, 0).numpy()
|
| 33 |
im2 = img2[i].cpu().permute(1, 2, 0).numpy()
|
| 34 |
if 'rgb_psnr' in out:
|
| 35 |
+
with np.errstate(divide='ignore'):
|
| 36 |
out['rgb_psnr'].append(float(peak_signal_noise_ratio(im1, im2, data_range=1.0)))
|
| 37 |
if 'rgb_ssim' in out:
|
| 38 |
out['rgb_ssim'].append(float(structural_similarity(im1, im2, channel_axis=2, data_range=1.0)))
|
|
|
|
| 42 |
|
| 43 |
|
| 44 |
def gt_float(gt_u8):
|
|
|
|
| 45 |
gt_u8 = np.asarray(gt_u8)
|
| 46 |
if gt_u8.dtype != np.uint8:
|
| 47 |
raise ValueError('GT must be the decoded uint8 frames')
|
|
|
|
| 61 |
return self.loss_fn
|
| 62 |
|
| 63 |
def frames(self, pred, gt_u8, metrics=METRICS):
|
|
|
|
|
|
|
| 64 |
import torch
|
| 65 |
pred = np.asarray(pred)
|
| 66 |
if pred.dtype not in (np.float32, np.float64) or pred.ndim != 4 or pred.shape[-1] != 3:
|
|
|
|
| 72 |
unknown = set(metrics) - set(METRICS)
|
| 73 |
if unknown:
|
| 74 |
raise ValueError(f'Unsupported RGB metric: {sorted(unknown)}')
|
|
|
|
|
|
|
|
|
|
| 75 |
img1 = torch.from_numpy(np.ascontiguousarray(pred, dtype=np.float32)).permute(0, 3, 1, 2).to(self.device)
|
| 76 |
img2 = torch.from_numpy(np.ascontiguousarray(gt_float(gt_u8).transpose(0, 3, 1, 2))).to(self.device)
|
| 77 |
with torch.inference_mode():
|
| 78 |
return frame_metrics(img1, img2, self.lpips() if 'rgb_lpips' in metrics else None, metrics)
|
| 79 |
|
| 80 |
def score(self, pred, gt_u8, frame_sets, metrics=METRICS):
|
|
|
|
| 81 |
per_frame = self.frames(pred, gt_u8, metrics)
|
| 82 |
result = {'frames': {m: [scalar(v) for v in values] for m, values in per_frame.items()}}
|
| 83 |
for m in metrics:
|
code/agt/eval/scorer.py
CHANGED
|
@@ -1,15 +1,3 @@
|
|
| 1 |
-
"""Scorer: a method directory against an exported clip set and the rebuilt ground truth of its data root.
|
| 2 |
-
|
| 3 |
-
Tables (all computed from one pass over the clips):
|
| 4 |
-
A1 whole-frame PSNR / SSIM / LPIPS
|
| 5 |
-
A2 the same per region: scene, observed, S = scene + observed, E = all but the mask-edge band, void,
|
| 6 |
-
and diagnostic overlaps (sky, motion, semi-transparent occluder, invalid depth)
|
| 7 |
-
B the hole U (inside the occluder mask, never visible from an input frame): PSNR / SSIM / LPIPS,
|
| 8 |
-
DISTS on GT-fixed component boxes, seam gradient residual, collection KID (and FID if requested)
|
| 9 |
-
depth_render affine D-RMSE / AbsRel of the rendered depth at the 16 scored positions
|
| 10 |
-
depth_input the same for the depth head at the four input frames
|
| 11 |
-
Frame sets: interp = the 12 interpolated frames, recon = the 4 input frames.
|
| 12 |
-
"""
|
| 13 |
from __future__ import annotations
|
| 14 |
|
| 15 |
import json
|
|
@@ -37,7 +25,6 @@ DEFAULTS = dict(protocol='partial', map_version='v2', source='waymo', scoring_ma
|
|
| 37 |
|
| 38 |
|
| 39 |
def score_depth(labels, clip, output, regions, frame_sets, *, eps, positions=None, declared=False):
|
| 40 |
-
"""Depth metrics of one clip; rendered and input depth share the same fit and validity rules."""
|
| 41 |
positions = list(range(16)) if positions is None else list(positions)
|
| 42 |
depth_keys = ('full',)+tuple(name for name in regions.masks if name in ('scene', 'observed', 'U', 'void') or name.startswith('diagnostic_'))
|
| 43 |
empty = {name: {metric: None for metric in ('drmse', 'absrel')} for name in depth_keys}
|
|
@@ -77,7 +64,6 @@ def flatten_depth(result, fs):
|
|
| 77 |
|
| 78 |
|
| 79 |
def unavailable_rows(meta, frame_sets, *, tables):
|
| 80 |
-
"""N/A rows of a clip without GT visibility (no region is defined)."""
|
| 81 |
depth = {region+'_'+metric: None for region in ('full', 'scene', 'observed', 'U', 'void')
|
| 82 |
for metric in ('drmse', 'absrel')}
|
| 83 |
for fs in frame_sets:
|
|
@@ -93,7 +79,6 @@ def unavailable_rows(meta, frame_sets, *, tables):
|
|
| 93 |
|
| 94 |
|
| 95 |
def load_diagnostics(data_root, reader, clip):
|
| 96 |
-
"""Overlap regions from existing labels (never remove RGB pixels): occluder alpha, clean sky, motion."""
|
| 97 |
from agt.data.labels import CleanSkyStore, MotionStore
|
| 98 |
src = reader.source(clip['sample_id'])
|
| 99 |
frames = clip['frame_indices']; source = source_of(clip)
|
|
@@ -114,8 +99,6 @@ def load_diagnostics(data_root, reader, clip):
|
|
| 114 |
|
| 115 |
|
| 116 |
def score(config: dict) -> dict:
|
| 117 |
-
"""Score config['method'] on the clips of config['export']; writes per_clip.json, tables.json, summary.json,
|
| 118 |
-
evidence.json under config['out'] and returns the summary."""
|
| 119 |
cfg = {**DEFAULTS, **config}
|
| 120 |
tables = frozenset(cfg['tables'])
|
| 121 |
if not tables or not tables <= set(ALL_TABLES):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
def score_depth(labels, clip, output, regions, frame_sets, *, eps, positions=None, declared=False):
|
|
|
|
| 28 |
positions = list(range(16)) if positions is None else list(positions)
|
| 29 |
depth_keys = ('full',)+tuple(name for name in regions.masks if name in ('scene', 'observed', 'U', 'void') or name.startswith('diagnostic_'))
|
| 30 |
empty = {name: {metric: None for metric in ('drmse', 'absrel')} for name in depth_keys}
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
def unavailable_rows(meta, frame_sets, *, tables):
|
|
|
|
| 67 |
depth = {region+'_'+metric: None for region in ('full', 'scene', 'observed', 'U', 'void')
|
| 68 |
for metric in ('drmse', 'absrel')}
|
| 69 |
for fs in frame_sets:
|
|
|
|
| 79 |
|
| 80 |
|
| 81 |
def load_diagnostics(data_root, reader, clip):
|
|
|
|
| 82 |
from agt.data.labels import CleanSkyStore, MotionStore
|
| 83 |
src = reader.source(clip['sample_id'])
|
| 84 |
frames = clip['frame_indices']; source = source_of(clip)
|
|
|
|
| 99 |
|
| 100 |
|
| 101 |
def score(config: dict) -> dict:
|
|
|
|
|
|
|
| 102 |
cfg = {**DEFAULTS, **config}
|
| 103 |
tables = frozenset(cfg['tables'])
|
| 104 |
if not tables or not tables <= set(ALL_TABLES):
|
code/agt/eval/summary.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
"""Per-clip rows -> per-table split statistics (all / day / night, equal-weight clip means of the valid values)
|
| 2 |
-
-> one flat summary per split with flat metric names (interp_psnr, u_lpips, ...)."""
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import json
|
|
@@ -17,7 +15,6 @@ COLLECTION_METRICS = ('kid', 'fid')
|
|
| 17 |
|
| 18 |
|
| 19 |
def write_json(path, value):
|
| 20 |
-
"""Strict JSON (+inf encoded as 'inf'), atomic replacement."""
|
| 21 |
path = Path(path)
|
| 22 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 23 |
temporary = path.with_name('.' + path.name + f'.{os.getpid()}.tmp')
|
|
@@ -38,7 +35,6 @@ def aggregate_rows(rows, key):
|
|
| 38 |
|
| 39 |
|
| 40 |
def build_columns():
|
| 41 |
-
"""(column, table, frame_set, per-table key) of the summary."""
|
| 42 |
cols = []
|
| 43 |
|
| 44 |
def add(new, tab, fs, old):
|
|
@@ -92,7 +88,6 @@ COLUMNS = build_columns()
|
|
| 92 |
|
| 93 |
|
| 94 |
def table_statistics(per_clip, collections):
|
| 95 |
-
"""{(table, frame_set): {'split', 'valid_clip_counts', 'collection_statistics'}} over the per-clip rows."""
|
| 96 |
tables = {}
|
| 97 |
for key in sorted({(r['table'], r['frame_set']) for r in per_clip}):
|
| 98 |
rows = [r for r in per_clip if (r['table'], r['frame_set']) == key]
|
|
@@ -109,13 +104,12 @@ def table_statistics(per_clip, collections):
|
|
| 109 |
coll[group] = collections.get((*key, group), {})
|
| 110 |
for k, value in coll[group].items():
|
| 111 |
split[group][k] = value['value']
|
| 112 |
-
counts[group][k] = None
|
| 113 |
tables[key] = dict(split=split, valid_clip_counts=counts, collection_statistics=coll)
|
| 114 |
return tables
|
| 115 |
|
| 116 |
|
| 117 |
def summary(tables):
|
| 118 |
-
"""{split: {column: value}} plus valid clip counts; columns of tables that were not scored are omitted."""
|
| 119 |
out = {s: {} for s in SPLITS}
|
| 120 |
counts = {s: {} for s in SPLITS}
|
| 121 |
for new, tab, fs, old in COLUMNS:
|
|
@@ -132,7 +126,6 @@ def summary(tables):
|
|
| 132 |
|
| 133 |
|
| 134 |
def export(per_clip, collections, destination):
|
| 135 |
-
"""per_clip.json, tables.json and summary.json under `destination`."""
|
| 136 |
destination = Path(destination)
|
| 137 |
tables = table_statistics(per_clip, collections)
|
| 138 |
write_json(destination / 'per_clip.json', per_clip)
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
def write_json(path, value):
|
|
|
|
| 18 |
path = Path(path)
|
| 19 |
path.parent.mkdir(parents=True, exist_ok=True)
|
| 20 |
temporary = path.with_name('.' + path.name + f'.{os.getpid()}.tmp')
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
def build_columns():
|
|
|
|
| 38 |
cols = []
|
| 39 |
|
| 40 |
def add(new, tab, fs, old):
|
|
|
|
| 88 |
|
| 89 |
|
| 90 |
def table_statistics(per_clip, collections):
|
|
|
|
| 91 |
tables = {}
|
| 92 |
for key in sorted({(r['table'], r['frame_set']) for r in per_clip}):
|
| 93 |
rows = [r for r in per_clip if (r['table'], r['frame_set']) == key]
|
|
|
|
| 104 |
coll[group] = collections.get((*key, group), {})
|
| 105 |
for k, value in coll[group].items():
|
| 106 |
split[group][k] = value['value']
|
| 107 |
+
counts[group][k] = None
|
| 108 |
tables[key] = dict(split=split, valid_clip_counts=counts, collection_statistics=coll)
|
| 109 |
return tables
|
| 110 |
|
| 111 |
|
| 112 |
def summary(tables):
|
|
|
|
| 113 |
out = {s: {} for s in SPLITS}
|
| 114 |
counts = {s: {} for s in SPLITS}
|
| 115 |
for new, tab, fs, old in COLUMNS:
|
|
|
|
| 126 |
|
| 127 |
|
| 128 |
def export(per_clip, collections, destination):
|
|
|
|
| 129 |
destination = Path(destination)
|
| 130 |
tables = table_statistics(per_clip, collections)
|
| 131 |
write_json(destination / 'per_clip.json', per_clip)
|
code/agt/masks/__init__.py
CHANGED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
"""Occluder masks: readers for the renderer (io) and the mask generation pipeline for new clips (pipeline)."""
|
|
|
|
|
|
code/agt/masks/io.py
CHANGED
|
@@ -1,15 +1,3 @@
|
|
| 1 |
-
"""Occluder masks read by the reconstruction step (294 x 518 grid, static over the clip).
|
| 2 |
-
|
| 3 |
-
Sources:
|
| 4 |
-
- DatasetMasks: the scene-level predicted occluder masks shipped with the AmodalDrive dataset
|
| 5 |
-
(<data_root>/masks/predicted/<source>/<scene>/mask.h5, dataset `occluder_pred_hard`), used to reproduce
|
| 6 |
-
the reported numbers on the test and validation sets;
|
| 7 |
-
- MaskDir: per-clip masks written by the mask generation step for new clips (tools/make_masks.py):
|
| 8 |
-
<dir>/manifest.json and <dir>/<clip_id>.npz with uint8 `solid_mask_hard`, `per_frame`, `votes`;
|
| 9 |
-
- MaskImages: <dir>/<clip_id>.png, 255 = occluder (the example cases).
|
| 10 |
-
load(clip) returns (mask, attention_mask): the mask used for visibility and gating, and the mask used in the
|
| 11 |
-
attention. DatasetMasks: the stored mask and its dilation by `dilate` pixels; MaskDir / MaskImages: both the dilated mask.
|
| 12 |
-
"""
|
| 13 |
from __future__ import annotations
|
| 14 |
|
| 15 |
import json
|
|
@@ -33,7 +21,6 @@ def binary(mask):
|
|
| 33 |
|
| 34 |
|
| 35 |
def dilate_mask(occluder, pixels):
|
| 36 |
-
"""Square dilation with radius `pixels` (PIL MaxFilter of size 2 * pixels + 1)."""
|
| 37 |
if type(pixels) is not int or pixels < 0:
|
| 38 |
raise ValueError('mask dilation must be a nonnegative integer')
|
| 39 |
if pixels == 0:
|
|
@@ -86,8 +73,6 @@ class MaskDir:
|
|
| 86 |
|
| 87 |
|
| 88 |
class MaskImages:
|
| 89 |
-
"""<dir>/<clip_id>.png, 518 x 294 mode L, 255 = occluder (e.g. the example cases' mask.png); dilated by `dilate`."""
|
| 90 |
-
|
| 91 |
def __init__(self, directory, dilate=0):
|
| 92 |
self.directory = Path(directory)
|
| 93 |
self.dilate = dilate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
def dilate_mask(occluder, pixels):
|
|
|
|
| 24 |
if type(pixels) is not int or pixels < 0:
|
| 25 |
raise ValueError('mask dilation must be a nonnegative integer')
|
| 26 |
if pixels == 0:
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
class MaskImages:
|
|
|
|
|
|
|
| 76 |
def __init__(self, directory, dilate=0):
|
| 77 |
self.directory = Path(directory)
|
| 78 |
self.dilate = dilate
|
code/agt/masks/pipeline.py
CHANGED
|
@@ -1,20 +1,3 @@
|
|
| 1 |
-
"""Occluder masks for real clips: SAM3 proposals -> verifier -> per-frame repair -> vote over the 4 input frames.
|
| 2 |
-
|
| 3 |
-
Input: a clip export (manifest.json + <clip_id>/clip.json + frame_XX.png, see agt.prepare.video_clip).
|
| 4 |
-
Stages (each one can run in its own environment; later stages reuse what earlier ones wrote):
|
| 5 |
-
|
| 6 |
-
1. propose: SAM3 concept prompts from the config vocabulary on input frames 0/5/10/15, geometric filters,
|
| 7 |
-
numbered candidate sheets (GPU, needs `sam3`).
|
| 8 |
-
2. verify: one verifier call per page; every candidate gets yes / no / uncertain and a category
|
| 9 |
-
(GPU for the local Qwen verifier).
|
| 10 |
-
3. finish: accepted candidates -> hole and panel-edge repairs -> binary mask on the 294x518 grid per frame ->
|
| 11 |
-
pixel kept when at least `vote.min_votes` of the 4 frames mark it; writes the output directory and QC
|
| 12 |
-
images (CPU).
|
| 13 |
-
|
| 14 |
-
Output: <out>/manifest.json {"schema": "clip_masks_v1", "grid_hw": [294, 518], "context_positions": [0, 5, 10, 15],
|
| 15 |
-
"vote_min": 3, "clips": [...]} and one <clip_id>.npz per clip with uint8 `solid_mask_hard` (294,518),
|
| 16 |
-
`per_frame` (4,294,518) and `votes` (294,518). Intermediate files go to <out>/work/, QC images to <out>/qc/.
|
| 17 |
-
"""
|
| 18 |
from __future__ import annotations
|
| 19 |
|
| 20 |
import json
|
|
@@ -31,12 +14,11 @@ from .verify import build_pages, read_proposals, read_verdicts, send_page, write
|
|
| 31 |
|
| 32 |
SCHEMA = "clip_masks_v1"
|
| 33 |
CONTEXT_POSITIONS = [0, 5, 10, 15]
|
| 34 |
-
GRID = (518, 294)
|
| 35 |
OVERLAY_COLOUR = (255, 0, 255)
|
| 36 |
|
| 37 |
|
| 38 |
def load_config(path) -> dict:
|
| 39 |
-
"""Mask config yaml; prompt and schema paths are relative to the yaml file."""
|
| 40 |
path = Path(path)
|
| 41 |
config = yaml.safe_load(path.read_text())
|
| 42 |
sam3, verify, post = config["sam3"], config["verify"], config["postprocess"]
|
|
@@ -49,7 +31,6 @@ def load_config(path) -> dict:
|
|
| 49 |
|
| 50 |
|
| 51 |
def read_export(export, clips=None) -> list[dict]:
|
| 52 |
-
"""The four input frames of every clip (or of `clips` only), in manifest order."""
|
| 53 |
export = Path(export)
|
| 54 |
frames = []
|
| 55 |
for cid in json.loads((export / "manifest.json").read_text())["clips"]:
|
|
@@ -74,7 +55,6 @@ def read_rgb(path) -> np.ndarray:
|
|
| 74 |
|
| 75 |
|
| 76 |
def select_candidates(directory: Path, frame: dict, config: dict) -> int:
|
| 77 |
-
"""Filter the raw SAM3 candidates of one frame and build its verification pages; returns the page count."""
|
| 78 |
proposals = directory / "proposals"
|
| 79 |
with np.load(proposals / "raw_candidates.npz", allow_pickle=False) as handle:
|
| 80 |
raw = handle["masks"]
|
|
@@ -104,13 +84,12 @@ def propose(export, out, config: dict, checkpoint: str | None = None, device: st
|
|
| 104 |
pages += select_candidates(frame_dir(out, frame), frame, config)
|
| 105 |
print(json.dumps({"frame": frame["template_id"], "raw_candidates": len(candidates)}), flush=True)
|
| 106 |
import torch
|
| 107 |
-
del proposer
|
| 108 |
torch.cuda.empty_cache()
|
| 109 |
return {"stage": "propose", "frames": len(frames), "pages": pages}
|
| 110 |
|
| 111 |
|
| 112 |
def verify(export, out, config: dict, verifier, clips=None) -> dict:
|
| 113 |
-
"""Send every page without verdicts; pages are sent one after another from one verifier instance."""
|
| 114 |
settings = config["verify"]
|
| 115 |
failed, sent = [], 0
|
| 116 |
for frame in read_export(export, clips):
|
|
@@ -128,7 +107,6 @@ def verify(export, out, config: dict, verifier, clips=None) -> dict:
|
|
| 128 |
|
| 129 |
|
| 130 |
def frame_mask(directory: Path, config: dict) -> dict:
|
| 131 |
-
"""Verified candidates of one frame -> binary mask on the output grid (+ union of accepted overlays, for QC)."""
|
| 132 |
post = config["postprocess"]
|
| 133 |
p = read_proposals(directory)
|
| 134 |
verdict_of = read_verdicts(directory, p["kept"])
|
|
@@ -178,7 +156,6 @@ def finish(export, out, config: dict, clips=None) -> dict:
|
|
| 178 |
|
| 179 |
|
| 180 |
def qc_image(path: Path, cid: str, frames: list[dict], occluder, per_frame, overlays, frame_stats) -> None:
|
| 181 |
-
"""Visualization only: per-frame masks (red), the vote outline (green), accepted overlays (magenta)."""
|
| 182 |
edge = outline(occluder.astype(bool))
|
| 183 |
canvas = Image.new("RGB", (2 * GRID[0], 2 * (GRID[1] + 26) + 26), "#101820")
|
| 184 |
draw = ImageDraw.Draw(canvas)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 14 |
|
| 15 |
SCHEMA = "clip_masks_v1"
|
| 16 |
CONTEXT_POSITIONS = [0, 5, 10, 15]
|
| 17 |
+
GRID = (518, 294)
|
| 18 |
OVERLAY_COLOUR = (255, 0, 255)
|
| 19 |
|
| 20 |
|
| 21 |
def load_config(path) -> dict:
|
|
|
|
| 22 |
path = Path(path)
|
| 23 |
config = yaml.safe_load(path.read_text())
|
| 24 |
sam3, verify, post = config["sam3"], config["verify"], config["postprocess"]
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
def read_export(export, clips=None) -> list[dict]:
|
|
|
|
| 34 |
export = Path(export)
|
| 35 |
frames = []
|
| 36 |
for cid in json.loads((export / "manifest.json").read_text())["clips"]:
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
def select_candidates(directory: Path, frame: dict, config: dict) -> int:
|
|
|
|
| 58 |
proposals = directory / "proposals"
|
| 59 |
with np.load(proposals / "raw_candidates.npz", allow_pickle=False) as handle:
|
| 60 |
raw = handle["masks"]
|
|
|
|
| 84 |
pages += select_candidates(frame_dir(out, frame), frame, config)
|
| 85 |
print(json.dumps({"frame": frame["template_id"], "raw_candidates": len(candidates)}), flush=True)
|
| 86 |
import torch
|
| 87 |
+
del proposer
|
| 88 |
torch.cuda.empty_cache()
|
| 89 |
return {"stage": "propose", "frames": len(frames), "pages": pages}
|
| 90 |
|
| 91 |
|
| 92 |
def verify(export, out, config: dict, verifier, clips=None) -> dict:
|
|
|
|
| 93 |
settings = config["verify"]
|
| 94 |
failed, sent = [], 0
|
| 95 |
for frame in read_export(export, clips):
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
def frame_mask(directory: Path, config: dict) -> dict:
|
|
|
|
| 110 |
post = config["postprocess"]
|
| 111 |
p = read_proposals(directory)
|
| 112 |
verdict_of = read_verdicts(directory, p["kept"])
|
|
|
|
| 156 |
|
| 157 |
|
| 158 |
def qc_image(path: Path, cid: str, frames: list[dict], occluder, per_frame, overlays, frame_stats) -> None:
|
|
|
|
| 159 |
edge = outline(occluder.astype(bool))
|
| 160 |
canvas = Image.new("RGB", (2 * GRID[0], 2 * (GRID[1] + 26) + 26), "#101820")
|
| 161 |
draw = ImageDraw.Draw(canvas)
|
code/agt/masks/postprocess.py
CHANGED
|
@@ -1,11 +1,3 @@
|
|
| 1 |
-
"""Accepted candidates -> one binary occluder mask per frame.
|
| 2 |
-
|
| 3 |
-
Accepted (yes) candidates become entities; the verifier's category maps to a mask role (dashboard/hood ->
|
| 4 |
-
panel roles, pillar -> pillar, everything else -> object). Per-entity holes are filled, then the panel upper
|
| 5 |
-
edge is fitted across columns (RANSAC + Huber polynomial) and everything below it is filled. The fitted
|
| 6 |
-
curve is normalized, so it is fitted once at source resolution and reused on the output grid.
|
| 7 |
-
Deterministic, CPU only.
|
| 8 |
-
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
import math
|
|
@@ -15,7 +7,7 @@ import numpy as np
|
|
| 15 |
from PIL import Image
|
| 16 |
from scipy.ndimage import binary_fill_holes
|
| 17 |
|
| 18 |
-
RANK_WARNING = getattr(np.exceptions, "RankWarning", None) or np.RankWarning
|
| 19 |
ROLE_OF_CATEGORY = {"dashboard": "dashboard", "hood": "hood", "pillar": "pillar"}
|
| 20 |
PANEL_ROLES = frozenset({"dashboard", "hood"})
|
| 21 |
DEFAULT_PANEL_EDGE = {"degree": 3, "ransac_iters": 500, "inlier_tau_frac": 0.01,
|
|
@@ -30,7 +22,6 @@ def panel_edge_settings(params: dict | None) -> dict:
|
|
| 30 |
|
| 31 |
|
| 32 |
def repair_entities(masks: np.ndarray, roles: list[str], *, bottom_ratio: float) -> dict[str, np.ndarray]:
|
| 33 |
-
"""Fill holes per entity; panel entities are also joined with the forced bottom strip (bottom_ratio rows)."""
|
| 34 |
height, width = masks.shape[1:]
|
| 35 |
bottom = np.zeros((height, width), bool)
|
| 36 |
rows = math.ceil(height * bottom_ratio)
|
|
@@ -49,11 +40,6 @@ def repair_entities(masks: np.ndarray, roles: list[str], *, bottom_ratio: float)
|
|
| 49 |
|
| 50 |
|
| 51 |
def extract_panel_edge(masks: np.ndarray, roles: list[str]) -> np.ndarray:
|
| 52 |
-
"""Per-column topmost panel pixel (row index); NaN where the column has no panel pixel.
|
| 53 |
-
|
| 54 |
-
Only dashboard/hood candidates define the panel. Pillars reach the image top and
|
| 55 |
-
mounted objects protrude above the panel, so both are excluded on purpose.
|
| 56 |
-
"""
|
| 57 |
height, width = masks.shape[1:]
|
| 58 |
members = [index for index, role in enumerate(roles) if role in PANEL_ROLES]
|
| 59 |
panel = np.any(masks[members].astype(bool), axis=0) if members else np.zeros((height, width), bool)
|
|
@@ -70,7 +56,6 @@ def _polyfit(x: np.ndarray, y: np.ndarray, degree: int, w: np.ndarray | None = N
|
|
| 70 |
|
| 71 |
|
| 72 |
def fit_panel_edge(top: np.ndarray, size: tuple[int, int], settings: dict) -> dict:
|
| 73 |
-
"""RANSAC + Huber polynomial fit of the panel upper edge in normalized coordinates."""
|
| 74 |
width, height = size
|
| 75 |
settings = panel_edge_settings(settings)
|
| 76 |
degree, tau = settings["degree"], settings["inlier_tau_frac"]
|
|
@@ -99,7 +84,7 @@ def fit_panel_edge(top: np.ndarray, size: tuple[int, int], settings: dict) -> di
|
|
| 99 |
info["reasons"].append("RANSAC found no consensus set")
|
| 100 |
return info
|
| 101 |
coeffs = _polyfit(x[best_inliers], y[best_inliers], degree)
|
| 102 |
-
for _ in range(5):
|
| 103 |
residual = np.polyval(coeffs, x[best_inliers]) - y[best_inliers]
|
| 104 |
scale = max(1.4826 * float(np.median(np.abs(residual))), 1e-6)
|
| 105 |
ratio = np.abs(residual) / (1.345 * scale)
|
|
@@ -123,7 +108,6 @@ def fit_panel_edge(top: np.ndarray, size: tuple[int, int], settings: dict) -> di
|
|
| 123 |
|
| 124 |
|
| 125 |
def edge_rows(info: dict, size: tuple[int, int]) -> np.ndarray:
|
| 126 |
-
"""Discretize the normalized curve at any resolution; rows at or below are opaque."""
|
| 127 |
width, height = size
|
| 128 |
x = (np.arange(width) + 0.5) / width
|
| 129 |
rows = np.polyval(np.asarray(info["coefficients"], float), x) * height
|
|
@@ -138,11 +122,6 @@ def fill_below_edge(rows: np.ndarray, size: tuple[int, int]) -> np.ndarray:
|
|
| 138 |
|
| 139 |
def repair_entities_edge(masks: np.ndarray, roles: list[str], *, bottom_ratio: float,
|
| 140 |
edge_settings: dict, edge: dict | None = None) -> dict:
|
| 141 |
-
"""Base per-entity repairs, then fill everything below the fitted panel edge.
|
| 142 |
-
|
| 143 |
-
`edge` may carry a previously fitted normalized curve (reuse on the output grid);
|
| 144 |
-
otherwise the curve is fitted from the panel candidates in `masks`.
|
| 145 |
-
"""
|
| 146 |
base = repair_entities(masks, roles, bottom_ratio=bottom_ratio)
|
| 147 |
height, width = masks.shape[1:]
|
| 148 |
if edge is None:
|
|
@@ -157,7 +136,6 @@ def repair_entities_edge(masks: np.ndarray, roles: list[str], *, bottom_ratio: f
|
|
| 157 |
|
| 158 |
|
| 159 |
def grid_masks(source: dict, roles: list[str], size: tuple[int, int], *, bottom_ratio: float, edge_settings: dict) -> dict:
|
| 160 |
-
"""Map the source-resolution entities to the output grid (NEAREST) and repeat the repairs there."""
|
| 161 |
width, height = size
|
| 162 |
mapped = [np.asarray(Image.fromarray(mask).resize(size, Image.Resampling.NEAREST), np.uint8) for mask in source["entities"]]
|
| 163 |
masks = np.stack(mapped) if mapped else np.zeros((0, height, width), np.uint8)
|
|
@@ -165,7 +143,6 @@ def grid_masks(source: dict, roles: list[str], size: tuple[int, int], *, bottom_
|
|
| 165 |
|
| 166 |
|
| 167 |
def assemble_entities(raw: np.ndarray, kept: list[dict], verdict_of: dict[int, dict], post: dict) -> dict:
|
| 168 |
-
"""yes-candidates -> entities with roles -> hole and panel-edge repairs at source resolution."""
|
| 169 |
yes = [d for d in kept if verdict_of[d["candidate_id"]]["opaque_hard"] == "yes"]
|
| 170 |
roles = [ROLE_OF_CATEGORY.get(verdict_of[d["candidate_id"]]["category"], "object") for d in yes]
|
| 171 |
height, width = raw.shape[1:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import math
|
|
|
|
| 7 |
from PIL import Image
|
| 8 |
from scipy.ndimage import binary_fill_holes
|
| 9 |
|
| 10 |
+
RANK_WARNING = getattr(np.exceptions, "RankWarning", None) or np.RankWarning
|
| 11 |
ROLE_OF_CATEGORY = {"dashboard": "dashboard", "hood": "hood", "pillar": "pillar"}
|
| 12 |
PANEL_ROLES = frozenset({"dashboard", "hood"})
|
| 13 |
DEFAULT_PANEL_EDGE = {"degree": 3, "ransac_iters": 500, "inlier_tau_frac": 0.01,
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
def repair_entities(masks: np.ndarray, roles: list[str], *, bottom_ratio: float) -> dict[str, np.ndarray]:
|
|
|
|
| 25 |
height, width = masks.shape[1:]
|
| 26 |
bottom = np.zeros((height, width), bool)
|
| 27 |
rows = math.ceil(height * bottom_ratio)
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
def extract_panel_edge(masks: np.ndarray, roles: list[str]) -> np.ndarray:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
height, width = masks.shape[1:]
|
| 44 |
members = [index for index, role in enumerate(roles) if role in PANEL_ROLES]
|
| 45 |
panel = np.any(masks[members].astype(bool), axis=0) if members else np.zeros((height, width), bool)
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
def fit_panel_edge(top: np.ndarray, size: tuple[int, int], settings: dict) -> dict:
|
|
|
|
| 59 |
width, height = size
|
| 60 |
settings = panel_edge_settings(settings)
|
| 61 |
degree, tau = settings["degree"], settings["inlier_tau_frac"]
|
|
|
|
| 84 |
info["reasons"].append("RANSAC found no consensus set")
|
| 85 |
return info
|
| 86 |
coeffs = _polyfit(x[best_inliers], y[best_inliers], degree)
|
| 87 |
+
for _ in range(5):
|
| 88 |
residual = np.polyval(coeffs, x[best_inliers]) - y[best_inliers]
|
| 89 |
scale = max(1.4826 * float(np.median(np.abs(residual))), 1e-6)
|
| 90 |
ratio = np.abs(residual) / (1.345 * scale)
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
def edge_rows(info: dict, size: tuple[int, int]) -> np.ndarray:
|
|
|
|
| 111 |
width, height = size
|
| 112 |
x = (np.arange(width) + 0.5) / width
|
| 113 |
rows = np.polyval(np.asarray(info["coefficients"], float), x) * height
|
|
|
|
| 122 |
|
| 123 |
def repair_entities_edge(masks: np.ndarray, roles: list[str], *, bottom_ratio: float,
|
| 124 |
edge_settings: dict, edge: dict | None = None) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
base = repair_entities(masks, roles, bottom_ratio=bottom_ratio)
|
| 126 |
height, width = masks.shape[1:]
|
| 127 |
if edge is None:
|
|
|
|
| 136 |
|
| 137 |
|
| 138 |
def grid_masks(source: dict, roles: list[str], size: tuple[int, int], *, bottom_ratio: float, edge_settings: dict) -> dict:
|
|
|
|
| 139 |
width, height = size
|
| 140 |
mapped = [np.asarray(Image.fromarray(mask).resize(size, Image.Resampling.NEAREST), np.uint8) for mask in source["entities"]]
|
| 141 |
masks = np.stack(mapped) if mapped else np.zeros((0, height, width), np.uint8)
|
|
|
|
| 143 |
|
| 144 |
|
| 145 |
def assemble_entities(raw: np.ndarray, kept: list[dict], verdict_of: dict[int, dict], post: dict) -> dict:
|
|
|
|
| 146 |
yes = [d for d in kept if verdict_of[d["candidate_id"]]["opaque_hard"] == "yes"]
|
| 147 |
roles = [ROLE_OF_CATEGORY.get(verdict_of[d["candidate_id"]]["category"], "object") for d in yes]
|
| 148 |
height, width = raw.shape[1:]
|
code/agt/masks/proposals.py
CHANGED
|
@@ -1,8 +1,3 @@
|
|
| 1 |
-
"""Scene-independent geometric filters on SAM3 candidate masks.
|
| 2 |
-
|
| 3 |
-
SAM3 concept prompts from a fixed vocabulary produce many instance candidates; this module only applies
|
| 4 |
-
filters that carry no per-scene parameters.
|
| 5 |
-
"""
|
| 6 |
from __future__ import annotations
|
| 7 |
|
| 8 |
import math
|
|
@@ -11,16 +6,9 @@ import numpy as np
|
|
| 11 |
ROLES = {"dashboard", "hood", "pillar", "object"}
|
| 12 |
PANEL_ROLES = {"dashboard", "hood"}
|
| 13 |
DEFAULT_PROPOSAL_FILTER = {"max_area_fraction": 0.6, "dedup_iou": 0.9, "min_area_pixels": 64,
|
| 14 |
-
# Per-role score floors (None = off). SAM3 concept mode is systematically
|
| 15 |
-
# under-confident on large uniform dashboards, so a role may need its own floor.
|
| 16 |
"min_score_by_role": None,
|
| 17 |
-
# Per-role caps are mandatory: a global top-K would truncate low-score panel masks first.
|
| 18 |
"max_candidates_by_role": None,
|
| 19 |
-
# A forward-facing dashcam always shows the ego panel against the bottom frame edge;
|
| 20 |
-
# dashboard/hood candidates that never reach the bottom band are other vehicles.
|
| 21 |
"panel_bottom_reach_fraction": None,
|
| 22 |
-
# The ego hood is near-field and therefore wide; other vehicles' hoods are narrow.
|
| 23 |
-
# A hood may skip the bottom-band test when it spans at least this frame-width fraction.
|
| 24 |
"hood_min_width_fraction": None}
|
| 25 |
|
| 26 |
|
|
@@ -53,10 +41,6 @@ def iou(a: np.ndarray, b: np.ndarray) -> float:
|
|
| 53 |
|
| 54 |
|
| 55 |
def filter_proposals(masks: np.ndarray, candidates: list[dict], settings: dict) -> tuple[list[dict], dict]:
|
| 56 |
-
"""Keep non-empty, not-too-large, de-duplicated, per-role top-K candidates. Returns decisions and a summary.
|
| 57 |
-
|
| 58 |
-
Every candidate gets a decision record so rejected ones remain auditable.
|
| 59 |
-
"""
|
| 60 |
settings = proposal_settings(settings)
|
| 61 |
if masks.ndim != 3 or len(candidates) != len(masks):
|
| 62 |
raise ValueError("candidates must align with [N,H,W] masks")
|
|
@@ -81,9 +65,6 @@ def filter_proposals(masks: np.ndarray, candidates: list[dict], settings: dict)
|
|
| 81 |
decisions.append({**candidate, "area_pixels": area, "area_fraction": area / total, "reasons": reasons, "kept": False})
|
| 82 |
reach, min_width = settings["panel_bottom_reach_fraction"], settings["hood_min_width_fraction"]
|
| 83 |
if reach is not None:
|
| 84 |
-
# Dashcam geometry prior. The ego dashboard rests on the bottom frame edge. The ego hood either reaches
|
| 85 |
-
# that band too or, sitting above the dashboard, is near-field and spans a large part of the frame width;
|
| 86 |
-
# narrow hoods floating higher in the frame belong to other vehicles.
|
| 87 |
band_top = height * (1 - reach) - 1
|
| 88 |
for decision in decisions:
|
| 89 |
if decision["reasons"] or decision["role"] not in PANEL_ROLES:
|
|
@@ -96,7 +77,6 @@ def filter_proposals(masks: np.ndarray, candidates: list[dict], settings: dict)
|
|
| 96 |
continue
|
| 97 |
decision["reasons"].append(f"{decision['role']} candidate does not reach the bottom {reach:g} of the frame"
|
| 98 |
+ (f" and spans less than {min_width:g} of its width" if decision["role"] == "hood" and min_width is not None else ""))
|
| 99 |
-
# de-duplicate among survivors: higher score wins
|
| 100 |
survivors = sorted([d for d in decisions if not d["reasons"]], key=lambda d: -d["score"])
|
| 101 |
kept = []
|
| 102 |
for decision in survivors:
|
|
@@ -105,7 +85,6 @@ def filter_proposals(masks: np.ndarray, candidates: list[dict], settings: dict)
|
|
| 105 |
decision["reasons"].append(f"duplicate of candidate {duplicate['index']} (IoU > {settings['dedup_iou']})")
|
| 106 |
continue
|
| 107 |
kept.append(decision)
|
| 108 |
-
# Per-role caps: each role keeps its own top-K by score.
|
| 109 |
by_role = settings["max_candidates_by_role"]
|
| 110 |
counts, capped = {}, []
|
| 111 |
for decision in kept:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import math
|
|
|
|
| 6 |
ROLES = {"dashboard", "hood", "pillar", "object"}
|
| 7 |
PANEL_ROLES = {"dashboard", "hood"}
|
| 8 |
DEFAULT_PROPOSAL_FILTER = {"max_area_fraction": 0.6, "dedup_iou": 0.9, "min_area_pixels": 64,
|
|
|
|
|
|
|
| 9 |
"min_score_by_role": None,
|
|
|
|
| 10 |
"max_candidates_by_role": None,
|
|
|
|
|
|
|
| 11 |
"panel_bottom_reach_fraction": None,
|
|
|
|
|
|
|
| 12 |
"hood_min_width_fraction": None}
|
| 13 |
|
| 14 |
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
def filter_proposals(masks: np.ndarray, candidates: list[dict], settings: dict) -> tuple[list[dict], dict]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
settings = proposal_settings(settings)
|
| 45 |
if masks.ndim != 3 or len(candidates) != len(masks):
|
| 46 |
raise ValueError("candidates must align with [N,H,W] masks")
|
|
|
|
| 65 |
decisions.append({**candidate, "area_pixels": area, "area_fraction": area / total, "reasons": reasons, "kept": False})
|
| 66 |
reach, min_width = settings["panel_bottom_reach_fraction"], settings["hood_min_width_fraction"]
|
| 67 |
if reach is not None:
|
|
|
|
|
|
|
|
|
|
| 68 |
band_top = height * (1 - reach) - 1
|
| 69 |
for decision in decisions:
|
| 70 |
if decision["reasons"] or decision["role"] not in PANEL_ROLES:
|
|
|
|
| 77 |
continue
|
| 78 |
decision["reasons"].append(f"{decision['role']} candidate does not reach the bottom {reach:g} of the frame"
|
| 79 |
+ (f" and spans less than {min_width:g} of its width" if decision["role"] == "hood" and min_width is not None else ""))
|
|
|
|
| 80 |
survivors = sorted([d for d in decisions if not d["reasons"]], key=lambda d: -d["score"])
|
| 81 |
kept = []
|
| 82 |
for decision in survivors:
|
|
|
|
| 85 |
decision["reasons"].append(f"duplicate of candidate {duplicate['index']} (IoU > {settings['dedup_iou']})")
|
| 86 |
continue
|
| 87 |
kept.append(decision)
|
|
|
|
| 88 |
by_role = settings["max_candidates_by_role"]
|
| 89 |
counts, capped = {}, []
|
| 90 |
for decision in kept:
|
code/agt/masks/sam3_proposer.py
CHANGED
|
@@ -1,8 +1,3 @@
|
|
| 1 |
-
"""SAM3 concept-prompt proposals: one model build, every vocabulary phrase on each frame.
|
| 2 |
-
|
| 3 |
-
Needs the upstream `sam3` package (facebookresearch/sam3) and a CUDA device. The checkpoint is a local
|
| 4 |
-
`sam3.pt` or, when none is given, `facebook/sam3` from the Hugging Face hub.
|
| 5 |
-
"""
|
| 6 |
from __future__ import annotations
|
| 7 |
|
| 8 |
import numpy as np
|
|
@@ -21,7 +16,6 @@ class Sam3Proposer:
|
|
| 21 |
self.processor = Sam3Processor(model, device=device, confidence_threshold=confidence_threshold)
|
| 22 |
|
| 23 |
def run(self, image_path, queries: list[dict]) -> tuple[np.ndarray, list[dict], tuple[int, int]]:
|
| 24 |
-
"""All vocabulary prompts on one image. set_image() without a state returns a fresh state per image."""
|
| 25 |
torch, processor = self.torch, self.processor
|
| 26 |
source = Image.open(image_path).convert("RGB")
|
| 27 |
masks, candidates = [], []
|
|
@@ -30,7 +24,6 @@ class Sam3Proposer:
|
|
| 30 |
for query in queries:
|
| 31 |
processor.reset_all_prompts(state)
|
| 32 |
output = processor.set_text_prompt(query["phrase"], state)
|
| 33 |
-
# Copies detach each phrase from the mutable processor state.
|
| 34 |
query_masks = output["masks"].detach().cpu().numpy().copy()
|
| 35 |
boxes = output["boxes"].detach().float().cpu().numpy().copy()
|
| 36 |
scores = output["scores"].detach().float().cpu().numpy().copy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 16 |
self.processor = Sam3Processor(model, device=device, confidence_threshold=confidence_threshold)
|
| 17 |
|
| 18 |
def run(self, image_path, queries: list[dict]) -> tuple[np.ndarray, list[dict], tuple[int, int]]:
|
|
|
|
| 19 |
torch, processor = self.torch, self.processor
|
| 20 |
source = Image.open(image_path).convert("RGB")
|
| 21 |
masks, candidates = [], []
|
|
|
|
| 24 |
for query in queries:
|
| 25 |
processor.reset_all_prompts(state)
|
| 26 |
output = processor.set_text_prompt(query["phrase"], state)
|
|
|
|
| 27 |
query_masks = output["masks"].detach().cpu().numpy().copy()
|
| 28 |
boxes = output["boxes"].detach().float().cpu().numpy().copy()
|
| 29 |
scores = output["scores"].detach().float().cpu().numpy().copy()
|
code/agt/masks/sheets.py
CHANGED
|
@@ -1,8 +1,3 @@
|
|
| 1 |
-
"""Numbered candidate sheets shown to the verifier.
|
| 2 |
-
|
| 3 |
-
Style is fixed and scene-independent; the only inputs are the source RGB and the kept proposals. The number
|
| 4 |
-
shown on each cell is the candidate_id the verifier must echo.
|
| 5 |
-
"""
|
| 6 |
from __future__ import annotations
|
| 7 |
|
| 8 |
import numpy as np
|
|
@@ -33,14 +28,13 @@ def outline(mask: np.ndarray) -> np.ndarray:
|
|
| 33 |
|
| 34 |
|
| 35 |
def _context_window(box, size):
|
| 36 |
-
"""Crop window around a box: 30% margin, never smaller than a quarter of the frame width / 15% of its height."""
|
| 37 |
width, height = size
|
| 38 |
x0, y0, x1, y1 = box
|
| 39 |
bw, bh = max(1.0, x1 - x0), max(1.0, y1 - y0)
|
| 40 |
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
|
| 41 |
w = max(bw * 1.6, width * 0.25, bw + 2 * width * 0.04)
|
| 42 |
h = max(bh * 1.6, height * 0.15, bh + 2 * height * 0.04)
|
| 43 |
-
ratio = CTX_W / CTX_H
|
| 44 |
if w / h < ratio:
|
| 45 |
w = h * ratio
|
| 46 |
else:
|
|
@@ -52,7 +46,6 @@ def _context_window(box, size):
|
|
| 52 |
|
| 53 |
|
| 54 |
def render_candidate_tile(rgb: np.ndarray, mask: np.ndarray, decision: dict, colour) -> Image.Image:
|
| 55 |
-
"""One tile: header text, full-frame locator with only this candidate marked, and a context crop."""
|
| 56 |
height, width = rgb.shape[:2]
|
| 57 |
mask = mask.astype(bool)
|
| 58 |
tile = Image.new("RGB", (TILE_W, TILE_HEADER + CTX_H), (18, 18, 18))
|
|
@@ -64,7 +57,6 @@ def render_candidate_tile(rgb: np.ndarray, mask: np.ndarray, decision: dict, col
|
|
| 64 |
draw.text((8, 4), f"#{decision['candidate_id']}", fill=colour, font=_font(24))
|
| 65 |
draw.text((8, 32), f"proposed as: {decision['phrase']} (score {decision['score']:.2f}) centre {cx*100:.0f}% from left, {cy*100:.0f}% from top "
|
| 66 |
f"reaches bottom edge: {'yes' if touches_bottom else 'no'}", fill=(200, 200, 200), font=_font(18))
|
| 67 |
-
# locator: whole frame, this candidate only
|
| 68 |
loc = rgb.astype(np.float32).copy()
|
| 69 |
loc[mask] = loc[mask] * 0.4 + np.array(colour, np.float32) * 0.6
|
| 70 |
loc_img = Image.fromarray(np.clip(loc, 0, 255).astype(np.uint8))
|
|
@@ -72,7 +64,6 @@ def render_candidate_tile(rgb: np.ndarray, mask: np.ndarray, decision: dict, col
|
|
| 72 |
loc_img = loc_img.resize((LOCATOR_W, max(1, int(round(height * scale)))), Image.LANCZOS)
|
| 73 |
ImageDraw.Draw(loc_img).rectangle((x0 * scale - 3, y0 * scale - 3, x1 * scale + 3, y1 * scale + 3), outline=colour, width=3)
|
| 74 |
tile.paste(loc_img, (0, TILE_HEADER + (CTX_H - loc_img.height) // 2))
|
| 75 |
-
# context crop with outline and light tint
|
| 76 |
cx0, cy0, cx1, cy1 = _context_window((x0, y0, x1, y1), (width, height))
|
| 77 |
crop = rgb[cy0:cy1, cx0:cx1].astype(np.float32).copy()
|
| 78 |
sub = mask[cy0:cy1, cx0:cx1]
|
|
@@ -86,7 +77,6 @@ def render_candidate_tile(rgb: np.ndarray, mask: np.ndarray, decision: dict, col
|
|
| 86 |
|
| 87 |
|
| 88 |
def render_candidate_sheets(rgb: np.ndarray, masks: np.ndarray, page: list[dict], per_sheet: int = CANDIDATES_PER_SHEET) -> list[Image.Image]:
|
| 89 |
-
"""Stack candidate tiles vertically, at most `per_sheet` per image so nothing is downscaled away."""
|
| 90 |
sheets = []
|
| 91 |
for start in range(0, len(page), per_sheet):
|
| 92 |
chunk = page[start:start + per_sheet]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import numpy as np
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
def _context_window(box, size):
|
|
|
|
| 31 |
width, height = size
|
| 32 |
x0, y0, x1, y1 = box
|
| 33 |
bw, bh = max(1.0, x1 - x0), max(1.0, y1 - y0)
|
| 34 |
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
|
| 35 |
w = max(bw * 1.6, width * 0.25, bw + 2 * width * 0.04)
|
| 36 |
h = max(bh * 1.6, height * 0.15, bh + 2 * height * 0.04)
|
| 37 |
+
ratio = CTX_W / CTX_H
|
| 38 |
if w / h < ratio:
|
| 39 |
w = h * ratio
|
| 40 |
else:
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
def render_candidate_tile(rgb: np.ndarray, mask: np.ndarray, decision: dict, colour) -> Image.Image:
|
|
|
|
| 49 |
height, width = rgb.shape[:2]
|
| 50 |
mask = mask.astype(bool)
|
| 51 |
tile = Image.new("RGB", (TILE_W, TILE_HEADER + CTX_H), (18, 18, 18))
|
|
|
|
| 57 |
draw.text((8, 4), f"#{decision['candidate_id']}", fill=colour, font=_font(24))
|
| 58 |
draw.text((8, 32), f"proposed as: {decision['phrase']} (score {decision['score']:.2f}) centre {cx*100:.0f}% from left, {cy*100:.0f}% from top "
|
| 59 |
f"reaches bottom edge: {'yes' if touches_bottom else 'no'}", fill=(200, 200, 200), font=_font(18))
|
|
|
|
| 60 |
loc = rgb.astype(np.float32).copy()
|
| 61 |
loc[mask] = loc[mask] * 0.4 + np.array(colour, np.float32) * 0.6
|
| 62 |
loc_img = Image.fromarray(np.clip(loc, 0, 255).astype(np.uint8))
|
|
|
|
| 64 |
loc_img = loc_img.resize((LOCATOR_W, max(1, int(round(height * scale)))), Image.LANCZOS)
|
| 65 |
ImageDraw.Draw(loc_img).rectangle((x0 * scale - 3, y0 * scale - 3, x1 * scale + 3, y1 * scale + 3), outline=colour, width=3)
|
| 66 |
tile.paste(loc_img, (0, TILE_HEADER + (CTX_H - loc_img.height) // 2))
|
|
|
|
| 67 |
cx0, cy0, cx1, cy1 = _context_window((x0, y0, x1, y1), (width, height))
|
| 68 |
crop = rgb[cy0:cy1, cx0:cx1].astype(np.float32).copy()
|
| 69 |
sub = mask[cy0:cy1, cx0:cx1]
|
|
|
|
| 77 |
|
| 78 |
|
| 79 |
def render_candidate_sheets(rgb: np.ndarray, masks: np.ndarray, page: list[dict], per_sheet: int = CANDIDATES_PER_SHEET) -> list[Image.Image]:
|
|
|
|
| 80 |
sheets = []
|
| 81 |
for start in range(0, len(page), per_sheet):
|
| 82 |
chunk = page[start:start + per_sheet]
|
code/agt/masks/verifiers/__init__.py
CHANGED
|
@@ -1,14 +1,3 @@
|
|
| 1 |
-
"""Pluggable candidate verifiers.
|
| 2 |
-
|
| 3 |
-
A verifier answers one verification page at a time. A page directory holds `source.png` (the untouched frame),
|
| 4 |
-
`candidates_XX.png` (numbered candidate sheets, at most six cells each) and `candidates.json`
|
| 5 |
-
(`template_id`, `page_index`, `candidates[*].candidate_id`). The verifier reads the prompt and the images and
|
| 6 |
-
returns, for every candidate, `opaque_hard` (yes / no / uncertain), `category` and `reason`, conforming to the
|
| 7 |
-
answer schema. The pipeline validates the answer again and writes `verdicts.json`; the verifier may also write
|
| 8 |
-
it itself.
|
| 9 |
-
|
| 10 |
-
To add a verifier, implement `Verifier.send_page` and register a factory in `FACTORIES`.
|
| 11 |
-
"""
|
| 12 |
from __future__ import annotations
|
| 13 |
|
| 14 |
from pathlib import Path
|
|
@@ -17,11 +6,6 @@ from typing import Protocol
|
|
| 17 |
|
| 18 |
class Verifier(Protocol):
|
| 19 |
def send_page(self, page_dir: Path, prompt: str, schema: dict, maximum_retries: int) -> dict:
|
| 20 |
-
"""Verify one page.
|
| 21 |
-
|
| 22 |
-
Returns {"status": "ready", "template_id", "page_index", "verdicts": [{"candidate_id", "opaque_hard",
|
| 23 |
-
"category", "reason"}, ...], ...} on success, or {"status": "failed", "errors": [...]}.
|
| 24 |
-
"""
|
| 25 |
...
|
| 26 |
|
| 27 |
|
|
@@ -35,5 +19,4 @@ FACTORIES = {"qwen": _qwen}
|
|
| 35 |
|
| 36 |
|
| 37 |
def build_verifier(settings: dict, device: str = "cuda") -> Verifier:
|
| 38 |
-
"""`settings` is the `verify` section of the mask config (`verifier`, `model`, ...)."""
|
| 39 |
return FACTORIES[settings["verifier"]](settings, device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
from pathlib import Path
|
|
|
|
| 6 |
|
| 7 |
class Verifier(Protocol):
|
| 8 |
def send_page(self, page_dir: Path, prompt: str, schema: dict, maximum_retries: int) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
...
|
| 10 |
|
| 11 |
|
|
|
|
| 19 |
|
| 20 |
|
| 21 |
def build_verifier(settings: dict, device: str = "cuda") -> Verifier:
|
|
|
|
| 22 |
return FACTORIES[settings["verifier"]](settings, device)
|
code/agt/masks/verifiers/qwen.py
CHANGED
|
@@ -1,17 +1,3 @@
|
|
| 1 |
-
"""Occluder candidate verifier backed by a locally run Qwen3.5 vision-language model.
|
| 2 |
-
|
| 3 |
-
One request per verification page. A page directory holds the attachments built by the mask
|
| 4 |
-
pipeline: ``source.png`` (the untouched frame), ``candidates_*.png`` (numbered candidate sheets,
|
| 5 |
-
at most six cells each), ``candidates.json`` (``template_id``, ``page_index``, ``candidates``).
|
| 6 |
-
The model reads the verification prompt plus the attachments and returns one JSON object that
|
| 7 |
-
must satisfy the answer schema; decoding is constrained to that schema. Invalid answers are
|
| 8 |
-
retried with the validation error appended. Per-candidate yes/no/uncertain verdicts are written
|
| 9 |
-
to ``verdicts.json``; voting across frames is left to the caller.
|
| 10 |
-
|
| 11 |
-
Weights are loaded once with vLLM on a single GPU; no network service or API key is involved.
|
| 12 |
-
vLLM starts its engine in a spawned process, so scripts that create a ``QwenVerifier`` need an
|
| 13 |
-
``if __name__ == "__main__":`` guard.
|
| 14 |
-
"""
|
| 15 |
from __future__ import annotations
|
| 16 |
|
| 17 |
import json
|
|
@@ -30,7 +16,6 @@ RETRY_FEEDBACK = ("\n\nYour previous response failed validation; re-check the at
|
|
| 30 |
|
| 31 |
|
| 32 |
def task_prompt(prompt: str, schema: dict, candidates: dict) -> str:
|
| 33 |
-
"""Verification prompt + task identity + the answer schema the reply is decoded against."""
|
| 34 |
identity = {"template_id": candidates["template_id"], "page_index": candidates["page_index"],
|
| 35 |
"candidate_ids": [c["candidate_id"] for c in candidates["candidates"]]}
|
| 36 |
return (prompt + "\n\nTask identity (return template_id and page_index verbatim; answer every listed candidate_id exactly once):\n"
|
|
@@ -39,8 +24,6 @@ def task_prompt(prompt: str, schema: dict, candidates: dict) -> str:
|
|
| 39 |
|
| 40 |
|
| 41 |
class QwenVerifier:
|
| 42 |
-
"""Local Qwen3.5 verifier. ``device`` is ``cuda`` or ``cuda:N`` (one GPU); ``dtype`` is passed to vLLM."""
|
| 43 |
-
|
| 44 |
def __init__(self, model_id_or_path: str = DEFAULT_MODEL, device: str = "cuda", dtype: str = "bfloat16", *,
|
| 45 |
revision: str | None = None, max_model_len: int = 65536, max_new_tokens: int = 16384,
|
| 46 |
gpu_memory_utilization: float = 0.85, enable_thinking: bool = False, temperature: float = 0.0, seed: int = 0):
|
|
@@ -57,7 +40,6 @@ class QwenVerifier:
|
|
| 57 |
structured_outputs_config={"backend": "xgrammar", "reasoning_parser": "qwen3" if enable_thinking else ""})
|
| 58 |
|
| 59 |
def generate(self, images: list, prompt: str, schema: dict) -> tuple[dict, str]:
|
| 60 |
-
"""One schema-constrained request. ``images`` are PIL images or paths, sent in order before the text."""
|
| 61 |
content = [{"type": "image_pil", "image_pil": im if isinstance(im, Image.Image) else Image.open(im).convert("RGB")} for im in images]
|
| 62 |
content.append({"type": "text", "text": prompt})
|
| 63 |
params = self._sampling(temperature=self.temperature, max_tokens=self.max_new_tokens, seed=self.seed,
|
|
@@ -68,7 +50,6 @@ class QwenVerifier:
|
|
| 68 |
return json.loads(text), out.text
|
| 69 |
|
| 70 |
def send_page(self, page_dir: Path, prompt: str, schema: dict, maximum_retries: int = 2) -> dict:
|
| 71 |
-
"""Verify one page; archives every attempt under page_dir/attempts/<id>/ and writes page_dir/verdicts.json."""
|
| 72 |
page_dir = Path(page_dir)
|
| 73 |
if (page_dir / "verdicts.json").exists():
|
| 74 |
return {"status": "ready", "reused": True, **json.loads((page_dir / "verdicts.json").read_text())}
|
|
@@ -88,7 +69,7 @@ class QwenVerifier:
|
|
| 88 |
started = time.time()
|
| 89 |
try:
|
| 90 |
answer, raw = self.generate(images, base + feedback, schema)
|
| 91 |
-
except ValueError as exc:
|
| 92 |
answer, raw = None, str(exc)
|
| 93 |
seconds = round(time.time() - started, 1)
|
| 94 |
(attempt / "response.txt").write_text(raw, encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
def task_prompt(prompt: str, schema: dict, candidates: dict) -> str:
|
|
|
|
| 19 |
identity = {"template_id": candidates["template_id"], "page_index": candidates["page_index"],
|
| 20 |
"candidate_ids": [c["candidate_id"] for c in candidates["candidates"]]}
|
| 21 |
return (prompt + "\n\nTask identity (return template_id and page_index verbatim; answer every listed candidate_id exactly once):\n"
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
class QwenVerifier:
|
|
|
|
|
|
|
| 27 |
def __init__(self, model_id_or_path: str = DEFAULT_MODEL, device: str = "cuda", dtype: str = "bfloat16", *,
|
| 28 |
revision: str | None = None, max_model_len: int = 65536, max_new_tokens: int = 16384,
|
| 29 |
gpu_memory_utilization: float = 0.85, enable_thinking: bool = False, temperature: float = 0.0, seed: int = 0):
|
|
|
|
| 40 |
structured_outputs_config={"backend": "xgrammar", "reasoning_parser": "qwen3" if enable_thinking else ""})
|
| 41 |
|
| 42 |
def generate(self, images: list, prompt: str, schema: dict) -> tuple[dict, str]:
|
|
|
|
| 43 |
content = [{"type": "image_pil", "image_pil": im if isinstance(im, Image.Image) else Image.open(im).convert("RGB")} for im in images]
|
| 44 |
content.append({"type": "text", "text": prompt})
|
| 45 |
params = self._sampling(temperature=self.temperature, max_tokens=self.max_new_tokens, seed=self.seed,
|
|
|
|
| 50 |
return json.loads(text), out.text
|
| 51 |
|
| 52 |
def send_page(self, page_dir: Path, prompt: str, schema: dict, maximum_retries: int = 2) -> dict:
|
|
|
|
| 53 |
page_dir = Path(page_dir)
|
| 54 |
if (page_dir / "verdicts.json").exists():
|
| 55 |
return {"status": "ready", "reused": True, **json.loads((page_dir / "verdicts.json").read_text())}
|
|
|
|
| 69 |
started = time.time()
|
| 70 |
try:
|
| 71 |
answer, raw = self.generate(images, base + feedback, schema)
|
| 72 |
+
except ValueError as exc:
|
| 73 |
answer, raw = None, str(exc)
|
| 74 |
seconds = round(time.time() - started, 1)
|
| 75 |
(attempt / "response.txt").write_text(raw, encoding="utf-8")
|
code/agt/masks/verify.py
CHANGED
|
@@ -1,9 +1,3 @@
|
|
| 1 |
-
"""Verification pages: build them from the kept proposals, send them to a verifier, read the verdicts back.
|
| 2 |
-
|
| 3 |
-
Per frame, `<frame dir>/verify/page_XX/` holds `source.png`, `candidates_XX.png` and `candidates.json`; the
|
| 4 |
-
accepted answer lands in `page_XX/verdicts.json`. Pages that already have verdicts are never sent again.
|
| 5 |
-
The verifier never receives or returns coordinates.
|
| 6 |
-
"""
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
import json
|
|
@@ -34,7 +28,6 @@ def validate_verdicts(answer: dict, schema: dict, template_id: str, page_index:
|
|
| 34 |
|
| 35 |
|
| 36 |
def read_proposals(frame_dir: Path) -> dict:
|
| 37 |
-
"""Raw SAM3 masks and the kept candidates (contiguous candidate_id) of one frame."""
|
| 38 |
directory = frame_dir / "proposals"
|
| 39 |
proposals = json.loads((directory / "proposals.json").read_text())
|
| 40 |
with np.load(directory / "raw_candidates.npz", allow_pickle=False) as handle:
|
|
@@ -44,7 +37,6 @@ def read_proposals(frame_dir: Path) -> dict:
|
|
| 44 |
|
| 45 |
|
| 46 |
def build_pages(frame_dir: Path, template_id: str, rgb: np.ndarray, per_page: int) -> list[Path]:
|
| 47 |
-
"""Write the verification pages of one frame; a frame without kept candidates has no pages."""
|
| 48 |
proposals = read_proposals(frame_dir)
|
| 49 |
directory = frame_dir / "verify"
|
| 50 |
directory.mkdir(parents=True, exist_ok=True)
|
|
@@ -53,7 +45,7 @@ def build_pages(frame_dir: Path, template_id: str, rgb: np.ndarray, per_page: in
|
|
| 53 |
for index, page in enumerate(pages):
|
| 54 |
page_dir = directory / f"page_{index:02d}"
|
| 55 |
page_dir.mkdir(exist_ok=True)
|
| 56 |
-
Image.fromarray(rgb).save(page_dir / "source.png")
|
| 57 |
for k, sheet in enumerate(render_candidate_sheets(rgb, proposals["raw"], page)):
|
| 58 |
sheet.save(page_dir / f"candidates_{k:02d}.png")
|
| 59 |
write_json(page_dir / "candidates.json", {"template_id": template_id, "page_index": index,
|
|
@@ -64,7 +56,6 @@ def build_pages(frame_dir: Path, template_id: str, rgb: np.ndarray, per_page: in
|
|
| 64 |
|
| 65 |
|
| 66 |
def send_page(verifier, page_dir: Path, prompt: str, schema: dict, maximum_retries: int) -> dict:
|
| 67 |
-
"""One verifier call per page; the answer is validated against the schema and the page's candidate ids."""
|
| 68 |
if (page_dir / "verdicts.json").exists():
|
| 69 |
return json.loads((page_dir / "verdicts.json").read_text())
|
| 70 |
candidates = json.loads((page_dir / "candidates.json").read_text())
|
|
@@ -81,7 +72,6 @@ def send_page(verifier, page_dir: Path, prompt: str, schema: dict, maximum_retri
|
|
| 81 |
|
| 82 |
|
| 83 |
def read_verdicts(frame_dir: Path, kept: list[dict]) -> dict[int, dict]:
|
| 84 |
-
"""candidate_id -> verdict over all pages of one frame; each kept candidate answered exactly once."""
|
| 85 |
directory = frame_dir / "verify"
|
| 86 |
pages = json.loads((directory / "pages.json").read_text())["pages"]
|
| 87 |
verdict_of = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
def read_proposals(frame_dir: Path) -> dict:
|
|
|
|
| 31 |
directory = frame_dir / "proposals"
|
| 32 |
proposals = json.loads((directory / "proposals.json").read_text())
|
| 33 |
with np.load(directory / "raw_candidates.npz", allow_pickle=False) as handle:
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def build_pages(frame_dir: Path, template_id: str, rgb: np.ndarray, per_page: int) -> list[Path]:
|
|
|
|
| 40 |
proposals = read_proposals(frame_dir)
|
| 41 |
directory = frame_dir / "verify"
|
| 42 |
directory.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 45 |
for index, page in enumerate(pages):
|
| 46 |
page_dir = directory / f"page_{index:02d}"
|
| 47 |
page_dir.mkdir(exist_ok=True)
|
| 48 |
+
Image.fromarray(rgb).save(page_dir / "source.png")
|
| 49 |
for k, sheet in enumerate(render_candidate_sheets(rgb, proposals["raw"], page)):
|
| 50 |
sheet.save(page_dir / f"candidates_{k:02d}.png")
|
| 51 |
write_json(page_dir / "candidates.json", {"template_id": template_id, "page_index": index,
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
def send_page(verifier, page_dir: Path, prompt: str, schema: dict, maximum_retries: int) -> dict:
|
|
|
|
| 59 |
if (page_dir / "verdicts.json").exists():
|
| 60 |
return json.loads((page_dir / "verdicts.json").read_text())
|
| 61 |
candidates = json.loads((page_dir / "candidates.json").read_text())
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
def read_verdicts(frame_dir: Path, kept: list[dict]) -> dict[int, dict]:
|
|
|
|
| 75 |
directory = frame_dir / "verify"
|
| 76 |
pages = json.loads((directory / "pages.json").read_text())["pages"]
|
| 77 |
verdict_of = {}
|
code/agt/model/build.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
"""Build the reconstruction model from configs/model.json and the released checkpoint."""
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import json
|
|
@@ -20,7 +19,6 @@ def load_config(path=DEFAULT_CONFIG) -> dict:
|
|
| 20 |
|
| 21 |
|
| 22 |
def resolve_checkpoint(config, checkpoint=None, checkpoint_dir=None) -> Path:
|
| 23 |
-
"""Explicit path > <checkpoint_dir>/<file name> > repo-relative path from the config."""
|
| 24 |
if checkpoint:
|
| 25 |
return Path(checkpoint)
|
| 26 |
if checkpoint_dir:
|
|
@@ -29,8 +27,6 @@ def resolve_checkpoint(config, checkpoint=None, checkpoint_dir=None) -> Path:
|
|
| 29 |
|
| 30 |
|
| 31 |
def build_model(config=None, checkpoint=None, checkpoint_dir=None):
|
| 32 |
-
"""DGGT VGGT with the removed heads dropped and the released weights loaded strictly, the occluder mask
|
| 33 |
-
installed in the global attention blocks; CUDA, eval, no grad."""
|
| 34 |
from safetensors.torch import load_file
|
| 35 |
from .mask_attention import install
|
| 36 |
config = load_config() if config is None else config
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import json
|
|
|
|
| 19 |
|
| 20 |
|
| 21 |
def resolve_checkpoint(config, checkpoint=None, checkpoint_dir=None) -> Path:
|
|
|
|
| 22 |
if checkpoint:
|
| 23 |
return Path(checkpoint)
|
| 24 |
if checkpoint_dir:
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
def build_model(config=None, checkpoint=None, checkpoint_dir=None):
|
|
|
|
|
|
|
| 30 |
from safetensors.torch import load_file
|
| 31 |
from .mask_attention import install
|
| 32 |
config = load_config() if config is None else config
|
code/agt/model/gating.py
CHANGED
|
@@ -1,9 +1,7 @@
|
|
| 1 |
-
"""Tensor helpers around the model outputs: occluder mask layout, visibility gating and the scale cap."""
|
| 2 |
import torch
|
| 3 |
|
| 4 |
|
| 5 |
def mask_for_images(mask, images):
|
| 6 |
-
"""Static [B, H, W] or per-frame [B, S, H, W] occluder mask -> bool [B, S, H, W] on the images' device."""
|
| 7 |
b, s, _, h, w = images.shape
|
| 8 |
if mask.ndim == 3 and mask.shape == (b, h, w):
|
| 9 |
mask = mask[:, None].expand(b, s, h, w)
|
|
@@ -15,7 +13,6 @@ def mask_for_images(mask, images):
|
|
| 15 |
|
| 16 |
|
| 17 |
def gate_predictions(predictions, mask):
|
| 18 |
-
"""Zero the Gaussian opacity channel where `mask` is True (pixels no input frame observed)."""
|
| 19 |
gs = predictions['gs_map']
|
| 20 |
if gs.ndim != 5 or gs.shape[:4] != mask.shape or gs.shape[-1] < 4:
|
| 21 |
raise ValueError(f'gs_map {tuple(gs.shape)} / mask {tuple(mask.shape)}')
|
|
@@ -27,7 +24,6 @@ def gate_predictions(predictions, mask):
|
|
| 27 |
|
| 28 |
|
| 29 |
def cap_scales(predictions, cap):
|
| 30 |
-
"""Clamp the Gaussian scales (gs_map channels 4:7) of the rendered copy to `cap`."""
|
| 31 |
if cap <= 0:
|
| 32 |
return predictions
|
| 33 |
gs = predictions['gs_map']
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
|
| 3 |
|
| 4 |
def mask_for_images(mask, images):
|
|
|
|
| 5 |
b, s, _, h, w = images.shape
|
| 6 |
if mask.ndim == 3 and mask.shape == (b, h, w):
|
| 7 |
mask = mask[:, None].expand(b, s, h, w)
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def gate_predictions(predictions, mask):
|
|
|
|
| 16 |
gs = predictions['gs_map']
|
| 17 |
if gs.ndim != 5 or gs.shape[:4] != mask.shape or gs.shape[-1] < 4:
|
| 18 |
raise ValueError(f'gs_map {tuple(gs.shape)} / mask {tuple(mask.shape)}')
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
def cap_scales(predictions, cap):
|
|
|
|
| 27 |
if cap <= 0:
|
| 28 |
return predictions
|
| 29 |
gs = predictions['gs_map']
|
code/agt/model/mask_attention.py
CHANGED
|
@@ -1,10 +1,3 @@
|
|
| 1 |
-
"""Occluder mask in the global attention blocks of the DGGT aggregator.
|
| 2 |
-
|
| 3 |
-
In every global (cross-frame) attention block, the keys of occluded patch tokens are excluded from attention.
|
| 4 |
-
The 5 special tokens (camera + 4 register tokens) and the visible patch tokens stay attendable, and no query row is
|
| 5 |
-
masked, so every row attends at least to the 5 special tokens. A patch is occluded when the occluder mask, resized
|
| 6 |
-
to the patch grid with nearest-neighbour sampling, is > 0.5.
|
| 7 |
-
"""
|
| 8 |
from contextlib import contextmanager
|
| 9 |
from types import MethodType
|
| 10 |
import weakref
|
|
@@ -17,8 +10,6 @@ from .gating import mask_for_images
|
|
| 17 |
|
| 18 |
|
| 19 |
class OccluderKeyMask:
|
| 20 |
-
"""Per-forward key mask [B, S, 5 + patches] of the global blocks."""
|
| 21 |
-
|
| 22 |
def __init__(self, aggregator):
|
| 23 |
self.patch_size = aggregator.patch_size
|
| 24 |
self.patch_start_idx = aggregator.patch_start_idx
|
|
@@ -26,7 +17,6 @@ class OccluderKeyMask:
|
|
| 26 |
self.current = None
|
| 27 |
|
| 28 |
def build(self, masks, height, width):
|
| 29 |
-
"""masks (B, S, 1, H, W) float 0/1 -> key mask (B, S, 5 + patches): 0 = attend, -inf = excluded."""
|
| 30 |
batch_size, num_views = masks.shape[:2]
|
| 31 |
patch_h, patch_w = height // self.patch_size, width // self.patch_size
|
| 32 |
small = F.interpolate(masks.flatten(0, 1), size=(patch_h, patch_w), mode='nearest')
|
|
@@ -42,7 +32,6 @@ class OccluderKeyMask:
|
|
| 42 |
return self.current.flatten(1)[:, None, None, :]
|
| 43 |
|
| 44 |
|
| 45 |
-
# DGGT dggt/layers/attention.py L50-78 (a3276d2) with the key mask passed to the attention.
|
| 46 |
def masked_attention(self, x: Tensor, pos=None):
|
| 47 |
key_mask = getattr(self, '_key_mask', None)
|
| 48 |
if key_mask is None:
|
|
@@ -66,7 +55,6 @@ def masked_attention(self, x: Tensor, pos=None):
|
|
| 66 |
return x
|
| 67 |
|
| 68 |
|
| 69 |
-
# DGGT dggt/models/aggregator.py L310-333 (a3276d2), with the key mask set before each global block.
|
| 70 |
def process_global(self, tokens, B, S, P, C, global_idx, pos=None):
|
| 71 |
controller = self._mask_controller()
|
| 72 |
if controller.current is None:
|
|
@@ -89,7 +77,6 @@ def process_global(self, tokens, B, S, P, C, global_idx, pos=None):
|
|
| 89 |
|
| 90 |
|
| 91 |
def install(model):
|
| 92 |
-
"""Attach the occluder mask to the global attention blocks of a DGGT model (idempotent)."""
|
| 93 |
if hasattr(model, '_occluder_mask'):
|
| 94 |
return model
|
| 95 |
aggregator = model.aggregator
|
|
@@ -106,7 +93,6 @@ def install(model):
|
|
| 106 |
|
| 107 |
@contextmanager
|
| 108 |
def mask_context(model, mask=None, images=None):
|
| 109 |
-
"""Scope of one model forward: mask (B, S, H, W) or (B, H, W) 0/1 occluder mask; None = no mask."""
|
| 110 |
controller = getattr(model, '_occluder_mask', None)
|
| 111 |
if controller is None:
|
| 112 |
yield
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from contextlib import contextmanager
|
| 2 |
from types import MethodType
|
| 3 |
import weakref
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
class OccluderKeyMask:
|
|
|
|
|
|
|
| 13 |
def __init__(self, aggregator):
|
| 14 |
self.patch_size = aggregator.patch_size
|
| 15 |
self.patch_start_idx = aggregator.patch_start_idx
|
|
|
|
| 17 |
self.current = None
|
| 18 |
|
| 19 |
def build(self, masks, height, width):
|
|
|
|
| 20 |
batch_size, num_views = masks.shape[:2]
|
| 21 |
patch_h, patch_w = height // self.patch_size, width // self.patch_size
|
| 22 |
small = F.interpolate(masks.flatten(0, 1), size=(patch_h, patch_w), mode='nearest')
|
|
|
|
| 32 |
return self.current.flatten(1)[:, None, None, :]
|
| 33 |
|
| 34 |
|
|
|
|
| 35 |
def masked_attention(self, x: Tensor, pos=None):
|
| 36 |
key_mask = getattr(self, '_key_mask', None)
|
| 37 |
if key_mask is None:
|
|
|
|
| 55 |
return x
|
| 56 |
|
| 57 |
|
|
|
|
| 58 |
def process_global(self, tokens, B, S, P, C, global_idx, pos=None):
|
| 59 |
controller = self._mask_controller()
|
| 60 |
if controller.current is None:
|
|
|
|
| 77 |
|
| 78 |
|
| 79 |
def install(model):
|
|
|
|
| 80 |
if hasattr(model, '_occluder_mask'):
|
| 81 |
return model
|
| 82 |
aggregator = model.aggregator
|
|
|
|
| 93 |
|
| 94 |
@contextmanager
|
| 95 |
def mask_context(model, mask=None, images=None):
|
|
|
|
| 96 |
controller = getattr(model, '_occluder_mask', None)
|
| 97 |
if controller is None:
|
| 98 |
yield
|
code/agt/model/runtime.py
CHANGED
|
@@ -1,9 +1,3 @@
|
|
| 1 |
-
"""One masked forward of the reconstruction model followed by the online visibility gate.
|
| 2 |
-
|
| 3 |
-
predict(): the model sees the raw input frames with the occluder mask applied in its global attention blocks;
|
| 4 |
-
the input-frame visibility V of occluded pixels is computed from the model's own depth and cameras; Gaussian
|
| 5 |
-
scales are capped and the opacity of Gaussians on occluded pixels that no other input frame observed is set to 0.
|
| 6 |
-
"""
|
| 7 |
from .gating import cap_scales, gate_predictions, mask_for_images
|
| 8 |
from .mask_attention import mask_context
|
| 9 |
from .visibility import ext_to_c2w, visibility, visibility_camera
|
|
@@ -16,8 +10,6 @@ def cameras(predictions, images):
|
|
| 16 |
|
| 17 |
|
| 18 |
def online_visibility(predictions, images, mask, *, z_tol=.05):
|
| 19 |
-
"""Depth-consistent visibility of the occluded pixels from the other input frames. More than 8 input frames:
|
| 20 |
-
sources in groups of 8, V = OR over the groups (bits are not returned)."""
|
| 21 |
mask = mask_for_images(mask, images)
|
| 22 |
ext, K = cameras(predictions, images)
|
| 23 |
t = mask.shape[1]
|
|
@@ -32,7 +24,6 @@ def online_visibility(predictions, images, mask, *, z_tol=.05):
|
|
| 32 |
|
| 33 |
|
| 34 |
def online_visibility_camera(predictions, images, mask):
|
| 35 |
-
"""Camera-occluder-only visibility from the model's own depth and cameras (groups of 8 as above)."""
|
| 36 |
mask = mask_for_images(mask, images)
|
| 37 |
ext, K = cameras(predictions, images)
|
| 38 |
t = mask.shape[1]
|
|
@@ -47,8 +38,6 @@ def online_visibility_camera(predictions, images, mask):
|
|
| 47 |
|
| 48 |
|
| 49 |
def predict(model, images, occluder_mask, *, z_tol=None, attention_mask=None):
|
| 50 |
-
"""images (1,S,3,H,W) in [0,1]; occluder_mask (1,S,H,W) bool (visibility); attention_mask: occluder mask used in
|
| 51 |
-
the attention (default: occluder_mask). Returns (gated predictions, V)."""
|
| 52 |
options = model._options
|
| 53 |
with mask_context(model, occluder_mask if attention_mask is None else attention_mask, images):
|
| 54 |
predictions = model(images)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from .gating import cap_scales, gate_predictions, mask_for_images
|
| 2 |
from .mask_attention import mask_context
|
| 3 |
from .visibility import ext_to_c2w, visibility, visibility_camera
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
def online_visibility(predictions, images, mask, *, z_tol=.05):
|
|
|
|
|
|
|
| 13 |
mask = mask_for_images(mask, images)
|
| 14 |
ext, K = cameras(predictions, images)
|
| 15 |
t = mask.shape[1]
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
def online_visibility_camera(predictions, images, mask):
|
|
|
|
| 27 |
mask = mask_for_images(mask, images)
|
| 28 |
ext, K = cameras(predictions, images)
|
| 29 |
t = mask.shape[1]
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
def predict(model, images, occluder_mask, *, z_tol=None, attention_mask=None):
|
|
|
|
|
|
|
| 41 |
options = model._options
|
| 42 |
with mask_context(model, occluder_mask if attention_mask is None else attention_mask, images):
|
| 43 |
predictions = model(images)
|