From 6751ae775c5a905d379f8207fa65323b81bf58a0 Mon Sep 17 00:00:00 2001 From: bentdixon Date: Wed, 14 Oct 2026 19:29:20 +0100 Subject: [PATCH] Add type-hints and docstrings, minor formatting --- perception/main.py | 101 ++++++++++++++++++++++++++++----------------- perception/sim.py | 74 ++++++++++++++++++++------------- 2 files changed, 108 insertions(+), 67 deletions(-) diff --git a/perception/main.py b/perception/main.py index c078d27..33d7740 100644 --- a/perception/main.py +++ b/perception/main.py @@ -1,42 +1,52 @@ import argparse +from typing import TYPE_CHECKING, Any import cv2 import numpy as np from ultralytics import YOLO +from ultralytics.engine.results import Results -from sim import SimSource, deproject +from sim import Intrinsics, SimSource, deproject -W, H, FPS = 640, 480, 30 -MODEL_PATH = "models/yolo11s-seg.pt" -CONF = 0.5 -MIN_HITS = 3 -EMA_ALPHA = 0.4 -Z_MIN, Z_MAX = 0.3, 3.0 +if TYPE_CHECKING: + import pyrealsense2 as rs -SIZE_RANGE = { +W, H, FPS = 640, 480, 30 # camera frame width and height (px), frames per second +MODEL_PATH = "models/yolo11s-seg.pt" # YOLO weights file, relative to the folder you run from +CONF = 0.5 # minimum YOLO confidence (0-1) to keep a detection +MIN_HITS = 3 # frames an object must be seen before it is reported +EMA_ALPHA = 0.4 # smoothing weight for the newest position (1 = no smoothing) +Z_MIN, Z_MAX = 0.3, 3.0 # accepted object distance from the camera (m) + +# YOLO label -> (min, max) real object height in metres; unlisted labels allow 0-10 m +SIZE_RANGE: dict[str, tuple[float, float]] = { } class RealSenseSource: - def __init__(self): + """Frame source for a live Intel RealSense D435 colour and depth stream.""" + + def __init__(self) -> None: + """Start the D435 colour and depth streams and set up alignment and filters.""" import pyrealsense2 as rs # lazy, so --sim works without the SDK - self.rs = rs - self.pipeline = rs.pipeline() + self.rs = rs # RealSense SDK module + self.pipeline = rs.pipeline() # handle that starts the camera and delivers frames config = rs.config() config.enable_stream(rs.stream.depth, W, H, rs.format.z16, FPS) config.enable_stream(rs.stream.color, W, H, rs.format.bgr8, FPS) profile = self.pipeline.start(config) sensor = profile.get_device().first_depth_sensor() - self.depth_scale = sensor.get_depth_scale() + self.depth_scale = sensor.get_depth_scale() # metres per raw depth unit (usually 0.001) sensor.set_option(rs.option.visual_preset, 3) # High Accuracy sensor.set_option(rs.option.emitter_enabled, 1) - self.align = rs.align(rs.stream.color) - self.spatial = rs.spatial_filter() - self.temporal = rs.temporal_filter() + self.align = rs.align(rs.stream.color) # remaps depth pixels to line up with colour pixels + self.spatial = rs.spatial_filter() # smooths depth noise within a frame + self.temporal = rs.temporal_filter() # smooths depth noise across frames - def read(self): + def read(self) -> tuple[np.ndarray, np.ndarray, "rs.intrinsics"]: + """Returns (color_bgr, depth_u16, intrinsics) with depth aligned to colour.""" frames = self.align.process(self.pipeline.wait_for_frames()) depth_frame = frames.get_depth_frame() color_frame = frames.get_color_frame() @@ -47,11 +57,16 @@ def read(self): return (np.asanyarray(color_frame.get_data()), np.asanyarray(depth_frame.get_data()), intr) - def stop(self): + def stop(self) -> None: + """Stop the camera pipeline.""" self.pipeline.stop() -def mask_depth_m(depth_img, poly, depth_scale): +def mask_depth_m(depth_img: np.ndarray, poly: np.ndarray, + depth_scale: float) -> float | None: + """Distance (m) to the object: the median depth of the pixels inside its YOLO + outline, after shrinking the outline by a few pixels so background pixels at + the edges are not counted. Returns None if fewer than 50 pixels have depth.""" mask = np.zeros(depth_img.shape, np.uint8) cv2.fillPoly(mask, [poly.astype(np.int32)], 1) mask = cv2.erode(mask, np.ones((5, 5), np.uint8)) @@ -61,7 +76,8 @@ def mask_depth_m(depth_img, poly, depth_scale): return float(np.median(vals)) * depth_scale -def parse_args(): +def parse_args() -> argparse.Namespace: + """Parse command-line options for sim mode.""" ap = argparse.ArgumentParser() ap.add_argument("--sim", metavar="PATH", help="image, folder of images or video to use instead of the D435") @@ -71,17 +87,26 @@ def parse_args(): help="constant synthetic depth in metres (default 1.5)") ap.add_argument("--loop", action="store_true", help="loop the sim media") return ap.parse_args() -def find_path(): - print() + + +def find_path() -> None: + """Plan servo coordinates from the object to its category's drop-off location. Not yet implemented.""" + pass #TODO: Draw a path to its designated location based on its category, could also be done in integration -def catogorize(name,x,y,z): - print() - #TODO -def main(): - args = parse_args() - model = YOLO(MODEL_PATH) +def catogorize(name: str, x: float, y: float, z: float) -> None: + """Assign a detected object to a sorting category. Not yet implemented.""" + pass + #TODO: Implement categorizaiton + + + +def main() -> None: + """Run detection, tracking and 3D localisation on each frame until quit or end of media.""" + args: argparse.Namespace = parse_args() + model: YOLO = YOLO(MODEL_PATH) + source: SimSource | RealSenseSource if args.sim: source = SimSource(args.sim, (W, H), FPS, args.sim_depth_m, args.sim_depth, args.loop) @@ -89,38 +114,38 @@ def main(): else: source = RealSenseSource() - tracks = {} + tracks: dict[int, dict[str, Any]] = {} # track ID -> {"xyz": smoothed position (m), "hits": frames seen} try: while True: - data = source.read() + data: tuple[np.ndarray, np.ndarray, Intrinsics | rs.intrinsics] | None = source.read() if data is None: print("End of media") break color, depth, intr = data - result = model.track(color, conf=CONF, persist=True, verbose=False)[0] + result: Results = model.track(color, conf=CONF, persist=True, verbose=False)[0] if result.boxes.id is not None and result.masks is not None: - for box, poly, tid in zip(result.boxes, result.masks.xy, result.boxes.id): - tid = int(tid) + for box, poly, raw_id in zip(result.boxes, result.masks.xy, result.boxes.id): + tid: int = int(raw_id) x1, y1, x2, y2 = map(int, box.xyxy[0]) - label = model.names[int(box.cls[0])] - conf = float(box.conf[0]) + label: str = model.names[int(box.cls[0])] + conf: float = float(box.conf[0]) - z = mask_depth_m(depth, poly, source.depth_scale) + z: float | None = mask_depth_m(depth, poly, source.depth_scale) if z is None or not (Z_MIN <= z <= Z_MAX): continue - height_m = (y2 - y1) * z / intr.fy + height_m: float = (y2 - y1) * z / intr.fy lo, hi = SIZE_RANGE.get(label, (0.0, 10.0)) if not (lo <= height_m <= hi): continue cx, cy = poly.mean(axis=0) - xyz = np.array(deproject(intr, [cx, cy], z)) + xyz: np.ndarray = np.array(deproject(intr, [cx, cy], z)) - t = tracks.setdefault(tid, {"xyz": xyz, "hits": 0}) + t: dict[str, Any] = tracks.setdefault(tid, {"xyz": xyz, "hits": 0}) t["xyz"] = EMA_ALPHA * xyz + (1 - EMA_ALPHA) * t["xyz"] t["hits"] += 1 if t["hits"] < MIN_HITS: diff --git a/perception/sim.py b/perception/sim.py index e9b3901..25ecb10 100644 --- a/perception/sim.py +++ b/perception/sim.py @@ -5,35 +5,45 @@ depth map is passed in millimetres. """ import time +from collections.abc import Sequence from dataclasses import dataclass from pathlib import Path import cv2 import numpy as np -IMG_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} -VID_EXT = {".mp4", ".avi", ".mov", ".mkv", ".webm"} +IMG_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} # file types loaded as still images +VID_EXT = {".mp4", ".avi", ".mov", ".mkv", ".webm"} # file types loaded as video @dataclass class Intrinsics: - width: int - height: int - fx: float - fy: float - ppx: float - ppy: float - - -def deproject(intr, pixel, z): - """Pixel plus depth (m) to a camera-frame point (x right, y down, z forward). - Works with both sim Intrinsics and rs.intrinsics (same attribute names).""" + """Camera lens parameters (image size, focal length, image centre) used to turn + a pixel plus depth into a 3D point. Field names match the RealSense SDK's + intrinsics, so deproject() accepts either.""" + width: int # image width (px) + height: int # image height (px) + fx: float # horizontal focal length (px) + fy: float # vertical focal length (px) + ppx: float # x pixel of the image centre (where the lens points) + ppy: float # y pixel of the image centre + + +def deproject(intr: Intrinsics, pixel: Sequence[float], z: float) -> list[float]: + """Convert a pixel (u, v) and its measured depth z (m) into a 3D point (m) + relative to the camera: + X = (u - ppx) / fx * z metres right of the lens centre + Y = (v - ppy) / fy * z metres below the lens centre + Z = z metres straight out from the lens + Returns [X, Y, Z]. Works with both sim Intrinsics and rs.intrinsics + (same attribute names).""" x = (pixel[0] - intr.ppx) / intr.fx y = (pixel[1] - intr.ppy) / intr.fy return [x * z, y * z, z] -def _letterbox(img, w, h, interp=cv2.INTER_AREA): +def _letterbox(img: np.ndarray, w: int, h: int, + interp: int = cv2.INTER_AREA) -> np.ndarray: """Resize keeping aspect ratio and pad, so object sizes are not distorted.""" s = min(w / img.shape[1], h / img.shape[0]) nw, nh = int(img.shape[1] * s), int(img.shape[0] * s) @@ -44,25 +54,30 @@ def _letterbox(img, w, h, interp=cv2.INTER_AREA): class SimSource: - def __init__(self, path, size=(640, 480), fps=30, depth_m=1.5, - depth_path=None, loop=False): - self.w, self.h = size - self.period = 1.0 / fps + """Frame source that replays an image, image folder or video with synthetic depth.""" + + def __init__(self, path: str | Path, size: tuple[int, int] = (640, 480), + fps: float = 30, depth_m: float = 1.5, + depth_path: str | Path | None = None, loop: bool = False) -> None: + """Open the media at path and prepare a constant or file-based depth map.""" + self.w, self.h = size # output frame width and height (px) + self.period = 1.0 / fps # seconds between frames self.depth_scale = 0.001 # depth image is in millimetres - self.loop = loop - self._last = 0.0 + self.loop = loop # restart the media when it ends + self._last = 0.0 # time the previous frame was returned, for pacing # D435 colour stream is roughly fx = fy = 615 at 640x480 f = 615.0 * self.w / 640 - self.intr = Intrinsics(self.w, self.h, f, f, self.w / 2, self.h / 2) + self.intr = Intrinsics(self.w, self.h, f, f, # fake D435-like lens parameters + self.w / 2, self.h / 2) p = Path(path) if not p.exists(): raise FileNotFoundError(f"Sim media not found: {p}") - self._cap = None - self._images = [] - self._idx = 0 + self._cap: cv2.VideoCapture | None = None # open video, or None for images + self._images: list[Path] = [] # image files to play, in order + self._idx = 0 # index of the next image to return if p.is_dir(): self._images = sorted(f for f in p.iterdir() if f.suffix.lower() in IMG_EXT) if not self._images: @@ -80,13 +95,13 @@ def __init__(self, path, size=(640, 480), fps=30, depth_m=1.5, d = cv2.imread(str(depth_path), cv2.IMREAD_UNCHANGED) if d is None or d.dtype != np.uint16: raise ValueError("--sim-depth must be a 16-bit PNG in millimetres") - self._depth = _letterbox(d, self.w, self.h, cv2.INTER_NEAREST) + self._depth = _letterbox(d, self.w, self.h, cv2.INTER_NEAREST) # depth map (mm) from file else: - self._depth = np.full((self.h, self.w), int(depth_m * 1000), np.uint16) + self._depth = np.full((self.h, self.w), int(depth_m * 1000), np.uint16) # constant depth (mm) - self.static = self._cap is None and len(self._images) == 1 + self.static = self._cap is None and len(self._images) == 1 # single image repeated forever - def read(self): + def read(self) -> tuple[np.ndarray, np.ndarray, Intrinsics] | None: """Returns (color_bgr, depth_u16, intrinsics) or None at end of media.""" wait = self.period - (time.time() - self._last) if wait > 0: @@ -113,6 +128,7 @@ def read(self): return _letterbox(frame, self.w, self.h), self._depth.copy(), self.intr - def stop(self): + def stop(self) -> None: + """Release the video capture, if one is open.""" if self._cap is not None: self._cap.release()