Files
avai/02/Perception/Perception_Assignment_Muster.ipynb
T
2026-06-03 17:09:31 +02:00

4.9 MiB

Assignment 4: Stereo Vision

Fill in only the TODO parts.

The package includes four stereo test pairs in:

test_images/1/
test_images/2/
test_images/3/
test_images/4/

Imports

Import the required libraries for numerical operations, image processing, and plotting.

In [1]:
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from pathlib import Path

Settings

These flags control whether intermediate images and the final disparity map are saved.

The two horizontal guide lines are used to visually compare the left and right images before and after rectification.

In [2]:
save_images = False
save_disparity_map = True

upper_line = 300
lower_line = 440

Available test image pairs

The four stereo input pairs are included below for reference.

Pair 1

Left image
Right image

Pair 2

Left image
Right image

Pair 3

Left image
Right image

Pair 4

Left image
Right image

Select one stereo image pair

Choose which test pair should be used for the current run by changing PAIR_ID.

For example:

PAIR_ID = 1

To test another pair, change it to 2, 3, or 4.

In [3]:
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)
Using left image: images\1\left_img.png
Using right image: images\1\right_img.png

Read the stereo image pair

Read the selected left and right images as grayscale images.

Example output after loading and plotting the original pair:

In [4]:
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()

Task 1: Detect keypoints and descriptors

Use SIFT to detect keypoints and compute descriptors for both images.

The descriptors are later used to match points between the left and right image.

Example SIFT keypoints on the left image:

Example SIFT keypoints on the right image:

In [5]:
# TODO: find the keypoints and descriptors with SIFT
# kp1, des1 = TODO
# kp2, des2 = TODO

# YOUR CODE HERE
sift = cv.SIFT_create()

kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
In [6]:
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)

Task 2: Match keypoints using FLANN

Match the SIFT descriptors from the left image with the descriptors from the right image.

After matching, Lowe's ratio test is used to keep only stronger matches.

Example keypoint matches:

In [7]:
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
flann = cv.FlannBasedMatcher(index_params, search_params)

des1 = np.float32(des1)
des2 = np.float32(des2)

matches = flann.knnMatch(des1, des2, k=2)
In [8]:
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)

Task 3: Calculate the fundamental matrix

Use the matched keypoints to estimate the fundamental matrix.

The fundamental matrix describes the epipolar geometry between the two images. RANSAC is used to reject outlier matches.

In [9]:
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
fundamental_matrix, inliers = cv.findFundamentalMat(
    pts1,
    pts2,
    cv.FM_RANSAC,
    3.0,
    0.99
)
In [10]:
pts1 = pts1[inliers.ravel() == 1]
pts2 = pts2[inliers.ravel() == 1]

Task 4: Draw epipolar lines

For a point in one image, the corresponding point in the other image should lie on its epipolar line.

This visualization helps check the estimated geometry.

Example epipolar line visualization:

In [11]:
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, img2color
In [12]:
# TODO: Find epilines corresponding to points in right image (second image)
# and draw its lines on the left image
# lines1 = TODO

# YOUR CODE HERE
lines1 = cv.computeCorrespondEpilines(
    pts2.reshape(-1, 1, 2),
    2,
    fundamental_matrix
)
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
lines2 = cv.computeCorrespondEpilines(
    pts1.reshape(-1, 1, 2),
    1,
    fundamental_matrix
)

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()

Task 5: Stereo rectification

Rectification warps both images so that corresponding points lie on the same horizontal scanline.

This makes the disparity calculation easier.

Example rectified image pair:

In [13]:
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
retval, H1, H2 = cv.stereoRectifyUncalibrated(
    np.float32(pts1),
    np.float32(pts2),
    fundamental_matrix,
    imgSize=(w1, h1)
)

if not retval:
    raise RuntimeError("Stereo rectification failed.")

img1_rectified = cv.warpPerspective(img1, H1, (w1, h1))
img2_rectified = cv.warpPerspective(img2, H2, (w2, h2))
In [14]:
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()

Task 6: Calculate the disparity map

Use StereoSGBM to calculate the disparity map from the rectified stereo pair.

The grayscale disparity map is saved without the colormap.
The colored version is only for easier visualization.

Example grayscale disparity map:

Example colored disparity map:

In [15]:
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
stereo = cv.StereoSGBM_create(
    minDisparity=min_disp,
    numDisparities=num_disp,
    blockSize=block_size,
    P1=8 * 1 * block_size ** 2,
    P2=32 * 1 * block_size ** 2,
    disp12MaxDiff=disp12MaxDiff,
    uniquenessRatio=uniquenessRatio,
    speckleWindowSize=speckleWindowSize,
    speckleRange=speckleRange,
    preFilterCap=63,
    mode=cv.STEREO_SGBM_MODE_SGBM_3WAY
)

