To address the issue of your camera trajectory incorrectly showing linear motion along the z-axis instead of the x-axis, we need to align the coordinate systems of Open3D and OpenCV with your desired configuration. Specifically, you want:
This discrepancy arises because Open3D and OpenCV use different conventions for the forward direction. To align them, we'll apply a fixed rotation transformation to convert the poses from Open3D's coordinate system to your desired coordinate system.
-
Define a Coordinate Conversion Rotation Matrix:
To change the forward direction from the z-axis to the x-axis, we can rotate the coordinate system around the Y-axis by -90 degrees. This rotation matrix (R_convert) transforms points from Open3D's coordinate system to your desired system.
import numpy as np
# Rotation matrix to convert Open3D's Z-forward to X-forward
R_convert = np.array([
[0, 0, -1],
[0, 1, 0],
[1, 0, 0]
])
-
Apply the Rotation to the Estimated Pose:
After estimating the rotation (R) and translation (t) between frames using OpenCV's recoverPose, apply the R_convert rotation to align the pose with your desired coordinate system.
Modify the estimate_pose method in the PoseEstimator class to include this rotation:
class PoseEstimator:
def __init__(self, focal_length, principal_point):
# ... existing initialization ...
# Define the conversion rotation matrix
self.R_convert = np.array([
[0, 0, -1],
[0, 1, 0],
[1, 0, 0]
])
def estimate_pose(self, kp1, kp2, matches, scale=1.0):
# ... existing pose estimation code ...
if R is not None and t is not None:
# Apply the conversion rotation to align coordinate systems
R_aligned = self.R_convert @ R
t_aligned = self.R_convert @ t
# Construct the transformation matrix with aligned rotation and translation
T = np.eye(4)
T[:3, :3] = R_aligned
T[:3, 3] = t_aligned.squeeze()
print(f"Aligned rotation R:\n{R_aligned}")
print(f"Aligned translation t:\n{t_aligned.T}")
return R_aligned, t_aligned
else:
print("Pose estimation failed after alignment.")
return None, None
-
Ensure Consistent Pose Updates in SLAMSystem:
In your SLAMSystem class, ensure that all pose transformations use the aligned rotation and translation. Since we've already applied R_convert in the PoseEstimator, the rest of the SLAM system can remain largely unchanged. However, it's a good practice to verify that no other transformations conflict with the new coordinate system.
class SLAMSystem:
def __init__(self, video_path, calibration_file, real_time_vis=False, model='zoe', save_point_clouds=False, frame_interval=1):
# ... existing initialization ...
# The PoseEstimator now handles coordinate conversion
self.estimator = PoseEstimator(focal_length, principal_point)
# ... rest of the initialization ...
-
Adjust Point Cloud Transformation:
When transforming the point cloud with the updated pose, no additional rotation is necessary since the pose is already aligned. However, ensure that when you save or visualize the global map, it reflects the new coordinate system.
# Inside the SLAMSystem.run() method
if not self.save_point_clouds:
current_pcd.transform(self.pose) # Pose is already aligned
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()
-
Update Camera Trajectory Plotting:
When plotting the camera trajectory, ensure that the axes labels correspond to the new coordinate system.
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 (Forward)')
ax.set_ylabel('Y (Up)')
ax.set_zlabel('Z (Right)')
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'.")
-
Verify and Fine-Tune:
-
Testing: Run your SLAM system with these changes and verify that the camera trajectory now correctly reflects forward motion along the x-axis.
-
Fine-Tuning: If you observe discrepancies, double-check the rotation matrix R_convert. Ensure that the rotation direction (clockwise vs. counter-clockwise) aligns with your coordinate system conventions.
-
Complete Modified Code Snippet:
Here's the modified PoseEstimator class with the necessary changes:
import cv2
import numpy as np
class PoseEstimator:
def __init__(self, focal_length, principal_point):
self.orb = cv2.ORB_create(5000)
self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
self.K = np.array([
[focal_length, 0, principal_point[0]],
[0, focal_length, principal_point[1]],
[0, 0, 1]
])
# Define the conversion rotation matrix
self.R_convert = np.array([
[0, 0, -1],
[0, 1, 0],
[1, 0, 0]
])
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}")
# Apply the conversion rotation to align coordinate systems
R_aligned = self.R_convert @ R
t_aligned = self.R_convert @ t
print(f"Aligned rotation R:\n{R_aligned}")
print(f"Aligned translation t:\n{t_aligned.T}")
return R_aligned, t_aligned
except Exception as e:
print(f"Exception during pose estimation: {e}")
return None, None
By applying a fixed rotation to align the coordinate systems, your camera trajectory should now correctly reflect forward motion along the x-axis, resolving the issue caused by the mismatch between Open3D and OpenCV's coordinate systems.