I created a slam script which contains 3 different scripts in total: slam.py pose_estimator.py and point_cloud_generator.py. It predicts the camera trajectory to a certain extent but it is not working correctly at the moment. Please give me detailed instructions with code examples on the project on how I can solve all these problems and how I can solve them by analyzing the code. The problems I am having are as follows:
The point clouds generated with frame interaval do not match the real world metric calculation. For example, even though I use metric3d in meters, the corridor in a video is only between 20-30 meters, but the map is almost 100 meters long. The main reason for this is that the point clouds created with frame interval overlap and are not mapped according to the actual speed and movement of the camera.
The overlapping problem leads to remapping of the same places. However, a given point should only be mapped once and then new points should be added to the map. For this reason, the point clouds created per frame are not correctly aligned.
Pose estimation is not working correctly. Orb is used as a method, but slamming with orb and making a 3d mapping using it causes many problems. For example, due to the mismatch between the coordinate systems, the straight movement is in the z direction when it should be in the x or y direction. We may use point cloud based pose estimation and icp
For example, the transformation matrices can be applied more than once because there are three different codes. There may be more than one example of this in the code.
The code currently does not apply an optimization to the three-dimensional point cloud that is extracted after the mapping is finished. For this reason, the extracted map can be quite inaccurate.
slam.py code is below
import os
import sys
import cv2
import numpy as np
import open3d as o3d
import argparse
import threading
import time
import matplotlib.pyplot as plt
from point_cloud_generator import PointCloudGenerator as MidasPointCloudGenerator
from zoe.point_cloud_generator import PointCloudGenerator as ZoePointCloudGenerator
from metric3dd.point_cloud_generator import PointCloudGenerator as Metric3DPointCloudGenerator
from pose_estimator import PoseEstimator
if model == 'midas':
self.generator = MidasPointCloudGenerator(calibration_path=calibration_file)
self.pcd_folder = 'pcd_midas'
elif model == 'metric3d':
self.generator = Metric3DPointCloudGenerator(calibration_path=calibration_file)
self.pcd_folder = 'pcd_metric'
else: # default to zoe
self.generator = ZoePointCloudGenerator(calibration_path=calibration_file)
self.pcd_folder = 'pcd_zoe'
focal_length = (self.camera_matrix[0, 0] + self.camera_matrix[1, 1]) / 2
principal_point = (self.camera_matrix[0, 2], self.camera_matrix[1, 2])
self.estimator = PoseEstimator(focal_length, principal_point)
self.cap = cv2.VideoCapture(video_path)
self.global_map = o3d.geometry.PointCloud()
self.prev_frame = None
self.pose = np.eye(4)
self.real_time_vis = real_time_vis
self.save_point_clouds = save_point_clouds
self.vis = None
self.is_running = True
self.camera_positions = []
self.vis_updated = threading.Event()
if self.real_time_vis:
self.vis = o3d.visualization.Visualizer()
self.vis.create_window()
self.vis.add_geometry(self.global_map)
self.vis_thread = threading.Thread(target=self.visualization_loop)
self.vis_thread.start()
self.frame_interval = frame_interval
self.keyframes = []
self.last_keyframe_index = -1
self.min_keyframe_distance = 10 # Minimum number of processed frames between keyframes
self.min_translation = 2 # Minimum translation to consider a new keyframe (in meters)
self.min_rotation = 20 # Minimum rotation to consider a new keyframe (in degrees)
def is_keyframe(self, frame_index, current_pose):
if not self.keyframes:
return True # Always select the first frame as a keyframe
frames_since_last_keyframe = frame_index - self.last_keyframe_index
if frames_since_last_keyframe < self.min_keyframe_distance:
return False
last_keyframe = self.keyframes[-1]
last_pose = last_keyframe['pose']
# Calculate translation and rotation between current pose and last keyframe
translation = np.linalg.norm(current_pose[:3, 3] - last_pose[:3, 3])
rotation = np.degrees(np.arccos((np.trace(current_pose[:3, :3] @ last_pose[:3, :3].T) - 1) / 2))
return translation > self.min_translation or rotation > self.min_rotation
def add_keyframe(self, frame, depth_map, pose, frame_index):
self.keyframes.append({
'frame': frame,
'depth_map': depth_map,
'pose': pose,
'index': frame_index
})
self.last_keyframe_index = frame_index
print(f"Added keyframe at frame {frame_index}")
def load_camera_parameters(self):
try:
data = np.load(self.calibration_file)
camera_matrix = data['Camera_matrix']
dist_coeffs = data['distCoeff'].ravel()
print(f"Camera matrix:\n{camera_matrix}")
print(f"Distortion coefficients: {dist_coeffs}")
return camera_matrix, dist_coeffs
except Exception as e:
print(f"Error loading camera parameters: {str(e)}")
print("Using default camera parameters")
return np.array([[700, 0, 320], [0, 700, 240], [0, 0, 1]]), np.zeros(5)
def calculate_scale(self, depth_prev, depth_curr):
depth_prev_nonzero = depth_prev[depth_prev > 0]
depth_curr_nonzero = depth_curr[depth_curr > 0]
if len(depth_prev_nonzero) == 0 or len(depth_curr_nonzero) == 0:
print("Insufficient depth information for scale calculation. Using default scale.")
return 1.0
# Use percentile-based scaling
prev_depth = np.percentile(depth_prev_nonzero, 50)
curr_depth = np.percentile(depth_curr_nonzero, 50)
if curr_depth == 0:
print("Current depth is zero, cannot calculate scale.")
return 1.0
scale = prev_depth / curr_depth
# Limit scale factor to prevent extreme values
max_scale = 1.1
min_scale = 0.9
scale = np.clip(scale, min_scale, max_scale)
print(f"Calculated scale factor: {scale}")
return scale
def update_visualization(self):
if self.real_time_vis:
self.vis.update_geometry(self.global_map)
self.vis.poll_events()
self.vis.update_renderer()
self.vis_updated.set()
def visualization_loop(self):
while self.is_running:
self.vis_updated.wait()
self.update_visualization()
self.vis_updated.clear()
def run(self):
frame_count = 0
processed_frame_count = 0
depth_prev = None
if self.save_point_clouds:
os.makedirs(self.pcd_folder, exist_ok=True)
try:
while True:
ret, frame = self.cap.read()
if not ret:
print("End of video stream.")
break
if frame_count % self.frame_interval == 0:
print(f"Processing frame {frame_count}")
point_cloud_np, depth_map = self.generator.process_frame_with_depth(frame)
if self.save_point_clouds:
pcd_filename = os.path.join(self.pcd_folder, f"frame_{frame_count:04d}.txt")
self.generator.save_point_cloud_txt(point_cloud_np, pcd_filename)
print(f"Saved point cloud to {pcd_filename}")
else:
current_pcd = o3d.geometry.PointCloud()
current_pcd.points = o3d.utility.Vector3dVector(point_cloud_np[:, :3])
current_pcd.colors = o3d.utility.Vector3dVector(point_cloud_np[:, 3:] / 255.0)
scale = None
if self.prev_frame is not None and depth_prev is not None:
gray_prev = cv2.cvtColor(self.prev_frame, cv2.COLOR_BGR2GRAY)
gray_current = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
kp1, desc1 = self.estimator.detect_and_compute(gray_prev)
kp2, desc2 = self.estimator.detect_and_compute(gray_current)
matches = self.estimator.match_features(desc1, desc2)
if len(matches) < 8:
print(f"Frame {frame_count}: Insufficient matches found ({len(matches)}). Skipping pose estimation.")
else:
scale = self.calculate_scale(depth_prev, depth_map)
R, t = self.estimator.estimate_pose(kp1, kp2, matches, scale=scale)
if R is not None and t is not None:
T = np.eye(4)
T[:3, :3] = R
T[:3, 3] = t.squeeze()
self.pose = self.pose @ T
print(f"Updated pose:\n{self.pose}")
# Add keyframe if necessary
if self.is_keyframe(processed_frame_count, self.pose):
self.add_keyframe(frame, depth_map, self.pose, processed_frame_count)
# Store the camera position
camera_position = self.pose[:3, 3]
self.camera_positions.append(camera_position)
else:
print(f"Frame {frame_count}: Pose estimation failed.")
current_pcd.transform(self.pose)
self.global_map += current_pcd
self.global_map = self.global_map.voxel_down_sample(voxel_size=0.05)
if self.real_time_vis:
self.vis_updated.set()
self.prev_frame = frame.copy()
depth_prev = depth_map.copy()
processed_frame_count +=1
frame_count += 1
except Exception as e:
print(f"An error occurred during SLAM processing: {str(e)}")
finally:
self.cap.release()
if not self.save_point_clouds:
o3d.io.write_point_cloud("global_map.pcd", self.global_map)
print("Saved global map to 'global_map.pcd'.")
if self.real_time_vis:
self.is_running = False
self.vis_thread.join()
self.vis.destroy_window()
else:
o3d.visualization.draw_geometries([self.global_map])
if len(self.camera_positions) > 0:
camera_positions = np.array(self.camera_positions)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(camera_positions[:, 0], camera_positions[:, 1], camera_positions[:, 2], 'r*-')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Camera Trajectory')
plt.show()
# Save camera trajectory to file
np.savetxt("camera_trajectory.txt", camera_positions, delimiter=",", header="X,Y,Z", comments="")
print("Saved camera trajectory to 'camera_trajectory.txt'.")
def main():
parser = argparse.ArgumentParser(description="Run SLAM system with optional real-time visualization or save point clouds")
parser.add_argument("--video_path", type=str, default="videos/kutupkisa.mp4", help="Path to input video")
parser.add_argument("--calibration_file", type=str, required=True, help="Path to camera calibration NPZ file")
parser.add_argument("--real_time_vis", action="store_true", help="Enable real-time visualization")
parser.add_argument("--model", type=str, choices=['midas', 'zoe', 'metric3d'], default='zoe', help="Choose the point cloud generation model")
parser.add_argument("--save_point_clouds", action="store_true", help="Save point clouds as txt files without running SLAM")
parser.add_argument("--frame_interval", type=int, default=1, help="Process every Nth frame (default: 1)")
args = parser.parse_args()
slam = SLAMSystem(args.video_path, args.calibration_file, args.real_time_vis, args.model, args.save_point_clouds, args.frame_interval)
slam.run()
if name == "main":
main()
point_cloud_generator.py code is below
import cv2
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
import open3d as o3d
def detect_and_compute(self, img):
keypoints, descriptors = self.orb.detectAndCompute(img, None)
return keypoints, descriptors
def match_features(self, desc1, desc2):
if desc1 is None or desc2 is None:
print("One of the descriptors is None.")
return []
# Use KNN matcher with k=2
matcher = cv2.BFMatcher(cv2.NORM_HAMMING)
knn_matches = matcher.knnMatch(desc1, desc2, k=2)
# Apply ratio test
good_matches = []
for m, n in knn_matches:
if m.distance < 0.75 * n.distance:
good_matches.append(m)
return good_matches
def estimate_pose(self, kp1, kp2, matches, scale=1.0):
if len(matches) < 8:
print("Not enough matches to compute pose.")
return None, None
try:
pts1 = np.float32([kp1[m.queryIdx].pt for m in matches])
pts2 = np.float32([kp2[m.trainIdx].pt for m in matches])
E, mask = cv2.findEssentialMat(pts1, pts2, self.K, method=cv2.RANSAC, prob=0.999, threshold=1.0)
if E is None:
print("Essential matrix computation failed.")
return None, None
_, R, t, mask_pose = cv2.recoverPose(E, pts1, pts2, self.K)
# Apply scale to the translation vector
t = t * scale
print(f"Applied scale factor: {scale}")
print(f"Estimated rotation R:\n{R}")
print(f"Estimated translation t:\n{t.T}")
return R, t
except Exception as e:
print(f"Exception during pose estimation: {e}")
return None, None
To help address the problems you're experiencing with your SLAM system, we'll walk through each issue and provide detailed explanations and code modifications where necessary.
1. Real-World Metric Scale Misalignment
Issue Explanation:
The map you're creating is significantly larger than the actual environment because the depth values from your depth estimation model may not accurately reflect real-world distances, or there might be inconsistency in scaling during pose estimation and point cloud generation.
Solution Steps:
Ensure Depth Scaling Is Correct:
Verify that the depth estimation model (Metric3D) provides depth maps in metric units (meters). Adjust the depth_scale accordingly in point_cloud_generator.py.
Adjust Depth Scaling in point_cloud_generator.py:
# PointCloudGenerator class in point_cloud_generator.py
class PointCloudGenerator:
# ...
def process_frame_with_depth(self, frame):
# ... existing code ...
# Adjust depth scaling based on Metric3D output
depth_scale = 10.0 # Adjust this value based on your depth model's output scale
scaled_depth_map = depth_map * depth_scale
# ... rest of the code ...
Note: If your corridor is estimated to be 100 meters when it should be 20-30 meters, set depth_scale = 0.2 (i.e., 20/100) to adjust the scaling factor.
Remove Scaling in Pose Estimation:
Since we're adjusting the depth scaling, we should remove any additional scaling in pose estimation to prevent double scaling.
In slam.py, remove or comment out the calculate_scale() function calls and their usage.
# SLAMSystem class in slam.py
class SLAMSystem:
# ...
def run(self):
# ... existing code ...
# Remove scale calculation and its application
# scale = self.calculate_scale(depth_prev, depth_map)
# R, t = self.estimator.estimate_pose(kp1, kp2, matches, scale=scale)
R, t = self.estimator.estimate_pose(kp1, kp2, matches)
2. Overlapping Point Clouds and Misalignment
Issue Explanation:
Overlapping point clouds indicate that the pose estimation between frames isn't accurate, leading to misalignment when mapping the current point cloud into the global map.
Solution Steps:
Use ICP for Pose Estimation Instead of ORB Features:
Replace ORB-based pose estimation with ICP (Iterative Closest Point) algorithm to align point clouds, which can provide more accurate alignment in certain contexts.
Modify slam.py to Use ICP:
# SLAMSystem class in slam.py
class SLAMSystem:
def __init__(self, ...):
# ... existing code ...
self.prev_pcd = None
def run(self):
# ... existing code ...
while True:
# ... existing code ...
if self.prev_pcd is not None:
# Perform ICP registration
threshold = 0.05 # Adjust as needed
reg_p2p = o3d.pipelines.registration.registration_icp(
current_pcd, self.prev_pcd, threshold, np.identity(4),
o3d.pipelines.registration.TransformationEstimationPointToPlane())
T = reg_p2p.transformation
self.pose = self.pose @ T
else:
T = np.identity(4)
current_pcd.transform(self.pose)
self.global_map += current_pcd
self.prev_pcd = current_pcd
# ... rest of the code ...
Update Initialization:
Remove ORB-specific initializations and variables if they're no longer needed.
Ensure Coordinate Systems Are Consistent:
Adjust the Y-axis in point cloud generation to match the coordinate system used by Open3D.
Modify Point Cloud Generation:
In point_cloud_generator.py:
# PointCloudGenerator class in point_cloud_generator.py
class PointCloudGenerator:
# ...
def process_frame_with_depth(self, frame):
# ... existing code ...
# Flip the Y-axis
points[:, 1] = -(r.flatten() - self.CY) * scaled_depth_map.flatten() / self.FY
# ... rest of the code ...
3. Coordinate System Mismatch
Issue Explanation:
A mismatch between coordinate systems in different parts of your code can lead to incorrect mapping directions, such as straight movement being represented along the Z-axis instead of the X or Y-axis.
Solution Steps:
Standardize the Coordinate System Across All Modules:
Ensure that all parts of your code use the same coordinate system, specifically with Y pointing up, as is standard in Open3D.
Adjust Point Cloud Generator:
As in the previous step, adjust the Y-axis in the point cloud generator.
Remove Redundant Transformations:
In point_cloud_generator.py, remove any transformations applied during point cloud generation, as they may interfere with global pose transformations in the SLAM system.
# Remove transformation application in point_cloud_generator.py
# Comment out or remove the following lines in process_frame_with_depth():
# transformed_points = np.dot(valid_points, self.R.T)
# homogeneous_points = np.hstack((valid_points, np.ones((valid_points.shape[0], 1))))
# transformed_points = np.dot(homogeneous_points, self.transformation.T)[:, :3]
# Replace with:
transformed_points = valid_points
4. Prevent Applying Transformation Matrices Multiple Times
Issue Explanation:
Applying transformation matrices in multiple places can lead to compounded transformations that misrepresent the true pose.
Solution Steps:
Apply Transformations in One Place:
Ensure that all coordinate transformations are applied solely in the SLAM system's main loop.
In point_cloud_generator.py:
As previously mentioned, remove any transformations being applied to the point cloud in the point cloud generator.
In slam.py:
Apply all transformations to the point clouds within the SLAM system after pose estimation.
5. Map Optimization for Improved Accuracy
Issue Explanation:
Accumulated errors over time can degrade the quality of the map. Optimizing the map after initial mapping helps reduce these errors.
Solution Steps:
Implement Pose Graph Optimization:
Use Open3D's pose graph optimization capabilities to refine camera poses and the global map.
Set Up a Pose Graph:
# In SLAMSystem class in slam.py
class SLAMSystem:
def __init__(self, ...):
# ... existing code ...
self.pose_graph = o3d.pipelines.registration.PoseGraph()
self.pose_graph.nodes.append(o3d.pipelines.registration.PoseGraphNode(np.identity(4)))
def run(self):
# ... existing code ...
if self.prev_pcd is not None:
# ... ICP registration code ...
# Add an edge to the pose graph
information = reg_p2p.get_information_matrix()
self.pose_graph.edges.append(
o3d.pipelines.registration.PoseGraphEdge(
frame_count - 1, frame_count, T, information, uncertain=False))
else:
T = np.identity(4)
# Update the pose graph node
self.pose_graph.nodes.append(o3d.pipelines.registration.PoseGraphNode(np.linalg.inv(self.pose)))
Optimize the Pose Graph After Mapping:
# After the mapping loop in run():
option = o3d.pipelines.registration.GlobalOptimizationOption(
max_correspondence_distance=0.05,
edge_prune_threshold=0.25,
reference_node=0)
o3d.pipelines.registration.global_optimization(
self.pose_graph,
o3d.pipelines.registration.GlobalOptimizationLevenbergMarquardt(),
o3d.pipelines.registration.GlobalOptimizationConvergenceCriteria(),
option)
Update Point Clouds with Optimized Poses:
# Update the global map with optimized poses
self.global_map.clear()
for i, node in enumerate(self.pose_graph.nodes):
# Load or keep track of individual point clouds per frame
pcd_i = self.load_point_cloud(i) # Implement this method to retrieve or store individual point clouds
pcd_i.transform(node.pose)
self.global_map += pcd_i
You'll need to store individual point clouds for each frame to re-integrate them after optimization.
Additional Notes:
Implementing load_point_cloud():
You'll need a method to store and retrieve each frame's point cloud. Modify your code to save each point cloud during processing.
# In SLAMSystem class in slam.py
class SLAMSystem:
# ...
def run(self):
# ... existing code ...
# Save current point cloud
self.save_point_cloud(current_pcd, frame_count)
def save_point_cloud(self, pcd, index):
o3d.io.write_point_cloud(f"pcds/frame_{index:04d}.pcd", pcd)
def load_point_cloud(self, index):
return o3d.io.read_point_cloud(f"pcds/frame_{index:04d}.pcd")
Create a directory pcds to store the point clouds.
Adjust Thresholds and Parameters:
The values for ICP thresholds, voxel sizes, and optimization options may need tweaking based on your specific dataset and environment.
Monitor and Debug:
Visualize intermediate results to monitor pose estimation and point cloud alignment. Use logs and plots to debug issues at each step.
Summary:
By adjusting depth scaling, aligning coordinate systems, removing redundant transformations, switching to ICP for pose estimation, and applying pose graph optimization, you should be able to resolve the issues with scale, overlapping point clouds, pose estimation inaccuracies, redundant transformations, and map inaccuracy.
Implementing the Changes:
Adjust Depth Scaling:
In point_cloud_generator.py:
depth_scale = 1.0 # Adjust based on your depth model
scaled_depth_map = depth_map * depth_scale
if self.prev_pcd is not None:
# Perform ICP registration
# ... ICP code as provided above ...
current_pcd.transform(self.pose)
else:
current_pcd.transform(self.pose)
Implement Pose Graph Optimization:
Add pose graph construction and optimization.
# Pose graph code as provided above
Store Individual Point Clouds:
Save and load point clouds for optimization.
# Methods save_point_cloud and load_point_cloud
Adjust Parameters as Needed:
Tweak thresholds, scales, and voxel sizes.
Test and Iterate:
Test the modified system, visualize results, and adjust parameters as needed.
By following these steps and incorporating the code changes, you should be able to resolve the issues in your SLAM system and improve its accuracy and consistency.