kubilaycaglayan commited on
Commit
c3a2d68
·
1 Parent(s): aab7d6f

Release v19 with fast-v2 inference preprocessing

Browse files
Files changed (7) hide show
  1. README.md +22 -20
  2. config.json +66 -67
  3. inference.py +7 -1
  4. model.ckpt +2 -2
  5. model.py +1 -1
  6. preprocessing.py +158 -328
  7. requirements.txt +3 -2
README.md CHANGED
@@ -12,34 +12,35 @@ tags:
12
 
13
  # Wave Regression
14
 
15
- This model estimates the **relative visual waviness** of sea water in a photograph. It returns one score from 0 (calm looking) to 1 (rough looking). The score is based on manual ratings and is **not** wave height, a sea-state category, or a safety measure.
16
 
17
- ## Current release: v16
18
 
19
  | Item | Value |
20
  | --- | --- |
21
- | Architecture | torchvision EfficientNet B0 features → Linear(1280, 1) → Sigmoid |
22
  | Checkpoint | `model.ckpt` (complete PyTorch Lightning checkpoint) |
23
- | Training | Frozen ImageNet backbone, trainable 1,281-parameter head |
24
- | Split | 149 training, 32 validation, 32 held-out test images |
25
- | Best validation MAE | 0.1567 on the v16 validation split |
26
- | Best validation RMSE | 0.2003 on the v16 validation split |
27
- | Held-out test | Not yet evaluated for this checkpoint |
 
 
28
 
29
- The split snapshot was `20261015T083233550489Z`. The selected checkpoint was epoch index 4, global step 95, from a run that trained for 15 epochs with early stopping. The original file was `wave-regression-efficientnet_b0-v16-best-val-mae-epoch=04-val_mae=0.1567.ckpt`. Full run settings and a SHA-256 checksum are in `config.json`. Validation results for earlier releases used different split snapshots and cannot be compared directly with this number.
30
 
