File size: 11,447 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env python3
"""Sample synchronized RGB/IR frame pairs.

Each RGB frame is paired with the IR frame nearest to ``rgb_time + ir_offset``. 
Matches farther than ``--max-gap`` seconds are omitted.

Usage:
    python scripts/sample_dataset.py \
        --out-root ./Data --start 300 --step 300
"""

import argparse
import csv
import logging
import math
import os
import sys
import tempfile
from pathlib import Path

import cv2

FIELDS = [
    "pair_id", "unit", "rgb_video", "ir_video", "ir_offset",
    "sample_index", "rgb_frame", "rgb_time_s", "ir_frame", "ir_time_s",
    "t_ir_target_s", "nearest_gap_s", "rgb_path", "ir_path", "ir_ok",
]
log = logging.getLogger("sample_dataset")


def open_video(path, kind):
    cap = cv2.VideoCapture(str(path))
    if not cap.isOpened():
        raise RuntimeError(f"cannot open {kind} video: {path}")
    return cap


def write_png(path, frame):
    if not cv2.imwrite(str(path), frame):
        raise RuntimeError(f"cannot write PNG: {path}")


def read_ir(cap, path, index, expected, previous_time=None):
    ok, frame = cap.read()
    if not ok:
        if expected > 0 and index < expected:
            raise RuntimeError(f"IR decode ended at frame {index}: {path}")
        return None
    if expected > 0 and index >= expected:
        raise RuntimeError(f"IR decoded more than {expected} reported frames: {path}")

    timestamp = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
    if not math.isfinite(timestamp):
        raise RuntimeError(f"non-finite IR timestamp at frame {index}: {path}")
    if previous_time is not None and timestamp <= previous_time:
        raise RuntimeError(f"unordered IR timestamp at frame {index}: {path}")
    return index, frame, timestamp


def sample_pair(pair, output, unit_dirs, start, step, max_gap):
    pair_id, unit = pair["pair_id"], pair["unit"]
    rgb_path = unit_dirs[unit] / pair["rgb_video"]
    ir_path = unit_dirs[unit] / pair["ir_video"]

    rgb_dir, ir_dir = output / "rgb", output / "ir"
    rgb_dir.mkdir(parents=True)
    ir_dir.mkdir()

    rows = []
    rgb = open_video(rgb_path, "RGB")
    try:
        ir = open_video(ir_path, "IR")
        try:
            frame_count = int(rgb.get(cv2.CAP_PROP_FRAME_COUNT))
            ir_count = int(ir.get(cv2.CAP_PROP_FRAME_COUNT))
            next_ir_index = 0
            current = read_ir(ir, ir_path, next_ir_index, ir_count)
            if current is None:
                raise RuntimeError(f"IR video decoded no frames: {ir_path}")
            next_ir_index += 1
            previous = None
            previous_target = None

            for index in range(start, frame_count, step):
                if not rgb.set(cv2.CAP_PROP_POS_FRAMES, index):
                    raise RuntimeError(f"cannot seek {rgb_path} to frame {index}")
                ok, rgb_frame = rgb.read()
                if not ok:
                    raise RuntimeError(f"cannot read {rgb_path} at frame {index}")

                rgb_time = rgb.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
                if not math.isfinite(rgb_time):
                    raise RuntimeError(f"non-finite RGB timestamp: {rgb_path}, frame {index}")
                target = rgb_time + pair["ir_offset"]
                if previous_target is not None and target < previous_target:
                    raise RuntimeError(f"RGB timestamps moved backwards: {rgb_path}")
                previous_target = target

                while current is not None and current[2] <= target:
                    previous = current
                    current = read_ir(
                        ir, ir_path, next_ir_index, ir_count, previous[2]
                    )
                    next_ir_index += 1

                if previous is None:
                    continue
                if current is None:
                    if target > previous[2]:
                        break
                    nearest = previous
                else:
                    nearest = (
                        current
                        if current[2] - target < target - previous[2]
                        else previous
                    )

                ir_index, ir_frame, ir_time = nearest
                gap = abs(target - ir_time)
                if gap > max_gap:
                    continue

                name = f"f{index:05d}.png"
                write_png(rgb_dir / name, rgb_frame)
                write_png(ir_dir / name, ir_frame)
                rows.append({
                    "pair_id": pair_id,
                    "unit": unit,
                    "rgb_video": pair["rgb_video"],
                    "ir_video": pair["ir_video"],
                    "ir_offset": pair["ir_offset"],
                    "sample_index": index,
                    "rgb_frame": index,
                    "rgb_time_s": round(rgb_time, 4),
                    "ir_frame": ir_index,
                    "ir_time_s": round(ir_time, 4),
                    "t_ir_target_s": round(target, 4),
                    "nearest_gap_s": round(gap, 4),
                    "rgb_path": (Path(unit) / pair_id / "rgb" / name).as_posix(),
                    "ir_path": (Path(unit) / pair_id / "ir" / name).as_posix(),
                    "ir_ok": True,
                })
        finally:
            ir.release()
    finally:
        rgb.release()

    log.info("%s: sampled %d frame pairs", pair_id, len(rows))
    return rows


