import argparse
import torch
import cv2
import numpy as np
import open3d as o3d
import sys
import time
import os
class SLAMSystem:
def __init__(self, input_source, calib_path, frame_interval, visualize):
"""
Initialize the SLAM system.
Args:
input_source (str): Path to video file or camera ID (integer as string).
calib_path (str): Path to calibration .npz file.
frame_interval (int): Interval to process frames.
visualize (bool): Whether to visualize the mapping in real-time.
"""
self.input_source = input_source
self.calib_path = calib_path
self.frame_interval = frame_interval
self.visualize = visualize
# Initialize video capture
self.cap = self.initialize_video_capture(self.input_source)
if not self.cap.isOpened():
print(f"Error: Cannot open video source {self.input_source}")
sys.exit(1)
# Load calibration matrix
self.K, self.dist_coeffs, self.R_init, self.t_init = self.load_calibration(self.calib_path)
# Load Metric3D model
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
try:
print("Loading Metric3D model from PyTorch Hub...")
self.metric3d_model = torch.hub.load('yvanyin/metric3d', 'metric3d_vit_large', pretrained=True)
self.metric3d_model.to(self.device)
self.metric3d_model.eval()
print("Metric3D model loaded successfully.")
except Exception as e:
print(f"Error loading Metric3D model: {e}")
sys.exit(1)
# Initialize pose
self.pose = np.eye(4)
# Initialize point cloud
self.global_pcd = o3d.geometry.PointCloud()
# Initialize Open3D visualizer
if self.visualize:
self.vis = o3d.visualization.Visualizer()
self.vis.create_window()
self.vis.add_geometry(self.global_pcd)
# Initialize feature matcher for pose estimation
self.orb = cv2.ORB_create(2000)
self.bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
self.prev_frame = None
self.prev_kp = None
self.prev_desc = None
def initialize_video_capture(self, source):
"""
Initialize OpenCV VideoCapture.
Args:
source (str): Video file path or camera ID.
Returns:
cv2.VideoCapture: VideoCapture object.
"""
# Check if source is digit (camera ID)
if source.isdigit():
source = int(source)
return cv2.VideoCapture(source)
def load_calibration(self, calib_path):
"""
Load camera calibration from .npz file.
Args:
calib_path (str): Path to calibration .npz file.
Returns:
K (np.ndarray): Camera intrinsic matrix.
dist_coeffs (np.ndarray): Distortion coefficients.
R_init (np.ndarray): Initial rotation vector.
t_init (np.ndarray): Initial translation vector.
"""
if calib_path is not None and os.path.exists(calib_path):
try:
calib = np.load(calib_path)
K = calib['Camera_matrix']
dist_coeffs = calib['distCoeff']
R_init = calib['RotationalV']
t_init = calib['TranslationV']
print(f"Loaded calibration from {calib_path}.")
return K, dist_coeffs, R_init, t_init
except Exception as e:
print(f"Error loading calibration file: {e}")
sys.exit(1)
else:
print("No calibration file provided or file does not exist. Using default calibration matrix.")
# Default calibration matrix
K = np.array([[726.65937849, 0. , 419.37380341],
[ 0. , 726.16188065, 249.3021722 ],
[ 0. , 0. , 1. ]])
dist_coeffs = np.array([[ 1.69558413e-01, -6.27337858e-01, -1.37015088e-03,
7.96379361e-04, 8.22763173e-01]])
R_init = np.array([[[ 0.0796394 ],
[ 0.43195933],
[-0.07977802]]])
t_init = np.array([[0], [0], [0]])
return K, dist_coeffs, R_init, t_init
def estimate_depth(self, frame):
"""
Estimate depth map using Metric3D model.
Args:
frame (np.ndarray): Input RGB frame.
Returns:
depth_map (np.ndarray): Estimated depth map.
"""
with torch.no_grad():
# Preprocess frame
input_tensor = torch.from_numpy(frame).permute(2, 0, 1).float().to(self.device) / 255.0
input_tensor = input_tensor.unsqueeze(0) # Add batch dimension
# Forward pass
depth = self.metric3d_model(input_tensor)
depth = depth.squeeze().cpu().numpy()
# Normalize depth for visualization (optional)
depth_min = depth.min()
depth_max = depth.max()
depth_normalized = (depth - depth_min) / (depth_max - depth_min)
return depth
def extract_features(self, frame):
"""
Extract ORB features from a frame.
Args:
frame (np.ndarray): Grayscale frame.
Returns:
keypoints (list): Detected keypoints.
descriptors (np.ndarray): Feature descriptors.
"""
kp, desc = self.orb.detectAndCompute(frame, None)
return kp, desc
def estimate_pose_rel(self, frame_prev, frame_curr):
"""
Estimate the relative pose between two frames.
Args:
frame_prev (np.ndarray): Previous RGB frame.
frame_curr (np.ndarray): Current RGB frame.
Returns:
R (np.ndarray): Rotation matrix (3x3).
t (np.ndarray): Translation vector (3x1).
"""
# Convert to grayscale
gray_prev = cv2.cvtColor(frame_prev, cv2.COLOR_BGR2GRAY)
gray_curr = cv2.cvtColor(frame_curr, cv2.COLOR_BGR2GRAY)
# Extract features
kp1, desc1 = self.extract_features(gray_prev)
kp2, desc2 = self.extract_features(gray_curr)
if desc1 is None or desc2 is None:
print("No descriptors found. Skipping pose estimation for this frame.")
return None, None
# Match descriptors
matches = self.bf.match(desc1, desc2)
matches = sorted(matches, key=lambda x: x.distance)
if len(matches) < 8:
print("Not enough matches for pose estimation.")
return None, None
# Extract matched keypoints
pts1 = np.array([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 2)
pts2 = np.array([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 2)
# Compute Essential matrix
E, mask = cv2.findEssentialMat(pts2, pts1, focal=self.K[0,0], pp=(self.K[0,2], self.K[1,2]), method=cv2.RANSAC, prob=0.999, threshold=1.0)
if E is None:
print("Essential matrix computation failed.")
return None, None
# Recover pose
_, R, t, mask_pose = cv2.recoverPose(E, pts2, pts1, focal=self.K[0,0], pp=(self.K[0,2], self.K[1,2]))
return R, t
def depth_to_point_cloud(self, depth_map, frame):
"""
Convert depth map and RGB frame to Open3D point cloud.
Args:
depth_map (np.ndarray): Depth map.
frame (np.ndarray): RGB frame.
Returns:
o3d.geometry.PointCloud: Point cloud.
"""
h, w = depth_map.shape
i, j = np.meshgrid(np.arange(w), np.arange(h), indexing='xy')
z = depth_map
x = (i - self.K[0,2]) * z / self.K[0,0]
y = (j - self.K[1,2]) * z / self.K[1,1]
points = np.stack((x, y, z), axis=-1).reshape(-1, 3)
colors = frame.reshape(-1, 3) / 255.0 # Normalize colors
# Remove points with zero depth
mask = z.reshape(-1) > 0
points = points[mask]
colors = colors[mask]
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(points)
pcd.colors = o3d.utility.Vector3dVector(colors)
return pcd
def run(self):
"""
Run the SLAM system.
"""
frame_idx = 0
success, frame = self.cap.read()
if not success:
print("Failed to read the first frame.")
sys.exit(1)
# Initialize by processing the first frame
depth_map = self.estimate_depth(frame)
pcd = self.depth_to_point_cloud(depth_map, frame)
self.global_pcd += pcd
if self.visualize:
self.vis.update_geometry(self.global_pcd)
self.vis.poll_events()
self.vis.update_renderer()
self.prev_frame = frame
while True:
success, frame = self.cap.read()
if not success:
print("End of video stream or cannot fetch the frame.")
break
frame_idx += 1
if frame_idx % self.frame_interval != 0:
continue
# Estimate depth
depth_map = self.estimate_depth(frame)
# Estimate pose
R, t = self.estimate_pose_rel(self.prev_frame, frame)
if R is not None and t is not None:
# Update pose
Rt = np.eye(4)
Rt[:3, :3] = R
Rt[:3, 3] = t.flatten()
self.pose = self.pose @ np.linalg.inv(Rt) # Update global pose
else:
print("Pose not updated for this frame due to insufficient data.")
Rt = np.eye(4)
# Convert depth map to point cloud
pcd = self.depth_to_point_cloud(depth_map, frame)
# Transform point cloud to global frame
pcd.transform(self.pose)
# Merge into global point cloud
self.global_pcd += pcd
# Optionally visualize
if self.visualize:
self.vis.clear_geometries()
self.vis.add_geometry(self.global_pcd)
self.vis.poll_events()
self.vis.update_renderer()
# Update previous frame
self.prev_frame = frame
# Optional: Print progress
print(f"Processed frame {frame_idx}")
# After processing all frames
if self.visualize:
self.vis.destroy_window()
# Save point cloud
output_pcd = "final_map.pcd"
o3d.io.write_point_cloud(output_pcd, self.global_pcd)
print(f"Final point cloud saved to {output_pcd}")
# Release video capture
self.cap.release()
def parse_arguments():
"""
Parse command-line arguments.
Returns:
args: Parsed arguments.
"""
parser = argparse.ArgumentParser(description="Real-time 3D SLAM using RGB video input and Metric3D depth estimation.")
parser.add_argument('--input', type=str, required=True,
help='Path to input video file or camera ID (integer as string).')
parser.add_argument('--calib', type=str, default=None,
help='Path to camera calibration .npz file.')
parser.add_argument('--interval', type=int, default=5,
help='Frame interval for processing (default: 5).')
parser.add_argument('--visualize', action='store_true',
help='Enable real-time visualization using Open3D.')
args = parser.parse_args()
return args
def main():
args = parse_arguments()
slam = SLAMSystem(
input_source=args.input,
calib_path=args.calib,
frame_interval=args.interval,
visualize=args.visualize
)
slam.run()
if __name__ == "__main__":
main()