File size: 4,752 Bytes
12819c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Take a .vrs file and create a sibling directory called "frames" that contains the frames.

Usage:
  python save_vrs_frames.py /path/to/recording.vrs

Behavior:
- Saves frames from a single image stream (default preference: camera-rgb).
- Output directory is: <dir_of_vrs>/frames
- Output images are: frame_000000.jpg, frame_000001.jpg, ...
- Also writes: <dir_of_vrs>/frames/timestamps.csv (frame_idx, timestamp_ns, stream_label)

Requires:
  pip install projectaria-tools opencv-python
"""

import os
import sys
import csv
import cv2
from projectaria_tools.core import data_provider


PREFERRED_LABELS = [
    "camera-rgb",
    "camera-slam-left",
    "camera-slam-right",
]


def pick_stream_id(provider):
    """
    Pick the first available image stream from PREFERRED_LABELS.
    Returns (stream_id, label).
    """
    for label in PREFERRED_LABELS:
        sid = provider.get_stream_id_from_label(label)
        if sid is not None:
            # sanity: can we read at least one image?
            try:
                n = provider.get_num_data(sid)
                if n <= 0:
                    continue
                img, rec = provider.get_image_data_by_index(sid, 0)
                if img is not None and rec is not None:
                    return sid, label
            except Exception:
                continue

    # If none of the preferred labels exist, try *any* stream in get_all_streams()
    # and see if it yields images.
    try:
        streams = provider.get_all_streams()  # list-like
    except Exception as e:
        raise RuntimeError(
            "Could not find an image stream. Tried camera-rgb and slam cameras, "
            "and provider.get_all_streams() was unavailable."
        ) from e

    for s in streams:
        # best-effort to obtain the stream id and label from whatever object type this is
        sid = None
        label = None
        for attr in ("stream_id", "id", "streamId"):
            if hasattr(s, attr):
                sid = getattr(s, attr)
                break
        for attr in ("label", "name"):
            if hasattr(s, attr):
                label = getattr(s, attr)
                break
        if sid is None:
            continue

        try:
            n = provider.get_num_data(sid)
            if n <= 0:
                continue
            img, rec = provider.get_image_data_by_index(sid, 0)
            if img is not None and rec is not None:
                return sid, (label or str(sid))
        except Exception:
            continue

    raise RuntimeError("No image stream found in this VRS (nothing readable as images).")


def to_numpy(img_data):
    """
    projectaria_tools sometimes returns an object with .to_numpy_array()
    """
    if hasattr(img_data, "to_numpy_array"):
        return img_data.to_numpy_array()
    return img_data


def main():
    if len(sys.argv) != 2:
        print("Usage: python save_vrs_frames.py /path/to/recording.vrs")
        sys.exit(2)

    vrs_path = sys.argv[1]
    if not (os.path.isfile(vrs_path) and vrs_path.lower().endswith(".vrs")):
        raise FileNotFoundError(f"Not a .vrs file: {vrs_path}")

    vrs_dir = os.path.dirname(os.path.abspath(vrs_path))
    out_dir = os.path.join(vrs_dir, "frames")
    os.makedirs(out_dir, exist_ok=True)

    provider = data_provider.create_vrs_data_provider(vrs_path)

    stream_id, stream_label = pick_stream_id(provider)
    num = provider.get_num_data(stream_id)

    ts_csv_path = os.path.join(out_dir, "timestamps.csv")
    with open(ts_csv_path, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["frame_idx", "timestamp_ns", "stream_label"])

        for i in range(num):
            img_data, rec = provider.get_image_data_by_index(stream_id, i)
            if img_data is None or rec is None:
                continue

            img = to_numpy(img_data)

            # If RGB -> convert to BGR for OpenCV saving
            if img.ndim == 3 and img.shape[2] == 3:
                img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

            out_path = os.path.join(out_dir, f"frame_{i:06d}.jpg")
            ok = cv2.imwrite(out_path, img, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
            if not ok:
                raise RuntimeError(f"Failed to write: {out_path}")

            ts_ns = int(getattr(rec, "capture_timestamp_ns", -1))
            w.writerow([i, ts_ns, stream_label])

            if i % 500 == 0:
                print(f"  saved {i}/{num} frames...")

    print(f"[OK] VRS: {vrs_path}")
    print(f"[OK] Stream: {stream_label} (id={stream_id})")
    print(f"[OK] Frames saved to: {out_dir}")
    print(f"[OK] Timestamps: {ts_csv_path}")


if __name__ == "__main__":
    main()