27 KiB
27 KiB
In [ ]:
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from pathlib import PathIn [ ]:
save_images = False
save_disparity_map = True
upper_line = 300
lower_line = 440In [ ]:
PAIR_ID = 1
pair_folder = Path("images") / str(PAIR_ID)
left_candidates = sorted(pair_folder.glob("left_img.*"))
right_candidates = sorted(pair_folder.glob("right_img.*"))
if not left_candidates or not right_candidates:
raise FileNotFoundError(
f"Could not find left_img.* and right_img.* in {pair_folder}"
)
left_image_path = left_candidates[0]
right_image_path = right_candidates[0]
print("Using left image:", left_image_path)
print("Using right image:", right_image_path)In [ ]:
img1 = cv.imread(str(left_image_path), cv.IMREAD_GRAYSCALE)
img2 = cv.imread(str(right_image_path), cv.IMREAD_GRAYSCALE)
fig, axes = plt.subplots(1, 2, figsize=(15, 10))
axes[0].imshow(img1, cmap="gray")
axes[1].imshow(img2, cmap="gray")
axes[0].axhline(upper_line)
axes[1].axhline(upper_line)
axes[0].axhline(lower_line)
axes[1].axhline(lower_line)
plt.suptitle("Original images")
if save_images == True:
plt.savefig("original_images.png")
plt.show()In [ ]:
# TODO: find the keypoints and descriptors with SIFT
# kp1, des1 = TODO
# kp2, des2 = TODO
# YOUR CODE HERE
raise NotImplementedError("Task 1: Implement SIFT keypoint detection and descriptor extraction.")In [ ]:
imgSift1 = cv.drawKeypoints(
img1, kp1, None, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS
)
imgSift2 = cv.drawKeypoints(
img2, kp2, None, cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS
)
plt.figure(figsize=(10, 8))
plt.imshow(cv.cvtColor(imgSift1, cv.COLOR_BGR2RGB))
plt.title("SIFT Keypoints - left image")
plt.axis("off")
plt.show()
plt.figure(figsize=(10, 8))
plt.imshow(cv.cvtColor(imgSift2, cv.COLOR_BGR2RGB))
plt.title("SIFT Keypoints - right image")
plt.axis("off")
plt.show()
if save_images:
cv.imwrite("Keypoints left_img.png", imgSift1)
cv.imwrite("Keypoints right_img.png", imgSift2)In [ ]:
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
# TODO: Match keypoints in both images using FLANN
# flann = TODO
# matches = TODO
# YOUR CODE HERE
raise NotImplementedError("Task 2: Implement FLANN matcher and compute descriptor matches.")In [ ]:
matchesMask = [[0, 0] for i in range(len(matches))]
good = []
pts1 = []
pts2 = []
for i, (m, n) in enumerate(matches):
if m.distance < 0.7 * n.distance:
matchesMask[i] = [1, 0]
good.append(m)
pts2.append(kp2[m.trainIdx].pt)
pts1.append(kp1[m.queryIdx].pt)
draw_params = dict(
matchColor=(0, 255, 0),
singlePointColor=(255, 0, 0),
matchesMask=matchesMask,
flags=cv.DrawMatchesFlags_DEFAULT
)
keypoint_matches = cv.drawMatchesKnn(
img1, kp1, img2, kp2, matches, None, **draw_params
)
plt.figure(figsize=(18, 8))
plt.imshow(cv.cvtColor(keypoint_matches, cv.COLOR_BGR2RGB))
plt.title("Keypoint matches")
plt.axis("off")
plt.show()
if save_images == True:
cv.imwrite("Keypoint matches.png", keypoint_matches)In [ ]:
pts1 = np.int32(pts1)
pts2 = np.int32(pts2)
# TODO: Calculate the fundamental matrix for relating the two cameras
# fundamental_matrix, inliers = TODO
# YOUR CODE HERE
raise NotImplementedError("Task 3: Compute the fundamental matrix using RANSAC.")In [ ]:
pts1 = pts1[inliers.ravel() == 1]
pts2 = pts2[inliers.ravel() == 1]In [ ]:
def drawlines(img1src, img2src, lines, pts1src, pts2src):
''' img1 - image on which we draw the epilines for the points in img2
lines - corresponding epilines '''
r, c = img1src.shape
img1color = cv.cvtColor(img1src, cv.COLOR_GRAY2BGR)
img2color = cv.cvtColor(img2src, cv.COLOR_GRAY2BGR)
np.random.seed(0)
for r, pt1, pt2 in zip(lines, pts1src, pts2src):
color = tuple(np.random.randint(0, 255, 3).tolist())
x0, y0 = map(int, [0, -r[2] / r[1]])
x1, y1 = map(int, [c, -(r[2] + r[0] * c) / r[1]])
img1color = cv.line(img1color, (x0, y0), (x1, y1), color, 1)
img1color = cv.circle(img1color, tuple(pt1), 5, color, -1)
img2color = cv.circle(img2color, tuple(pt2), 5, color, -1)
return img1color, img2colorIn [ ]:
# TODO: Find epilines corresponding to points in right image (second image)
# and draw its lines on the left image
# lines1 = TODO
# YOUR CODE HERE
raise NotImplementedError("Task 4a: Compute epilines for points from the right image.")
lines1 = lines1.reshape(-1, 3)
img5, img6 = drawlines(img1, img2, lines1, pts1, pts2)
# TODO: Find epilines corresponding to points in left image (first image)
# and draw its lines on the right image
# lines2 = TODO
# YOUR CODE HERE
raise NotImplementedError("Task 4b: Compute epilines for points from the left image.")
lines2 = lines2.reshape(-1, 3)
img3, img4 = drawlines(img2, img1, lines2, pts2, pts1)
plt.subplot(121), plt.imshow(img5)
plt.subplot(122), plt.imshow(img3)
plt.suptitle("Epilines in both images")
if save_images == True:
plt.savefig("Epilines in both images.png")
plt.show()In [ ]:
h1, w1 = img1.shape
h2, w2 = img2.shape
# TODO: Stereo rectification using the uncalibrated variant
# _, H1, H2 = TODO
# TODO: Undistort / rectify the images
# img1_rectified = TODO
# img2_rectified = TODO
# YOUR CODE HERE
raise NotImplementedError("Task 5: Implement uncalibrated stereo rectification and warp both images.")In [ ]:
if save_images == True:
cv.imwrite("rectified_1.png", img1_rectified)
cv.imwrite("rectified_2.png", img2_rectified)
fig, axes = plt.subplots(1, 2, figsize=(15, 10))
axes[0].imshow(img1_rectified, cmap="gray")
axes[1].imshow(img2_rectified, cmap="gray")
axes[0].axhline(upper_line)
axes[1].axhline(upper_line)
axes[0].axhline(lower_line)
axes[1].axhline(lower_line)
plt.suptitle("Rectified images")
if save_images == True:
plt.savefig("rectified_images.png")
plt.show()In [ ]:
block_size = 9
min_disp = -64
max_disp = 64
num_disp = max_disp - min_disp
uniquenessRatio = 5
speckleWindowSize = 200
speckleRange = 2
disp12MaxDiff = 0
# TODO: calculate the disparity map
# stereo = TODO
# disparity_SGBM = TODO
# YOUR CODE HERE
raise NotImplementedError("Task 6: Create StereoSGBM and compute the disparity map.")In [ ]:
disparity_SGBM = cv.normalize(
disparity_SGBM,
disparity_SGBM,
alpha=255,
beta=0,
norm_type=cv.NORM_MINMAX
)
disparity_SGBM = np.uint8(disparity_SGBM)
plt.figure(figsize=(10, 7))
plt.imshow(disparity_SGBM, cmap="gray")
plt.title("Disparity")
plt.axis("off")
plt.show()
if save_images == True or save_disparity_map == True:
cv.imwrite("disparity_SGBM_norm.png", disparity_SGBM)
plt.imshow(disparity_SGBM, cmap="plasma")
plt.colorbar()
if save_images == True:
plt.savefig("Colored disparity map.png")
plt.show()In [ ]:
# Example: Static transform from camera_link to base_link
t_base_camera = np.array([0.12, 0.0, 0.155])
R_base_camera = np.eye(3)
T_base_camera = np.eye(4)
T_base_camera[:3, :3] = R_base_camera
T_base_camera[:3, 3] = t_base_camera
print("T_base_camera:")
print(T_base_camera)In [ ]:
# Example detected point in camera_link frame
# Homogeneous coordinate: [x, y, z, 1]
p_camera = np.array([2.0, 0.0, 0.0, 1.0])
# Transform detected point from camera_link to base_link
p_base = T_base_camera @ p_camera
print("Point in camera_link:")
print(p_camera)
print("\nPoint transformed to base_link:")
print(p_base)In [ ]:
# TODO: Declare the car/base_link position and yaw in the map frame
x_map_base = ...
y_map_base = ...
z_map_base = ...
yaw_map_base_deg = ...
# YOUR CODE HERE
raise NotImplementedError("Task 7.1: Declare the base_link pose in the map frame.")
print("base_link position in map:")
print(x_map_base, y_map_base, z_map_base)
print("\nyaw angle in degrees:")
print(yaw_map_base_deg)In [ ]:
# TODO: Convert yaw from degrees to radians
yaw = ...
# TODO: Build the 3x3 yaw rotation matrix around the z-axis
R_map_base = ...
# YOUR CODE HERE
raise NotImplementedError("Task 7.2: Build the yaw rotation matrix R_map_base.")
print("yaw in radians:")
print(yaw)
print("\nR_map_base:")
print(R_map_base)In [ ]:
# TODO: Build the homogeneous transformation matrix T_map_base
T_map_base = ...
T_map_base[:3, :3] = ...
T_map_base[:3, 3] = ...
# YOUR CODE HERE
raise NotImplementedError("Task 7.3: Build the homogeneous transformation matrix T_map_base.")
print("T_map_base:")
print(T_map_base)In [ ]:
# TODO: Transform the detected point from base_link to map
p_map = ...
# YOUR CODE HERE
raise NotImplementedError("Task 7.4: Transform the detected point into the map frame.")
print("Point in base_link:")
print(p_base)
print("\nPoint transformed to map:")
print(p_map)In [ ]:
from mpl_toolkits.mplot3d import Axes3D
def plot_frame(ax, T, name, axis_length=0.4):
"""Plot a coordinate frame from a 4x4 homogeneous transform."""
origin = T[:3, 3]
x_axis = T[:3, 0] * axis_length
y_axis = T[:3, 1] * axis_length
z_axis = T[:3, 2] * axis_length
ax.quiver(origin[0], origin[1], origin[2], x_axis[0], x_axis[1], x_axis[2], color="r", arrow_length_ratio=0.15)
ax.quiver(origin[0], origin[1], origin[2], y_axis[0], y_axis[1], y_axis[2], color="g", arrow_length_ratio=0.15)
ax.quiver(origin[0], origin[1], origin[2], z_axis[0], z_axis[1], z_axis[2], color="b", arrow_length_ratio=0.15)
ax.text(origin[0], origin[1], origin[2], f" {name}", fontsize=10)
T_map = np.eye(4)
T_map_camera = T_map_base @ T_base_camera
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection="3d")
plot_frame(ax, T_map, "map", axis_length=0.6)
plot_frame(ax, T_map_base, "base_link", axis_length=0.5)
plot_frame(ax, T_map_camera, "camera_link", axis_length=0.4)
ax.scatter(p_map[0], p_map[1], p_map[2], s=60, marker="o", label="Detected point in map")
base_origin = T_map_base[:3, 3]
ax.scatter(base_origin[0], base_origin[1], base_origin[2], s=50, marker="^", label="base_link origin")
camera_origin = T_map_camera[:3, 3]
ax.scatter(camera_origin[0], camera_origin[1], camera_origin[2], s=50, marker="s", label="camera_link origin")
ax.set_title("Coordinate Frame Visualization")
ax.set_xlabel("X [m]")
ax.set_ylabel("Y [m]")
ax.set_zlabel("Z [m]")
ax.legend()
ax.grid(True)
all_points = np.array([T_map[:3, 3], T_map_base[:3, 3], T_map_camera[:3, 3], p_map[:3]])
max_range = np.ptp(all_points, axis=0).max()
center = all_points.mean(axis=0)
if max_range == 0:
max_range = 1.0
ax.set_xlim(center[0] - max_range, center[0] + max_range)
ax.set_ylim(center[1] - max_range, center[1] + max_range)
ax.set_zlim(center[2] - max_range / 2, center[2] + max_range / 2)
plt.show()














