| """ |
| Go2 Robot Dog β Projector Surface Capture Script |
| ================================================= |
| Workflow: |
| 1. Connect to Go2 camera via WebRTC |
| 2. Capture baseline frames (no projection) |
| 3. SSH into robot, project each image one-by-one using feh |
| 4. After each image is projected, capture camera frames |
| 5. Save all frames to an organized output directory |
| |
| Requirements: |
| pip install unitree-webrtc-connect aiortc opencv-python paramiko |
| """ |
| import asyncio |
| import logging |
| import threading |
| import time |
| import os |
| import cv2 |
| import numpy as np |
| import paramiko |
| from queue import Queue, Empty |
| from pathlib import Path |
| from datetime import datetime |
| from unitree_webrtc_connect.webrtc_driver import UnitreeWebRTCConnection, WebRTCConnectionMethod |
| from aiortc import MediaStreamTrack |
|
|
| |
| |
| |
|
|
| ROBOT_CAMERA_IP = "192.168.0.224" |
| ROBOT_SSH_IP = "192.168.0.113" |
| SSH_USER = "unitree" |
| SSH_PASSWORD = "123" |
|
|
| PROJECTOR_SLIDES_DIR = "~/Projector_Slides" |
| LOCAL_IMAGES_DIR = "./images_to_project" |
| OUTPUT_DIR = "./capture_output" |
|
|
| FRAMES_TO_CAPTURE = 1 |
| FRAME_CAPTURE_DELAY = 0.5 |
| PROJECTION_WARMUP = 2.0 |
|
|
| DISPLAY = ":1" |
| PREVIEW_WINDOW = True |
|
|
| logging.basicConfig(level=logging.WARNING) |
|
|
| |
| |
| |
|
|
| class CameraStream: |
| def __init__(self, ip: str): |
| self.ip = ip |
| self.frame_queue: Queue = Queue(maxsize=30) |
| self.loop = None |
| self.thread = None |
| self.conn = None |
|
|
| def start(self): |
| self.conn = UnitreeWebRTCConnection(WebRTCConnectionMethod.LocalSTA, ip=self.ip) |
| self.loop = asyncio.new_event_loop() |
| self.thread = threading.Thread(target=self._run_loop, daemon=True) |
| self.thread.start() |
| |
| print(" Waiting for camera stream...") |
| timeout = 15 |
| start = time.time() |
| while self.frame_queue.empty(): |
| if time.time() - start > timeout: |
| raise TimeoutError("Camera stream did not start within timeout.") |
| time.sleep(0.2) |
| print(" Camera stream active.") |
|
|
| def _run_loop(self): |
| asyncio.set_event_loop(self.loop) |
|
|
| async def setup(): |
| await self.conn.connect() |
| self.conn.video.switchVideoChannel(True) |
| self.conn.video.add_track_callback(self._recv_track) |
|
|
| self.loop.run_until_complete(setup()) |
| self.loop.run_forever() |
|
|
| def clear_queue(self): |
| """Empty the queue so we don't get old frames.""" |
| while not self.frame_queue.empty(): |
| try: |
| self.frame_queue.get_nowait() |
| except Empty: |
| break |
|
|
| async def _recv_track(self, track: MediaStreamTrack): |
| while True: |
| try: |
| frame = await track.recv() |
| img = frame.to_ndarray(format="bgr24") |
| except Exception as e: |
| logging.warning(f"Frame decode/receive error (skipping): {e}") |
| continue |
|
|
| if self.frame_queue.full(): |
| try: |
| self.frame_queue.get_nowait() |
| except Empty: |
| pass |
| self.frame_queue.put(img) |
|
|
| def get_latest_frame(self, timeout=2.0): |
| """Return the most recent frame, or None if timeout reached.""" |
| try: |
| |
| return self.frame_queue.get(timeout=timeout) |
| except Empty: |
| logging.warning(" Camera Timeout: No frame received in queue.") |
| return None |
|
|
| def capture_frames(self, count: int, delay: float) -> list: |
| """Capture `count` frames spaced `delay` seconds apart.""" |
| frames = [] |
| for i in range(count): |
| frame = self.get_latest_frame() |
| if frame is not None: |
| frames.append(frame) |
| if PREVIEW_WINDOW: |
| cv2.imshow("Go2 Camera", frame) |
| cv2.waitKey(1) |
| if i < count - 1: |
| time.sleep(delay) |
| return frames |
|
|
| def stop(self): |
| if self.loop: |
| self.loop.call_soon_threadsafe(self.loop.stop) |
| if self.thread: |
| self.thread.join(timeout=3) |
| cv2.destroyAllWindows() |
|
|
|
|
| |
| |
| |
|
|
| class ProjectorController: |
| def __init__(self, ip: str, user: str, password: str): |
| self.ip = ip |
| self.user = user |
| self.password = password |
| self.ssh: paramiko.SSHClient = None |
| self.current_pid = None |
|
|
| def connect(self): |
| print(f" Connecting via SSH to {self.user}@{self.ip}...") |
| self.ssh = paramiko.SSHClient() |
| self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
| self.ssh.connect(self.ip, username=self.user, password=self.password) |
| print(" SSH connected.") |
|
|
| def _exec(self, cmd: str) -> str: |
| _, stdout, stderr = self.ssh.exec_command(cmd) |
| out = stdout.read().decode().strip() |
| err = stderr.read().decode().strip() |
| if err: |
| logging.debug(f"SSH stderr: {err}") |
| return out |
|
|
| def upload_images(self, local_dir: str, remote_dir: str): |
| """Upload local images to the robot via SCP.""" |
| local_path = Path(local_dir) |
| if not local_path.exists(): |
| print(f" Local image dir '{local_dir}' not found, skipping upload.") |
| return |
|
|
| images = sorted(local_path.glob("*")) |
| images = [f for f in images if f.suffix.lower() in {".jpg", ".jpeg", ".png", ".bmp", ".gif"}] |
| if not images: |
| print(f" No images found in '{local_dir}', skipping upload.") |
| return |
|
|
| print(f" Uploading {len(images)} images to robot...") |
| self._exec(f"mkdir -p {remote_dir}") |
| sftp = self.ssh.open_sftp() |
| for img in images: |
| remote_path = f"{remote_dir.rstrip('~').replace('~', '/root')}/{img.name}" |
| |
| remote_expanded = self._exec(f"echo {remote_dir}/{img.name}") |
| sftp.put(str(img), remote_expanded) |
| print(f" Uploaded: {img.name}") |
| sftp.close() |
|
|
| def list_remote_images(self, remote_dir: str) -> list: |
| """Return sorted list of image filenames in the remote directory.""" |
| out = self._exec( |
| f"find {remote_dir} -maxdepth 1 -type f " |
| r"\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.bmp' \) | sort" |
| ) |
| return [line for line in out.splitlines() if line.strip()] |
| |
| def start_slideshow(self, image_paths: list): |
| """Launch feh once with all images. Starts on the first image.""" |
| self.stop_projection() |
| files = " ".join(f"'{p}'" for p in image_paths) |
| cmd = ( |
| f"DISPLAY={DISPLAY} feh --fullscreen --auto-zoom --borderless " |
| f"--slideshow-delay 0 {files} > /dev/null 2>&1 &" |
| ) |
| self._exec(cmd) |
| time.sleep(0.5) |
| pid_out = self._exec("pgrep -n feh") |
| self.current_pid = pid_out if pid_out else None |
| print(f" Slideshow started (PID {self.current_pid}) with {len(image_paths)} images.") |
|
|
| def create_black_slide(self) -> str: |
| """Create a black image on the robot and return its path.""" |
| path = "/tmp/black_baseline.png" |
| self._exec(f"python3 -c \"from PIL import Image; Image.new('RGB', (1920, 1080)).save('{path}')\"") |
| return path |
|
|
| def next_image(self): |
| """Advance feh to the next image with no close/reopen flash.""" |
| if self.current_pid: |
| self._exec(f"kill -SIGUSR1 {self.current_pid}") |
|
|
| def stop_projection(self): |
| """Kill any running feh process.""" |
| self._exec("pkill feh 2>/dev/null || true") |
| self.current_pid = None |
|
|
| def disconnect(self): |
| self.stop_projection() |
| if self.ssh: |
| self.ssh.close() |
|
|
|
|
| |
| |
| |
|
|
| def save_frames(frames: list, out_dir: Path, prefix: str): |
| out_dir.mkdir(parents=True, exist_ok=True) |
| saved = [] |
| for i, frame in enumerate(frames): |
| filename = out_dir / f"{prefix}_frame{i+1:03d}.png" |
| cv2.imwrite(str(filename), frame) |
| saved.append(filename) |
| return saved |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| out_root = Path(OUTPUT_DIR) / f"session_{timestamp}" |
| out_root.mkdir(parents=True, exist_ok=True) |
| print(f"\n{'='*55}") |
| print(f" Go2 Projector Surface Capture") |
| print(f" Session output: {out_root}") |
| print(f"{'='*55}\n") |
|
|
| |
| print("[1/3] Starting camera stream...") |
| camera = CameraStream(ROBOT_CAMERA_IP) |
| try: |
| camera.start() |
| except TimeoutError as e: |
| print(f" ERROR: {e}") |
| return |
|
|
| |
| print("\n[2/3] Connecting to projector via SSH...") |
| projector = ProjectorController(ROBOT_SSH_IP, SSH_USER, SSH_PASSWORD) |
| try: |
| projector.connect() |
| except Exception as e: |
| print(f" ERROR: Could not connect via SSH: {e}") |
| camera.stop() |
| return |
|
|
| projector.upload_images(LOCAL_IMAGES_DIR, PROJECTOR_SLIDES_DIR) |
|
|
| images = projector.list_remote_images(PROJECTOR_SLIDES_DIR) |
| if not images: |
| print(f" ERROR: No images found in {PROJECTOR_SLIDES_DIR} on the robot.") |
| projector.disconnect() |
| camera.stop() |
| return |
|
|
| print(f" Found {len(images)} images to project.") |
|
|
| |
| print(f"\n[3/3] Projecting images and capturing frames...\n") |
|
|
| black_slide = projector.create_black_slide() |
| images = [black_slide] + images |
|
|
| projector.start_slideshow(images) |
| print(f" Waiting {PROJECTION_WARMUP}s for first image to stabilize...") |
| time.sleep(PROJECTION_WARMUP) |
|
|
| for idx, image_path in enumerate(images): |
| image_name = "baseline" if idx == 0 else Path(image_path).stem |
| label = f"{idx:03d}_{image_name}" |
|
|
| print(f" [{idx+1}/{len(images)}] Capturing: {Path(image_path).name}") |
|
|
| camera.clear_queue() |
| frames = camera.capture_frames(FRAMES_TO_CAPTURE, FRAME_CAPTURE_DELAY) |
|
|
| if not frames: |
| print(f" β οΈ WARNING: No frames captured for {image_name}.") |
| else: |
| saved = save_frames(frames, out_root, label) |
| print(f" Saved {len(saved)} frames β {out_root}") |
|
|
| if idx < len(images) - 1: |
| projector.next_image() |
| print(f" Waiting {PROJECTION_WARMUP}s for next image to stabilize...") |
| time.sleep(PROJECTION_WARMUP) |
|
|
| |
| print("\nStopping projection and cleaning up...") |
| projector.disconnect() |
| camera.stop() |
|
|
| print(f"\n{'='*55}") |
| print(f" Done! All captures saved to:") |
| print(f" {out_root.resolve()}") |
| print(f"{'='*55}\n") |
|
|
|
|
| if __name__ == "__main__": |
| main() |