#!/usr/bin/env python3 """Draw SOVIS samples: camera frame (with fish boxes) next to the synchronized sonar fan. The sonar fan shows range rings, the approximate horizontal field of view of the camera (dashed cyan, from sovis.camera_x_to_bearing), the bearing span of each camera fish box and the sonar fish boxes. Examples python tools/show_samples.py --repo /SOVIS --config mini --n 6 --out samples.jpg python tools/show_samples.py --data-dir data/frames/train --where seabed --n 8 python tools/show_samples.py --repo /SOVIS --config fish --split test --n 6 MIT licence. Needs: numpy, opencv-python, datasets (for --repo) or pyarrow (for --data-dir). """ import argparse import io import sys from pathlib import Path import cv2 import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) import sovis # noqa: E402 PANEL_H = 360 def to_array(img): """Image column value (PIL image, or {'bytes': ...} dict when read with pyarrow) -> numpy array.""" if isinstance(img, dict): from PIL import Image img = Image.open(io.BytesIO(img["bytes"])) return np.asarray(img) def draw_pair(row, panel_h=PANEL_H): """Camera frame next to the sonar fan, both panel_h pixels high. Camera fish boxes are green when they have a matched sonar box and yellow otherwise; on the fan, thin lines of the same colour mark each camera box's bearing span (sovis.camera_x_to_bearing) and green arcs mark the sonar boxes. The dashed cyan lines are the camera's approximate field of view.""" cam = cv2.cvtColor(to_array(row["camera"]), cv2.COLOR_RGB2BGR) polar = to_array(row["sonar"]) bearings = sovis.sonar_bearings(row["sonar_mode"]) rres = row["sonar_range_resolution_m"] max_r = polar.shape[0] * rres fan, valid = sovis.polar_to_fan(polar, bearings, rres, size=panel_h) fan = cv2.applyColorMap(fan, cv2.COLORMAP_INFERNO) fan[~valid] = 40 def to_px(bearing_deg, range_m): x, y = sovis.fan_xy(bearing_deg, range_m, panel_h, fan.shape[1], max_r) return int(x), int(y) step = 1 if max_r <= 10 else 5 if max_r <= 40 else 20 # range rings for r in np.arange(step, max_r + 1e-6, step): pts = np.array([to_px(b, r) for b in np.linspace(bearings[0], bearings[-1], 60)]) cv2.polylines(fan, [pts], False, (90, 90, 90), 1) cv2.putText(fan, f"{r:g} m", to_px(bearings[-1] + 2, r), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (160, 160, 160), 1) for x in (0, cam.shape[1] - 1): # approximate camera field of view b = float(sovis.camera_x_to_bearing(x)) for r0 in np.arange(0, max_r, max_r / 20)[::2]: cv2.line(fan, to_px(b, r0), to_px(b, r0 + max_r / 20), (255, 255, 0), 1, cv2.LINE_AA) for box in row.get("fish_boxes") or []: matched = box["sonar_range_min_m"] is not None and np.isfinite(box["sonar_range_min_m"]) color = (0, 255, 0) if matched else (0, 255, 255) cv2.rectangle(cam, (box["x"], box["y"]), (box["x"] + box["w"], box["y"] + box["h"]), color, 4) for x in (box["x"], box["x"] + box["w"]): b = float(sovis.camera_x_to_bearing(x)) cv2.line(fan, to_px(b, 0), to_px(b, max_r), color, 1, cv2.LINE_AA) if matched: b0, b1 = box["sonar_bearing_min_deg"], box["sonar_bearing_max_deg"] r0, r1 = box["sonar_range_min_m"], box["sonar_range_max_m"] arc = [to_px(b, r0) for b in np.linspace(b0, b1, 8)] + [to_px(b, r1) for b in np.linspace(b1, b0, 8)] cv2.polylines(fan, [np.array(arc)], True, (0, 255, 0), 2) cam = cv2.resize(cam, (int(cam.shape[1] * panel_h / cam.shape[0]), panel_h), interpolation=cv2.INTER_AREA) label = f"{row['frame_id']} depth {row['depth_m']:.1f} m tilt {row['camera_tilt_deg']:.0f} deg" cv2.putText(cam, label, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2, cv2.LINE_AA) return np.hstack([cam, fan]) def load_rows(args): """Pick n random rows that match --where, deciding on light columns before touching any image.""" if args.data_dir: import pyarrow as pa import pyarrow.parquet as pq files, n_rows = [], 0 for f in sorted(Path(args.data_dir).glob("*.parquet")): files.append(f) n_rows += pq.ParquetFile(f).metadata.num_rows if n_rows > 50 * args.n: break light = pa.concat_tables([pq.read_table(f, columns=["seabed_in_camera", "fish_boxes"]) for f in files]).to_pydict() else: from datasets import load_dataset rows = load_dataset(args.repo, args.config, split=args.split) light = {c: rows[c] for c in ("seabed_in_camera", "fish_boxes")} # column access decodes no images keep = {"seabed": lambda i: light["seabed_in_camera"][i], "fish": lambda i: bool(light["fish_boxes"][i]), "any": lambda i: True}[args.where] perm = np.random.default_rng(args.seed).permutation(len(light["seabed_in_camera"])) idx = [int(i) for i in perm if keep(i)][:args.n] if not args.data_dir: return [rows[i] for i in idx] table = pa.concat_tables([pq.read_table(f) for f in files]) return [table.slice(i, 1).to_pylist()[0] for i in idx] def stack_panels(panels, gap=4, fill=0): """Stack panels of different widths vertically, padding each to the widest one.""" width = max(p.shape[1] for p in panels) return np.vstack([np.pad(p, ((0, gap), (0, width - p.shape[1]), (0, 0)), constant_values=fill) for p in panels]) def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) src = ap.add_mutually_exclusive_group(required=True) src.add_argument("--repo", help="Hugging Face dataset id, e.g. /SOVIS") src.add_argument("--data-dir", help="a local folder of SOVIS parquet files") ap.add_argument("--config", default="mini") ap.add_argument("--split", default="train") ap.add_argument("--where", choices=["any", "seabed", "fish"], default="any") ap.add_argument("--n", type=int, default=6) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", default="samples.jpg") args = ap.parse_args() panels = [draw_pair(r) for r in load_rows(args)] cv2.imwrite(args.out, stack_panels(panels), [cv2.IMWRITE_JPEG_QUALITY, 90]) print(f"wrote {args.out} ({len(panels)} pairs)") if __name__ == "__main__": main()