It seems that the issues you're encountering are due to inaccuracies in the pose estimation and scale estimation, which are causing the SLAM system to incorrectly estimate the camera trajectory, even when there's no movement (as in the video with a single image).
Here are several suggestions to address these issues:
1. Modify the Scale Estimation:
The scale estimation using depth maps might not be reliable due to noise and inaccuracies in the depth estimation. To test whether scale estimation is the issue, try setting the scale factor to a constant value (e.g., 1.0). Modify the calculate_scale function in your SLAMSystem class to return a fixed scale:
def calculate_scale(self, depth_prev, depth_curr):
# Temporarily set scale to 1.0
return 1.0
2. Improve Feature Matching:
False matches can lead to incorrect pose estimations. Make the ratio test in match_features stricter by reducing the threshold, which can eliminate many false matches. In your PoseEstimator class, modify the match_features method:
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 stricter ratio test
good_matches = []
for m, n in knn_matches:
if m.distance < 0.6 * n.distance: # Reduce the ratio threshold from 0.75 to 0.6
good_matches.append(m)
return good_matches
3. Check the Number of Inliers in Pose Estimation:
After computing the Essential matrix and recovering the pose, ensure that there are enough inliers to make a reliable pose estimation. If not, skip updating the pose for that frame. Modify the estimate_pose method in your PoseEstimator class:
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
# Count the number of inliers
inlier_count = np.sum(mask)
if inlier_count < 50: # Set an appropriate threshold based on your situation
print(f"Not enough inliers: {inlier_count}")
return None, None
_, R, t, mask_pose = cv2.recoverPose(E, pts1, pts2, self.K, mask)
# 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
4. Verify Camera Calibration:
Ensure that your camera calibration parameters are accurate and correctly loaded. Incorrect calibration can lead to errors in pose estimation. If possible, double-check your calibration file or try using default camera parameters to see if it improves the results.
In your SLAMSystem class, modify the load_camera_parameters method to print out the loaded parameters for verification:
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)
5. Adjust RANSAC Parameters:
You can try adjusting the RANSAC parameters in the findEssentialMat function to make the pose estimation more robust. For example, you can reduce the threshold to make the RANSAC more stringent:
E, mask = cv2.findEssentialMat(pts1, pts2, self.K, method=cv2.RANSAC, prob=0.999, threshold=0.5)
6. Sanity Check on Pose Updates:
Implement a sanity check on the estimated translation vector t. If the magnitude of t is unrealistically large or very small (e.g., close to zero when there should be movement, or excessively large when movement is minimal), you can choose to ignore that pose update:
if np.linalg.norm(t) > max_translation_threshold:
print("Translation is too large, skipping pose update.")
return None, None
if np.linalg.norm(t) < min_translation_threshold:
print("Translation is too small, might be noise. Skipping pose update.")
return None, None
Set appropriate values for max_translation_threshold and min_translation_threshold based on your expectations.
7. Handle Static Scenes Appropriately:
For cases where there's no movement (like your static image video), the SLAM system should ideally recognize that there's no movement. If the estimated translation and rotation are negligible, you can avoid updating the pose:
# In your main SLAM loop, after estimating R and t
if R is not None and t is not None:
translation_norm = np.linalg.norm(t)
rotation_angle = np.arccos((np.trace(R) - 1) / 2)
if translation_norm < 0.01 and rotation_angle < 0.01:
print("Negligible movement detected, skipping pose update.")
else:
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}")
# Store the camera position
camera_position = self.pose[:3, 3]
self.camera_positions.append(camera_position)
8. Additional Filtering of Point Clouds:
In the point cloud generation, ensure that you're filtering out noise effectively. Adjust the depth thresholds or brightness thresholds in your process_frame_with_depth method:
# Improved filtering parameters
min_depth = 0.5 # Adjust based on your scene
max_depth = 5.0 # Adjust based on your scene
min_brightness = 30 # Adjust to filter out very dark points
# Update the mask accordingly
mask = (scaled_depth_map.flatten() > min_depth) & \
(scaled_depth_map.flatten() < max_depth) & \
(np.mean(color_image.reshape(-1, 3), axis=1) > min_brightness)
9. Use a Different Depth Estimation Model:
If the depth estimation is a significant source of error, consider using a different depth estimation model or method that's more accurate for your specific scenario. Some models might perform better in certain environments or lighting conditions.
10. Visualize Matches and Inliers:
For debugging purposes, visualize the matched keypoints and inliers to see if the matches make sense. In your estimate_pose method, after obtaining the matches, you can draw them:
def estimate_pose(self, kp1, kp2, matches, scale=1.0):
# ... existing code ...
# Draw matches for debugging
img_matches = cv2.drawMatches(self.prev_frame, kp1, self.current_frame, kp2, matches, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
cv2.imshow('Feature Matches', img_matches)
cv2.waitKey(1) # Adjust or remove in a script
# ... continue with pose estimation ...
Make sure self.prev_frame and self.current_frame are available in your class.
11. Ensure Consistency in Camera Parameters Across Modules:
Make sure that all parts of your code (pose estimation, point cloud generation, etc.) use the same camera parameters. Inconsistencies can lead to errors.
By implementing these changes, you should see an improvement in the accuracy of the camera trajectory and the SLAM map. The key is to make the pose estimation more robust to errors and to ensure that the scale estimation does not introduce incorrect scaling due to unreliable depth data.
Summary of Changes:
- Set the scale factor to a constant value in
calculate_scale.
- Make the ratio test stricter in
match_features.
- Check the number of inliers after estimating the Essential matrix.
- Verify your camera calibration parameters.
- Adjust the RANSAC threshold in
findEssentialMat.
- Implement sanity checks on the estimated translation and rotation.
- Handle static scenes by checking for negligible movements.
- Improve the filtering of point clouds in
process_frame_with_depth.
- Consider using a more accurate depth estimation model.
- Visualize feature matches and inliers for debugging.
Implementing these suggestions should help your SLAM system produce a more accurate representation of the corridor and correctly detect turns and movements.