Datasets:
Download scripts/analyze_label_distribution.py from hotsightdataset/HotSight: direct link, hf CLI and curl.
- Browser
- Download file 6.62 kB
-
https://huggingface.co/datasets/hotsightdataset/HotSight/resolve/main/scripts/analyze_label_distribution.py
- Command line
-
hf download hf://datasets/hotsightdataset/HotSight/scripts/analyze_label_distribution.py
-
curl -L -o analyze_label_distribution.py https://huggingface.co/datasets/hotsightdataset/HotSight/resolve/main/scripts/analyze_label_distribution.py
6.62 kB
| #!/usr/bin/env python3 | |
| """Write pixel-label percentages by clip and, optionally, by dataset split.""" | |
| import argparse | |
| import csv | |
| import os | |
| from collections import defaultdict | |
| from concurrent.futures import ProcessPoolExecutor | |
| from pathlib import Path | |
| import numpy as np | |
| LABEL_COLUMNS = [ | |
| "red_1_pct", | |
| "blue_2_pct", | |
| "yellow_3_pct", | |
| "green_4_pct", | |
| "black_5_pct", | |
| ] | |
| EXPECTED_PIXELS = 2688 * 1512 | |
| SPLIT_ORDER = ("train", "val", "test") | |
| def parse_args(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "root", | |
| nargs="?", | |
| type=Path, | |
| default=Path("Data"), | |
| help="dataset root (default: %(default)s)", | |
| ) | |
| parser.add_argument( | |
| "--manifest", | |
| type=Path, | |
| help="input CSV (default: Data/samples.csv)", | |
| ) | |
| parser.add_argument( | |
| "--output", | |
| type=Path, | |
| help="destination CSV (default: Data/annotation_label_by_clip.csv)", | |
| ) | |
| parser.add_argument( | |
| "--splits", | |
| type=Path, | |
| help=( | |
| "optional per-frame splits CSV; also writes " | |
| "Data/annotation_label_by_split.csv" | |
| ), | |
| ) | |
| return parser.parse_args() | |
| def mask_path(root, rgb_path): | |
| relative = rgb_path.replace("/rgb/", "/mask/") | |
| return root / Path(relative).with_suffix(".txt") | |
| def frame_id(rgb_path): | |
| path = Path(rgb_path) | |
| if len(path.parts) < 2 or path.parts[-2] != "rgb": | |
| raise RuntimeError(f"unexpected rgb_path: {rgb_path!r}") | |
| return (Path(*path.parts[:-2]) / path.name).as_posix() | |
| def load_splits(path): | |
| assignments = {} | |
| with 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: {path}") | |
| for line_number, row in enumerate(reader, start=2): | |
| frame = row["frame"].strip() | |
| split = row["split"].strip() | |
| if not frame: | |
| raise RuntimeError(f"empty frame on splits.csv line {line_number}") | |
| if split not in SPLIT_ORDER: | |
| raise RuntimeError( | |
| f"unknown split {split!r} on splits.csv line {line_number}" | |
| ) | |
| if frame in assignments: | |
| raise RuntimeError(f"duplicate frame {frame!r} in splits.csv") | |
| assignments[frame] = split | |
| return assignments | |
| def count_mask(path): | |
| data = np.fromfile(path, dtype=np.uint8) | |
| byte_counts = np.bincount(data, minlength=256) | |
| label_counts = np.array([byte_counts[ord("0") + label] for label in range(1, 6)]) | |
| zero_count = int(byte_counts[ord("0")]) | |
| unknown = int(data.size - label_counts.sum() - zero_count) | |
| return data.size, label_counts, zero_count, unknown | |
| def write_distribution(path, key_column, counts_by_key, masks_by_key, keys): | |
| with path.open("w", newline="") as handle: | |
| writer = csv.writer(handle) | |
| writer.writerow([key_column, "masks", *LABEL_COLUMNS]) | |
| for key in keys: | |
| counts = counts_by_key[key] | |
| total = int(counts.sum()) | |
| percentages = [f"{100 * int(count) / total:.4f}" for count in counts] | |
| writer.writerow([key, masks_by_key[key], *percentages]) | |
| def main(): | |
| args = parse_args() | |
| root = args.root.resolve() | |
| manifest = (args.manifest or root / "samples.csv").resolve() | |
| output = (args.output or root / "annotation_label_by_clip.csv").resolve() | |
| splits_path = args.splits.resolve() if args.splits else None | |
| split_output = root / "annotation_label_by_split.csv" | |
| with manifest.open(newline="") as handle: | |
| reader = csv.DictReader(handle) | |
| required = {"pair_id", "rgb_path"} | |
| if not reader.fieldnames or not required.issubset(reader.fieldnames): | |
| raise RuntimeError(f"invalid samples.csv header: {manifest}") | |
| samples = list(reader) | |
| sample_frames = set() | |
| for row in samples: | |
| frame = frame_id(row["rgb_path"].strip()) | |
| if frame in sample_frames: | |
| raise RuntimeError(f"duplicate frame {frame!r} in samples.csv") | |
| sample_frames.add(frame) | |
| row["_frame_id"] = frame | |
| splits = load_splits(splits_path) if splits_path else None | |
| if splits is not None: | |
| missing = sample_frames - splits.keys() | |
| extra = splits.keys() - sample_frames | |
| if missing or extra: | |
| raise RuntimeError( | |
| "splits.csv does not match samples.csv: " | |
| f"{len(missing)} missing and {len(extra)} extra frames" | |
| ) | |
| labeled = [] | |
| missing = [] | |
| for row in samples: | |
| path = mask_path(root, row["rgb_path"]) | |
| if path.is_file(): | |
| labeled.append((row, path)) | |
| else: | |
| missing.append(path) | |
| clip_counts = defaultdict(lambda: np.zeros(5, dtype=np.int64)) | |
| clip_masks = defaultdict(int) | |
| split_counts = defaultdict(lambda: np.zeros(5, dtype=np.int64)) | |
| split_masks = defaultdict(int) | |
| zero_pixels = 0 | |
| workers = min(8, os.cpu_count() or 1) | |
| with ProcessPoolExecutor(max_workers=workers) as pool: | |
| results = pool.map(count_mask, (path for _, path in labeled), chunksize=4) | |
| for (row, path), (pixels, counts, zeros, unknown) in zip(labeled, results): | |
| if unknown: | |
| raise ValueError(f"{path}: {unknown} pixels have labels outside 1-5") | |
| if pixels != EXPECTED_PIXELS: | |
| raise ValueError(f"{path}: {pixels} pixels; expected {EXPECTED_PIXELS}") | |
| clip_counts[row["pair_id"]] += counts | |
| clip_masks[row["pair_id"]] += 1 | |
| if splits is not None: | |
| split = splits[row["_frame_id"]] | |
| split_counts[split] += counts | |
| split_masks[split] += 1 | |
| zero_pixels += zeros | |
| write_distribution( | |
| output, "clip", clip_counts, clip_masks, sorted(clip_counts) | |
| ) | |
| if splits is not None: | |
| split_keys = [split for split in SPLIT_ORDER if split in split_counts] | |
| write_distribution( | |
| split_output, "split", split_counts, split_masks, split_keys | |
| ) | |
| print(f"wrote {output}") | |
| if splits is not None: | |
| print(f"wrote {split_output}") | |
| print(f"{len(clip_counts)} clips, {len(labeled)} masks") | |
| if zero_pixels: | |
| print(f"warning: excluded {zero_pixels} pixels with label 0 (classes are 1-5)") | |
| if missing: | |
| print(f"skipped {len(missing)} sampled frames without masks") | |
| if __name__ == "__main__": | |
| main() | |