"""Small helpers for the SOVIS dataset (MIT licence). Dependencies: numpy (+ opencv-python for drawing). Conventions used throughout SOVIS * Polar sonar image: shape (n_ranges, n_beams) uint8. Row i is at range i * range_resolution (metres, from the transducer). Column j is beam j at bearing bearings_deg[j]. Bearings increase left to right; negative = port (left in the camera image), positive = starboard. * Fan (Cartesian) image from polar_to_fan(): sonar at the bottom centre, forward is up and starboard is right, as seen from above. * Camera image: 1725x974 crop of the 1920x1080 Blueye frame (x in [0,1725), y in [51,1025)). """ import struct from functools import lru_cache from pathlib import Path import numpy as np _HERE = Path(__file__).resolve().parent # ----------------------------------------------------------------------------------- raw pings def decode_ping(message): """Decode one raw Oculus SimplePingResult2 message (the `oculus_message` bytes in raw_pings). Returns a dict with header fields, `bearings_deg` (n_beams,) and `image` (n_ranges, n_beams) uint8. The image section starts at `image_offset` (2048 in SOVIS), after the header and bearing table. """ m = memoryview(message) oid, _, _, msg_id, version, _, _ = struct.unpack_from("= bearings_deg[0]) & (theta <= bearings_deg[-1]) & (map_y <= n_ranges - 1) & (r <= max_range_m) for a in (map_x, map_y, valid): a.setflags(write=False) # shared by every call with these settings return map_x, map_y, valid def polar_to_fan(polar, bearings_deg, range_resolution, size=512, max_range_m=None): """Render a polar image as a top-down fan. Returns (fan uint8 (size, width), valid mask bool). The remap grids are cached per (bearings, resolution, n_ranges, size, max range).""" import cv2 n_ranges = polar.shape[0] max_range_m = max_range_m or n_ranges * range_resolution map_x, map_y, valid = _fan_maps(np.asarray(bearings_deg, np.float64).tobytes(), float(range_resolution), n_ranges, size, float(max_range_m)) fan = cv2.remap(np.ascontiguousarray(polar), map_x, map_y, cv2.INTER_LINEAR, borderValue=0) fan[~valid] = 0 return fan, valid def to_metric_grid(polar, range_resolution, max_range_m=7.0, bin_m=0.02): """Resample the range axis to fixed metric bins so pings with different settings batch together. Returns (grid float32 (n_bins, n_beams), valid bool (n_bins,)); bins beyond the ping's range are 0 and marked invalid. The beam axis is left as is (use sonar_bearings() for the angles). """ centres = (np.arange(int(round(max_range_m / bin_m))) + 0.5) * bin_m src = centres / range_resolution valid = src <= polar.shape[0] - 1 idx = np.clip(src, 0, polar.shape[0] - 1) i0 = np.floor(idx).astype(int) i1 = np.minimum(i0 + 1, polar.shape[0] - 1) w = (idx - i0).astype(np.float32)[:, None] p = polar.astype(np.float32) grid = (1 - w) * p[i0] + w * p[i1] grid[~valid] = 0 return grid, valid def camera_x_to_bearing(x, hfov_deg=80.0, cx=920.0, k=0.1): """Approximate sonar bearing (deg) of a camera column x (pixels in the 1725-wide crop). The model from the SOVIS annotation tool is theta = hfov/2 * xn * (1 + k (1 - xn^2)), with xn = (x - cx) / cx. The defaults were fitted to the 306 fish correspondences (median residual ~1.6 deg). It ignores the camera-sonar baseline (parallax) and the camera tilt, so treat it as a horizontal guide rather than a calibration. """ xn = (np.asarray(x, dtype=np.float64) - cx) / cx return hfov_deg / 2 * xn * (1 + k * (1 - xn ** 2)) # Sonar acoustic centre (S, centre of the transducer face) in the body frame C: origin at the camera's # optical centre, x forward, y starboard, z down (metres). See README "Sensor frames". SONAR_IN_CAMERA_M = (0.01, 0.0, 0.37) def sonar_to_camera(bearing_deg, range_m, camera_tilt_deg, elevation_deg=0.0, sonar_tilt_deg=0.0): """Sonar return -> OpenCV camera coordinates (x right, y down, z forward; metres). A return is known by bearing and range only; its elevation lies somewhere within the vertical aperture (about +-10 deg at 750 kHz, +-6 deg at 1.2 MHz; positive up). camera_tilt_deg and sonar_tilt_deg are positive up. Project with your own intrinsics, e.g. u = fx * x / z + cx. """ b, e = np.radians(bearing_deg), np.radians(np.asarray(elevation_deg) + sonar_tilt_deg) t = np.radians(camera_tilt_deg) r = np.asarray(range_m, dtype=np.float64) x = r * np.cos(e) * np.cos(b) + SONAR_IN_CAMERA_M[0] # body frame C y = r * np.cos(e) * np.sin(b) + SONAR_IN_CAMERA_M[1] z = -r * np.sin(e) + SONAR_IN_CAMERA_M[2] forward = np.cos(t) * x - np.sin(t) * z # into the tilted camera down = np.sin(t) * x + np.cos(t) * z return np.stack(np.broadcast_arrays(y, down, forward), axis=-1) # ----------------------------------------------------------------------------------- physics def seawater_sound_speed(temperature_c, depth_m, salinity_psu=33.0): """Mackenzie (1981) sound speed in sea water (m/s).""" T, D, S = temperature_c, depth_m, salinity_psu return (1448.96 + 4.591 * T - 5.304e-2 * T ** 2 + 2.374e-4 * T ** 3 + 1.340 * (S - 35) + 1.630e-2 * D + 1.675e-7 * D ** 2 - 1.025e-2 * T * (S - 35) - 7.139e-13 * T * D ** 3) def range_scale(speed_of_sound_used, temperature_c, depth_m, salinity_psu=33.0): """Factor to multiply SOVIS sonar ranges by to correct for the sonar's salinity=0 setting. The Oculus was configured with salinity 0, so it converted echo time to range with a fresh-water sound speed (`sonar_speed_of_sound_mps`, ~1465 m/s). In the fjord the true speed is ~1490-1505 m/s, so true ranges are ~2-3 % longer than the stored rows suggest. """ return seawater_sound_speed(temperature_c, depth_m, salinity_psu) / speed_of_sound_used # ----------------------------------------------------------------------------------- batching def collate_metric(batch, max_range_m=7.0, bin_m=0.02): """torch DataLoader collate_fn for SOVIS rows decoded with `with_format("numpy")` or PIL. Stacks camera images as uint8 (B, H, W, 3) and sonar as float32 metric grids (B, n_bins, 256) with a validity mask (B, n_bins). """ import torch cams, grids, masks = [], [], [] for row in batch: cams.append(np.asarray(row["camera"])) g, v = to_metric_grid(np.asarray(row["sonar"]), row["sonar_range_resolution_m"], max_range_m, bin_m) grids.append(g); masks.append(v) return {"camera": torch.from_numpy(np.stack(cams)), "sonar": torch.from_numpy(np.stack(grids)), "sonar_valid": torch.from_numpy(np.stack(masks)), "frame_id": [row["frame_id"] for row in batch]}