File size: 13,548 Bytes
c3a2d68 040138b c3a2d68 84edd4e 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b 6e5b1a5 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 84edd4e 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 84edd4e 040138b c3a2d68 84edd4e c3a2d68 84edd4e c3a2d68 84edd4e c3a2d68 84edd4e c3a2d68 84edd4e c3a2d68 84edd4e c3a2d68 84edd4e 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b c3a2d68 040138b aab7d6f c3a2d68 aab7d6f c3a2d68 040138b c3a2d68 040138b c3a2d68 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | """Self-contained fast-v2 photo preprocessing for the v19 regressor.
The public inference route is: EXIF-normalized photo -> one 448 px SegFormer
pass -> 224 px water mask -> lower-water crop mapped to source coordinates ->
masked 224x224 JPEG (quality 95, 4:4:4) -> ImageNet-normalized tensor.
This is the coordinate-crop pipeline used to create v19 training inputs.
"""
from __future__ import annotations
import io
import math
import time
from dataclasses import dataclass
from pathlib import Path
import cv2
import numpy as np
import torch
from PIL import Image, ImageOps
SEGMENTATION_MODEL_NAME = "nvidia/segformer-b2-finetuned-ade-512-512"
SEGMENTATION_MODEL_REVISION = "de01bae28967510f9ddd496c60a969357195400c"
SEGMENTATION_RESOLUTION = 448
WATER_CLASS_NAMES = {"water", "sea", "river", "lake"}
OUTPUT_SIZE = (224, 224)
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
LOWER_WATER_FRACTION = 0.35
MINIMUM_LOWER_RETENTION = 0.95
BLACK_RATIO_BUCKET = 0.005
MINIMUM_WATER_FRACTION = 0.0005
MINIMUM_CROP_AREA_FRACTION = 0.10
MINIMUM_CROP_WIDTH = 8
SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff", ".heic", ".heif"}
class PreprocessingError(RuntimeError):
"""Raised when a photo cannot be converted into a valid model input."""
def load_rgb_image(path: str | Path) -> Image.Image:
"""Load an image as RGB and apply its EXIF orientation (including iPhone HEIC)."""
path = Path(path)
if not path.is_file():
raise FileNotFoundError(f"Image not found: {path}")
if path.suffix.lower() in {".heic", ".heif"}:
try:
from pillow_heif import register_heif_opener
except ImportError as error:
raise ImportError("HEIC/HEIF input requires pillow-heif; install requirements.txt") from error
register_heif_opener()
with Image.open(path) as opened:
return ImageOps.exif_transpose(opened).convert("RGB")
def encode_jpeg(image: Image.Image) -> bytes:
"""Encode the final training input using the fast-v2 JPEG settings."""
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=95, subsampling=0)
return buffer.getvalue()
def decode_image(encoded: bytes) -> Image.Image:
with Image.open(io.BytesIO(encoded)) as decoded:
return decoded.convert("RGB")
@dataclass
class WaterSegmenter:
model: torch.nn.Module
processor: object
water_class_ids: tuple[int, ...]
device: torch.device
def load_segmenter(device: str | torch.device = "cpu") -> WaterSegmenter:
"""Load the exact pinned segmentation model used by the v19 training pipeline."""
try:
from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor
except ImportError as error:
raise ImportError("Water segmentation requires transformers; install requirements.txt") from error
from transformers.utils import logging as transformers_logging
transformers_logging.disable_progress_bar()
device = torch.device(device)
try:
processor = SegformerImageProcessor.from_pretrained(
SEGMENTATION_MODEL_NAME,
revision=SEGMENTATION_MODEL_REVISION,
size={"height": SEGMENTATION_RESOLUTION, "width": SEGMENTATION_RESOLUTION},
do_resize=True,
)
model = SegformerForSemanticSegmentation.from_pretrained(
SEGMENTATION_MODEL_NAME, revision=SEGMENTATION_MODEL_REVISION
)
except OSError as error:
raise RuntimeError(
f"Could not load {SEGMENTATION_MODEL_NAME} at revision {SEGMENTATION_MODEL_REVISION}. "
"Check network access or download the model with: "
f"hf download {SEGMENTATION_MODEL_NAME} --revision {SEGMENTATION_MODEL_REVISION}"
) from error
model.to(device).eval()
id2label = {int(key): value.lower().strip() for key, value in model.config.id2label.items()}
class_ids = tuple(index for index, name in id2label.items() if name in WATER_CLASS_NAMES)
if not class_ids:
raise RuntimeError(f"No water labels found in {SEGMENTATION_MODEL_NAME}")
return WaterSegmenter(model, processor, class_ids, device)
@torch.inference_mode()
def segment_water_mask(image: Image.Image, segmenter: WaterSegmenter) -> np.ndarray:
"""Run one 448x448 segmentation pass and return the water classes at 448 px."""
started = time.perf_counter()
inputs = segmenter.processor(images=image.convert("RGB"), return_tensors="pt")
inputs = {name: tensor.to(segmenter.device) for name, tensor in inputs.items()}
use_fp16 = segmenter.device.type == "cuda"
context = torch.autocast(device_type="cuda", dtype=torch.float16) if use_fp16 else torch.autocast(
device_type="cpu", enabled=False
)
try:
with context:
logits = segmenter.model(**inputs).logits
target_size = (
(image.height, image.width)
if max(image.size) <= SEGMENTATION_RESOLUTION
else (SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION)
)
logits = torch.nn.functional.interpolate(logits, size=target_size, mode="bilinear", align_corners=False)
except RuntimeError as error:
retryable = any(word in str(error).lower() for word in ("out of memory", "engine to execute"))
if segmenter.device.type != "cuda" or not retryable:
raise
print(f"CUDA segmentation failed ({error}); retrying this image on CPU.", flush=True)
segmenter.device = torch.device("cpu")
segmenter.model.to(segmenter.device)
return segment_water_mask(image, segmenter)
class_map = logits.argmax(dim=1)[0].to(device="cpu", dtype=torch.uint8).numpy()
if class_map.shape != (SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION):
class_map = np.asarray(
Image.fromarray(class_map).resize(
(SEGMENTATION_RESOLUTION, SEGMENTATION_RESOLUTION), Image.Resampling.NEAREST
),
dtype=np.uint8,
)
water = np.isin(class_map, segmenter.water_class_ids)
print(
f"Segmentation: one {SEGMENTATION_RESOLUTION}x{SEGMENTATION_RESOLUTION} pass "
f"on {segmenter.device}, {time.perf_counter() - started:.3f}s",
flush=True,
)
return water
def _summed_area(mask: np.ndarray) -> np.ndarray:
return np.pad(mask.astype(np.int64), ((1, 0), (1, 0))).cumsum(0).cumsum(1)
def _rect_sum(table: np.ndarray, left: int, top: int, right: int, bottom: int) -> int:
return int(table[bottom, right] - table[top, right] - table[bottom, left] + table[top, left])
def _resized_content_size(width: int, height: int) -> tuple[int, int]:
scale = min(224 / width, 224 / height)
return max(1, round(width * scale)), max(1, round(height * scale))
def select_lower_water_crop(water_mask: np.ndarray) -> tuple[int, int, int, int] | None:
"""Select the fast-v2 bottom-anchored crop on the 224x224 water mask.
This is the same lexicographic selector used during training. The black
mask is all false for fast-v2 because the crop is selected on the raw
source-photo mask before the final canvas is built.
"""
water_mask = np.ascontiguousarray(water_mask, dtype=bool)
ys, xs = np.where(water_mask)
if not len(xs):
return None
height, width = water_mask.shape
left_bound, top_bound = int(xs.min()), int(ys.min())
right_bound, bottom_bound = int(xs.max()) + 1, int(ys.max()) + 1
bbox_width, bbox_height = right_bound - left_bound, bottom_bound - top_bound
minimum_water_pixels = max(32, round(width * height * MINIMUM_WATER_FRACTION))
if int(water_mask.sum()) < minimum_water_pixels:
return None
lower_top = max(top_bound, bottom_bound - max(1, round(bbox_height * LOWER_WATER_FRACTION)))
lower_total = int(water_mask[lower_top:bottom_bound].sum())
if lower_total < minimum_water_pixels:
return None
horizontal_step = max(1, round(width / 56.0))
boundaries = sorted(set(range(left_bound, right_bound + 1, horizontal_step)) | {right_bound})
water_table = _summed_area(water_mask)
lower_table = _summed_area(water_mask & (np.arange(height)[:, None] >= lower_top))
minimum_area = max(256, round(bbox_width * bbox_height * MINIMUM_CROP_AREA_FRACTION))
best_key = None
best_box = None
for left_index, left in enumerate(boundaries[:-1]):
for right in boundaries[left_index + 1:]:
crop_width = right - left
if crop_width < MINIMUM_CROP_WIDTH:
continue
lower_in_view = _rect_sum(lower_table, left, lower_top, right, bottom_bound)
if lower_in_view < minimum_water_pixels:
continue
for top in range(top_bound, lower_top + 1):
crop_height = bottom_bound - top
crop_area = crop_width * crop_height
if crop_height < 8 or crop_area < minimum_area:
continue
retention = _rect_sum(lower_table, left, top, right, bottom_bound) / lower_in_view
if retention + 1e-12 < MINIMUM_LOWER_RETENTION:
continue
water_pixels = _rect_sum(water_table, left, top, right, bottom_bound)
resized_width, resized_height = _resized_content_size(crop_width, crop_height)
occupied = resized_width * resized_height / float(224 * 224)
water_ratio = (water_pixels / crop_area) * occupied
# Black pixels are zero for this source-coordinate profile.
black_ratio = 1.0 - occupied
tier = 3 if retention >= 0.995 else 2 if retention >= 0.98 else 1
bucket = int(np.rint(black_ratio / BLACK_RATIO_BUCKET))
key = (-tier, bucket, -water_pixels, -water_ratio,
abs(math.log(crop_width / crop_height)), left, top, right)
if best_key is None or key < best_key:
best_key, best_box = key, (left, top, right, bottom_bound)
return best_box
def preprocess_photo_encoded(
image: Image.Image,
segmenter: WaterSegmenter,
diagnostic_dir: str | Path | None = None,
) -> bytes:
"""Return the exact final 224x224 JPEG input format used for v19 training."""
started = time.perf_counter()
source = np.asarray(image.convert("RGB"), dtype=np.uint8)
water_448 = segment_water_mask(image, segmenter)
output_dir = Path(diagnostic_dir) if diagnostic_dir is not None else None
if output_dir is not None:
output_dir.mkdir(parents=True, exist_ok=True)
Image.fromarray(water_448.astype(np.uint8) * 255, mode="L").save(output_dir / "water-mask-448.png")
water_224 = cv2.resize(
water_448.astype(np.uint8), (224, 224), interpolation=cv2.INTER_NEAREST_EXACT
).astype(bool)
if output_dir is not None:
Image.fromarray(water_224.astype(np.uint8) * 255, mode="L").save(output_dir / "selector-mask-224.png")
selected = select_lower_water_crop(water_224)
if selected is None:
raise PreprocessingError("No reliable lower-water crop could be selected from this photo.")
left, top, right, bottom = selected
source_height, source_width = source.shape[:2]
x0 = max(0, min(source_width, int(np.floor(left * source_width / 224))))
x1 = max(x0 + 1, min(source_width, int(np.ceil(right * source_width / 224))))
y0 = max(0, min(source_height, int(np.floor(top * source_height / 224))))
y1 = max(y0 + 1, min(source_height, int(np.ceil(bottom * source_height / 224))))
source_roi = source[y0:y1, x0:x1]
mask_roi = water_224[top:bottom, left:right]
if output_dir is not None:
Image.fromarray(source_roi, mode="RGB").save(output_dir / "selected-source-region.jpg", quality=95)
scale = min(224 / source_roi.shape[1], 224 / source_roi.shape[0])
resized_width = max(1, min(224, round(source_roi.shape[1] * scale)))
resized_height = max(1, min(224, round(source_roi.shape[0] * scale)))
offset_x, offset_y = (224 - resized_width) // 2, (224 - resized_height) // 2
canvas = np.zeros((224, 224, 3), dtype=np.uint8)
canvas_roi = canvas[offset_y:offset_y + resized_height, offset_x:offset_x + resized_width]
cv2.resize(source_roi, (resized_width, resized_height), dst=canvas_roi, interpolation=cv2.INTER_LANCZOS4)
final_mask = cv2.resize(
mask_roi.astype(np.uint8), (resized_width, resized_height), interpolation=cv2.INTER_NEAREST_EXACT
)
canvas_roi[final_mask == 0] = 0
result = Image.fromarray(canvas, mode="RGB")
encoded = encode_jpeg(result)
if output_dir is not None:
(output_dir / "final-model-input.jpg").write_bytes(encoded)
print(
f"Lower-water crop: mask_box={selected}, source_box=({x0},{y0},{x1},{y1}), "
f"complete in {time.perf_counter() - started:.3f}s",
flush=True,
)
return encoded
def to_model_tensor(model_input: Image.Image) -> torch.Tensor:
"""Convert the decoded 224 px JPEG input to ImageNet-normalized NCHW float32."""
if model_input.mode != "RGB" or model_input.size != OUTPUT_SIZE:
raise PreprocessingError(f"Expected RGB {OUTPUT_SIZE[0]}x{OUTPUT_SIZE[1]} model input")
pixels = torch.from_numpy(np.asarray(model_input, dtype=np.uint8).copy()).permute(2, 0, 1).float() / 255.0
mean = torch.tensor(IMAGENET_MEAN, dtype=torch.float32)[:, None, None]
std = torch.tensor(IMAGENET_STD, dtype=torch.float32)[:, None, None]
return ((pixels - mean) / std).unsqueeze(0)
|