File size: 6,618 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/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()