YangLiu1021 commited on
Commit
e77cfce
·
1 Parent(s): 394909b

Add downstream learning demo to dataset card

Browse files
.gitattributes CHANGED
@@ -15,3 +15,4 @@
15
  *.zst filter=lfs diff=lfs merge=lfs -text
16
  *.tar filter=lfs diff=lfs merge=lfs -text
17
  *.tar.gz filter=lfs diff=lfs merge=lfs -text
 
 
15
  *.zst filter=lfs diff=lfs merge=lfs -text
16
  *.tar filter=lfs diff=lfs merge=lfs -text
17
  *.tar.gz filter=lfs diff=lfs merge=lfs -text
18
+ *.gif filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -143,6 +143,28 @@ examples/foxglove/visual_demo.bag # ready-to-open Foxglove example
143
 
144
  `scripts/foxglove_visual.py` creates Foxglove-ready visualization bags with compressed TOFSense-M overview images, optional RGB topics, standard `sensor_msgs/PointCloud2` output at `/foxglove/livox/points`, accumulated `nav_msgs/Path` output at `/foxglove/odom/path`, MAVROS IMU topics, and odometry TF. In Foxglove, use `Fixed frame = odom` and `Display frame = odom` for the 3D panel. A ready-to-open example is available at `examples/foxglove/visual_demo.bag`. See `docs/foxglove_visualization.md`.
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  ## Limitations
147
 
148
  - No train/validation/test split is defined in this first version.
 
143
 
144
  `scripts/foxglove_visual.py` creates Foxglove-ready visualization bags with compressed TOFSense-M overview images, optional RGB topics, standard `sensor_msgs/PointCloud2` output at `/foxglove/livox/points`, accumulated `nav_msgs/Path` output at `/foxglove/odom/path`, MAVROS IMU topics, and odometry TF. In Foxglove, use `Fixed frame = odom` and `Display frame = odom` for the 3D panel. A ready-to-open example is available at `examples/foxglove/visual_demo.bag`. See `docs/foxglove_visualization.md`.
145
 
146
+ ## Downstream Learning Example
147
+
148
+ The dataset can also be used for compact non-visual motion estimation research. One example uses synchronized TOFSense-M range measurements and flight-controller IMU streams as temporal inputs, with recorded odometry as the trajectory reference. This demonstrates how the ROS timestamps, topic-level synchronization, sensor metadata, and calibration files can be used to align sparse ToF structure, inertial dynamics, and trajectory supervision.
149
+
150
+ <p align="center">
151
+ <img src="docs/assets/readme/tof_imu_realtime_inference.gif" alt="Real-time ToF and IMU inference visualization" width="86%">
152
+ </p>
153
+
154
+ | Example | Modalities | Reference signal | Purpose |
155
+ | --- | --- | --- | --- |
156
+ | ToF + IMU trajectory modeling | Six-node Nooploop TOFSense-M cascade and MAVROS IMU | Recorded odometry trajectory | Temporal motion prediction and qualitative trajectory fitting |
157
+
158
+ <p align="center">
159
+ <img src="docs/assets/readme/model_trajectory_fit_summary.png" alt="Trajectory fitting summary" width="86%">
160
+ </p>
161
+
162
+ The axis-wise error visualization below reports the fitted trajectory residuals along x, y, and z, which is useful for checking drift direction, vertical consistency, and segment-level error concentration.
163
+
164
+ <p align="center">
165
+ <img src="docs/assets/readme/model_axis_error_xyz.png" alt="Axis-wise trajectory error" width="86%">
166
+ </p>
167
+
168
  ## Limitations
169
 
170
  - No train/validation/test split is defined in this first version.
docs/assets/readme/model_axis_error_xyz.png ADDED

Git LFS Details

  • SHA256: 20ce2a212aa081e9c1738d8ce3fd466ab0f713852f5385e75c835e53a339bc0c
  • Pointer size: 131 Bytes
  • Size of remote file: 259 kB
docs/assets/readme/model_trajectory_fit_run1.png ADDED

Git LFS Details

  • SHA256: 2dddd3e9821b801f043e6916501a56c39718e637776e2b75bae4584d95e2e1d9
  • Pointer size: 131 Bytes
  • Size of remote file: 342 kB
docs/assets/readme/model_trajectory_fit_run2.png ADDED

Git LFS Details

  • SHA256: 9606b3be8914deef97b77afdf234f8ccafb46cd99067ad1337c2ac25a6e023d4
  • Pointer size: 131 Bytes
  • Size of remote file: 354 kB
