"""Offline OpenCV lab for Ch21: feature detection, matching, homography & image stitching."""
import json
import platform
import cv2
import numpy as np
def build_textured_panorama() -> np.ndarray:
"""Create a rich 200x340 textured BGR scene with plenty of distinct SIFT/ORB keypoints."""
rng = np.random.default_rng(2026)
pano = np.full((200, 340, 3), 30, dtype=np.uint8)
# Deterministic geometric textures across the full width
for _ in range(95):
cx = int(rng.integers(12, 328))
cy = int(rng.integers(12, 188))
rad = int(rng.integers(5, 16))
color = tuple(int(c) for c in rng.integers(60, 245, size=3))
shape_type = int(rng.integers(0, 3))
if shape_type == 0:
cv2.circle(pano, (cx, cy), rad, color, -1)
cv2.circle(pano, (cx, cy), max(2, rad // 2), (25, 25, 25), 1)
elif shape_type == 1:
cv2.rectangle(pano, (cx - rad, cy - rad // 2), (cx + rad, cy + rad // 2), color, -1)
cv2.rectangle(pano, (cx - rad, cy - rad // 2), (cx + rad, cy + rad // 2), (240, 240, 240), 1)
else:
pts = np.array([[cx, cy - rad], [cx - rad, cy + rad], [cx + rad, cy + rad]], dtype=np.int32)
cv2.fillPoly(pano, [pts], color)
# Mild Gaussian blur so edges are anti-aliased like natural photos
pano = cv2.GaussianBlur(pano, (3, 3), 0.6)
return pano
def run_cases():
cases = []
pano = build_textured_panorama()
# Left view (image2): x in [0, 220), Right view (image1): x in [100, 320) -> overlap = 120px, known shift tx = +100
image2 = pano[:, 0:220].copy()
image1 = pano[:, 100:320].copy()
gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
# Case 1: SIFT + BFMatcher + Lowe's ratio test + RANSAC findHomography
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(gray1, None)
kp2, des2 = sift.detectAndCompute(gray2, None)
bf_l2 = cv2.BFMatcher(cv2.NORM_L2)
raw_matches = bf_l2.knnMatch(des1, des2, k=2)
good_sift = [m for m, n in raw_matches if m.distance < 0.75 * n.distance]
src_pts = np.float32([kp1[m.queryIdx].pt for m in good_sift]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_sift]).reshape(-1, 1, 2)
H_sift, mask_sift = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
inliers_sift = int(mask_sift.ravel().sum())
tx_sift = round(float(H_sift[0, 2]), 3)
ty_sift = round(float(H_sift[1, 2]), 3)
c1_ok = (len(good_sift) >= 30 and inliers_sift >= 25
and abs(tx_sift - 100.0) < 1.5 and abs(ty_sift) < 1.5)
cases.append(dict(
name="sift_matching_and_homography",
inputs=dict(img1_shape=list(image1.shape), img2_shape=list(image2.shape), true_tx=100.0, ratio=0.75),
prerequisites="两幅 200×220 且水平重叠 120 像素的合成纹理图像(真实平移 tx=100, ty=0)",
action="使用 cv2.SIFT_create() 提取特征、BFMatcher.knnMatch(k=2) 与 0.75 比率测试筛选匹配,并用 RANSAC 估计单应性矩阵 H。",
expected=dict(
good_matches_ge_30=True,
inliers_ge_25=True,
recovered_tx_near_100=True,
recovered_ty_near_0=True,
),
actual=dict(
good_matches_ge_30=len(good_sift) >= 30,
inliers_ge_25=inliers_sift >= 25,
recovered_tx_near_100=abs(tx_sift - 100.0) < 1.5,
recovered_ty_near_0=abs(ty_sift) < 1.5,
),
measurements=dict(
kp1=len(kp1), kp2=len(kp2), good_matches=len(good_sift),
ransac_inliers=inliers_sift, H_tx=tx_sift, H_ty=ty_sift,
),
passed=c1_ok,
))
# Case 2: ORB + Hamming BFMatcher + RANSAC Homography
orb = cv2.ORB_create(nfeatures=600)
okp1, odes1 = orb.detectAndCompute(gray1, None)
okp2, odes2 = orb.detectAndCompute(gray2, None)
bf_ham = cv2.BFMatcher(cv2.NORM_HAMMING)
orb_knn = bf_ham.knnMatch(odes1, odes2, k=2)
good_orb = [m for pair in orb_knn if len(pair) == 2 for m, n in [pair] if m.distance < 0.75 * n.distance]
osrc = np.float32([okp1[m.queryIdx].pt for m in good_orb]).reshape(-1, 1, 2)
odst = np.float32([okp2[m.trainIdx].pt for m in good_orb]).reshape(-1, 1, 2)
H_orb, mask_orb = cv2.findHomography(osrc, odst, cv2.RANSAC, 5.0)
inliers_orb = int(mask_orb.ravel().sum())
tx_orb = round(float(H_orb[0, 2]), 3)
ty_orb = round(float(H_orb[1, 2]), 3)
c2_ok = (len(good_orb) >= 20 and inliers_orb >= 15
and abs(tx_orb - 100.0) < 2.0 and abs(ty_orb) < 2.0)
cases.append(dict(
name="orb_hamming_homography",
inputs=dict(detector="ORB", nfeatures=600, norm="NORM_HAMMING"),
prerequisites="同一对水平重叠 120 像素的合成纹理图像",
action="使用 cv2.ORB_create() 与汉明距离 BFMatcher 验证轻量级特征检测与单应性矩阵求解。",
expected=dict(
orb_good_matches_ge_20=True,
orb_inliers_ge_15=True,
orb_tx_near_100=True,
orb_ty_near_0=True,
),
actual=dict(
orb_good_matches_ge_20=len(good_orb) >= 20,
orb_inliers_ge_15=inliers_orb >= 15,
orb_tx_near_100=abs(tx_orb - 100.0) < 2.0,
orb_ty_near_0=abs(ty_orb) < 2.0,
),
measurements=dict(
orb_kp1=len(okp1), orb_kp2=len(okp2), orb_good_matches=len(good_orb),
orb_inliers=inliers_orb, orb_tx=tx_orb, orb_ty=ty_orb,
),
passed=c2_ok,
))
# Case 3: perspectiveTransform canvas bounds + warpPerspective stitching accuracy vs ground-truth panorama
h1, w1 = image1.shape[:2]
h2, w2 = image2.shape[:2]
corners1 = np.float32([[0, 0], [0, h1], [w1, h1], [w1, 0]]).reshape(-1, 1, 2)
warped_corners1 = cv2.perspectiveTransform(corners1, H_sift)
corners2 = np.float32([[0, 0], [0, h2], [w2, h2], [w2, 0]]).reshape(-1, 1, 2)
all_corners = np.concatenate((corners2, warped_corners1), axis=0)
x_min, y_min = np.int32(all_corners.min(axis=0).ravel() - 0.5)
x_max, y_max = np.int32(all_corners.max(axis=0).ravel() + 0.5)
trans = np.array([[1.0, 0.0, -x_min], [0.0, 1.0, -y_min], [0.0, 0.0, 1.0]])
stitched = cv2.warpPerspective(image1, trans @ H_sift, (int(x_max - x_min), int(y_max - y_min)))
stitched[-y_min:h2 - y_min, -x_min:w2 - x_min] = image2
# Crop ground-truth aligned window from stitched canvas and compare MAE against pano[:, 0:320]
gt = pano[:, 0:320]
cropped = stitched[-y_min:200 - y_min, -x_min:320 - x_min]
stitch_mae = round(float(np.mean(np.abs(cropped.astype(np.float32) - gt.astype(np.float32)))), 3)
c3_ok = (cropped.shape == (200, 320, 3) and stitch_mae < 3.0)
cases.append(dict(
name="perspective_warp_and_stitch_fidelity",
inputs=dict(gt_panorama_shape=[200, 320, 3]),
prerequisites="SIFT 估计得到的 3×3 单应性矩阵 H 与左右两幅 200×220 重叠视图",
action="用 cv2.perspectiveTransform() 计算全景画布边界并用 cv2.warpPerspective() 拼接两图,与真值全景核对像素平均绝对误差。",
expected=dict(
aligned_crop_shape=[200, 320, 3],
stitch_mae_lt_3=True,
),
actual=dict(
aligned_crop_shape=list(cropped.shape),
stitch_mae_lt_3=stitch_mae < 3.0,
),
measurements=dict(
stitched_canvas_shape=list(stitched.shape),
canvas_offset=[int(-x_min), int(-y_min)],
stitch_mae=stitch_mae,
),
passed=c3_ok,
))
payload = dict(version=platform.python_version(), opencv=cv2.__version__, cases=cases)
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。
入口文件:projects/opencv-image-stitching-lab/explore-image-stitching.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-image-stitching.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a588.zip