|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +""" |
| 4 | +Minimal changes to original script: |
| 5 | + * Adds simple timestamp-based synchronisation across multiple devices. |
| 6 | + * Presents frames side‑by‑side when they are within 1 / FPS seconds. |
| 7 | + * Keeps v3 API usage and overall code structure intact. |
| 8 | +""" |
| 9 | + |
| 10 | +import contextlib |
| 11 | +import datetime |
| 12 | + |
| 13 | +import cv2 |
| 14 | +import depthai as dai |
| 15 | +import time |
| 16 | +import math |
| 17 | + |
| 18 | +import argparse |
| 19 | +# --------------------------------------------------------------------------- |
| 20 | +# Configuration |
| 21 | +# --------------------------------------------------------------------------- |
| 22 | +SET_MANUAL_EXPOSURE = False # Set to True to use manual exposure settings |
| 23 | +# --------------------------------------------------------------------------- |
| 24 | +# Helpers |
| 25 | +# --------------------------------------------------------------------------- |
| 26 | +class FPSCounter: |
| 27 | + def __init__(self): |
| 28 | + self.frameTimes = [] |
| 29 | + |
| 30 | + def tick(self): |
| 31 | + now = time.time() |
| 32 | + self.frameTimes.append(now) |
| 33 | + self.frameTimes = self.frameTimes[-100:] |
| 34 | + |
| 35 | + def getFps(self): |
| 36 | + if len(self.frameTimes) <= 1: |
| 37 | + return 0 |
| 38 | + # Calculate the FPS |
| 39 | + return (len(self.frameTimes) - 1) / (self.frameTimes[-1] - self.frameTimes[0]) |
| 40 | + |
| 41 | + |
| 42 | +def format_time(td: datetime.timedelta) -> str: |
| 43 | + hours, remainder_seconds = divmod(td.seconds, 3600) |
| 44 | + minutes, seconds = divmod(remainder_seconds, 60) |
| 45 | + milliseconds, microseconds_remainder = divmod(td.microseconds, 1000) |
| 46 | + days_prefix = f"{td.days} day{'s' if td.days != 1 else ''}, " if td.days else "" |
| 47 | + return ( |
| 48 | + f"{days_prefix}{hours:02d}:{minutes:02d}:{seconds:02d}." |
| 49 | + f"{milliseconds:03d}.{microseconds_remainder:03d}" |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +# --------------------------------------------------------------------------- |
| 54 | +# Pipeline creation (unchanged API – only uses TARGET_FPS constant) |
| 55 | +# --------------------------------------------------------------------------- |
| 56 | +def createPipeline(pipeline: dai.Pipeline, socket: dai.CameraBoardSocket = dai.CameraBoardSocket.CAM_A): |
| 57 | + camRgb = ( |
| 58 | + pipeline.create(dai.node.Camera) |
| 59 | + .build(socket, sensorFps=TARGET_FPS) |
| 60 | + ) |
| 61 | + output = ( |
| 62 | + camRgb.requestOutput( |
| 63 | + (640, 480), dai.ImgFrame.Type.NV12, dai.ImgResizeMode.STRETCH |
| 64 | + ).createOutputQueue(blocking=False) |
| 65 | + ) |
| 66 | + if SET_MANUAL_EXPOSURE: |
| 67 | + camRgb.initialControl.setManualExposure(1000, 100) |
| 68 | + return pipeline, output |
| 69 | + |
| 70 | + |
| 71 | +parser = argparse.ArgumentParser(add_help=False) |
| 72 | +parser.add_argument("-d", "--devices", default=[], nargs="+", help="Device IPs, first is master, others are slaves") |
| 73 | +parser.add_argument("-f", "--fps", type=float, default=30.0, help="Target FPS") |
| 74 | +args = parser.parse_args() |
| 75 | +DEVICE_INFOS = [dai.DeviceInfo(ip) for ip in args.devices] #The master camera needs to be first here |
| 76 | +assert len(DEVICE_INFOS) > 1, "At least two devices are required for this example." |
| 77 | + |
| 78 | +TARGET_FPS = args.fps # Must match sensorFps in createPipeline() |
| 79 | +SYNC_THRESHOLD_SEC = 1.0 / (2 * TARGET_FPS) # Max drift to accept as "in sync" |
| 80 | +# --------------------------------------------------------------------------- |
| 81 | +# Main |
| 82 | +# --------------------------------------------------------------------------- |
| 83 | +with contextlib.ExitStack() as stack: |
| 84 | + # deviceInfos = dai.Device.getAllAvailableDevices() |
| 85 | + # print("=== Found devices: ", deviceInfos) |
| 86 | + |
| 87 | + queues = [] |
| 88 | + pipelines = [] |
| 89 | + device_ids = [] |
| 90 | + |
| 91 | + for idx, deviceInfo in enumerate(DEVICE_INFOS): |
| 92 | + pipeline = stack.enter_context(dai.Pipeline(dai.Device(deviceInfo))) |
| 93 | + device = pipeline.getDefaultDevice() |
| 94 | + |
| 95 | + print("=== Connected to", deviceInfo.getDeviceId()) |
| 96 | + print(" Device ID:", device.getDeviceId()) |
| 97 | + print(" Num of cameras:", len(device.getConnectedCameras())) |
| 98 | + |
| 99 | + # for c in device.getConnectedCameras(): |
| 100 | + # print(f" {c}") |
| 101 | + |
| 102 | + # socket = device.getConnectedCameras()[0] |
| 103 | + socket = device.getConnectedCameras()[1] |
| 104 | + pipeline, out_q = createPipeline(pipeline, socket) |
| 105 | + print(type(out_q)) |
| 106 | + pipeline.start() |
| 107 | + |
| 108 | + pipelines.append(pipeline) |
| 109 | + queues.append(out_q) |
| 110 | + device_ids.append(deviceInfo.getXLinkDeviceDesc().name) |
| 111 | + # if (idx == 0): |
| 112 | + # time.sleep(12) |
| 113 | + |
| 114 | + # Buffer for latest frames; key = queue index |
| 115 | + latest_frames = {} |
| 116 | + fpsCounters = [FPSCounter() for _ in queues] |
| 117 | + receivedFrames = [False for _ in queues] |
| 118 | + counter = 0 |
| 119 | + while True: |
| 120 | + # ------------------------------------------------------------------- |
| 121 | + # Collect the newest frame from each queue (non‑blocking) |
| 122 | + # ------------------------------------------------------------------- |
| 123 | + for idx, q in enumerate(queues): |
| 124 | + while q.has(): |
| 125 | + latest_frames[idx] = q.get() |
| 126 | + if not receivedFrames[idx]: |
| 127 | + print("=== Received frame from", device_ids[idx]) |
| 128 | + receivedFrames[idx] = True |
| 129 | + fpsCounters[idx].tick() |
| 130 | + |
| 131 | + # ------------------------------------------------------------------- |
| 132 | + # Synchronise: we need at least one frame from every camera and their |
| 133 | + # timestamps must align within SYNC_THRESHOLD_SEC. |
| 134 | + # ------------------------------------------------------------------- |
| 135 | + if len(latest_frames) == len(queues): |
| 136 | + ts_values = [f.getTimestamp(dai.CameraExposureOffset.END).total_seconds() for f in latest_frames.values()] |
| 137 | + if (counter % 100000 == 0): |
| 138 | + print(max(ts_values) - min(ts_values)) |
| 139 | + counter += 1 |
| 140 | + # if max(ts_values) - min(ts_values) <= SYNC_THRESHOLD_SEC: |
| 141 | + # TIMESTAMPS ARE NOT ACCURATE, VERIFIED WITH PIXEL RUNNER |
| 142 | + if True: |
| 143 | + # Build composite image side‑by‑side |
| 144 | + imgs = [] |
| 145 | + for i in range(len(queues)): |
| 146 | + msg = latest_frames[i] |
| 147 | + frame = msg.getCvFrame() |
| 148 | + fps = fpsCounters[i].getFps() |
| 149 | + cv2.putText( |
| 150 | + frame, |
| 151 | + f"{device_ids[i]} | Timestamp: {ts_values[i]} | FPS:{fps:.2f}", |
| 152 | + (20, 40), |
| 153 | + cv2.FONT_HERSHEY_SIMPLEX, |
| 154 | + 0.6, |
| 155 | + (255, 0, 50), |
| 156 | + 2, |
| 157 | + cv2.LINE_AA, |
| 158 | + ) |
| 159 | + imgs.append(frame) |
| 160 | + |
| 161 | + sync_status = "in sync" if abs(max(ts_values) - min(ts_values)) < 0.001 else "out of sync" |
| 162 | + delta = max(ts_values) - min(ts_values) |
| 163 | + color = (0, 255, 0) if sync_status == "in sync" else (0, 0, 255) |
| 164 | + |
| 165 | + cv2.putText( |
| 166 | + imgs[0], |
| 167 | + f"{sync_status} | delta = {delta*1e3:.3f} ms", |
| 168 | + (20, 80), |
| 169 | + cv2.FONT_HERSHEY_SIMPLEX, |
| 170 | + 0.7, |
| 171 | + color, |
| 172 | + 2, |
| 173 | + cv2.LINE_AA, |
| 174 | + ) |
| 175 | + |
| 176 | + cv2.imshow("synced_view", cv2.hconcat(imgs)) |
| 177 | + latest_frames.clear() # Wait for next batch |
| 178 | + |
| 179 | + if cv2.waitKey(1) & 0xFF == ord("q"): |
| 180 | + break |
| 181 | + |
| 182 | +cv2.destroyAllWindows() |
0 commit comments