disparity_SGBM = stereo.compute(
    img1_rectified,
    img2_rectified
).astype(np.float32) / 16.0
In [16]:
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()

Coordinate Transform for Perception Results

In the stereo vision part, we estimate depth/disparity from camera images. In a real perception pipeline, a detected point is first known in the camera frame. To use this point for planning or for a world/map model, we need to express it in another frame.

In this task, use the frame chain:

camera_link → base_link → map

The transform from camera_link to base_link is shown as an example. Then you complete the base_link → map transform step by step.

The camera mounting pose is taken from the vehicle description:

camera_link relative to base_link:
x = 0.12 m, y = 0.0 m, z = 0.155 m
roll = 0, pitch = 0, yaw = 0

This means the camera is 12 cm in front of the vehicle base and 15.5 cm above it.

The following cell is already completed as an example.

In [17]:
# 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)
T_base_camera:
[[1.    0.    0.    0.12 ]
 [0.    1.    0.    0.   ]
 [0.    0.    1.    0.155]
 [0.    0.    0.    1.   ]]

Example: A detected point in the camera frame

Assume the perception system detected one point in the camera frame.

We use homogeneous coordinates:

[x, y, z, 1]

The example point below is 2.0 m in front of the camera.

In [18]:
# 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)
Point in camera_link:
[2. 0. 0. 1.]

Point transformed to base_link:
[2.12  0.    0.155 1.   ]

Task 7.1: Declare the car pose in the map frame

Now assume the car itself has a pose in the map frame.

Use the following values:

base_link position in map:
x = 4.0 m
y = 2.0 m
z = 0.0 m

base_link orientation in map:
yaw = 30 degrees

Fill in the missing values below.

In [19]:
# 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
x_map_base = 4.0
y_map_base = 2.0
z_map_base = 0.0
yaw_map_base_deg = 30.0

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)
base_link position in map:
4.0 2.0 0.0

yaw angle in degrees:
30.0

Task 7.2: Convert yaw and build the rotation matrix

The car orientation is given as a yaw angle.

Convert the yaw angle from degrees to radians, then build the 3×3 rotation matrix around the z-axis:

R_map_base
In [20]:
# 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
yaw = np.deg2rad(yaw_map_base_deg)

R_map_base = np.array([
    [np.cos(yaw), -np.sin(yaw), 0.0],
    [np.sin(yaw),  np.cos(yaw), 0.0],
    [0.0,          0.0,         1.0]
])

print("yaw in radians:")
print(yaw)

print("\nR_map_base:")
print(R_map_base)
yaw in radians:
0.5235987755982988

R_map_base:
[[ 0.8660254 -0.5        0.       ]
 [ 0.5        0.8660254  0.       ]
 [ 0.         0.         1.       ]]

Task 7.3: Build the homogeneous transform T_map_base

Now combine translation and rotation into a 4×4 homogeneous transformation matrix.

This matrix transforms a point from base_link coordinates into map coordinates.

In [22]:
# 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
T_map_base = np.eye(4)
T_map_base[:3, :3] = R_map_base
T_map_base[:3, 3] = np.array([x_map_base, y_map_base, z_map_base])

print("T_map_base:")
print(T_map_base)
T_map_base:
[[ 0.8660254 -0.5        0.         4.       ]
 [ 0.5        0.8660254  0.         2.       ]
 [ 0.         0.         1.         0.       ]
 [ 0.         0.         0.         1.       ]]

Task 7.4: Transform the detected point into the map frame

The point has already been transformed from camera_link to base_link.

Now transform it from:

base_link → map

This gives the position of the detected point in the world/map model.

In [23]:
# TODO: Transform the detected point from base_link to map

p_map = ...

# YOUR CODE HERE
p_map = T_map_base @ p_base

print("Point in base_link:")
print(p_base)

print("\nPoint transformed to map:")
print(p_map)
Point in base_link:
[2.12  0.    0.155 1.   ]

Point transformed to map:
[5.83597386 3.06       0.155      1.        ]

Task 7.5: Visualize the coordinate frames

After completing the coordinate transform TODOs, run the following cell to visualize the frames.

The plot shows:

  • map
  • base_link
  • camera_link
  • detected point in map

This is only a visualization helper. It does not change the transformation logic.

In [24]:
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()