"""Offline verification lab for OpenCV Chapter 26: C++ OpenCV feature detection."""
import json
import cv2
import numpy as np
def _make_textured_scene():
rng = np.random.default_rng(2026)
img = np.full((256, 256), 30, dtype=np.uint8)
# Checkerboard block + multi-scale polygons for rich corners and descriptors
for r in range(4):
for c in range(4):
val = 230 if (r + c) % 2 == 0 else 45
cv2.rectangle(img, (24 + c * 22, 24 + r * 22), (46 + c * 22, 46 + r * 22), val, -1)
for _ in range(35):
x, y = int(rng.integers(30, 215)), int(rng.integers(30, 215))
w, h = int(rng.integers(10, 26)), int(rng.integers(10, 26))
val = int(rng.integers(90, 250))
cv2.rectangle(img, (x, y), (x + w, y + h), val, -1)
cv2.circle(img, (x + w // 2, y + h // 2), max(3, min(w, h) // 3), 255 - val, -1)
return img
def case_corner_harris_and_shi_tomasi():
src = _make_textured_scene()
harris = cv2.cornerHarris(src, blockSize=2, ksize=3, k=0.04)
harris_norm = cv2.normalize(harris, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_32FC1)
strong_harris = int(np.count_nonzero(harris > 0.01 * harris.max()))
corners = cv2.goodFeaturesToTrack(src, maxCorners=100, qualityLevel=0.01, minDistance=10)
corner_count = int(len(corners)) if corners is not None else 0
actual = dict(
harris_norm_range=[round(float(harris_norm.min()), 1), round(float(harris_norm.max()), 1)],
strong_harris_gt_20=bool(strong_harris > 20),
shi_tomasi_count_in_range=bool(20 <= corner_count <= 100),
shi_tomasi_exact_count=corner_count,
)
expected = dict(
harris_norm_range=[0.0, 255.0],
strong_harris_gt_20=True,
shi_tomasi_count_in_range=True,
shi_tomasi_exact_count=100,
)
return dict(name="corner_harris_and_shi_tomasi", passed=actual == expected, expected=expected, actual=actual)
def case_sift_orb_fast_descriptors():
src = _make_textured_scene()
sift = cv2.SIFT_create()
kp_sift, des_sift = sift.detectAndCompute(src, None)
orb = cv2.ORB_create(nfeatures=500)
kp_orb, des_orb = orb.detectAndCompute(src, None)
fast = cv2.FastFeatureDetector_create()
kp_fast = fast.detect(src, None)
vis = cv2.drawKeypoints(src, kp_orb, None)
actual = dict(
sift_kp_gt_50=bool(len(kp_sift) > 50),
sift_desc_dim=int(des_sift.shape[1]),
sift_desc_dtype=str(des_sift.dtype),
orb_kp_gt_50=bool(len(kp_orb) > 50),
orb_desc_dim=int(des_orb.shape[1]),
orb_desc_dtype=str(des_orb.dtype),
fast_kp_gt_50=bool(len(kp_fast) > 50),
vis_shape=list(vis.shape),
)
expected = dict(
sift_kp_gt_50=True,
sift_desc_dim=128,
sift_desc_dtype="float32",
orb_kp_gt_50=True,
orb_desc_dim=32,
orb_desc_dtype="uint8",
fast_kp_gt_50=True,
vis_shape=[256, 256, 3],
)
return dict(name="sift_orb_fast_descriptors", passed=actual == expected, expected=expected, actual=actual)
def case_bf_and_flann_matching():
src1 = _make_textured_scene()
mat = cv2.getRotationMatrix2D((128.0, 128.0), 12.0, 1.0)
mat[0, 2] += 15.0
mat[1, 2] += 10.0
src2 = cv2.warpAffine(src1, mat, (256, 256))
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(src1, None)
kp2, des2 = sift.detectAndCompute(src2, None)
bf = cv2.BFMatcher(cv2.NORM_L2)
bf_matches = bf.match(des1, des2)
flann = cv2.FlannBasedMatcher(dict(algorithm=1, trees=5), dict(checks=50))
flann_matches = flann.match(des1, des2)
orb = cv2.ORB_create(nfeatures=500)
okp1, odes1 = orb.detectAndCompute(src1, None)
okp2, odes2 = orb.detectAndCompute(src2, None)
bf_hamming = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
orb_matches = bf_hamming.match(odes1, odes2)
drawn = cv2.drawMatches(src1, kp1, src2, kp2, bf_matches[:20], None)
actual = dict(
bf_sift_matches_eq_kp1=bool(len(bf_matches) == len(kp1)),
flann_sift_matches_eq_kp1=bool(len(flann_matches) == len(kp1)),
orb_crosscheck_gt_40=bool(len(orb_matches) > 40),
draw_matches_width=int(drawn.shape[1]),
)
expected = dict(
bf_sift_matches_eq_kp1=True,
flann_sift_matches_eq_kp1=True,
orb_crosscheck_gt_40=True,
draw_matches_width=512,
)
return dict(name="bf_and_flann_matching", passed=actual == expected, expected=expected, actual=actual)
def case_distance_radius_and_homography_filtering():
src1 = _make_textured_scene()
mat = cv2.getRotationMatrix2D((128.0, 128.0), 12.0, 1.0)
mat[0, 2] += 15.0
mat[1, 2] += 10.0
src2 = cv2.warpAffine(src1, mat, (256, 256))
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(src1, None)
kp2, des2 = sift.detectAndCompute(src2, None)
bf = cv2.BFMatcher(cv2.NORM_L2)
raw_matches = bf.match(des1, des2)
radius_lists = bf.radiusMatch(des1, des2, maxDistance=120.0)
radius_kept = sum(1 for lst in radius_lists if len(lst) > 0)
pts1 = np.float32([kp1[m.queryIdx].pt for m in raw_matches]).reshape(-1, 1, 2)
pts2 = np.float32([kp2[m.trainIdx].pt for m in raw_matches]).reshape(-1, 1, 2)
H, h_mask = cv2.findHomography(pts1, pts2, cv2.RANSAC, 3.0)
F, f_mask = cv2.findFundamentalMat(pts1, pts2, cv2.FM_RANSAC)
# Verify recovered homography maps center (128, 128) to ground-truth (143, 138)
pt_true = mat @ np.array([128.0, 128.0, 1.0])
pt_h = H @ np.array([128.0, 128.0, 1.0])
pt_h = pt_h[:2] / pt_h[2]
reproj_err = float(np.linalg.norm(pt_h - pt_true))
inliers_h = int(h_mask.sum())
inliers_f = int(f_mask.sum())
actual = dict(
radius_filtered_subset=bool(0 < radius_kept < len(raw_matches)),
homography_shape=list(H.shape),
homography_inliers_gt_40=bool(inliers_h > 40),
fundamental_shape=list(F.shape),
fundamental_inliers_gt_40=bool(inliers_f > 40),
reproj_err_lt_1px=bool(reproj_err < 1.0),
)
expected = dict(
radius_filtered_subset=True,
homography_shape=[3, 3],
homography_inliers_gt_40=True,
fundamental_shape=[3, 3],
fundamental_inliers_gt_40=True,
reproj_err_lt_1px=True,
)
return dict(name="distance_radius_and_homography_filtering", passed=actual == expected, expected=expected, actual=actual)
def main():
cases = [
case_corner_harris_and_shi_tomasi(),
case_sift_orb_fast_descriptors(),
case_bf_and_flann_matching(),
case_distance_radius_and_homography_filtering(),
]
print(json.dumps({"cases": cases, "figures": {}}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 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-cpp-opencv-feature-detection-lab/explore-cpp-opencv-feature-detection.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-cpp-opencv-feature-detection.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a571.zip