def load_pairs(sync_csv, unit_dirs):
    with sync_csv.open(newline="") as file:
        reader = csv.DictReader(file)
        required = {"pair_id", "unit", "rgb_video", "ir_video", "ir_offset"}
        if not reader.fieldnames or not required.issubset(reader.fieldnames):
            raise RuntimeError(f"invalid sync.csv header: {sync_csv}")
        source = list(reader)

    pairs, seen = [], set()
    for row in source:
        pair = {key: (row[key] or "").strip() for key in required - {"ir_offset"}}
        pair_id = pair["pair_id"]
        if not pair_id or Path(pair_id).name != pair_id:
            raise RuntimeError(f"unsafe pair_id: {pair_id!r}")
        if pair_id in seen:
            raise RuntimeError(f"duplicate pair_id: {pair_id}")
        if pair["unit"] not in unit_dirs:
            raise RuntimeError(f"unknown unit for {pair_id}: {pair['unit']!r}")
        offset = row["ir_offset"].strip()
        if offset.upper() == "N/A":
            log.info("%s: skipped because IR offset is N/A", pair_id)
            continue
        try:
            pair["ir_offset"] = float(offset)
        except ValueError as error:
            raise RuntimeError(f"invalid IR offset for {pair_id}") from error
        if not math.isfinite(pair["ir_offset"]):
            raise RuntimeError(f"non-finite IR offset for {pair_id}")

        for key in ("rgb_video", "ir_video"):
            path = unit_dirs[pair["unit"]] / pair[key]
            if not path.is_file():
                raise RuntimeError(f"missing input for {pair_id}: {path}")
        seen.add(pair_id)
        pairs.append(pair)
    return pairs


def write_manifest(path, rows):
    with path.open("w", newline="") as file:
        writer = csv.DictWriter(file, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(rows)
        file.flush()
        os.fsync(file.fileno())


def commit(stage, pairs, out_root):
    """Install staged RGB/IR directories, rolling them back if commit fails."""
    installed = []
    out_root.mkdir(parents=True, exist_ok=True)
    try:
        for pair in pairs:
            relative = Path(pair["unit"]) / pair["pair_id"]
            for kind in ("rgb", "ir"):
                source = stage / "new" / relative / kind
                target = out_root / relative / kind
                backup = stage / "old" / relative / kind
                target.parent.mkdir(parents=True, exist_ok=True)
                backup.parent.mkdir(parents=True, exist_ok=True)

                had_old = target.exists()
                if had_old:
                    if target.is_symlink() or not target.is_dir():
                        raise RuntimeError(f"unexpected output path: {target}")
                    target.rename(backup)
                try:
                    source.rename(target)
                except Exception:
                    if had_old:
                        backup.rename(target)
                    raise
                installed.append((source, target, backup, had_old))

        os.replace(stage / "samples.csv", out_root / "samples.csv")
    except Exception:
        for source, target, backup, had_old in reversed(installed):
            source.parent.mkdir(parents=True, exist_ok=True)
            target.rename(source)
            if had_old:
                backup.rename(target)
        raise


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--raw-root", type=Path, default=Path("RawVideos"),
        help="root directory containing the raw unit imagery",
    )
    parser.add_argument(
        "--sync-csv", type=Path, default=Path("sync.csv"),
        help="CSV describing synchronized RGB/IR video pairs",
    )
    parser.add_argument(
        "--out-root", type=Path, default=Path("Data"),
        help="destination directory for sampled frames and samples.csv",
    )
    parser.add_argument(
        "--start", type=int, default=300,
        help="zero-based index of the first RGB frame to sample (default: 300)",
    )
    parser.add_argument(
        "--step", type=int, default=300,
        help="number of RGB frames between samples (default: 300)",
    )
    parser.add_argument(
        "--max-gap", type=float, default=10.0,
        help="maximum allowed RGB/IR timestamp gap in seconds (default: 10.0)",
    )
    args = parser.parse_args()
    if args.start < 0:
        parser.error("--start must be non-negative")
    if args.step <= 0:
        parser.error("--step must be positive")
    if not math.isfinite(args.max_gap) or args.max_gap < 0:
        parser.error("--max-gap must be a finite, non-negative number")
    return args


def main():
    args = parse_args()
    unit_dirs = {
        "Canopy": args.raw_root / "Livingston Place 18 19 20 March 2026"
        / "Canopy Unit 18 March 2026" / "DCIM" / "100MEDIA",
        "Graminoid": args.raw_root / "Livingston Place 18 19 20 March 2026"
        / "Graminoid Unit 20 March 2026" / "DCIM" / "100MEDIA",
    }
    pairs = load_pairs(args.sync_csv, unit_dirs)
    if not pairs:
        raise RuntimeError("sync.csv contains no pairs")

    args.out_root.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(
        prefix=".sample-dataset-", dir=args.out_root.parent,
        ignore_cleanup_errors=True,
    ) as temporary:
        stage = Path(temporary)
        rows = []
        for pair in pairs:
            output = stage / "new" / pair["unit"] / pair["pair_id"]
            rows.extend(
                sample_pair(
                    pair, output, unit_dirs, args.start, args.step, args.max_gap
                )
            )
        write_manifest(stage / "samples.csv", rows)
        commit(stage, pairs, args.out_root)

    log.info("complete: %d pairs, %d samples", len(pairs), len(rows))


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    try:
        main()
    except Exception as error:
        log.error("%s", error)
        sys.exit(1)