Files
depth-estimation/08_depth_estimation.py
2026-10-14 04:20:47 +00:00

195 lines
7.2 KiB
Python

"""
============================================================
BASIC YOLO TASK 7 : DEPTH ESTIMATION (+ YOLO DETECTION)
============================================================
WHAT THIS FILE DOES:
- IMPORTANT: YOLO itself has no "depth" task (unlike detect /
segment / pose / obb / classify). Depth here comes from a
separate MONOCULAR DEPTH model (MiDaS small), run alongside
YOLO26n detection on the same frame:
1. YOLO26n finds objects -> boxes + class + confidence
2. MiDaS looks at the WHOLE frame -> a per-pixel relative
"how far is this pixel" map (closer = brighter here)
The depth value at each object's box center is then shown
next to its label, plus a color depth-map preview window.
- The depth numbers are RELATIVE, not real-world meters/feet.
A single camera can't measure true distance from one image;
MiDaS gives you "closer vs farther" ordering + a rough relative
scale, not calibrated units. If you need real metric distance
you'd need a stereo camera, depth (RGB-D) camera, or LiDAR.
WHEN TO USE THIS:
Any time you need a rough sense of "which object is closer to
the camera" alongside knowing what it is, e.g.:
- basic obstacle-avoidance ("that box in front is close")
- rough "near / medium / far" zone alerts
- sorting detections by approximate distance instead of
just by confidence or size
Do NOT use this if you need precise, real-world distances
(e.g. actual speed/ANPR distance measurement) — use a
depth/stereo camera or a calibrated single-camera + known
object-size method instead.
Install deps:
pip install ultralytics opencv-python numpy torch torchvision timm
(torch + timm are needed to load the MiDaS depth model via torch.hub)
============================================================
"""
import cv2
import time
import numpy as np
import torch
from ultralytics import YOLO
# ------------------------------------------------------------
# SETTINGS
# ------------------------------------------------------------
CAMERA_INDEX = 0
FRAME_W = 1280
FRAME_H = 720
CONF_THRESHOLD = 0.45
MODEL_WEIGHTS = 'yolo26n.pt' # normal YOLO26n for "what + where"
DEPTH_MODEL_TYPE = 'MiDaS_small' # smallest/fastest MiDaS variant (good for Jetson/CPU)
DEPTH_ALPHA = 0.35 # 0 = only camera feed, 1 = only depth map (for the blended view)
def load_models():
"""Load YOLO26n (detection) and MiDaS (relative depth) once at startup."""
print("Loading YOLO26n detection model...")
yolo_model = YOLO(MODEL_WEIGHTS)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Loading MiDaS ({DEPTH_MODEL_TYPE}) depth model on {device}...")
depth_model = torch.hub.load('intel-isl/MiDaS', DEPTH_MODEL_TYPE)
depth_model.to(device).eval()
# MiDaS ships its own matching preprocessing transforms
transforms = torch.hub.load('intel-isl/MiDaS', 'transforms')
depth_transform = transforms.small_transform if 'small' in DEPTH_MODEL_TYPE.lower() \
else transforms.default_transform
print("Models ready.")
return yolo_model, depth_model, depth_transform, device
def compute_depth_map(frame, depth_model, depth_transform, device):
"""Run MiDaS on the whole frame -> a per-pixel relative depth map,
resized back to the original frame size and normalized to 0-1
(0 = farthest predicted point, 1 = closest predicted point)."""
img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
input_batch = depth_transform(img_rgb).to(device)
with torch.no_grad():
prediction = depth_model(input_batch)
prediction = torch.nn.functional.interpolate(
prediction.unsqueeze(1),
size=frame.shape[:2], # (H, W) of the original frame
mode="bicubic",
align_corners=False,
).squeeze()
depth_map = prediction.cpu().numpy()
# normalize to 0-1 so we can turn it into a color image + compare
# values consistently frame-to-frame
d_min, d_max = depth_map.min(), depth_map.max()
if d_max - d_min > 1e-6:
depth_norm = (depth_map - d_min) / (d_max - d_min)
else:
depth_norm = np.zeros_like(depth_map)
return depth_norm # higher value = closer to camera
def depth_to_label(value):
"""Turn a 0-1 relative depth value into a human-readable zone."""
if value >= 0.66:
return "NEAR"
elif value >= 0.33:
return "MID"
else:
return "FAR"
def draw_detections_with_depth(frame, results, depth_norm):
boxes = results[0].boxes
names = results[0].names
for box in boxes:
cls_id = int(box.cls[0])
conf = float(box.conf[0])
x1, y1, x2, y2 = map(int, box.xyxy[0])
cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
# sample a small patch around the center instead of a single
# pixel, so noise in the depth map doesn't flip the reading
pad = 5
y_lo, y_hi = max(cy - pad, 0), min(cy + pad, depth_norm.shape[0] - 1)
x_lo, x_hi = max(cx - pad, 0), min(cx + pad, depth_norm.shape[1] - 1)
depth_val = float(np.mean(depth_norm[y_lo:y_hi, x_lo:x_hi]))
zone = depth_to_label(depth_val)
label = f"{names[cls_id]} {conf:.2f} | {zone} ({depth_val:.2f})"
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.circle(frame, (cx, cy), 4, (0, 255, 255), -1)
cv2.putText(frame, label, (x1, y1 - 6),
cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 255, 0), 2)
return frame
def run():
yolo_model, depth_model, depth_transform, device = load_models()
cap = cv2.VideoCapture(CAMERA_INDEX)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_W)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_H)
if not cap.isOpened():
print(f"ERROR: could not open camera {CAMERA_INDEX}")
return
print("Running detection + depth estimation — press Q to quit")
print("A second window shows the raw depth map (brighter = closer).\n")
prev_t = time.time()
while True:
ok, frame = cap.read()
if not ok:
continue
# ---- Core calls --------------------------------------------
# 1) YOLO26n: what's in the frame + where (boxes)
results = yolo_model(frame, conf=CONF_THRESHOLD, verbose=False)
# 2) MiDaS: how far is every pixel (relative depth map)
depth_norm = compute_depth_map(frame, depth_model, depth_transform, device)
frame = draw_detections_with_depth(frame, results, depth_norm)
# colorized depth map for a separate preview window
depth_vis = (depth_norm * 255).astype(np.uint8)
depth_vis_color = cv2.applyColorMap(depth_vis, cv2.COLORMAP_MAGMA)
now = time.time()
fps = 1.0 / (now - prev_t) if now != prev_t else 0.0
prev_t = now
cv2.putText(frame, f"FPS: {fps:.1f} Objects: {len(results[0].boxes)}",
(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)
cv2.imshow("YOLO - Detection + Depth", frame)
cv2.imshow("Depth Map (brighter = closer)", depth_vis_color)
if cv2.waitKey(1) & 0xFF in (ord('q'), ord('Q')):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
run()