#!/usr/bin/env python3 """Calculate RGB and IR channel statistics for training frames.""" import argparse import csv import math import os from concurrent.futures import ProcessPoolExecutor from pathlib import Path from PIL import Image CHANNELS = ("R", "G", "B") VALID_SPLITS = {"train", "val", "test"} def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "splits", type=Path, help="splits.csv containing frame and split columns", ) parser.add_argument( "data_root", type=Path, help="dataset root containing the RGB and IR images", ) return parser.parse_args() def load_training_paths(splits_path, data_root): paths = [] seen_frames = set() recovered_count = 0 with splits_path.open(newline="") as handle: reader = csv.DictReader(handle) required = {"frame", "split"} if not reader.fieldnames or not required.issubset(reader.fieldnames): raise RuntimeError(f"invalid splits.csv header: {splits_path}") for line_number, row in enumerate(reader, start=2): frame = Path(row["frame"].strip()) split = row["split"].strip() if len(frame.parts) != 3: raise RuntimeError( f"unexpected frame path {frame.as_posix()!r} on line " f"{line_number} of {splits_path}" ) if split not in VALID_SPLITS: raise RuntimeError( f"unknown split {split!r} on line {line_number} of " f"{splits_path}" ) frame_id = frame.as_posix() if frame_id in seen_frames: raise RuntimeError(f"duplicate frame {frame_id!r} in {splits_path}") seen_frames.add(frame_id) if split != "train": continue clip_root = data_root / frame.parts[0] / frame.parts[1] rgb_path = clip_root / "rgb" / frame.name ir_path = clip_root / "ir" / frame.name recovered_path = ir_path.with_name(f"{ir_path.stem}_recovered.png") if recovered_path.is_file(): ir_path = recovered_path recovered_count += 1 if not rgb_path.is_file(): raise RuntimeError(f"missing training RGB image: {rgb_path}") if not ir_path.is_file(): raise RuntimeError(f"missing training IR image: {ir_path}") paths.append((rgb_path, ir_path)) if not paths: raise RuntimeError(f"no training frames found in {splits_path}") return paths, recovered_count def image_stats(path): with Image.open(path) as image: image = image.convert("RGB") pixels = image.width * image.height histogram = image.histogram() sums = [] squared_sums = [] for channel in range(len(CHANNELS)): counts = histogram[channel * 256 : (channel + 1) * 256] sums.append(sum(value * count for value, count in enumerate(counts))) squared_sums.append( sum(value * value * count for value, count in enumerate(counts)) ) return pixels, sums, squared_sums def frame_stats(paths): rgb_path, ir_path = paths return image_stats(rgb_path), image_stats(ir_path) def summarize(pixel_count, sums, squared_sums): scale = 255 means = [value / (pixel_count * scale) for value in sums] second_moments = [ value / (pixel_count * scale * scale) for value in squared_sums ] standard_deviations = [ math.sqrt(max(0.0, second_moment - mean * mean)) for mean, second_moment in zip(means, second_moments) ] return means, standard_deviations def calculate(paths): totals = { "rgb": {"pixels": 0, "sum": [0, 0, 0], "squared_sum": [0, 0, 0]}, "ir": {"pixels": 0, "sum": [0, 0, 0], "squared_sum": [0, 0, 0]}, } workers = min(8, os.cpu_count() or 1) with ProcessPoolExecutor(max_workers=workers) as pool: results = pool.map(frame_stats, paths, chunksize=2) for result in results: for modality, stats in zip(("rgb", "ir"), result): pixels, sums, squared_sums = stats totals[modality]["pixels"] += pixels for channel in range(len(CHANNELS)): totals[modality]["sum"][channel] += sums[channel] totals[modality]["squared_sum"][channel] += squared_sums[ channel ] return totals def format_values(values): return "[" + ", ".join(f"{value:.8f}" for value in values) + "]" def main(): args = parse_args() splits_path = args.splits.resolve() data_root = args.data_root.resolve() paths, recovered_count = load_training_paths(splits_path, data_root) print(f"processing {len(paths)} training frame pairs...") totals = calculate(paths) print(f"training frame pairs: {len(paths)}") print(f"recovered IR alternatives used: {recovered_count}") print(f"channels: {list(CHANNELS)}") for modality in ("rgb", "ir"): values = totals[modality] means, standard_deviations = summarize( values["pixels"], values["sum"], values["squared_sum"] ) print(f"{modality.upper()} pixels: {values['pixels']}") print(f"{modality.upper()} mean: {format_values(means)}") print(f"{modality.upper()} std: {format_values(standard_deviations)}") if __name__ == "__main__": main()