"""Offline OpenCV lab for Ch13: image edge detection (Canny, Sobel, Scharr, Laplacian)."""
import argparse
import hashlib
import json
import platform
from pathlib import Path
import cv2
import numpy as np
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def build_synthetic_gray() -> np.ndarray:
"""160x200 grayscale test scene with rectangle, circle, and diagonal triangle."""
img = np.full((160, 200), 30, dtype=np.uint8)
cv2.rectangle(img, (20, 25), (85, 130), 220, -1)
cv2.circle(img, (145, 65), 32, 200, -1)
tri = np.array([[110, 145], [148, 102], [182, 145]], dtype=np.int32)
cv2.fillPoly(img, [tri], 180)
return img
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
gray = build_synthetic_gray()
rng = np.random.default_rng(2026)
noise = rng.normal(0.0, 12.0, size=gray.shape)
noisy = np.clip(gray.astype(np.float64) + noise, 0, 255).astype(np.uint8)
# Case 1: Canny edge detection (L1 vs L2 gradient & double threshold)
canny_l1 = cv2.Canny(gray, 100, 200, apertureSize=3, L2gradient=False)
canny_l2 = cv2.Canny(gray, 100, 200, apertureSize=3, L2gradient=True)
canny_low = cv2.Canny(gray, 30, 80)
l1_edges = int(np.count_nonzero(canny_l1))
l2_edges = int(np.count_nonzero(canny_l2))
low_edges = int(np.count_nonzero(canny_low))
# Verify interior of rectangle is 0 (non-maximum suppression leaves thin boundary)
interior_zero = int(np.count_nonzero(canny_l1[40:115, 35:70])) == 0
c1_ok = l1_edges > 400 and l2_edges > 400 and interior_zero and low_edges >= l1_edges
cases.append(dict(
name="canny_edge_detection",
inputs=dict(shape=[160, 200], thresholds=[100, 200], apertureSize=3),
prerequisites="160x200 合成灰度图(含矩形、圆形与三角形高亮目标)",
action="运行 cv2.Canny() 对比 L1/L2 梯度范数及高低阈值组合,核对单像素轮廓特性与平坦内部零响应。",
expected=dict(
l1_edges_gt_400=True,
l2_edges_gt_400=True,
interior_zero=True,
lower_thresh_ge_edges=True,
),
actual=dict(
l1_edges_gt_400=l1_edges > 400,
l2_edges_gt_400=l2_edges > 400,
interior_zero=interior_zero,
lower_thresh_ge_edges=low_edges >= l1_edges,
),
measurements=dict(l1_edge_pixels=l1_edges, l2_edge_pixels=l2_edges, low_thresh_edge_pixels=low_edges),
passed=c1_ok,
))
# Case 2: Sobel & Scharr first-order gradient operators
sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
sobel_mag = np.sqrt(sobel_x ** 2 + sobel_y ** 2)
scharr_x = cv2.Scharr(gray, cv2.CV_64F, 1, 0)
scharr_y = cv2.Scharr(gray, cv2.CV_64F, 0, 1)
scharr_mag = np.sqrt(scharr_x ** 2 + scharr_y ** 2)
# Vertical edge at x=20 (y=60) should respond strongly to sobel_x and 0 to sobel_y
vert_gx = round(float(abs(sobel_x[60, 20])), 2)
vert_gy = round(float(abs(sobel_y[60, 20])), 2)
# Horizontal edge at y=25 (x=50) should respond strongly to sobel_y and 0 to sobel_x
horiz_gx = round(float(abs(sobel_x[25, 50])), 2)
horiz_gy = round(float(abs(sobel_y[25, 50])), 2)
sobel_max = round(float(sobel_mag.max()), 2)
scharr_max = round(float(scharr_mag.max()), 2)
c2_ok = (vert_gx > 300 and vert_gy == 0.0 and horiz_gx == 0.0 and horiz_gy > 300 and scharr_max > sobel_max)
cases.append(dict(
name="sobel_and_scharr_gradients",
inputs=dict(ddepth="CV_64F", ksize=3),
prerequisites="160x200 合成灰度图,在矩形垂直边 (y=60,x=20) 与水平边 (y=25,x=50) 采样",
action="计算 cv2.Sobel(dx=1/dy=1) 与 cv2.Scharr() 梯度及合成幅值,验证方向选择性与 Scharr 更强响应。",
expected=dict(
vertical_edge_gx_gt_300=True,
vertical_edge_gy_zero=True,
horizontal_edge_gx_zero=True,
horizontal_edge_gy_gt_300=True,
scharr_stronger_than_sobel=True,
),
actual=dict(
vertical_edge_gx_gt_300=vert_gx > 300,
vertical_edge_gy_zero=vert_gy == 0.0,
horizontal_edge_gx_zero=horiz_gx == 0.0,
horizontal_edge_gy_gt_300=horiz_gy > 300,
scharr_stronger_than_sobel=scharr_max > sobel_max,
),
measurements=dict(
vert_gx=vert_gx, vert_gy=vert_gy, horiz_gx=horiz_gx, horiz_gy=horiz_gy,
sobel_max_mag=sobel_max, scharr_max_mag=scharr_max,
),
passed=c2_ok,
))
# Case 3: Laplacian second-order operator & Gaussian pre-smoothing noise sensitivity
lap_clean = cv2.Laplacian(gray, cv2.CV_64F, ksize=1)
lap_noisy = cv2.Laplacian(noisy, cv2.CV_64F, ksize=1)
blurred_noisy = cv2.GaussianBlur(noisy, (5, 5), 1.0)
lap_smoothed = cv2.Laplacian(blurred_noisy, cv2.CV_64F, ksize=1)
# Measure flat interior std of Laplacian response on noisy vs Gaussian-smoothed noisy image
flat_std_clean = round(float(np.std(lap_clean[40:115, 35:70])), 4)
flat_std_noisy = round(float(np.std(lap_noisy[40:115, 35:70])), 4)
flat_std_smoothed = round(float(np.std(lap_smoothed[40:115, 35:70])), 4)
has_pos_and_neg = bool(lap_clean.min() < -100 and lap_clean.max() > 100)
c3_ok = (flat_std_clean == 0.0 and flat_std_noisy > 30.0 and flat_std_smoothed < flat_std_noisy * 0.35 and has_pos_and_neg)
cases.append(dict(
name="laplacian_and_noise_sensitivity",
inputs=dict(ddepth="CV_64F", ksize=1, noise_sigma=12.0, blur_ksize=[5, 5]),
prerequisites="无噪灰度图与叠加 sigma=12 高斯噪声的灰度图",
action="对比 cv2.Laplacian() 在无噪、含噪及高斯平滑后平坦区域响应标准差,验证二阶微分对噪声的高度敏感性。",
expected=dict(
clean_flat_std_zero=True,
noisy_flat_std_gt_30=True,
blur_reduces_noise_response=True,
has_signed_zero_crossing=True,
),
actual=dict(
clean_flat_std_zero=flat_std_clean == 0.0,
noisy_flat_std_gt_30=flat_std_noisy > 30.0,
blur_reduces_noise_response=flat_std_smoothed < flat_std_noisy * 0.35,
has_signed_zero_crossing=has_pos_and_neg,
),
measurements=dict(
flat_std_clean=flat_std_clean,
flat_std_noisy=flat_std_noisy,
flat_std_smoothed=flat_std_smoothed,
lap_min=round(float(lap_clean.min()), 2),
lap_max=round(float(lap_clean.max()), 2),
),
passed=c3_ok,
))
# Case 4: Matplotlib 2x2 edge detection comparison chart
mpl_ver = None
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "DejaVu Sans"]
plt.rcParams["axes.unicode_minus"] = False
fig_dir.mkdir(parents=True, exist_ok=True)
sobel_vis = cv2.convertScaleAbs(sobel_mag / max(sobel_mag.max(), 1.0) * 255.0)
lap_vis = cv2.convertScaleAbs(np.abs(lap_clean) / max(np.abs(lap_clean).max(), 1.0) * 255.0)
fig, axes = plt.subplots(2, 2, figsize=(8.8, 6.2), dpi=140)
panels = [
(gray, "原始合成灰度图 (矩形 / 圆 / 三角形)"),
(canny_l1, f"Canny (100, 200) 边缘像素={l1_edges}"),
(sobel_vis, f"Sobel 梯度幅值 (峰值={sobel_max:.1f})"),
(lap_vis, f"Laplacian 二阶响应 (峰值={abs(lap_clean).max():.1f})"),
]
for ax, (im, title) in zip(axes.ravel(), panels):
ax.imshow(im, cmap="gray", vmin=0, vmax=255)
ax.set_title(title, fontsize=10)
ax.axis("off")
fig.suptitle("OpenCV 边缘检测算子实测对比 (Canny / Sobel / Laplacian)", fontsize=12)
fig.tight_layout()
out_png = fig_dir / "edge-detection-comparison.png"
fig.savefig(out_png)
plt.close(fig)
figures["edge-detection-comparison.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
cases.append(dict(
name="edge_detection_comparison_plot",
inputs=dict(panels=4, figure="edge-detection-comparison.png"),
prerequisites="合成灰度图与 Canny、Sobel、Laplacian 实测结果",
action="输出 2×2 边缘检测对比图 PNG。",
expected=dict(panel_count=4, canny_nonempty=True),
actual=dict(panel_count=4, canny_nonempty=l1_edges > 0),
measurements=dict(figure_generated="edge-detection-comparison.png" in figures),
passed=l1_edges > 0,
))
payload = dict(version=platform.python_version(), opencv=cv2.__version__, cases=cases)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
本例需在 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-edge-detection-lab/explore-image-edge-detection.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-image-edge-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章) · 含当前章节或实例 · mbskycom202612a583.zip