蓝色天空.知识 · 实践 · 创造
我的收藏
OpenCV 教程目录 31章
OpenCV / LEARN BY DOING

OpenCV 图像边缘检测

核对 Canny 五阶段边缘检测、Sobel/Scharr 一阶方向梯度与 Laplacian 二阶微分的数学原理、参数含义及噪声敏感度实测。

学完这一章,你能够

  • 核对 Canny 五阶段边缘检测、Sobel/Scharr 一阶方向梯度与 Laplacian 二阶微分的数学原理、参数含义及噪声敏感度实测。

边缘检测概述与 Canny 多阶段算法

图像边缘检测旨在定位像素亮度发生剧烈跃迁的区域,这些边界通常对应物体轮廓或表面法向变化,是后续轮廓分析、分割与目标识别的基础步骤。OpenCV 内置 Canny、Sobel、Scharr 与 Laplacian 等多类算子,分别适配通用边界提取、方向梯度计算与二阶细节检测。

Canny 边缘检测由 John F. Canny 于 1986 年提出,凭借在抑噪与精确定位之间的平衡成为边缘提取的经典标准。算法串联五个阶段:先用高斯滤波抑制高频噪声;再用 Sobel 计算梯度幅值与方向;接着沿梯度方向执行非极大值抑制(NMS)将粗边缘细化为单像素宽;然后用低、高双阈值区分强边缘、弱边缘与非边缘;最后借滞后连接仅保留与强边缘连通的弱边缘。

OpenCV 接口为 `cv2.Canny(image, threshold1, threshold2, apertureSize=3, L2gradient=False)`,其中 `image` 为单通道灰度图,`threshold1`/`threshold2` 分别对应低高阈值,`apertureSize` 控制内部 Sobel 孔径,`L2gradient` 为 `False` 时用 L1 范数近似幅值、为 `True` 时用更精确的 L2 欧氏范数。本站离线在 160×200 合成灰度图(含矩形、圆、三角形)上实测:`Canny(100, 200)` 在 L1 模式下提取 `761` 个单像素边缘点、L2 模式提取 `763` 个,且矩形平坦内部边缘响应严格为 `0`。

一阶梯度算子:Sobel 与 Scharr

Sobel 算子将离散微分与高斯加权平滑相结合,通过水平卷积核 `[[-1,0,1],[-2,0,2],[-1,0,1]]` 与垂直卷积核 `[[-1,-2,-1],[0,0,0],[1,2,1]]` 分别计算一阶偏导 `Gx` 与 `Gy`,再以 `G = sqrt(Gx^2 + Gy^2)` 合成总梯度幅值,兼具方向选择性与一定抗噪能力。

`cv2.Sobel(src, ddepth, dx, dy, ksize=3, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT)` 的输出深度 `ddepth` 工程上通常设为 `cv2.CV_64F`(避免 `uint8` 截断负梯度导致一半边缘丢失),`dx`/`dy` 指定求导阶数,`ksize` 为核尺寸。本站实测矩形垂直边处 `|Gx| = 760.0`、`Gy = 0.0`,水平边处 `Gx = 0.0`、`|Gy| = 760.0`,全图 Sobel 幅值峰值 `806.1`;改用改进权重核 `cv2.Scharr()` 后,同图梯度峰值升至 `3493.11`,对细微边缘响应更敏锐。

二阶微分算子 Laplacian 与算子对比

Laplacian 算子(`cv2.Laplacian(src, ddepth, ksize=1, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT)`)基于默认 4 邻域二阶微分核 `[[0,1,0],[1,-4,1],[0,1,0]]` 检测各向同性边缘与角点,在边界两侧产生正负过零跃变(需以 `cv2.CV_64F` 保留符号)。由于二阶导数会显著放大随机扰动,使用前通常先做高斯平滑。本站实测无噪图平坦区 Laplacian 标准差为 `0.0`(全图极值 `-510.0` 至 `340.0`),叠加 `sigma=12` 高斯噪声后平坦区标准差飙升至 `53.1692`,经 `5×5` 高斯预平滑后迅速回落至 `4.3736`。

综合选型时,通用边界提取优先选用具备非极大值抑制与滞后阈值的 `cv2.Canny()`;需拆分水平或垂直方向梯度时选用 `cv2.Sobel()`,追求更强旋转对称性与细微梯度响应时选用 `cv2.Scharr()`;对角点或斑点二阶变化敏感的任务则配合高斯滤波使用 `cv2.Laplacian()`(LoG 流程)。

160×200 合成灰度图经 Canny(100,200)、Sobel 梯度幅值与 Laplacian 二阶响应处理的 2×2 对比图
本站使用 OpenCV 5.1.0 与 Matplotlib 离线实测生成的边缘检测算子对比图。

OpenCV 常用边缘检测函数概览

函数算法说明适用场景
`cv2.Canny()`Canny 边缘检测含高斯平滑、梯度、NMS 与双阈值滞后连接的多阶段算法。通用边缘提取,适合大多数视觉任务。
`cv2.Sobel()`Sobel 算子基于一阶偏导卷积,可独立提取水平与垂直方向梯度。方向性边缘检测与梯度特征计算。
`cv2.Scharr()`Scharr 算子3×3 梯度核权重改进版,对细微变化与斜边响应更强。高精度 3×3 细微边缘提取。
`cv2.Laplacian()`Laplacian 算子各向同性二阶微分算子,对高频噪声高度敏感。配合高斯模糊检测闭合边缘与角点。

常用边缘检测算子优缺点对比

函数算法优点缺点适用场景
`cv2.Canny()`Canny 边缘检测抗噪能力强,输出单像素细化且连通的边缘。高低阈值与孔径参数需按场景调节。通用高精度边缘检测。
`cv2.Sobel()`Sobel 算子实现简洁高效,天然区分 X/Y 梯度方向。直接输出边缘较粗且易受较强噪声影响。水平/垂直边缘定位与梯度幅值计算。
`cv2.Scharr()`Scharr 算子相比 3×3 Sobel 梯度幅值响应更强、旋转误差更低。同样对图像噪声较敏感,且固定为 3×3 核。对细节梯度敏感的细微边缘检测。
`cv2.Laplacian()`Laplacian 算子单次卷积即可无方向性地响应所有边缘与角点。对随机噪声极为敏感,通常必须先做高斯平滑。清晰度评估及结合平滑的边缘/角点检测。

运行 Canny、Sobel、Scharr 与 Laplacian 边缘检测对比实验

含完整源码 · 204 行
展开查看收起
python
"""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)
核对 Canny(100,200) 单像素轮廓(761/763px)、Sobel 方向正交性(760.0/0.0)与 Scharr 更强幅值(3493.11 > 806.1)、Laplacian 平滑降噪(std 53.17→4.37),并输出对比图。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a566.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:OpenCV

课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip

下载课程关联工程包:OpenCV

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a583.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

亮到暗的边界会产生负值一阶或二阶导数,uint8 会将负值截断为 0 从而丢失一半边缘;使用 cv2.CV_64F 可完整保留正负导数,后续再按需取绝对值并缩放显示。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习