31
- The previous ResNet18 release remains available at the [`v1` tag](https://huggingface.co/kubilaycaglayan/wave-regression/tree/v1).
32
 
33
- ## Preprocessing
34
 
35
- `preprocessing.py` mirrors the development pipeline used for v16:
 
 
 
 
36
 
37
- 1. Segment water with `nvidia/segformer-b2-finetuned-ade-512-512`, using a 768×768 processor on 768-pixel source image tiles with 25% overlap. Accumulate resized logits for the `water`, `sea`, `river`, and `lake` classes.
38
- 2. Erode the water mask, black out other pixels, crop to the water bounds, and fit the result into a black 224×224 square. Save and decode a quality-95 JPEG.
39
- 3. Segment that Step 1 output again. Select a bottom-anchored rectangle that retains at least 95% of the lowest 35% of detected water, prioritizing low black padding. Fit it into 224×224, then save and decode a quality-95 JPEG with 4:4:4 chroma.
40
- 4. Convert to a tensor and apply ImageNet normalization.
41
-
42
- The JPEG round trips match the files used in training. `--preprocessed` expects an image produced by this pipeline, not a raw photo resized to 224×224. SegFormer is downloaded from its pinned Hub revision on first use; it is not included here. Processing large source photos with full-resolution overlapping tiles can use substantial memory and take time.
43
 
44
  ## Usage
45
 
@@ -57,14 +58,15 @@ Useful options:
57
  ```bash
58
  python inference.py photo.heic --device cpu
59
  python inference.py photo.jpg --save-model-input model_input.jpg
 
60
  python inference.py model_input.jpg --preprocessed
61
  python inference.py photo.jpg --json
62
  ```
63
 
64
- The checkpoint contains all backbone weights, so loading the regressor needs no ImageNet download. Raw photo inference requires the separate segmentation model. Photos are not included in this repository.
65
 
66
  ## Limitations
67
 
68
- The labels came from one person rating a small collection of sea photos, mainly from recurring coastal viewpoints. The scale is subjective. The v16 held-out test set has not been evaluated, and behavior on different locations, camera angles, or lighting is unknown. Do not use the output for navigation, swimming, surfing, warnings, or physical wave-height estimation.
69
 
70
  This project is for learning and experimentation. The source training pipeline is in the [development repository](https://github.com/kubilaycaglayan/wave-regression-model). Licensed under MIT.
 
12
 
13
  # Wave Regression
14
 
15
+ This model estimates **relative visual waviness** of sea water in a photograph. It returns one score from 0 (calm looking) to 1 (rough looking). The score is based on manual ratings; it is not wave height, a sea-state category, or a safety measure.
16
 
17
+ ## Current checkpoint: v19
18
 
19
  | Item | Value |
20
  | --- | --- |
21
+ | Architecture | torchvision EfficientNet-B0 features → Linear(1280, 1) → Sigmoid |
22
  | Checkpoint | `model.ckpt` (complete PyTorch Lightning checkpoint) |
23
+ | Training | Frozen ImageNet backbone; trainable 1,281-parameter head |
24
+ | Split | 218 training, 47 validation, 46 held-out test photos |
25
+ | Best validation MAE | 0.1141 on split snapshot `20261030T131341470649Z` |
26
+ | Best validation RMSE | 0.1417 on that validation split |
27
+ | Held-out test MAE | 0.1177 on the untouched 46-photo test split |
28
+ | Held-out test RMSE | 0.1504 on that test split |
29
+ | Checkpoint SHA-256 | `a77c370dd3bd0d587e16502332fb6a62efd00223d4ba9f475abda0921798d432` |
30
 
31
+ Validation results from different split snapshots are not directly comparable. On the v19 test split, the training-label mean baseline has MAE 0.2343 and RMSE 0.2741; the model has MAE 0.1177 and RMSE 0.1504. The split snapshot is `20261030T131341470649Z`. Full checkpoint, split, and evaluation metadata are in [`config.json`](config.json). The previous v16 release is preserved in [the v16 release commit](https://huggingface.co/kubilaycaglayan/wave-regression/commit/84edd4e).
32
 
33
+ ## Photo preprocessing
34
 
35
+ Raw-photo inference uses the same `fast-v2` preprocessing profile used to prepare v19's training images. The rules are implemented in [`preprocessing.py`](preprocessing.py) and summarized in [`config.json`](config.json).
36
 
37
+ 1. Decode the image as RGB and apply EXIF orientation. HEIC/HEIF photos are supported with `pillow-heif`.
38
+ 2. Run one SegFormer-B2 pass using the pinned revision `de01bae28967510f9ddd496c60a969357195400c`. The image processor resizes the photo to 448×448. The model's logits are bilinearly resized to 448×448, then the `water`, `sea`, `river`, and `lake` classes form the water mask. CUDA uses FP16 autocast; CPU and MPS use float32.
39
+ 3. Resize the mask to 224×224 with OpenCV nearest-exact interpolation. Select a rectangle anchored to the bottom of the detected sea, retaining at least 95% of the lowest 35% of detected water. The selector prefers higher retention tiers (99.5%, 98%, then 95%), then lower projected black padding, more detected water, higher projected water fraction, and a less extreme rectangle shape, in that order.
40
+ 4. Map the rectangle to the oriented source photo, crop the original RGB pixels, resize proportionally with OpenCV Lanczos4, and place them on a black 224×224 canvas. Resize the selected mask with nearest-exact interpolation and black out pixels outside the water mask.
41
+ 5. Save as JPEG quality 95 with 4:4:4 chroma subsampling, decode that JPEG, convert to a tensor, and apply ImageNet normalization.
42
 
43
+ The regressor expects this processed model input. A raw photo resized directly to 224×224 is not a valid input. The segmentation model is downloaded from the Hub on first raw-photo prediction; it is pinned separately from this repository's regression checkpoint.
 
 
 
 
 
44
 
45
  ## Usage
46
 
 
58
  ```bash
59
  python inference.py photo.heic --device cpu
60
  python inference.py photo.jpg --save-model-input model_input.jpg
61
+ python inference.py photo.jpg --diagnostic-dir preprocessing-stages/
62
  python inference.py model_input.jpg --preprocessed
63
  python inference.py photo.jpg --json
64
  ```
65
 
66
+ The default device is `auto` (CUDA, then MPS, then CPU). CPU inference is supported but can be substantially slower for raw photos. `--save-model-input` writes the exact JPEG model input used for the score; use it with `--preprocessed` to skip segmentation on a later run. `--diagnostic-dir` saves the 448 px and 224 px masks, selected source crop, and final model input for inspection.
67
 
68
  ## Limitations
69
 
70
+ The labels came from one person rating a small collection of sea photos, mainly from recurring coastal viewpoints. The scale is subjective. v19 was evaluated on its held-out split, but behavior on different locations, camera angles, or lighting is unknown. Do not use the output for navigation, swimming, surfing, warnings, or physical wave-height estimation.
71
 
72
  This project is for learning and experimentation. The source training pipeline is in the [development repository](https://github.com/kubilaycaglayan/wave-regression-model). Licensed under MIT.
config.json CHANGED
@@ -1,13 +1,24 @@
1
  {
2
  "model_name": "wave-regression",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  "task": "image-regression",
4
  "output": {
5
  "name": "waviness",
6
  "description": "Relative visual sea-surface waviness; 0.0 = calm, 1.0 = rough. Not a physical wave height or sea-state scale.",
7
- "range": [
8
- 0.0,
9
- 1.0
10
- ],
11
  "activation": "sigmoid",
12
  "post_processing": "none (the sigmoid output is the score)"
13
  },
@@ -23,12 +34,12 @@
23
  "checkpoint": {
24
  "file": "model.ckpt",
25
  "format": "PyTorch Lightning checkpoint",
26
- "run_version": "v16",
27
- "source_file": "wave-regression-efficientnet_b0-v16-best-val-mae-epoch=04-val_mae=0.1567.ckpt",
28
- "source_sha256": "91938b857aa4d6f44d23f0b289f2a76fefd7ed8de2a8cb350e5c7d0e95599289",
29
- "sha256": "91938b857aa4d6f44d23f0b289f2a76fefd7ed8de2a8cb350e5c7d0e95599289",
30
  "epoch": 4,
31
- "global_step": 95,
32
  "pytorch_lightning_version": "2.6.6"
33
  },
34
  "training": {
@@ -43,74 +54,62 @@
43
  "patience": 10
44
  },
45
  "epochs_trained": 15,
46
- "augmentation": "RandomHorizontalFlip(p=0.5), ColorJitter(brightness=0.25, contrast=0.25, saturation=0.20, hue=0.02)",
47
- "train_samples": 149,
48
- "validation_samples": 32,
49
- "test_samples": 32,
50
- "split_snapshot": "step-3-dataset-splits/snapshots/20261015T083233550489Z",
51
  "random_seed": 42,
52
- "best_validation_mae": 0.15674245357513428,
53
- "best_validation_rmse": 0.20032399892807007,
54
- "test_evaluated": false,
55
- "label_range": [
56
- 0.0,
57
- 1.0
58
- ],
59
  "label_normalization": "none; labels were assigned directly on a 0.0-1.0 scale in 0.05 steps"
60
  },
61
  "preprocessing": {
 
62
  "segmentation_model": "nvidia/segformer-b2-finetuned-ade-512-512",
63
  "segmentation_model_revision": "de01bae28967510f9ddd496c60a969357195400c",
64
- "segmentation_mode": "768x768 processor; source-resolution 768px overlapping tiles with 25% overlap; bilinear-resized logits accumulated then argmax; CPU retry after supported CUDA errors",
65
- "water_classes": [
66
- "water",
67
- "sea",
68
- "river",
69
- "lake"
70
- ],
71
  "step_1": {
72
- "mask_erosion_radius": "max(1, min(12, round(0.005 * min(width, height))))",
73
- "non_water_pixels": "set to black",
74
- "crop": "bounding box of eroded water mask",
75
- "minimum_water_fraction": 0.0005,
76
- "resize": "aspect-preserving LANCZOS into black 224x224, centered",
77
- "jpeg_round_trip": {
78
- "quality": 95
79
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  },
81
- "step_2": {
82
- "black_threshold": 12,
83
- "lower_water_fraction": 0.35,
84
- "minimum_lower_water_retention": 0.95,
85
- "black_ratio_bucket": 0.005,
86
- "crop": "bottom-anchored rectangle selected on a re-segmentation of the Step 1 image",
87
- "resize": "aspect-preserving LANCZOS into black 224x224, centered",
88
- "jpeg_round_trip": {
89
- "quality": 95,
90
- "subsampling": "4:4:4"
91
- }
92
  },
93
- "input_size": [
94
- 224,
95
- 224
96
- ],
97
  "normalization": {
98
- "mean": [
99
- 0.485,
100
- 0.456,
101
- 0.406
102
- ],
103
- "std": [
104
- 0.229,
105
- 0.224,
106
- 0.225
107
- ]
108
  },
109
- "segmentation_resolution": [
110
- 768,
111
- 768
112
- ],
113
- "tile_size": 768,
114
- "tile_overlap": 0.25
115
  }
116
  }
 
1
  {
2
  "model_name": "wave-regression",
3
+ "release": {
4
+ "version": "v19",
5
+ "released_checkpoint_source": "wave-regression-efficientnet_b0-v19-best-val-mae-epoch=04-val_mae=0.1141.ckpt",
6
+ "split_snapshot": "20261030T131341470649Z",
7
+ "test_evaluated": true,
8
+ "test_split_snapshot": "20261030T131341470649Z",
9
+ "test_samples": 46,
10
+ "test_mae": 0.117672,
11
+ "test_rmse": 0.150373,
12
+ "training_label_mean_baseline_test_mae": 0.234284,
13
+ "training_label_mean_baseline_test_rmse": 0.274062,
14
+ "evaluation_checkpoint_sha256": "a77c370dd3bd0d587e16502332fb6a62efd00223d4ba9f475abda0921798d432",
15
+ "test_manifest_sha256": "b9a7d6c008aef966c83559165562769186eb27b4f0b735aa66affdd1689020d6"
16
+ },
17
  "task": "image-regression",
18
  "output": {
19
  "name": "waviness",
20
  "description": "Relative visual sea-surface waviness; 0.0 = calm, 1.0 = rough. Not a physical wave height or sea-state scale.",
21
+ "range": [0.0, 1.0],
 
 
 
22
  "activation": "sigmoid",
23
  "post_processing": "none (the sigmoid output is the score)"
24
  },
 
34
  "checkpoint": {
35
  "file": "model.ckpt",
36
  "format": "PyTorch Lightning checkpoint",
37
+ "run_version": "v19",
38
+ "source_file": "wave-regression-efficientnet_b0-v19-best-val-mae-epoch=04-val_mae=0.1141.ckpt",
39
+ "source_sha256": "a77c370dd3bd0d587e16502332fb6a62efd00223d4ba9f475abda0921798d432",
40
+ "sha256": "a77c370dd3bd0d587e16502332fb6a62efd00223d4ba9f475abda0921798d432",
41
  "epoch": 4,
42
+ "global_step": 140,
43
  "pytorch_lightning_version": "2.6.6"
44
  },
45
  "training": {
 
54
  "patience": 10
55
  },
56
  "epochs_trained": 15,
57
+ "train_samples": 218,
58
+ "validation_samples": 47,
59
+ "test_samples": 46,
60
+ "split_snapshot": "step-3-dataset-splits/snapshots/20261030T131341470649Z",
 
61
  "random_seed": 42,
62
+ "best_validation_mae": 0.11409179121255875,
63
+ "best_validation_rmse": 0.14166997373104095,
64
+ "test_evaluated": true,
65
+ "test_mae": 0.117672,
66
+ "test_rmse": 0.150373,
67
+ "test_manifest_sha256": "b9a7d6c008aef966c83559165562769186eb27b4f0b735aa66affdd1689020d6",
68
+ "label_range": [0.0, 1.0],
69
  "label_normalization": "none; labels were assigned directly on a 0.0-1.0 scale in 0.05 steps"
70
  },
71
  "preprocessing": {
72
+ "profile": "fast-v2",
73
  "segmentation_model": "nvidia/segformer-b2-finetuned-ade-512-512",
74
  "segmentation_model_revision": "de01bae28967510f9ddd496c60a969357195400c",
75
+ "segmentation_mode": "single source-photo pass; SegformerImageProcessor resizes to 448x448; logits bilinearly resized to 448x448 before argmax; CUDA FP16 autocast when available and float32 otherwise",
76
+ "water_classes": ["water", "sea", "river", "lake"],
 
 
 
 
 
77
  "step_1": {
78
+ "mask_resolution": [448, 448],
79
+ "mask_resize_to_selector": "OpenCV INTER_NEAREST_EXACT to 224x224",
80
+ "crop_selector": "bottom-anchored rectangle retaining at least 95% of the lowest 35% of detected water; selected on the 224x224 mask",
81
+ "crop_selector_parameters": {
82
+ "minimum_water_pixels": "max(32, round(224 * 224 * 0.0005))",
83
+ "lower_water_fraction": 0.35,
84
+ "minimum_lower_water_retention": 0.95,
85
+ "retention_tiers": [0.95, 0.98, 0.995],
86
+ "horizontal_candidate_spacing": "max(1, round(224 / 56)) pixels",
87
+ "minimum_crop_width_px": 8,
88
+ "minimum_crop_height_px": 8,
89
+ "minimum_crop_area": "max(256, round(water_bbox_area * 0.10))",
90
+ "candidate_order": [
91
+ "highest retention tier (>=0.995, >=0.98, then >=0.95)",
92
+ "lowest projected black-padding bucket (bucket size 0.005)",
93
+ "most water pixels",
94
+ "highest projected water fraction",
95
+ "least extreme width-to-height ratio",
96
+ "leftmost, then highest, then narrowest tied rectangle"
97
+ ]
98
+ },
99
+ "source_mapping": "floor left/top and ceil right/bottom when mapping selected 224x224 rectangle onto the EXIF-oriented source image",
100
+ "resize": "crop original source RGB pixels; aspect-preserving OpenCV INTER_LANCZOS4 into black 224x224 canvas",
101
+ "masking": "resize selected water mask with OpenCV INTER_NEAREST_EXACT and black out non-water pixels"
102
  },
103
+ "step_2": null,
104
+ "input_size": [224, 224],
105
+ "jpeg_round_trip": {
106
+ "quality": 95,
107
+ "subsampling": "4:4:4"
 
 
 
 
 
 
108
  },
 
 
 
 
109
  "normalization": {
110
+ "mean": [0.485, 0.456, 0.406],
111
+ "std": [0.229, 0.224, 0.225]
 
 
 
 
 
 
 
 
112
  },
113
+ "image_orientation": "EXIF orientation is applied before segmentation and crop mapping"
 
 
 
 
 
114
  }
115
  }
inference.py CHANGED
@@ -29,7 +29,13 @@ DEFAULT_CHECKPOINT = HERE / "model.ckpt"
29
 
30
  def _require_dependencies() -> None:
31
  missing = []
32
- for module, package in (("torch", "torch"), ("torchvision", "torchvision"), ("PIL", "pillow"), ("numpy", "numpy")):
 
 
 
 
 
 
33
  try:
34
  __import__(module)
35
  except ImportError:
 
29
 
30
  def _require_dependencies() -> None:
31
  missing = []
32
+ for module, package in (
33
+ ("torch", "torch"),
34
+ ("torchvision", "torchvision"),
35
+ ("PIL", "pillow"),
36
+ ("numpy", "numpy"),
37
+ ("cv2", "opencv-python-headless"),
38
+ ):
39
  try:
40
  __import__(module)
41
  except ImportError:
model.ckpt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:91938b857aa4d6f44d23f0b289f2a76fefd7ed8de2a8cb350e5c7d0e95599289
3
- size 16355487
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a77c370dd3bd0d587e16502332fb6a62efd00223d4ba9f475abda0921798d432
3
+ size 16356895
model.py CHANGED
@@ -1,4 +1,4 @@
1
- """EfficientNet B0 architecture for the v16 sea-waviness checkpoint."""
2
 
3
  from __future__ import annotations
4
 
 
1
+ """EfficientNet B0 architecture for the v19 sea-waviness checkpoint."""
2
 
3
  from __future__ import annotations
4
 
preprocessing.py CHANGED
@@ -1,75 +1,46 @@
1
- """Inference preprocessing for the sea-waviness regression model.
2
-
3
- This is a self-contained port of the preprocessing used to build the training
4
- images in the development repository. A raw sea photograph goes through:
5
-
6
- 1. Water segmentation with SegFormer-B2 (ADE20K): overlapping 768-pixel
7
- source-resolution tiles with 25% overlap have their logits averaged before
8
- selecting the class at each source pixel. Classes
9
- ``water``, ``sea``, ``river`` and ``lake`` count as water. If this path cannot
10
- produce a valid crop, segment a scaled view of the whole photo so the model
11
- can use horizon context.
12
- 2. Step 1 standardization: erode the water mask slightly, black out non-water
13
- pixels, crop to the water bounding box and fit it, aspect preserved, into
14
- a black 224x224 square. The result is JPEG-encoded (quality 95), exactly as
15
- the Step 1 files were written to disk during training.
16
- 3. Step 2 lower-water crop: segment the Step 1 image again, choose a
17
- bottom-anchored rectangle that keeps at least 95% of the lowest 35% of
18
- the detected water while minimizing black padding, then fit it into
19
- 224x224. The result is JPEG-encoded (quality 95, 4:4:4), as the training
20
- files were.
21
- 4. ``ToTensor`` and ImageNet normalization.
22
-
23
- The JPEG round trips are intentional: the model was trained on the decoded
24
- JPEG files, so inference reproduces them.
25
  """
26
 
27
  from __future__ import annotations
28
 
29
  import io
 
30
  import time
31
  from dataclasses import dataclass
32
  from pathlib import Path
33
 
 
34
  import numpy as np
35
  import torch
36
- from PIL import Image, ImageFilter, ImageOps
37
-
38
- # ---------------------------------------------------------------------------
39
- # Configuration (mirrors config.json)
40
- # ---------------------------------------------------------------------------
41
 
42
  SEGMENTATION_MODEL_NAME = "nvidia/segformer-b2-finetuned-ade-512-512"
43
- # Pinned commit of the segmentation model on the Hugging Face Hub.
44
  SEGMENTATION_MODEL_REVISION = "de01bae28967510f9ddd496c60a969357195400c"
 
45
  WATER_CLASS_NAMES = {"water", "sea", "river", "lake"}
46
- SEGMENTATION_RESOLUTION = 768
47
- TILE_SIZE = 768
48
- TILE_OVERLAP = 0.25
49
-
50
  OUTPUT_SIZE = (224, 224)
51
  IMAGENET_MEAN = (0.485, 0.456, 0.406)
52
  IMAGENET_STD = (0.229, 0.224, 0.225)
53
-
54
- BLACK_THRESHOLD = 12
55
  LOWER_WATER_FRACTION = 0.35
56
  MINIMUM_LOWER_RETENTION = 0.95
57
  BLACK_RATIO_BUCKET = 0.005
58
-
 
 
59
  SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff", ".heic", ".heif"}
60
 
61
 
62
  class PreprocessingError(RuntimeError):
63
- """Raised when a photograph cannot be turned into a valid model input."""
64
-
65
-
66
- # ---------------------------------------------------------------------------
67
- # Image loading
68
- # ---------------------------------------------------------------------------
69
 
70
 
71
  def load_rgb_image(path: str | Path) -> Image.Image:
72
- """Decode an image file (including HEIC/HEIF when pillow-heif is installed) as RGB."""
73
  path = Path(path)
74
  if not path.is_file():
75
  raise FileNotFoundError(f"Image not found: {path}")
@@ -77,37 +48,24 @@ def load_rgb_image(path: str | Path) -> Image.Image:
77
  try:
78
  from pillow_heif import register_heif_opener
79
  except ImportError as error:
80
- raise ImportError(
81
- "Reading HEIC/HEIF photos requires pillow-heif: pip install pillow-heif"
82
- ) from error
83
  register_heif_opener()
84
  with Image.open(path) as opened:
85
  return ImageOps.exif_transpose(opened).convert("RGB")
86
 
87
 
88
- def encode_jpeg(image: Image.Image, **save_options: object) -> bytes:
89
- """Encode an image to JPEG bytes in memory."""
90
  buffer = io.BytesIO()
91
- image.save(buffer, format="JPEG", **save_options)
92
  return buffer.getvalue()
93
 
94
 
95
  def decode_image(encoded: bytes) -> Image.Image:
96
- """Decode encoded image bytes into a detached RGB image."""
97
  with Image.open(io.BytesIO(encoded)) as decoded:
98
  return decoded.convert("RGB")
99
 
100
 
101
- def jpeg_round_trip(image: Image.Image, **save_options: object) -> Image.Image:
102
- """Encode to JPEG in memory and decode again, as the training files were."""
103
- return decode_image(encode_jpeg(image, **save_options))
104
-
105
-
106
- # ---------------------------------------------------------------------------
107
- # Water segmentation
108
- # ---------------------------------------------------------------------------
109
-
110
-
111
  @dataclass
112
  class WaterSegmenter:
113
  model: torch.nn.Module
@@ -117,21 +75,19 @@ class WaterSegmenter:
117
 
118
 
119
  def load_segmenter(device: str | torch.device = "cpu") -> WaterSegmenter:
120
- """Download (once) and load the pinned SegFormer water-segmentation model."""
121
  try:
122
  from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor
123
  except ImportError as error:
124
- raise ImportError(
125
- "Water segmentation requires the transformers package: pip install -r requirements.txt"
126
- ) from error
127
-
128
  from transformers.utils import logging as transformers_logging
129
 
130
  transformers_logging.disable_progress_bar()
131
  device = torch.device(device)
132
  try:
133
  processor = SegformerImageProcessor.from_pretrained(
134
- SEGMENTATION_MODEL_NAME, revision=SEGMENTATION_MODEL_REVISION,
 
135
  size={"height": SEGMENTATION_RESOLUTION, "width": SEGMENTATION_RESOLUTION},
136
  do_resize=True,
137
  )
@@ -140,322 +96,196 @@ def load_segmenter(device: str | torch.device = "cpu") -> WaterSegmenter:
140
  )
141
  except OSError as error:
142
  raise RuntimeError(
143
- f"Could not load the segmentation model {SEGMENTATION_MODEL_NAME} "
144
- f"(revision {SEGMENTATION_MODEL_REVISION}). It is downloaded from the Hugging Face Hub "
145
- "on first use; check the network connection or pre-download it with:\n"
146
- f" hf download {SEGMENTATION_MODEL_NAME} --revision {SEGMENTATION_MODEL_REVISION}"
147
  ) from error
148
- model.to(device)
149
- model.eval()
150
  id2label = {int(key): value.lower().strip() for key, value in model.config.id2label.items()}
151
- water_class_ids = tuple(i for i, label in id2label.items() if label in WATER_CLASS_NAMES)
152
- if not water_class_ids:
153
- raise RuntimeError(f"{SEGMENTATION_MODEL_NAME} does not expose water classes {WATER_CLASS_NAMES}")
154
- return WaterSegmenter(model, processor, water_class_ids, device)
155
-
156
-
157
- def tile_starts(length: int, tile_size: int, stride: int) -> list[int]:
158
- """Cover an axis and anchor the last tile at its far end."""
159
- if length <= tile_size:
160
- return [0]
161
- starts = list(range(0, length - tile_size + 1, stride))
162
- last = length - tile_size
163
- if starts[-1] != last:
164
- starts.append(last)
165
- return starts
166
 
167
 
168
  @torch.inference_mode()
169
- def segment_water(image: Image.Image, segmenter: WaterSegmenter) -> np.ndarray:
170
- """Return the source-resolution water mask used by the training pipeline."""
171
  started = time.perf_counter()
172
- image = image.convert("RGB")
173
- width, height = image.size
174
- if TILE_SIZE <= 0 or not 0 <= TILE_OVERLAP < 1:
175
- raise ValueError("Invalid segmentation tile configuration")
176
- stride = max(1, round(TILE_SIZE * (1.0 - TILE_OVERLAP)))
177
- left_starts = tile_starts(width, TILE_SIZE, stride)
178
- top_starts = tile_starts(height, TILE_SIZE, stride)
179
- class_count = segmenter.model.config.num_labels
180
- accumulator_bytes = class_count * height * width * torch.tensor([], dtype=torch.float32).element_size()
181
- accumulator_device = torch.device("cpu")
182
- if segmenter.device.type == "cuda":
183
- free_bytes, _ = torch.cuda.mem_get_info(segmenter.device)
184
- headroom_bytes = max(2 * 1024**3, int(free_bytes * 0.25))
185
- if free_bytes - accumulator_bytes >= headroom_bytes:
186
- accumulator_device = segmenter.device
187
- accumulated_logits = torch.zeros(
188
- (class_count, height, width), dtype=torch.float32, device=accumulator_device
189
- )
190
- print(
191
- f"Logit accumulator: {accumulator_device} "
192
- f"({accumulator_bytes / 1024**3:.2f} GiB); model inference: {segmenter.device}",
193
- flush=True,
194
  )
195
  try:
196
- for top in top_starts:
197
- for left in left_starts:
198
- right = min(width, left + TILE_SIZE)
199
- bottom = min(height, top + TILE_SIZE)
200
- tile = image.crop((left, top, right, bottom))
201
- inputs = segmenter.processor(images=tile, return_tensors="pt")
202
- inputs = {key: value.to(segmenter.device) for key, value in inputs.items()}
203
- logits = segmenter.model(**inputs).logits
204
- logits = torch.nn.functional.interpolate(
205
- logits, size=(bottom - top, right - left), mode="bilinear", align_corners=False
206
- )[0]
207
- accumulated_logits[:, top:bottom, left:right] += logits.to(accumulator_device)
208
  except RuntimeError as error:
209
- retryable = any(message in str(error).lower() for message in (
210
- "engine to execute", "out of memory", "cuda out of memory"
211
- ))
212
  if segmenter.device.type != "cuda" or not retryable:
213
  raise
214
- print("CUDA inference unavailable or out of memory; retrying this image on CPU.", flush=True)
215
  segmenter.device = torch.device("cpu")
216
  segmenter.model.to(segmenter.device)
217
- return segment_water(image, segmenter)
218
- class_map = accumulated_logits.argmax(dim=0).to(device="cpu", dtype=torch.uint8)
 
 
 
 
 
 
 
 
219
  print(
220
- f"Segmentation tiles: {len(left_starts) * len(top_starts)} "
221
- f"({width}x{height}), completed in {time.perf_counter() - started:.3f}s",
222
  flush=True,
223
  )
224
- return np.isin(class_map.numpy(), segmenter.water_class_ids)
225
-
226
-
227
- @torch.inference_mode()
228
- def segment_water_whole_image(image: Image.Image, segmenter: WaterSegmenter) -> np.ndarray:
229
- """Segment a scaled view of the entire photo so the horizon stays in context."""
230
- image = image.convert("RGB")
231
- scale = min(1.0, SEGMENTATION_RESOLUTION / max(image.size))
232
- preview_size = (max(1, round(image.width * scale)), max(1, round(image.height * scale)))
233
- preview = image.resize(preview_size, Image.Resampling.LANCZOS)
234
- inputs = segmenter.processor(images=preview, return_tensors="pt")
235
- inputs = {key: value.to(segmenter.device) for key, value in inputs.items()}
236
- logits = segmenter.model(**inputs).logits
237
- logits = torch.nn.functional.interpolate(
238
- logits, size=(preview_size[1], preview_size[0]), mode="bilinear", align_corners=False
239
- )[0]
240
- water = np.isin(logits.argmax(dim=0).to(device="cpu").numpy(), segmenter.water_class_ids)
241
- return np.asarray(
242
- Image.fromarray(water.astype(np.uint8) * 255, mode="L").resize(image.size, Image.Resampling.NEAREST)
243
- ) > 0
244
-
245
-
246
- # ---------------------------------------------------------------------------
247
- # Step 1: mask, crop to water and standardize to 224x224
248
- # ---------------------------------------------------------------------------
249
-
250
-
251
- def _fit_in_square(image: Image.Image) -> Image.Image:
252
- scale = min(OUTPUT_SIZE[0] / image.width, OUTPUT_SIZE[1] / image.height)
253
- resized_size = (max(1, round(image.width * scale)), max(1, round(image.height * scale)))
254
- resized = image.resize(resized_size, Image.Resampling.LANCZOS)
255
- output = Image.new("RGB", OUTPUT_SIZE, (0, 0, 0))
256
- output.paste(resized, ((OUTPUT_SIZE[0] - resized.width) // 2, (OUTPUT_SIZE[1] - resized.height) // 2))
257
- return output
258
-
259
-
260
- def _mask_bbox(mask: np.ndarray) -> tuple[int, int, int, int] | None:
261
- ys, xs = np.where(mask)
262
- if not len(xs):
263
- return None
264
- return int(xs.min()), int(ys.min()), int(xs.max() + 1), int(ys.max() + 1)
265
-
266
-
267
- def standardize_water(image: Image.Image, water_mask: np.ndarray) -> Image.Image | None:
268
- """Step 1: keep eroded water pixels, crop to their bounding box and fit into 224x224."""
269
- radius = max(1, min(12, round(min(image.size) * 0.005)))
270
- eroded = Image.fromarray((water_mask.astype(bool) * 255).astype(np.uint8), mode="L").filter(
271
- ImageFilter.MinFilter(radius * 2 + 1)
272
- )
273
- mask = (np.asarray(eroded) > 0).astype(np.uint8)
274
- bbox = _mask_bbox(mask.astype(bool))
275
- minimum_pixels = max(32, round(image.width * image.height * 0.0005))
276
- if bbox is None or int(mask.sum()) < minimum_pixels:
277
- return None
278
- left, top, right, bottom = bbox
279
- rgb = np.asarray(image.convert("RGB"), dtype=np.uint8).copy()
280
- rgb[mask == 0] = 0
281
- return _fit_in_square(Image.fromarray(rgb[top:bottom, left:right], mode="RGB"))
282
-
283
-
284
- # ---------------------------------------------------------------------------
285
- # Step 2: lower-water crop with minimal black padding
286
- # ---------------------------------------------------------------------------
287
 
288
 
289
  def _summed_area(mask: np.ndarray) -> np.ndarray:
290
  return np.pad(mask.astype(np.int64), ((1, 0), (1, 0))).cumsum(0).cumsum(1)
291
 
292
 
293
- def _rectangle_sum(table: np.ndarray, box: tuple[int, int, int, int]) -> int:
294
- left, top, right, bottom = box
295
  return int(table[bottom, right] - table[top, right] - table[bottom, left] + table[top, left])
296
 
297
 
298
  def _resized_content_size(width: int, height: int) -> tuple[int, int]:
299
- scale = min(OUTPUT_SIZE[0] / width, OUTPUT_SIZE[1] / height)
300
  return max(1, round(width * scale)), max(1, round(height * scale))
301
 
302
 
303
- def _projected_ratio(pixel_count: int, crop_area: int, width: int, height: int) -> float:
304
- resized_width, resized_height = _resized_content_size(width, height)
305
- occupied_fraction = resized_width * resized_height / (OUTPUT_SIZE[0] * OUTPUT_SIZE[1])
306
- return (pixel_count / crop_area) * occupied_fraction
307
 
308
-
309
- def select_lower_water_crop(water_mask: np.ndarray, black_mask: np.ndarray) -> tuple[int, int, int, int] | None:
310
- """Return the bottom-anchored crop box used by Step 2, or None if no valid crop exists."""
311
- bbox = _mask_bbox(water_mask)
312
- if bbox is None:
 
 
313
  return None
314
- bbox_left, bbox_top, bbox_right, bbox_bottom = bbox
315
- bbox_width, bbox_height = bbox_right - bbox_left, bbox_bottom - bbox_top
316
- minimum_water_pixels = max(32, round(water_mask.size * 0.0005))
 
 
317
  if int(water_mask.sum()) < minimum_water_pixels:
318
  return None
319
-
320
- lower_top = max(bbox_top, bbox_bottom - max(1, round(bbox_height * LOWER_WATER_FRACTION)))
321
- lower_mask = water_mask.copy()
322
- lower_mask[:lower_top, :] = False
323
- if int(lower_mask.sum()) < minimum_water_pixels:
324
  return None
325
 
326
- horizontal_step = max(1, round(water_mask.shape[1] / 56))
327
- boundaries = sorted(set(range(bbox_left, bbox_right + 1, horizontal_step)) | {bbox_left, bbox_right})
328
- tops = list(range(bbox_top, lower_top + 1))
329
  water_table = _summed_area(water_mask)
330
- black_table = _summed_area(black_mask)
331
- lower_table = _summed_area(lower_mask)
332
- minimum_crop_area = max(256, round(bbox_width * bbox_height * 0.10))
333
-
334
  best_key = None
335
  best_box = None
336
  for left_index, left in enumerate(boundaries[:-1]):
337
  for right in boundaries[left_index + 1:]:
338
- width = right - left
339
- if width < 8:
340
  continue
341
- for top in tops:
342
- height = bbox_bottom - top
343
- crop_area = width * height
344
- if height < 8 or crop_area < minimum_crop_area:
345
- continue
346
- box = (left, top, right, bbox_bottom)
347
- lower_in_view = _rectangle_sum(lower_table, (left, lower_top, right, bbox_bottom))
348
- if lower_in_view < minimum_water_pixels:
349
  continue
350
- retention = _rectangle_sum(lower_table, box) / lower_in_view
351
  if retention + 1e-12 < MINIMUM_LOWER_RETENTION:
352
  continue
353
- water_pixels = _rectangle_sum(water_table, box)
354
- black_pixels = _rectangle_sum(black_table, box)
355
- water_ratio = _projected_ratio(water_pixels, crop_area, width, height)
356
- black_ratio = 1.0 - _projected_ratio(crop_area - black_pixels, crop_area, width, height)
357
- shape_penalty = abs(np.log(width / height))
358
- retention_tier = 3 if retention >= 0.995 else 2 if retention >= 0.98 else 1
359
- key = (
360
- -retention_tier,
361
- round(black_ratio / BLACK_RATIO_BUCKET),
362
- -water_pixels,
363
- -water_ratio,
364
- shape_penalty,
365
- box,
366
- )
367
  if best_key is None or key < best_key:
368
- best_key, best_box = key, box
369
  return best_box
370
 
371
 
372
- def lower_water_crop(
373
- step_1_image: Image.Image,
374
- segmenter: WaterSegmenter,
375
- diagnostic_dir: str | Path | None = None,
376
- ) -> Image.Image | None:
377
- """Step 2: re-segment the Step 1 image and keep the lower water region."""
378
- rgb = np.asarray(step_1_image.convert("RGB"), dtype=np.uint8)
379
- black_mask = np.all(rgb <= BLACK_THRESHOLD, axis=2)
380
- water_mask = segment_water(step_1_image, segmenter) & ~black_mask
381
- if diagnostic_dir is not None:
382
- output_dir = Path(diagnostic_dir)
383
- output_dir.mkdir(parents=True, exist_ok=True)
384
- Image.fromarray(water_mask.astype(np.uint8) * 255, mode="L").save(output_dir / "step-1-water-mask.png")
385
- box = select_lower_water_crop(water_mask, black_mask)
386
- if box is None:
387
- return None
388
- selected = step_1_image.crop(box)
389
- result = _fit_in_square(selected)
390
- if diagnostic_dir is not None:
391
- selected.save(output_dir / "step-2-selected-region.jpg", format="JPEG", quality=95)
392
- result.save(output_dir / "step-2-final.jpg", format="JPEG", quality=95, subsampling=0)
393
- return result
394
-
395
-
396
- # ---------------------------------------------------------------------------
397
- # Public API
398
- # ---------------------------------------------------------------------------
399
-
400
-
401
- def _preprocess_with_mask(
402
- image: Image.Image,
403
- source_mask: np.ndarray,
404
- segmenter: WaterSegmenter,
405
- output_dir: Path | None,
406
- ) -> bytes:
407
- if output_dir is not None:
408
- output_dir.mkdir(parents=True, exist_ok=True)
409
- Image.fromarray(source_mask.astype(np.uint8) * 255, mode="L").save(output_dir / "source-water-mask.png")
410
- step_1 = standardize_water(image.convert("RGB"), source_mask)
411
- if step_1 is None:
412
- raise PreprocessingError("No reliable water region was detected in the photograph (Step 1).")
413
- step_1 = jpeg_round_trip(step_1, quality=95)
414
- if output_dir is not None:
415
- step_1.save(output_dir / "step-1-standardized.jpg", format="JPEG", quality=95)
416
- step_2 = lower_water_crop(step_1, segmenter, output_dir)
417
- if step_2 is None:
418
- raise PreprocessingError("No reliable lower-water crop could be selected (Step 2).")
419
- return encode_jpeg(step_2, quality=95, subsampling=0)
420
-
421
-
422
  def preprocess_photo_encoded(
423
  image: Image.Image,
424
  segmenter: WaterSegmenter,
425
  diagnostic_dir: str | Path | None = None,
426
  ) -> bytes:
427
- """Return the final 224x224 JPEG model input, using whole-photo context if tiles fail."""
 
 
 
428
  output_dir = Path(diagnostic_dir) if diagnostic_dir is not None else None
429
- source_mask = segment_water(image, segmenter)
430
- try:
431
- return _preprocess_with_mask(image, source_mask, segmenter, output_dir)
432
- except PreprocessingError as tiled_error:
433
- print(f"Tiled water detection failed ({tiled_error}); retrying with whole-photo context.", flush=True)
434
- fallback_mask = segment_water_whole_image(image, segmenter)
435
- fallback_dir = output_dir / "whole-image-fallback" if output_dir is not None else None
436
- try:
437
- return _preprocess_with_mask(image, fallback_mask, segmenter, fallback_dir)
438
- except PreprocessingError as fallback_error:
439
- raise PreprocessingError(
440
- f"No reliable water region after tiled and whole-photo segmentation: {fallback_error}"
441
- ) from fallback_error
442
-
443
-
444
- def preprocess_photo(image: Image.Image, segmenter: WaterSegmenter) -> Image.Image:
445
- """Turn a raw sea photograph into the 224x224 RGB image the model was trained on."""
446
- return decode_image(preprocess_photo_encoded(image, segmenter))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
 
448
 
449
  def to_model_tensor(model_input: Image.Image) -> torch.Tensor:
450
- """Apply ``ToTensor`` and ImageNet normalization; returns a ``[1, 3, 224, 224]`` tensor."""
451
  if model_input.mode != "RGB" or model_input.size != OUTPUT_SIZE:
452
- raise PreprocessingError(
453
- f"Model input must be an RGB {OUTPUT_SIZE[0]}x{OUTPUT_SIZE[1]} image, "
454
- f"got {model_input.mode} {model_input.size[0]}x{model_input.size[1]}"
455
- )
456
- from torchvision import transforms
457
-
458
- transform = transforms.Compose(
459
- [transforms.ToTensor(), transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD)]
460
- )
461
- return transform(model_input).float().unsqueeze(0)
 
1
+ """Self-contained fast-v2 photo preprocessing for the v19 regressor.
2
+
3
+ The public inference route is: EXIF-normalized photo -> one 448 px SegFormer
4
+ pass -> 224 px water mask -> lower-water crop mapped to source coordinates ->
5
+ masked 224x224 JPEG (quality 95, 4:4:4) -> ImageNet-normalized tensor.
6
+ This is the coordinate-crop pipeline used to create v19 training inputs.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  """
8
 
9
  from __future__ import annotations
10
 
11
  import io
12
+ import math
13
  import time
14
  from dataclasses import dataclass
15
  from pathlib import Path
16
 
17
+ import cv2
18
  import numpy as np
19
  import torch
20
+ from PIL import Image, ImageOps
 
 
 
 
21
 
22
  SEGMENTATION_MODEL_NAME = "nvidia/segformer-b2-finetuned-ade-512-512"
 
23
  SEGMENTATION_MODEL_REVISION = "de01bae28967510f9ddd496c60a969357195400c"
24
+ SEGMENTATION_RESOLUTION = 448
25
  WATER_CLASS_NAMES = {"water", "sea", "river", "lake"}
 
 
 
 
26
  OUTPUT_SIZE = (224, 224)
27
  IMAGENET_MEAN = (0.485, 0.456, 0.406)
28
  IMAGENET_STD = (0.229, 0.224, 0.225)
 
 
29
  LOWER_WATER_FRACTION = 0.35
30
  MINIMUM_LOWER_RETENTION = 0.95
31
  BLACK_RATIO_BUCKET = 0.005
32
+ MINIMUM_WATER_FRACTION = 0.0005
33
+ MINIMUM_CROP_AREA_FRACTION = 0.10
34
+ MINIMUM_CROP_WIDTH = 8
35
  SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff", ".heic", ".heif"}
36
 
37
 
38
  class PreprocessingError(RuntimeError):
39
+ """Raised when a photo cannot be converted into a valid model input."""
 
 
 
 
 
40
 
41
 
42
  def load_rgb_image(path: str | Path) -> Image.Image:
43
+ """Load an image as RGB and apply its EXIF orientation (including iPhone HEIC)."""
44
  path = Path(path)
45
  if not path.is_file():
46
  raise FileNotFoundError(f"Image not found: {path}")
 
48
  try:
49
  from pillow_heif import register_heif_opener
50
  except ImportError as error:
51
+ raise ImportError("HEIC/HEIF input requires pillow-heif; install requirements.txt") from error
 
 
52
  register_heif_opener()
53
  with Image.open(path) as opened:
54
  return ImageOps.exif_transpose(opened).convert("RGB")
55
 
56
 
57
+ def encode_jpeg(image: Image.Image) -> bytes:
58
+ """Encode the final training input using the fast-v2 JPEG settings."""
59
  buffer = io.BytesIO()
60
+ image.save(buffer, format="JPEG", quality=95, subsampling=0)
61
  return buffer.getvalue()
62
 
63
 
64
  def decode_image(encoded: bytes) -> Image.Image:
 
65
  with Image.open(io.BytesIO(encoded)) as decoded:
66
  return decoded.convert("RGB")
67
 
68
 
 
 
 
 
 
 
 
 
 
 
69
  @dataclass
70
  class WaterSegmenter:
71
  model: torch.nn.Module
 
75
 
76
 
77
  def load_segmenter(device: str | torch.device = "cpu") -> WaterSegmenter:
78
+ """Load the exact pinned segmentation model used by the v19 training pipeline."""
79
  try:
80
  from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor
81
  except ImportError as error:
82
+ raise ImportError("Water segmentation requires transformers; install requirements.txt") from error
 
 
 
83
  from transformers.utils import logging as transformers_logging
84
 
85
  transformers_logging.disable_progress_bar()
86
  device = torch.device(device)
87
  try:
88
  processor = SegformerImageProcessor.from_pretrained(
89
+ SEGMENTATION_MODEL_NAME,
90
+ revision=SEGMENTATION_MODEL_REVISION,
91
  size={"height": SEGMENTATION_RESOLUTION, "width": SEGMENTATION_RESOLUTION},
92
  do_resize=True,
93
  )
 
96
  )
97
  except OSError as error:
98
  raise RuntimeError(
99
+ f"Could not load {SEGMENTATION_MODEL_NAME} at revision {SEGMENTATION_MODEL_REVISION}. "
100
+ "Check network access or download the model with: "
101
+ f"hf download {SEGMENTATION_MODEL_NAME} --revision {SEGMENTATION_MODEL_REVISION}"
 
102
  ) from error
103
+ model.to(device).eval()
 
104
  id2label = {int(key): value.lower().strip() for key, value in model.config.id2label.items()}
105
+ class_ids = tuple(index for index, name in id2label.items() if name in WATER_CLASS_NAMES)
106
+ if not class_ids:
107
+ raise RuntimeError(f"No water labels found in {SEGMENTATION_MODEL_NAME}")
108
+ return WaterSegmenter(model, processor, class_ids, device)
 
 
 
 
 
 
 
 
 
 
 
109
 
110
 
111
  @torch.inference_mode()
112
+ def segment_water_mask(image: Image.Image, segmenter: WaterSegmenter) -> np.ndarray:
113
+ """Run one 448x448 segmentation pass and return the water classes at 448 px."""
114
  started = time.perf_counter()
115
+ inputs = segmenter.processor(images=image.convert("RGB"), return_tensors="pt")
116
+ inputs = {name: tensor.to(segmenter.device) for name, tensor in inputs.items()}
117
+ use_fp16 = segmenter.device.type == "cuda"
118
+ context = torch.autocast(device_type="cuda", dtype=torch.float16) if use_fp16 else torch.autocast(
119
+ device_type="cpu", enabled=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  )
121
  try:
122
+ with context:
123
+ logits = segmenter.model(**inputs).logits
124
+ target_size = (
125
+ (image.height, image.width)
126
+ if max(image.size) <= SEGMENTATION_RESOLUTION
127
+ else (SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION)
128
+ )
129
+ logits = torch.nn.functional.interpolate(logits, size=target_size, mode="bilinear", align_corners=False)
 
 
 
 
130
  except RuntimeError as error:
131
+ retryable = any(word in str(error).lower() for word in ("out of memory", "engine to execute"))
 
 
132
  if segmenter.device.type != "cuda" or not retryable:
133
  raise
134
+ print(f"CUDA segmentation failed ({error}); retrying this image on CPU.", flush=True)
135
  segmenter.device = torch.device("cpu")
136
  segmenter.model.to(segmenter.device)
137
+ return segment_water_mask(image, segmenter)
138
+ class_map = logits.argmax(dim=1)[0].to(device="cpu", dtype=torch.uint8).numpy()
139
+ if class_map.shape != (SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION):
140
+ class_map = np.asarray(
141
+ Image.fromarray(class_map).resize(
142
+ (SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION), Image.Resampling.NEAREST
143
+ ),
144
+ dtype=np.uint8,
145
+ )
146
+ water = np.isin(class_map, segmenter.water_class_ids)
147
  print(
148
+ f"Segmentation: one {SEGMENTATION_RESOLUTION}x{SEGMENTATION_RESOLUTION} pass "
149
+ f"on {segmenter.device}, {time.perf_counter() - started:.3f}s",
150
  flush=True,
151
  )
152
+ return water
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
 
155
  def _summed_area(mask: np.ndarray) -> np.ndarray:
156
  return np.pad(mask.astype(np.int64), ((1, 0), (1, 0))).cumsum(0).cumsum(1)
157
 
158
 
159
+ def _rect_sum(table: np.ndarray, left: int, top: int, right: int, bottom: int) -> int:
 
160
  return int(table[bottom, right] - table[top, right] - table[bottom, left] + table[top, left])
161
 
162
 
163
  def _resized_content_size(width: int, height: int) -> tuple[int, int]:
164
+ scale = min(224 / width, 224 / height)
165
  return max(1, round(width * scale)), max(1, round(height * scale))
166
 
167
 
168
+ def select_lower_water_crop(water_mask: np.ndarray) -> tuple[int, int, int, int] | None:
169
+ """Select the fast-v2 bottom-anchored crop on the 224x224 water mask.
 
 
170
 
171
+ This is the same lexicographic selector used during training. The black
172
+ mask is all false for fast-v2 because the crop is selected on the raw
173
+ source-photo mask before the final canvas is built.
174
+ """
175
+ water_mask = np.ascontiguousarray(water_mask, dtype=bool)
176
+ ys, xs = np.where(water_mask)
177
+ if not len(xs):
178
  return None
179
+ height, width = water_mask.shape
180
+ left_bound, top_bound = int(xs.min()), int(ys.min())
181
+ right_bound, bottom_bound = int(xs.max()) + 1, int(ys.max()) + 1
182
+ bbox_width, bbox_height = right_bound - left_bound, bottom_bound - top_bound
183
+ minimum_water_pixels = max(32, round(width * height * MINIMUM_WATER_FRACTION))
184
  if int(water_mask.sum()) < minimum_water_pixels:
185
  return None
186
+ lower_top = max(top_bound, bottom_bound - max(1, round(bbox_height * LOWER_WATER_FRACTION)))
187
+ lower_total = int(water_mask[lower_top:bottom_bound].sum())
188
+ if lower_total < minimum_water_pixels:
 
 
189
  return None
190
 
191
+ horizontal_step = max(1, round(width / 56.0))
192
+ boundaries = sorted(set(range(left_bound, right_bound + 1, horizontal_step)) | {right_bound})
 
193
  water_table = _summed_area(water_mask)
194
+ lower_table = _summed_area(water_mask & (np.arange(height)[:, None] >= lower_top))
195
+ minimum_area = max(256, round(bbox_width * bbox_height * MINIMUM_CROP_AREA_FRACTION))
 
 
196
  best_key = None
197
  best_box = None
198
  for left_index, left in enumerate(boundaries[:-1]):
199
  for right in boundaries[left_index + 1:]:
200
+ crop_width = right - left
201
+ if crop_width < MINIMUM_CROP_WIDTH:
202
  continue
203
+ lower_in_view = _rect_sum(lower_table, left, lower_top, right, bottom_bound)
204
+ if lower_in_view < minimum_water_pixels:
205
+ continue
206
+ for top in range(top_bound, lower_top + 1):
207
+ crop_height = bottom_bound - top
208
+ crop_area = crop_width * crop_height
209
+ if crop_height < 8 or crop_area < minimum_area:
 
210
  continue
211
+ retention = _rect_sum(lower_table, left, top, right, bottom_bound) / lower_in_view
212
  if retention + 1e-12 < MINIMUM_LOWER_RETENTION:
213
  continue
214
+ water_pixels = _rect_sum(water_table, left, top, right, bottom_bound)
215
+ resized_width, resized_height = _resized_content_size(crop_width, crop_height)
216
+ occupied = resized_width * resized_height / float(224 * 224)
217
+ water_ratio = (water_pixels / crop_area) * occupied
218
+ # Black pixels are zero for this source-coordinate profile.
219
+ black_ratio = 1.0 - occupied
220
+ tier = 3 if retention >= 0.995 else 2 if retention >= 0.98 else 1
221
+ bucket = int(np.rint(black_ratio / BLACK_RATIO_BUCKET))
222
+ key = (-tier, bucket, -water_pixels, -water_ratio,
223
+ abs(math.log(crop_width / crop_height)), left, top, right)
 
 
 
 
224
  if best_key is None or key < best_key:
225
+ best_key, best_box = key, (left, top, right, bottom_bound)
226
  return best_box
227
 
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  def preprocess_photo_encoded(
230
  image: Image.Image,
231
  segmenter: WaterSegmenter,
232
  diagnostic_dir: str | Path | None = None,
233
  ) -> bytes:
234
+ """Return the exact final 224x224 JPEG input format used for v19 training."""
235
+ started = time.perf_counter()
236
+ source = np.asarray(image.convert("RGB"), dtype=np.uint8)
237
+ water_448 = segment_water_mask(image, segmenter)
238
  output_dir = Path(diagnostic_dir) if diagnostic_dir is not None else None
239
+ if output_dir is not None:
240
+ output_dir.mkdir(parents=True, exist_ok=True)
241
+ Image.fromarray(water_448.astype(np.uint8) * 255, mode="L").save(output_dir / "water-mask-448.png")
242
+ water_224 = cv2.resize(
243
+ water_448.astype(np.uint8), (224, 224), interpolation=cv2.INTER_NEAREST_EXACT
244
+ ).astype(bool)
245
+ if output_dir is not None:
246
+ Image.fromarray(water_224.astype(np.uint8) * 255, mode="L").save(output_dir / "selector-mask-224.png")
247
+ selected = select_lower_water_crop(water_224)
248
+ if selected is None:
249
+ raise PreprocessingError("No reliable lower-water crop could be selected from this photo.")
250
+ left, top, right, bottom = selected
251
+ source_height, source_width = source.shape[:2]
252
+ x0 = max(0, min(source_width, int(np.floor(left * source_width / 224))))
253
+ x1 = max(x0 + 1, min(source_width, int(np.ceil(right * source_width / 224))))
254
+ y0 = max(0, min(source_height, int(np.floor(top * source_height / 224))))
255
+ y1 = max(y0 + 1, min(source_height, int(np.ceil(bottom * source_height / 224))))
256
+ source_roi = source[y0:y1, x0:x1]
257
+ mask_roi = water_224[top:bottom, left:right]
258
+ if output_dir is not None:
259
+ Image.fromarray(source_roi, mode="RGB").save(output_dir / "selected-source-region.jpg", quality=95)
260
+
261
+ scale = min(224 / source_roi.shape[1], 224 / source_roi.shape[0])
262
+ resized_width = max(1, min(224, round(source_roi.shape[1] * scale)))
263
+ resized_height = max(1, min(224, round(source_roi.shape[0] * scale)))
264
+ offset_x, offset_y = (224 - resized_width) // 2, (224 - resized_height) // 2
265
+ canvas = np.zeros((224, 224, 3), dtype=np.uint8)
266
+ canvas_roi = canvas[offset_y:offset_y + resized_height, offset_x:offset_x + resized_width]
267
+ cv2.resize(source_roi, (resized_width, resized_height), dst=canvas_roi, interpolation=cv2.INTER_LANCZOS4)
268
+ final_mask = cv2.resize(
269
+ mask_roi.astype(np.uint8), (resized_width, resized_height), interpolation=cv2.INTER_NEAREST_EXACT
270
+ )
271
+ canvas_roi[final_mask == 0] = 0
272
+ result = Image.fromarray(canvas, mode="RGB")
273
+ encoded = encode_jpeg(result)
274
+ if output_dir is not None:
275
+ (output_dir / "final-model-input.jpg").write_bytes(encoded)
276
+ print(
277
+ f"Lower-water crop: mask_box={selected}, source_box=({x0},{y0},{x1},{y1}), "
278
+ f"complete in {time.perf_counter() - started:.3f}s",
279
+ flush=True,
280
+ )
281
+ return encoded
282
 
283
 
284
  def to_model_tensor(model_input: Image.Image) -> torch.Tensor:
285
+ """Convert the decoded 224 px JPEG input to ImageNet-normalized NCHW float32."""
286
  if model_input.mode != "RGB" or model_input.size != OUTPUT_SIZE:
287
+ raise PreprocessingError(f"Expected RGB {OUTPUT_SIZE[0]}x{OUTPUT_SIZE[1]} model input")
288
+ pixels = torch.from_numpy(np.asarray(model_input, dtype=np.uint8).copy()).permute(2, 0, 1).float() / 255.0
289
+ mean = torch.tensor(IMAGENET_MEAN, dtype=torch.float32)[:, None, None]
290
+ std = torch.tensor(IMAGENET_STD, dtype=torch.float32)[:, None, None]
291
+ return ((pixels - mean) / std).unsqueeze(0)
 
 
 
 
 
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
- # Inference dependencies, pinned to the versions this release was tested with
2
- # (Python 3.14, CPU). CPU-only PyTorch wheels are available from
3
  # https://download.pytorch.org/whl/cpu
4
  torch==2.13.0
5
  torchvision==0.28.0
@@ -7,5 +7,6 @@ transformers==5.15.1
7
  huggingface_hub==1.32.0
8
  pillow==12.3.0
9
  numpy==2.5.2
 
10
  # Only needed to read HEIC/HEIF photos (e.g. from iPhones).
11
  pillow-heif==1.6.0
 
1
+ # Inference dependencies for Python 3.14. OpenCV is constrained to a compatible
2
+ # release range; CPU-only PyTorch wheels are available from
3
  # https://download.pytorch.org/whl/cpu
4
  torch==2.13.0
5
  torchvision==0.28.0
 
7
  huggingface_hub==1.32.0
8
  pillow==12.3.0
9
  numpy==2.5.2
10
+ opencv-python-headless>=4.10.0.84,<5
11
  # Only needed to read HEIC/HEIF photos (e.g. from iPhones).
12
  pillow-heif==1.6.0