Download src/preprocessing.py from Anlea/cloudie: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/spaces/Anlea/cloudie/resolve/main/src/preprocessing.py
- Command line
-
hf download hf://spaces/Anlea/cloudie/src/preprocessing.py
-
curl -L -o preprocessing.py https://huggingface.co/spaces/Anlea/cloudie/resolve/main/src/preprocessing.py
11.8 kB
| """Image checks, resize, train-only normalization, and train-only augmentation. | |
| Southern Hemisphere frames stay as stored. ``leave_unflipped`` records a | |
| hemisphere label and does not mirror the array. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import numpy as np | |
| from PIL import Image | |
| from src.config import parse_image_size | |
| from src.splits import LeakageError | |
| # A missing-pixel fraction above this value fails closed. It does not warn. | |
| MAX_MISSING_FRACTION = 0.30 | |
| class NormStats: | |
| mean: float | |
| std: float | |
| source_split: str | |
| # Pixel units stay on the dataset that produced them. NASA chips are 8-bit | |
| # counts. TCIR IR1 is brightness temperature in kelvin. They are never | |
| # pooled into one mean and std. A later dataset gets its own entry. | |
| PIXEL_KIND = { | |
| "nasa": "uint8", | |
| "tcir": "brightness_temperature_k", | |
| "incyde": "jpeg_uncalibrated", | |
| "smoke": "synthetic", | |
| } | |
| def pixel_kind(dataset: str) -> str: | |
| """Unit label for one dataset. Unknown datasets stay unspecified.""" | |
| return PIXEL_KIND.get(str(dataset).strip().lower(), "unspecified") | |
| def norm_by_dataset(dataset: str, stats: NormStats) -> dict: | |
| """One dataset's train-split stats. The map has that key only.""" | |
| if stats.source_split != "train": | |
| raise LeakageError("normalization stats may be fit on the train split only") | |
| name = str(dataset).strip().lower() | |
| if not name: | |
| raise ValueError("dataset name is required for normalization stats") | |
| return { | |
| name: { | |
| "mean": float(stats.mean), | |
| "std": float(stats.std), | |
| "source_split": "train", | |
| "pixel_kind": pixel_kind(name), | |
| } | |
| } | |
| def norm_stats_from_checkpoint(payload: dict) -> NormStats: | |
| """Stats for the checkpoint's own dataset. Mixed maps are refused. | |
| A checkpoint written before per-dataset stats still uses ``norm_mean`` | |
| and ``norm_std``. A map with two datasets, or a key that is not the | |
| checkpoint dataset, is not applied. | |
| """ | |
| grouped = payload.get("norm_by_dataset") | |
| dataset = payload.get("dataset") | |
| if isinstance(grouped, dict) and grouped: | |
| if len(grouped) != 1: | |
| raise ValueError( | |
| "checkpoint mixes normalization stats across datasets; refusing to apply them" | |
| ) | |
| name = None if dataset is None else str(dataset) | |
| if name not in grouped: | |
| raise ValueError( | |
| "checkpoint norm_by_dataset does not match the checkpoint dataset; " | |
| "refusing to mix normalization stats" | |
| ) | |
| entry = grouped[name] | |
| if str(entry.get("source_split")) != "train": | |
| raise ValueError("checkpoint normalization was not fit on train") | |
| return NormStats( | |
| mean=float(entry["mean"]), | |
| std=float(entry["std"]), | |
| source_split="train", | |
| ) | |
| if "norm_mean" not in payload or "norm_std" not in payload: | |
| raise ValueError("checkpoint is missing normalization stats") | |
| source = payload.get("norm_source_split") | |
| if source is not None and str(source) != "train": | |
| raise ValueError("checkpoint normalization was not fit on train") | |
| return NormStats( | |
| mean=float(payload["norm_mean"]), | |
| std=float(payload["norm_std"]), | |
| source_split="train", | |
| ) | |
| def as_channel_first(image: np.ndarray) -> np.ndarray: | |
| array = np.asarray(image, dtype=np.float32) | |
| if array.ndim == 2: | |
| return array[None, ...] | |
| if array.ndim != 3: | |
| raise ValueError(f"expected a 2D or 3D image, got {array.shape}") | |
| if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4: | |
| return array | |
| if array.shape[-1] <= 4: | |
| return np.moveaxis(array, -1, 0) | |
| raise ValueError(f"cannot infer the channel axis for shape {array.shape}") | |
| def missing_fraction(image: np.ndarray) -> float: | |
| return float((~np.isfinite(image)).mean()) | |
| def fit_norm_stats(images: list[np.ndarray], source_split: str) -> NormStats: | |
| """Fit mean and std. Refuses anything other than the train split.""" | |
| if source_split != "train": | |
| raise LeakageError("normalization stats may be fit on the train split only") | |
| if not images: | |
| raise ValueError("need at least one train image") | |
| values = [np.asarray(image, dtype=np.float32) for image in images] | |
| finite = np.concatenate([image[np.isfinite(image)].ravel() for image in values]) | |
| if finite.size == 0: | |
| raise ValueError("train images have no finite pixels") | |
| std = float(finite.std()) | |
| if std < 1e-6: | |
| std = 1.0 | |
| return NormStats(mean=float(finite.mean()), std=std, source_split=source_split) | |
| def stack_prepared(images: list[np.ndarray]) -> np.ndarray: | |
| """Stack chips that have already been prepared. | |
| A native ``image_size`` does not resize, so every chip in the stack | |
| must already share a height and width. | |
| """ | |
| if not images: | |
| raise ValueError("no images to stack") | |
| try: | |
| return np.stack(images) | |
| except ValueError as exc: | |
| shapes = sorted({tuple(np.shape(image)) for image in images}) | |
| raise ValueError( | |
| "prepared chips do not share a height and width " | |
| f"{shapes}. A native image_size does not resize them onto one grid." | |
| ) from exc | |
| def _resize(image: np.ndarray, size: int) -> np.ndarray: | |
| channels = [] | |
| for channel in image: | |
| picture = Image.fromarray(channel.astype(np.float32), mode="F") | |
| picture = picture.resize((size, size), Image.Resampling.BILINEAR) | |
| channels.append(np.asarray(picture, dtype=np.float32)) | |
| return np.stack(channels, axis=0) | |
| def prepare_image( | |
| image: np.ndarray, | |
| image_size: int | str | None, | |
| stats: NormStats | None, | |
| max_missing_fraction: float = MAX_MISSING_FRACTION, | |
| ) -> np.ndarray: | |
| """Return ``(C, H, W)`` float32. Does not invent brightness temperature. | |
| ``image_size`` ``None`` or ``native`` keeps the chip's height and width. | |
| An integer resizes to that square. ``max_missing_fraction`` is | |
| ``data.max_missing_fraction`` when the caller has a config. | |
| A missing-pixel fraction above ``max_missing_fraction`` raises. Raw | |
| digital numbers stay pixel values; this function does not name them Tb. | |
| """ | |
| array = as_channel_first(image) | |
| fraction = missing_fraction(array) | |
| if fraction > max_missing_fraction: | |
| raise ValueError( | |
| f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}" | |
| ) | |
| filled = array.copy() | |
| for index in range(filled.shape[0]): | |
| finite = np.isfinite(filled[index]) | |
| fill = float(np.median(filled[index][finite])) if finite.any() else 0.0 | |
| filled[index][~finite] = fill | |
| side = parse_image_size(image_size) | |
| output = filled if side is None else _resize(filled, side) | |
| if stats is not None: | |
| output = (output - stats.mean) / stats.std | |
| return output | |
| def dn_to_brightness_temperature(dn: np.ndarray, gain: float, offset: float) -> np.ndarray: | |
| """Apply a caller-supplied calibration. This does not look up a sensor table.""" | |
| return np.asarray(dn, dtype=np.float32) * float(gain) + float(offset) | |
| def leave_unflipped(image: np.ndarray, hemisphere: str | None = None) -> np.ndarray: | |
| """Use the frame as stored. | |
| Southern Hemisphere TCIR imagery is not mirrored. ``hemisphere`` records | |
| the caller's label and does not change the array. | |
| """ | |
| del hemisphere | |
| return np.asarray(image) | |
| def as_grey_plane(image: np.ndarray) -> np.ndarray: | |
| """One plane. Identical RGB channels collapse. Differing channels raise. | |
| PIL JPEGs are often ``(H, W, C)`` even when every channel is the same | |
| grey IR value. A leading singleton channel is accepted too. | |
| """ | |
| array = np.asarray(image, dtype=np.float32) | |
| if array.ndim == 2: | |
| return array | |
| if array.ndim != 3: | |
| raise ValueError(f"expected one grey plane, got {array.shape}") | |
| channel_last = ( | |
| array.shape[-1] <= 4 | |
| and array.shape[0] > array.shape[-1] | |
| and array.shape[1] > array.shape[-1] | |
| ) | |
| channel_first = ( | |
| array.shape[0] <= 4 | |
| and array.shape[1] > array.shape[0] | |
| and array.shape[2] > array.shape[0] | |
| ) | |
| if channel_last: | |
| count = int(array.shape[-1]) | |
| if count == 1 or all(np.array_equal(array[..., 0], array[..., index]) for index in range(1, count)): | |
| return array[..., 0] | |
| raise ValueError(f"expected grey IR, channels differ, shape {array.shape}") | |
| if channel_first: | |
| count = int(array.shape[0]) | |
| if count == 1 or all(np.array_equal(array[0], array[index]) for index in range(1, count)): | |
| return array[0] | |
| raise ValueError(f"expected grey IR, channels differ, shape {array.shape}") | |
| raise ValueError(f"expected grey IR, got {array.shape}") | |
| def rotate_with_circular_mask(image: np.ndarray, angle_deg: float) -> np.ndarray: | |
| """Rotate about the centre and drop pixels outside the inscribed circle. | |
| There is no flip. A square rotation otherwise paints the corners from | |
| empty space, and those bars must not enter training. The disk of | |
| diameter equal to the short side stays inside the original chip for | |
| any angle, so the kept pixels are source pixels. Outside the disk the | |
| values are NaN. Callers that already normalized fill those NaNs with 0. | |
| Channel-last grey JPEGs are accepted and returned as one plane. | |
| """ | |
| plane = as_grey_plane(image) | |
| finite = np.isfinite(plane) | |
| filled = plane.copy() | |
| filled[~finite] = 0.0 | |
| picture = Image.fromarray(filled, mode="F") | |
| rotated = np.asarray( | |
| picture.rotate( | |
| float(angle_deg), | |
| resample=Image.Resampling.BILINEAR, | |
| fillcolor=0.0, | |
| ), | |
| dtype=np.float32, | |
| ) | |
| height, width = rotated.shape | |
| yy, xx = np.ogrid[:height, :width] | |
| center_y = (height - 1) / 2.0 | |
| center_x = (width - 1) / 2.0 | |
| radius = min(height, width) / 2.0 | |
| disk = (yy - center_y) ** 2 + (xx - center_x) ** 2 <= radius**2 | |
| out = rotated.copy() | |
| out[~disk] = np.nan | |
| return out | |
| def prepare_training_chip( | |
| image: np.ndarray, | |
| image_size: int | str | None, | |
| angle: float | None, | |
| stats: NormStats | None, | |
| max_missing_fraction: float = MAX_MISSING_FRACTION, | |
| ) -> np.ndarray: | |
| """Prepare one training chip, then optionally rotate on that grid. | |
| The missing-pixel gate sees the source image, before the circular mask. | |
| A configured square resize happens first, so the mask is the inscribed | |
| circle of the training grid (about a fifth of the square) and not the | |
| corners of a wide native crop. Masked pixels are 0 after normalization, | |
| which is the training mean, not a black bar. | |
| """ | |
| prepared = prepare_image(as_grey_plane(image), image_size, stats, max_missing_fraction) | |
| if angle is None: | |
| return prepared | |
| masked = rotate_with_circular_mask(prepared, float(angle)) | |
| if masked.ndim == 2: | |
| masked = masked[None, ...] | |
| return np.where(np.isfinite(masked), masked, np.float32(0.0)).astype(np.float32) | |
| def augment_image(image: np.ndarray, split: str, rng: np.random.Generator) -> np.ndarray: | |
| """Flip or rotate a train image. Refuses every other split. | |
| Classical features do not call this. A later training loop may, and only | |
| on rows whose split is ``train``. | |
| """ | |
| if split != "train": | |
| raise LeakageError("augmentation is allowed on the train split only") | |
| array = as_channel_first(image) | |
| choice = int(rng.integers(0, 3)) | |
| if choice == 0: | |
| return np.flip(array, axis=-1).copy() | |
| if choice == 1: | |
| return np.rot90(array, k=1, axes=(-2, -1)).copy() | |
| return array.copy() | |