#!/usr/bin/env python3 """Recover the blended IR frames listed in markdown/blend.md. Canopy-01/02/03 use the chroma fix. Canopy-08/09 additionally recover white-hot regions from neighboring thermal colors. Graminoid-17/18 are skipped. Recovered images are written beside their inputs as ``fXXXXX_recovered.png``. Usage: python scripts/recover_ir.py Data """ import argparse import csv import os import tempfile from collections import deque from decimal import Decimal, InvalidOperation from pathlib import Path import numpy as np from PIL import Image, ImageFilter CHROMA_THRESHOLD = 15 BRIGHTNESS_THRESHOLD = 150 HOT_RED_MIN = 120 COLD_BLUE_MIN = 80 HOT_RED_OVER_BLUE = 25 COLD_BLUE_OVER_RED = 20 WHITE_HOLE_CLOSE_SIZE = 21 def is_blended(pair_id, timestamp): if pair_id in {"Canopy-01", "Canopy-02"}: return True if pair_id == "Canopy-03": return timestamp <= Decimal("67") if pair_id == "Canopy-08": return ( Decimal("291") <= timestamp <= Decimal("317") or timestamp >= Decimal("322") ) if pair_id == "Canopy-09": return timestamp <= Decimal("70") if pair_id in {"Graminoid-17", "Graminoid-18"}: return False return False def load_rgb(path): with Image.open(path) as image: return np.asarray(image.convert("RGB"), dtype=np.uint8) def image_components(rgb): values = rgb.astype(np.float32) chroma = values.max(axis=2) - values.min(axis=2) brightness = values.mean(axis=2) return values, chroma, brightness def chroma_fix(rgb): _, chroma, brightness = image_components(rgb) mask = (chroma > CHROMA_THRESHOLD) | ( brightness > BRIGHTNESS_THRESHOLD ) recovered = np.zeros_like(rgb) recovered[mask] = rgb[mask] return recovered def contextual_white_hot(values, chroma, brightness): red, _, blue = values.transpose(2, 0, 1) colored = chroma > CHROMA_THRESHOLD white_candidate = (~colored) & (brightness > BRIGHTNESS_THRESHOLD) hot_seed = ( colored & (red > HOT_RED_MIN) & (red > blue + HOT_RED_OVER_BLUE) ) cold_seed = ( colored & (blue > COLD_BLUE_MIN) & (blue > red + COLD_BLUE_OVER_RED) ) if not hot_seed.any(): return np.zeros_like(white_candidate) if not cold_seed.any(): return white_candidate height, width = colored.shape owner = np.zeros((height, width), dtype=np.int8) owner[hot_seed] = 1 owner[cold_seed] = -1 queue = deque(int(index) for index in np.flatnonzero(owner)) while queue: index = queue.popleft() y, x = divmod(index, width) label = owner[y, x] if y > 0 and owner[y - 1, x] == 0: owner[y - 1, x] = label queue.append(index - width) if y + 1 < height and owner[y + 1, x] == 0: owner[y + 1, x] = label queue.append(index + width) if x > 0 and owner[y, x - 1] == 0: owner[y, x - 1] = label queue.append(index - 1) if x + 1 < width and owner[y, x + 1] == 0: owner[y, x + 1] = label queue.append(index + 1) return white_candidate & (owner == 1) def fill_white_hot_holes(image): values, chroma, brightness = image_components(image) white = ( (chroma <= CHROMA_THRESHOLD) & (brightness > BRIGHTNESS_THRESHOLD) ) black = np.all(image == 0, axis=2) closed_white = np.asarray( Image.fromarray(white.astype(np.uint8) * 255) .filter(ImageFilter.MaxFilter(WHITE_HOLE_CLOSE_SIZE)) .filter(ImageFilter.MinFilter(WHITE_HOLE_CLOSE_SIZE)) ) > 0 fill_mask = black & closed_white if not fill_mask.any(): return image result = values.copy() known = ~fill_mask remaining = fill_mask.copy() height, width = fill_mask.shape while remaining.any(): sums = np.zeros_like(result) counts = np.zeros((height, width), dtype=np.float32) sums[1:] += result[:-1] * known[:-1, :, None] counts[1:] += known[:-1] sums[:-1] += result[1:] * known[1:, :, None] counts[:-1] += known[1:] sums[:, 1:] += result[:, :-1] * known[:, :-1, None] counts[:, 1:] += known[:, :-1] sums[:, :-1] += result[:, 1:] * known[:, 1:, None] counts[:, :-1] += known[:, 1:] newly_filled = remaining & (counts > 0) if not newly_filled.any(): break result[newly_filled] = ( sums[newly_filled] / counts[newly_filled, None] ) known[newly_filled] = True remaining[newly_filled] = False return np.clip(np.round(result), 0, 255).astype(np.uint8) def contextual_fix(rgb): values, chroma, brightness = image_components(rgb) mask = chroma > CHROMA_THRESHOLD mask |= contextual_white_hot(values, chroma, brightness) recovered = np.zeros_like(rgb) recovered[mask] = rgb[mask] return fill_white_hot_holes(recovered) def manifest_path(dataset_root, relative_path): relative = Path(relative_path) if relative.is_absolute() or ".." in relative.parts: raise RuntimeError(f"unsafe frame path in samples.csv: {relative_path!r}") path = dataset_root / relative if not path.is_file() or path.is_symlink(): raise RuntimeError(f"missing or invalid frame: {path}") return path def selected_rows(dataset_root): manifest = dataset_root / "samples.csv" if not manifest.is_file() or manifest.is_symlink(): raise RuntimeError(f"missing or invalid manifest: {manifest}") selected = [] with manifest.open(newline="") as file: reader = csv.DictReader(file) required = {"pair_id", "rgb_time_s", "ir_path"} if not reader.fieldnames or not required.issubset(reader.fieldnames): raise RuntimeError(f"invalid samples.csv header: {manifest}") for line_number, row in enumerate(reader, start=2): try: timestamp = Decimal(row["rgb_time_s"]) except (InvalidOperation, TypeError): raise RuntimeError( f"invalid rgb_time_s on samples.csv line {line_number}" ) from None if not timestamp.is_finite(): raise RuntimeError( f"non-finite rgb_time_s on samples.csv line {line_number}" ) if is_blended(row["pair_id"], timestamp): selected.append(( row["pair_id"], manifest_path(dataset_root, row["ir_path"]), )) paths = [path for _, path in selected] if len(paths) != len(set(paths)): raise RuntimeError(f"duplicate IR path in {manifest}") return selected def recover_dataset(dataset_root): dataset_root = dataset_root.resolve() rows = selected_rows(dataset_root) if not rows: print(f"{dataset_root}: no supported blended IR frames found") return with tempfile.TemporaryDirectory(prefix=".recover_ir.", dir=dataset_root) as stage: staged = [] for number, (pair_id, input_path) in enumerate(rows): rgb = load_rgb(input_path) if pair_id in {"Canopy-01", "Canopy-02", "Canopy-03"}: recovered = chroma_fix(rgb) elif pair_id in {"Canopy-08", "Canopy-09"}: recovered = contextual_fix(rgb) else: continue temporary = Path(stage) / f"{number}.png" Image.fromarray(recovered).save(temporary) output_path = input_path.with_name( f"{input_path.stem}_recovered.png" ) staged.append((temporary, output_path)) for temporary, output_path in staged: os.replace(temporary, output_path) print(f"{dataset_root}: wrote {len(staged)} recovered IR frames in place") def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "dataset_roots", type=Path, nargs="+", help="sampled dataset directories containing samples.csv", ) return parser.parse_args() def main(): args = parse_args() for dataset_root in args.dataset_roots: recover_dataset(dataset_root) if __name__ == "__main__": main()