docs/assets/readme/model_trajectory_fit_run3.png ADDED

Git LFS Details

  • SHA256: 2dddd3e9821b801f043e6916501a56c39718e637776e2b75bae4584d95e2e1d9
  • Pointer size: 131 Bytes
  • Size of remote file: 342 kB
docs/assets/readme/model_trajectory_fit_summary.png ADDED

Git LFS Details

  • SHA256: 87d4e04064da732252d8824d8250fcd3407cedfd9daa81c2c7770993d97c8f8a
  • Pointer size: 131 Bytes
  • Size of remote file: 148 kB
docs/assets/readme/tof_imu_realtime_inference.gif ADDED

Git LFS Details

  • SHA256: 670dff628eaa67b4510b13ca220ca8d6ca8cf69f75171fd446a2aa65178f16aa
  • Pointer size: 132 Bytes
  • Size of remote file: 1.81 MB
scripts/foxglove_visualization_bridge.py DELETED
@@ -1,641 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Build a compact Foxglove-friendly rosbag from the raw dataset bags.
3
-
4
- The raw bags are the source of truth. This script is only for visualization.
5
- It keeps a small set of original topics, adds throttled compressed ToF heatmaps,
6
- and can inject dynamic TF from odometry for Foxglove 3D view.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import argparse
12
- import glob
13
- import math
14
- import os
15
- from pathlib import Path
16
-
17
- cv2 = None
18
- np = None
19
-
20
-
21
- TOF_CASCADE_TOPIC = "/nlink_tofsensem_cascade"
22
- TOF_FRAME0_TOPIC = "/nlink_tofsensem_frame0"
23
-
24
- ODOM_CANDIDATE_TOPICS = (
25
- "/fusion_odometry/current_point_odom",
26
- "/fusion_odometry/lazy_point_odom",
27
- "/ekf_quat/ekf_odom",
28
- "/ekf/ekf_odom",
29
- "/Odometry",
30
- "/vrpn_client_node/crazy/pose",
31
- )
32
-
33
- COMPACT_COPY_TOPICS = (
34
- "/tf_static",
35
- "/fusion_odometry/current_point_odom",
36
- "/fusion_odometry/lazy_point_odom",
37
- "/ekf_quat/ekf_odom",
38
- "/mavros/imu/data",
39
- "/mavros/imu/data_raw",
40
- "/livox/imu",
41
- TOF_CASCADE_TOPIC,
42
- TOF_FRAME0_TOPIC,
43
- )
44
-
45
-
46
- def import_ros_deps():
47
- try:
48
- import genpy
49
- import rosbag
50
- from geometry_msgs.msg import TransformStamped
51
- from sensor_msgs.msg import CompressedImage, Image
52
- from tf2_msgs.msg import TFMessage
53
- except ImportError as exc:
54
- raise RuntimeError(
55
- "ROS1 Python dependencies are not available. Run this script inside a ROS1 environment "
56
- "that can import rosbag, geometry_msgs, sensor_msgs, and tf2_msgs."
57
- ) from exc
58
- return genpy, rosbag, TransformStamped, CompressedImage, Image, TFMessage
59
-
60
-
61
- def import_visual_deps():
62
- global cv2, np
63
- try:
64
- import cv2 as cv2_module
65
- import numpy as np_module
66
- except ImportError as exc:
67
- raise RuntimeError(
68
- "Visualization dependencies are not available. Install python3-opencv and numpy "
69
- "inside the ROS1 environment used to run this script."
70
- ) from exc
71
- cv2 = cv2_module
72
- np = np_module
73
-
74
-
75
- def is_valid_stamp(stamp) -> bool:
76
- return stamp is not None and hasattr(stamp, "to_sec") and stamp.to_sec() > 0.0
77
-
78
-
79
- def select_time(stamp, fallback_time):
80
- return stamp if is_valid_stamp(stamp) else fallback_time
81
-
82
-
83
- def parse_topic_csv(text: str) -> list[str]:
84
- if not text:
85
- return []
86
- return [item.strip() for item in text.split(",") if item.strip()]
87
-
88
-
89
- def bag_stem(path: str) -> str:
90
- name = Path(path).name
91
- return name[:-4] if name.endswith(".bag") else name
92
-
93
-
94
- class RateLimiter:
95
- def __init__(self, hz: float):
96
- self.period = 0.0 if hz <= 0.0 else 1.0 / float(hz)
97
- self.next_time = None
98
-
99
- def allow(self, stamp) -> bool:
100
- if self.period <= 0.0:
101
- return True
102
- if not is_valid_stamp(stamp):
103
- return True
104
- now = stamp.to_sec()
105
- if self.next_time is None or now >= self.next_time:
106
- self.next_time = now + self.period
107
- return True
108
- return False
109
-
110
-
111
- class TofHeatmapRenderer:
112
- def __init__(
113
- self,
114
- compressed_image_cls,
115
- raw_image_cls,
116
- max_nodes: int,
117
- grid_size: int,
118
- cell_px: int,
119
- min_distance_mm: float,
120
- max_distance_mm: float,
121
- valid_status: int,
122
- colormap_name: str,
123
- output_format: str,
124
- jpeg_quality: int,
125
- draw_distance_text: bool,
126
- show_tables: bool,
127
- include_overview_image: bool,
128
- include_node_images: bool,
129
- overview_topic: str,
130
- node_topic_prefix: str,
131
- ):
132
- self.CompressedImage = compressed_image_cls
133
- self.Image = raw_image_cls
134
- self.max_nodes = max(1, int(max_nodes))
135
- self.grid_size = int(grid_size)
136
- self.cell_px = int(cell_px)
137
- self.min_distance_mm = float(min_distance_mm)
138
- self.max_distance_mm = float(max_distance_mm)
139
- self.valid_status = int(valid_status)
140
- self.colormap = getattr(cv2, colormap_name, cv2.COLORMAP_TURBO)
141
- self.output_format = output_format
142
- self.jpeg_quality = int(jpeg_quality)
143
- self.draw_distance_text = bool(draw_distance_text)
144
- self.show_tables = bool(show_tables)
145
- self.include_overview_image = bool(include_overview_image)
146
- self.include_node_images = bool(include_node_images)
147
- self.overview_topic = overview_topic
148
- self.node_topic_prefix = node_topic_prefix
149
- self.latest_frame0_panels = {}
150
-
151
- @staticmethod
152
- def get_nodes(msg) -> list:
153
- if hasattr(msg, "nodes"):
154
- return list(msg.nodes)
155
- if hasattr(msg, "node"):
156
- return list(msg.node)
157
- return []
158
-
159
- def reshape_or_pad(self, values, fill_value: float = 0.0) -> np.ndarray:
160
- target = self.grid_size * self.grid_size
161
- data = list(values[:target])
162
- if len(data) < target:
163
- data.extend([fill_value] * (target - len(data)))
164
- return np.array(data, dtype=np.float32).reshape(self.grid_size, self.grid_size)
165
-
166
- def render_numeric_table(self, grid, title: str, cell_w: int = 44, cell_h: int = 20) -> np.ndarray:
167
- rows, cols = grid.shape
168
- header_h = 24
169
- width = cols * cell_w
170
- height = header_h + rows * cell_h
171
- image = np.full((height, width, 3), 248, dtype=np.uint8)
172
-
173
- cv2.putText(image, title, (5, 17), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (20, 20, 20), 1, cv2.LINE_AA)
174
- for row in range(rows + 1):
175
- y = header_h + row * cell_h
176
- cv2.line(image, (0, y), (width, y), (180, 180, 180), 1)
177
- for col in range(cols + 1):
178
- x = col * cell_w
179
- cv2.line(image, (x, header_h), (x, height), (180, 180, 180), 1)
180
-
181
- for row in range(rows):
182
- for col in range(cols):
183
- text = str(int(grid[row, col]))
184
- x = col * cell_w + 3
185
- y = header_h + row * cell_h + 14
186
- cv2.putText(image, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.34, (30, 30, 30), 1, cv2.LINE_AA)
187
- return image
188
-
189
- def render_node(self, node_id: int, pixels, stamp) -> np.ndarray:
190
- distances = [float(getattr(pixel, "dis", 0.0)) for pixel in pixels]
191
- statuses = [int(getattr(pixel, "dis_status", 255)) for pixel in pixels]
192
- strengths = [int(getattr(pixel, "signal_strength", 0)) for pixel in pixels]
193
-
194
- dis = self.reshape_or_pad(distances, fill_value=0.0)
195
- status = self.reshape_or_pad(statuses, fill_value=255).astype(np.int32)
196
- strength = self.reshape_or_pad(strengths, fill_value=0).astype(np.int32)
197
- valid = np.logical_and(status == self.valid_status, dis > 0.0)
198
-
199
- clipped = np.clip(dis, self.min_distance_mm, self.max_distance_mm)
200
- scale = max(1e-6, self.max_distance_mm - self.min_distance_mm)
201
- normalized = ((clipped - self.min_distance_mm) / scale * 255.0).astype(np.uint8)
202
- heat = cv2.applyColorMap(normalized, self.colormap)
203
- heat = cv2.cvtColor(heat, cv2.COLOR_BGR2RGB)
204
- heat[~valid] = np.array([88, 88, 88], dtype=np.uint8)
205
-
206
- tile_size = self.grid_size * self.cell_px
207
- tile = cv2.resize(heat, (tile_size, tile_size), interpolation=cv2.INTER_NEAREST)
208
- for idx in range(self.grid_size + 1):
209
- offset = idx * self.cell_px
210
- cv2.line(tile, (offset, 0), (offset, tile.shape[0]), (255, 255, 255), 1)
211
- cv2.line(tile, (0, offset), (tile.shape[1], offset), (255, 255, 255), 1)
212
-
213
- if self.draw_distance_text:
214
- for row in range(self.grid_size):
215
- for col in range(self.grid_size):
216
- text = str(int(dis[row, col]))
217
- x = col * self.cell_px + 3
218
- y = row * self.cell_px + int(self.cell_px * 0.65)
219
- color = (255, 255, 255) if valid[row, col] else (220, 220, 220)
220
- cv2.putText(tile, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.32, color, 1, cv2.LINE_AA)
221
-
222
- body = tile
223
- if self.show_tables:
224
- status_table = self.render_numeric_table(status, "dis_status")
225
- strength_table = self.render_numeric_table(strength, "signal_strength")
226
- table_w = max(status_table.shape[1], strength_table.shape[1])
227
-
228
- def pad_width(image, width):
229
- if image.shape[1] == width:
230
- return image
231
- pad = np.full((image.shape[0], width - image.shape[1], 3), 248, dtype=np.uint8)
232
- return np.concatenate([image, pad], axis=1)
233
-
234
- status_table = pad_width(status_table, table_w)
235
- strength_table = pad_width(strength_table, table_w)
236
- table_gap = np.full((8, table_w, 3), 245, dtype=np.uint8)
237
- tables = np.concatenate([status_table, table_gap, strength_table], axis=0)
238
-
239
- content_h = max(tile.shape[0], tables.shape[0])
240
- tile_pad = np.full((content_h, tile.shape[1], 3), 245, dtype=np.uint8)
241
- table_pad = np.full((content_h, tables.shape[1], 3), 245, dtype=np.uint8)
242
- tile_pad[:tile.shape[0], :tile.shape[1], :] = tile
243
- table_pad[:tables.shape[0], :tables.shape[1], :] = tables
244
- gap = np.full((content_h, 10, 3), 245, dtype=np.uint8)
245
- body = np.concatenate([tile_pad, gap, table_pad], axis=1)
246
-
247
- header_h = 32
248
- panel = np.full((header_h + body.shape[0], body.shape[1], 3), 245, dtype=np.uint8)
249
- valid_ratio = float(np.count_nonzero(valid)) / float(valid.size) if valid.size else 0.0
250
- title = "node {} dis(mm) heatmap valid {:.0f}%".format(node_id, valid_ratio * 100.0)
251
- if is_valid_stamp(stamp):
252
- title += " t={:.2f}".format(stamp.to_sec())
253
- cv2.putText(panel, title, (6, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (20, 20, 20), 1, cv2.LINE_AA)
254
- panel[header_h:, :, :] = body
255
- return panel
256
-
257
- @staticmethod
258
- def render_overview(node_panels):
259
- if not node_panels:
260
- return np.full((260, 420, 3), 245, dtype=np.uint8)
261
-
262
- cols = min(3, len(node_panels))
263
- rows = int(math.ceil(len(node_panels) / float(cols)))
264
- gap = 12
265
- top = 38
266
- tile_h = max(panel.shape[0] for panel in node_panels)
267
- tile_w = max(panel.shape[1] for panel in node_panels)
268
- canvas_h = top + rows * tile_h + max(0, rows - 1) * gap + 12
269
- canvas_w = cols * tile_w + max(0, cols - 1) * gap + 12
270
- canvas = np.full((canvas_h, canvas_w, 3), 245, dtype=np.uint8)
271
- cv2.putText(
272
- canvas,
273
- "TOFSense-M cascade heatmap",
274
- (6, 25),
275
- cv2.FONT_HERSHEY_SIMPLEX,
276
- 0.72,
277
- (20, 20, 20),
278
- 2,
279
- cv2.LINE_AA,
280
- )
281
- for idx, panel in enumerate(node_panels):
282
- row = idx // cols
283
- col = idx % cols
284
- y = top + row * (tile_h + gap)
285
- x = 6 + col * (tile_w + gap)
286
- canvas[y:y + panel.shape[0], x:x + panel.shape[1], :] = panel
287
- return canvas
288
-
289
- def to_ros_image(self, image_rgb: np.ndarray, stamp):
290
- if self.output_format == "raw":
291
- msg = self.Image()
292
- if is_valid_stamp(stamp):
293
- msg.header.stamp = stamp
294
- msg.height = image_rgb.shape[0]
295
- msg.width = image_rgb.shape[1]
296
- msg.encoding = "rgb8"
297
- msg.is_bigendian = 0
298
- msg.step = msg.width * 3
299
- msg.data = np.ascontiguousarray(image_rgb).tobytes()
300
- return msg
301
-
302
- msg = self.CompressedImage()
303
- if is_valid_stamp(stamp):
304
- msg.header.stamp = stamp
305
- image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)
306
- if self.output_format == "png":
307
- ok, encoded = cv2.imencode(".png", image_bgr, [cv2.IMWRITE_PNG_COMPRESSION, 3])
308
- msg.format = "png"
309
- else:
310
- ok, encoded = cv2.imencode(".jpg", image_bgr, [cv2.IMWRITE_JPEG_QUALITY, self.jpeg_quality])
311
- msg.format = "jpeg"
312
- if not ok:
313
- raise RuntimeError("failed to encode ToF heatmap")
314
- msg.data = encoded.tobytes()
315
- return msg
316
-
317
- def consume_cascade(self, msg, fallback_time) -> list[tuple[str, object, object]]:
318
- stamp = fallback_time
319
- if hasattr(msg, "header") and hasattr(msg.header, "stamp"):
320
- stamp = select_time(msg.header.stamp, fallback_time)
321
-
322
- node_panels = []
323
- node_outputs = []
324
- for idx, node in enumerate(self.get_nodes(msg)[:self.max_nodes]):
325
- node_id = int(getattr(node, "id", idx))
326
- panel = self.render_node(node_id, list(getattr(node, "pixels", [])), stamp)
327
- node_panels.append(panel)
328
- if self.include_node_images:
329
- node_outputs.append((
330
- self.node_topic_prefix + str(node_id),
331
- self.to_ros_image(panel, stamp),
332
- select_time(stamp, fallback_time),
333
- ))
334
-
335
- outputs = []
336
- if self.include_overview_image:
337
- overview = self.render_overview(node_panels)
338
- outputs.append((self.overview_topic, self.to_ros_image(overview, stamp), select_time(stamp, fallback_time)))
339
- outputs.extend(node_outputs)
340
- return outputs
341
-
342
- def consume_frame0(self, msg, fallback_time) -> list[tuple[str, object, object]]:
343
- stamp = fallback_time
344
- if hasattr(msg, "header") and hasattr(msg.header, "stamp"):
345
- stamp = select_time(msg.header.stamp, fallback_time)
346
-
347
- node_id = int(getattr(msg, "id", 0))
348
- panel = self.render_node(node_id, list(getattr(msg, "pixels", [])), stamp)
349
- self.latest_frame0_panels[node_id] = panel
350
-
351
- ordered_ids = sorted(self.latest_frame0_panels.keys())[:self.max_nodes]
352
- outputs = []
353
- if self.include_overview_image:
354
- overview = self.render_overview([self.latest_frame0_panels[item] for item in ordered_ids])
355
- outputs.append((self.overview_topic, self.to_ros_image(overview, stamp), select_time(stamp, fallback_time)))
356
- if self.include_node_images:
357
- outputs.append((self.node_topic_prefix + str(node_id), self.to_ros_image(panel, stamp), select_time(stamp, fallback_time)))
358
- return outputs
359
-
360
-
361
- class Converter:
362
- def __init__(self, args):
363
- self.args = args
364
- import_visual_deps()
365
- self.genpy, self.rosbag, self.TransformStamped, self.CompressedImage, self.Image, self.TFMessage = import_ros_deps()
366
- self.input_bag = Path(args.input_bag).resolve()
367
- self.output_bag = self.resolve_output_bag()
368
- self.tof_limiter = RateLimiter(args.tof_rate_hz)
369
- self.tf_limiter = RateLimiter(args.tf_rate_hz)
370
- self.copy_topics = self.resolve_copy_topics()
371
- self.renderer = TofHeatmapRenderer(
372
- compressed_image_cls=self.CompressedImage,
373
- raw_image_cls=self.Image,
374
- max_nodes=args.tof_max_nodes,
375
- grid_size=args.tof_grid_size,
376
- cell_px=args.tof_cell_px,
377
- min_distance_mm=args.tof_min_dis,
378
- max_distance_mm=args.tof_max_dis,
379
- valid_status=args.tof_valid_status,
380
- colormap_name=args.tof_colormap,
381
- output_format=args.tof_output_format,
382
- jpeg_quality=args.tof_jpeg_quality,
383
- draw_distance_text=args.tof_draw_distance_text,
384
- show_tables=args.tof_show_tables,
385
- include_overview_image=args.tof_image_mode in ("overview", "both"),
386
- include_node_images=args.tof_image_mode in ("nodes", "both"),
387
- overview_topic=args.tof_overview_topic,
388
- node_topic_prefix=args.tof_node_topic_prefix,
389
- )
390
-
391
- def resolve_output_bag(self) -> Path:
392
- if self.args.output_bag:
393
- output = Path(self.args.output_bag).resolve()
394
- else:
395
- output_dir = Path(self.args.output_dir).resolve() if self.args.output_dir else self.input_bag.parent / "foxglove"
396
- output = output_dir / (bag_stem(str(self.input_bag)) + "_foxglove_compact.bag")
397
- if output == self.input_bag:
398
- raise RuntimeError("output bag path must be different from input bag path")
399
- output.parent.mkdir(parents=True, exist_ok=True)
400
- if output.exists():
401
- if self.args.force:
402
- output.unlink()
403
- else:
404
- raise RuntimeError("output bag already exists: {} (use --force)".format(output))
405
- return output
406
-
407
- def resolve_copy_topics(self) -> set[str]:
408
- mode = self.args.copy_mode
409
- if mode == "none":
410
- topics = set()
411
- elif mode == "compact":
412
- topics = set(COMPACT_COPY_TOPICS)
413
- elif mode == "custom":
414
- topics = set()
415
- else:
416
- topics = None
417
-
418
- if topics is not None:
419
- topics.update(parse_topic_csv(self.args.copy_topics))
420
- topics.update(parse_topic_csv(self.args.keep_topics))
421
- return topics
422
-
423
- def choose_topic(self, topic_info, requested, candidates, label):
424
- if requested and requested != "auto":
425
- if requested not in topic_info:
426
- raise RuntimeError("{} topic not found in bag: {}".format(label, requested))
427
- return requested
428
- for topic in candidates:
429
- if topic in topic_info:
430
- return topic
431
- return None
432
-
433
- def build_tf_from_pose(self, msg, bag_time):
434
- if hasattr(msg, "pose") and hasattr(msg.pose, "pose"):
435
- pose = msg.pose.pose
436
- stamp = select_time(msg.header.stamp, bag_time)
437
- parent = self.args.tf_parent_frame or getattr(msg.header, "frame_id", "") or "map"
438
- elif hasattr(msg, "pose"):
439
- pose = msg.pose
440
- stamp = select_time(msg.header.stamp, bag_time)
441
- parent = self.args.tf_parent_frame or getattr(msg.header, "frame_id", "") or "map"
442
- else:
443
- return None, None
444
-
445
- transform = self.TransformStamped()
446
- transform.header.stamp = stamp
447
- transform.header.frame_id = parent
448
- transform.child_frame_id = self.args.tf_child_frame
449
- transform.transform.translation.x = pose.position.x
450
- transform.transform.translation.y = pose.position.y
451
- transform.transform.translation.z = pose.position.z
452
- transform.transform.rotation.x = pose.orientation.x
453
- transform.transform.rotation.y = pose.orientation.y
454
- transform.transform.rotation.z = pose.orientation.z
455
- transform.transform.rotation.w = pose.orientation.w
456
- return self.TFMessage(transforms=[transform]), stamp
457
-
458
- def output_compression(self):
459
- if self.args.bag_compression == "none":
460
- return "none"
461
- return self.args.bag_compression
462
-
463
- def resolve_time_window(self, in_bag):
464
- if self.args.start_offset_sec is None and self.args.duration_sec is None:
465
- return None, None
466
-
467
- bag_start = float(in_bag.get_start_time())
468
- bag_end = float(in_bag.get_end_time())
469
- start_offset = float(self.args.start_offset_sec or 0.0)
470
- start_sec = bag_start + max(0.0, start_offset)
471
- if self.args.duration_sec is None:
472
- end_sec = bag_end
473
- else:
474
- end_sec = min(bag_end, start_sec + max(0.0, float(self.args.duration_sec)))
475
- if start_sec >= end_sec:
476
- raise RuntimeError("empty time window: start={} end={}".format(start_sec, end_sec))
477
- return self.genpy.Time.from_sec(start_sec), self.genpy.Time.from_sec(end_sec)
478
-
479
- def write_static_tf_for_window(self, in_bag, out_bag, window_start):
480
- if window_start is None:
481
- return 0
482
- if self.copy_topics is not None and "/tf_static" not in self.copy_topics:
483
- return 0
484
- written = 0
485
- for _, msg, _ in in_bag.read_messages(topics=["/tf_static"]):
486
- out_bag.write("/tf_static", msg, t=window_start)
487
- written += 1
488
- return written
489
-
490
- def convert(self):
491
- if not self.input_bag.is_file():
492
- raise RuntimeError("input bag does not exist: {}".format(self.input_bag))
493
-
494
- processed = 0
495
- copied = 0
496
- tof_images = 0
497
- tf_inserted = 0
498
-
499
- with self.rosbag.Bag(str(self.input_bag), "r") as in_bag:
500
- window_start, window_end = self.resolve_time_window(in_bag)
501
- topic_info = in_bag.get_type_and_topic_info().topics
502
- tof_topic = self.choose_topic(
503
- topic_info,
504
- self.args.tof_input_topic,
505
- (TOF_CASCADE_TOPIC, TOF_FRAME0_TOPIC),
506
- "ToF",
507
- )
508
- odom_topic = self.choose_topic(topic_info, self.args.odom_input_topic, ODOM_CANDIDATE_TOPICS, "odometry")
509
-
510
- read_topics = None
511
- if self.copy_topics is not None:
512
- read_topics = set(topic for topic in self.copy_topics if topic in topic_info)
513
- if tof_topic:
514
- read_topics.add(tof_topic)
515
- if self.args.inject_dynamic_tf and odom_topic:
516
- read_topics.add(odom_topic)
517
- read_topics = sorted(read_topics)
518
-
519
- print("[INFO] input bag: {}".format(self.input_bag))
520
- print("[INFO] output bag: {}".format(self.output_bag))
521
- print("[INFO] copy mode: {}".format(self.args.copy_mode))
522
- print("[INFO] ToF topic: {}".format(tof_topic or "not found"))
523
- print("[INFO] ToF image mode: {} format={} rate={}Hz".format(
524
- self.args.tof_image_mode, self.args.tof_output_format, self.args.tof_rate_hz
525
- ))
526
- print("[INFO] odometry topic for TF: {}".format(odom_topic or "not found"))
527
- if window_start is not None:
528
- print("[INFO] time window: {:.3f} -> {:.3f} ({:.3f}s)".format(
529
- window_start.to_sec(), window_end.to_sec(), window_end.to_sec() - window_start.to_sec()
530
- ))
531
-
532
- with self.rosbag.Bag(str(self.output_bag), "w", compression=self.output_compression()) as out_bag:
533
- copied += self.write_static_tf_for_window(in_bag, out_bag, window_start)
534
-
535
- for topic, msg, bag_time in in_bag.read_messages(
536
- topics=read_topics,
537
- start_time=window_start,
538
- end_time=window_end,
539
- ):
540
- processed += 1
541
-
542
- if self.copy_topics is None or topic in self.copy_topics:
543
- out_bag.write(topic, msg, t=bag_time)
544
- copied += 1
545
-
546
- if self.args.inject_dynamic_tf and odom_topic and topic == odom_topic and self.tf_limiter.allow(bag_time):
547
- tf_msg, tf_time = self.build_tf_from_pose(msg, bag_time)
548
- if tf_msg is not None:
549
- out_bag.write(self.args.tf_topic, tf_msg, t=tf_time)
550
- tf_inserted += 1
551
-
552
- if tof_topic and topic == tof_topic and self.args.tof_image_mode != "none" and self.tof_limiter.allow(bag_time):
553
- if topic == TOF_CASCADE_TOPIC or hasattr(msg, "nodes") or hasattr(msg, "node"):
554
- outputs = self.renderer.consume_cascade(msg, bag_time)
555
- else:
556
- outputs = self.renderer.consume_frame0(msg, bag_time)
557
- for out_topic, out_msg, out_time in outputs:
558
- out_bag.write(out_topic, out_msg, t=out_time)
559
- tof_images += 1
560
-
561
- if processed % 10000 == 0:
562
- print("[RUNNING] processed={} copied={} tof_images={} tf={}".format(
563
- processed, copied, tof_images, tf_inserted
564
- ))
565
-
566
- input_size = self.input_bag.stat().st_size
567
- output_size = self.output_bag.stat().st_size
568
- ratio = float(output_size) / float(input_size) if input_size else 0.0
569
- print("[DONE] processed={} copied={} tof_images={} tf={}".format(processed, copied, tof_images, tf_inserted))
570
- print("[DONE] input_size={:.2f} GB output_size={:.2f} GB ratio={:.3f}".format(
571
- input_size / 1e9, output_size / 1e9, ratio
572
- ))
573
-
574
-
575
- def parse_args():
576
- parser = argparse.ArgumentParser(description="Create a compact Foxglove visualization rosbag.")
577
- parser.add_argument("--input-bag", required=True, help="Input ROS1 bag")
578
- parser.add_argument("--output-bag", default=None, help="Output ROS1 bag")
579
- parser.add_argument("--output-dir", default=None, help="Output directory when --output-bag is omitted")
580
- parser.add_argument("--force", action="store_true", help="Overwrite output bag")
581
- parser.add_argument("--start-offset-sec", type=float, default=None, help="Start offset from input bag start")
582
- parser.add_argument("--duration-sec", type=float, default=None, help="Maximum duration to convert")
583
-
584
- parser.add_argument(
585
- "--copy-mode",
586
- choices=("compact", "all", "none", "custom"),
587
- default="compact",
588
- help="Original topic copy policy. compact avoids camera/lidar by default.",
589
- )
590
- parser.add_argument("--copy-topics", default="", help="Comma-separated extra original topics to copy")
591
- parser.add_argument(
592
- "--keep-topics",
593
- default="",
594
- help="Alias for --copy-topics. Use with --copy-mode custom to keep exactly the listed original topics.",
595
- )
596
- parser.add_argument("--bag-compression", choices=("none", "bz2", "lz4"), default="bz2")
597
-
598
- parser.add_argument("--tof-input-topic", default="auto")
599
- parser.add_argument("--tof-image-mode", choices=("overview", "nodes", "both", "none"), default="overview")
600
- parser.add_argument("--tof-output-format", choices=("jpeg", "png", "raw"), default="jpeg")
601
- parser.add_argument(
602
- "--tof-rate-hz",
603
- type=float,
604
- default=15.0,
605
- help="Visualization image rate. 15 matches TOFSense-M 8x8 nominal rate; 0 disables throttling.",
606
- )
607
- parser.add_argument("--tof-overview-topic", default="/foxglove/tof/overview/compressed")
608
- parser.add_argument("--tof-node-topic-prefix", default="/foxglove/tof/node_")
609
- parser.add_argument("--tof-max-nodes", type=int, default=6)
610
- parser.add_argument("--tof-grid-size", type=int, default=8)
611
- parser.add_argument("--tof-cell-px", type=int, default=28)
612
- parser.add_argument("--tof-min-dis", type=float, default=0.0)
613
- parser.add_argument("--tof-max-dis", type=float, default=5000.0)
614
- parser.add_argument("--tof-valid-status", type=int, default=0)
615
- parser.add_argument("--tof-colormap", default="COLORMAP_TURBO")
616
- parser.add_argument("--tof-jpeg-quality", type=int, default=82)
617
- parser.add_argument("--tof-draw-distance-text", dest="tof_draw_distance_text", action="store_true")
618
- parser.add_argument("--tof-hide-distance-text", dest="tof_draw_distance_text", action="store_false")
619
- parser.set_defaults(tof_draw_distance_text=True)
620
- parser.add_argument("--tof-show-tables", dest="tof_show_tables", action="store_true")
621
- parser.add_argument("--tof-hide-tables", dest="tof_show_tables", action="store_false")
622
- parser.set_defaults(tof_show_tables=True)
623
-
624
- parser.add_argument("--inject-dynamic-tf", dest="inject_dynamic_tf", action="store_true")
625
- parser.add_argument("--no-inject-dynamic-tf", dest="inject_dynamic_tf", action="store_false")
626
- parser.set_defaults(inject_dynamic_tf=True)
627
- parser.add_argument("--odom-input-topic", default="auto")
628
- parser.add_argument("--tf-rate-hz", type=float, default=10.0, help="0 disables TF throttling")
629
- parser.add_argument("--tf-topic", default="/tf")
630
- parser.add_argument("--tf-parent-frame", default="map")
631
- parser.add_argument("--tf-child-frame", default="base_link")
632
- return parser.parse_args()
633
-
634
-
635
- def main():
636
- args = parse_args()
637
- Converter(args).convert()
638
-
639
-
640
- if __name__ == "__main__":
641
- main()