Datasets:
File size: 5,584 Bytes
4e6a175 | 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 | #!/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()
|