蓝色天空网mbsky.com · 知识 · 实践 · 创造OpenCV · 本地阅读预览
教程 / AI / 智能开发 / OpenCV

OpenCV 图像轮廓检测

系统核对轮廓提取模式、链码近似、绘制渲染以及面积、周长、轴对齐/最小旋转外接矩形、最小外接圆与多边形逼近的完整几何实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

轮廓基本概念与提取绘制(findContours / drawContours)

轮廓是由具有相同颜色或强度的连续边界像素构成的点集曲线,广泛用于物体识别、形状分析、目标跟踪与图像分割。分析轮廓时不仅关注边界点序列本身,还常结合轮廓间的内外嵌套层次结构(hierarchy)以及面积、周长、外接几何体等形状特征。

`contours, hierarchy = cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]])` 从二值图像中检索轮廓列表与层次数组。`mode` 决定拓扑组织:`cv2.RETR_EXTERNAL` 仅保留最外层边界,`cv2.RETR_LIST` 列出所有轮廓但不建父子关系,`cv2.RETR_TREE` 构建完整嵌套树;`method` 决定点集压缩:`cv2.CHAIN_APPROX_NONE` 保留全部边界点,`cv2.CHAIN_APPROX_SIMPLE` 仅保留直线段端点。本站离线在含 4 个外部形状(其中 80×80 方块内嵌 1 个 30×30 孔洞)的 240×360 二值图实测:`RETR_EXTERNAL` 检出 `4` 条轮廓,`RETR_LIST` 与 `RETR_TREE` 检出 `5` 条且 `RETR_TREE` 准确标记 `1` 个子孔洞;对 80×80 方块,`CHAIN_APPROX_SIMPLE` 仅用 `4` 个顶点即完整描述轮廓,而 `CHAIN_APPROX_NONE` 存储 `320` 个点。

`cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]])` 直接在目标画布上原地绘制轮廓(无返回值),当 `contourIdx=-1` 时绘制全部轮廓,`thickness<0` 时执行内部实心填充,还可传入 `hierarchy` 与 `maxLevel` 按层级渲染。本站实测将 `5` 条树形轮廓以 2 像素绿线绘制到 BGR 画布,成功着色 `4014` 个轮廓像素。

轮廓几何度量与外接拟合函数

`cv2.contourArea(contour[, oriented])` 计算轮廓包围面积(`oriented=True` 时按顶点绕向返回带符号面积);`cv2.arcLength(curve, closed)` 计算闭合周长或开放弧长(`closed=True` 表示首尾闭合)。本站对 80×80 外方块轮廓实测面积为 `6400.0`、闭合周长为 `320.0`。

`x, y, w, h = cv2.boundingRect(points)` 返回轴对齐外接矩形,适合快速框选(80×80 方块测得 `[20, 20, 81, 81]`);面对倾斜目标时,`rect = cv2.minAreaRect(points)` 返回紧贴目标的最小面积旋转矩形 `(center, (w, h), angle)`,需经 `cv2.boxPoints(rect)` 转为 4 个角点再绘制。需特别注意:NumPy 2.x 已移除旧别名 `np.int0`,现代 OpenCV + NumPy 2.5.4 环境应改用 `np.intp(np.round(box))` 或 `box.astype(np.int32)`。本站对旋转 30° 的 90×40 倾斜矩形实测:轴对齐外接框面积高达 `8019.0`,而 `minAreaRect` 面积收紧至 `3742.0`。

`(x, y), radius = cv2.minEnclosingCircle(points)` 拟合覆盖轮廓全部点的最小外接圆,本站对半径 36 像素的合成圆精确还原圆心 `(300.0, 68.0)` 与半径 `36.0`。`cv2.approxPolyDP(curve, epsilon, closed)` 按 Douglas-Peucker 算法进行多边形逼近,`epsilon` 越小越贴近原曲线;实测取 `0.02 * arcLength` 将三角形逼近为 `3` 顶点、正方块与旋转矩形均为 `4` 顶点,圆形在 `0.015 * arcLength` 下逼近为 `12` 边形。

轮廓检测典型应用与完整流水线

工程应用中,轮廓检测串联“灰度化 (`cv2.cvtColor`) → 二值化 (`cv2.threshold`) → 检索 (`cv2.findContours`) → 特征计算与筛选 → 渲染标注 (`cv2.drawContours`)”的标准流水线,可直接落地为规则几何体分类(按多边形顶点数区分圆/三角/矩形)、面积过滤去噪、视频运动块追踪及前景实例分割。

左为含嵌套方块、三角形、圆形与旋转矩形的二值图,右为外接矩形、多边形逼近、最小外接圆与最小旋转框实测标注图
本站使用 OpenCV 5.1.0 与 Matplotlib 离线实测生成的轮廓几何特征可视化对比图。

OpenCV 轮廓检测核心函数清单

函数名称功能描述
`cv2.findContours()`在二值图像中提取轮廓点集与层次嵌套关系。
`cv2.drawContours()`在图像画布上描边或实心填充指定轮廓。
`cv2.contourArea()`计算轮廓包围的面积(可选带符号面积)。
`cv2.arcLength()`计算闭合轮廓周长或开放曲线弧长。
`cv2.boundingRect()`计算轮廓的轴对齐最小外接矩形 `(x, y, w, h)`。
`cv2.minAreaRect()`计算轮廓的最小面积旋转外接矩形。
`cv2.minEnclosingCircle()`计算覆盖轮廓点集的最小外接圆圆心与半径。
`cv2.approxPolyDP()`按指定容差 `epsilon` 对轮廓进行多边形逼近。

轮廓检测标准处理步骤与对应 API

步骤函数说明
图像预处理`cv2.cvtColor()`将彩色 BGR 图像转换为单通道灰度图。
二值化处理`cv2.threshold()`按阈值分离前景与背景,得到二值掩码。
查找轮廓`cv2.findContours()`按检索模式与链码近似方法提取轮廓与层次。
绘制轮廓`cv2.drawContours()`按索引、颜色与线宽在画布上可视化轮廓。
计算轮廓面积`cv2.contourArea()`度量轮廓内部像素面积以供尺寸筛选。
计算轮廓周长`cv2.arcLength()`度量闭合轮廓周长,常作逼近精度基准。
计算边界矩形`cv2.boundingRect()`生成水平垂直对齐的快速外接框。
计算最小外接矩形`cv2.minAreaRect()`生成带旋转角度的紧致外接框(配 `cv2.boxPoints`)。
计算最小外接圆`cv2.minEnclosingCircle()`拟合最小包围圆,适合圆形度分析。
多边形逼近`cv2.approxPolyDP()`压缩冗余边界点并借顶点数判别几何形状。

运行轮廓层次提取、几何特征度量与多边形逼近实验

python · 阅读源码
"""Offline OpenCV lab for Ch14: image contour detection and shape geometry."""
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_shapes_scene():
    """240x360 BGR scene with 4 shapes: nested square (outer+inner hole), triangle, circle, tilted rectangle."""
    bgr = np.zeros((240, 360, 3), dtype=np.uint8)
    # 1. Outer square (80x80) with inner black hole (30x30) -> tests RETR_EXTERNAL vs RETR_TREE
    cv2.rectangle(bgr, (20, 20), (100, 100), (240, 240, 240), -1)
    cv2.rectangle(bgr, (45, 45), (75, 75), (0, 0, 0), -1)
    # 2. Triangle
    tri = np.array([[185, 25], [135, 105], [235, 105]], dtype=np.int32)
    cv2.fillPoly(bgr, [tri], (240, 240, 240))
    # 3. Circle (radius 36)
    cv2.circle(bgr, (300, 68), 36, (240, 240, 240), -1)
    # 4. Rotated rectangle (center=(180, 180), size=(90, 40), angle=30 deg)
    rot_box = cv2.boxPoints(((180.0, 180.0), (90.0, 40.0), 30.0))
    cv2.fillPoly(bgr, [np.intp(np.round(rot_box))], (240, 240, 240))
    return bgr


def run_cases(fig_dir: Path | None):
    cases = []
    figures = {}

    bgr = build_shapes_scene()
    gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
    _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

    # Case 1: findContours retrieval modes & chain approximation methods
    ext_simple, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    list_simple, _ = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    tree_simple, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    ext_none, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    # Identify outer square contour in ext_simple and ext_none (top-left bounding box near x=20,y=20)
    sq_simple = [c for c in ext_simple if cv2.boundingRect(c)[0] == 20 and cv2.boundingRect(c)[1] == 20][0]
    sq_none = [c for c in ext_none if cv2.boundingRect(c)[0] == 20 and cv2.boundingRect(c)[1] == 20][0]
    # Check hierarchy has exactly 1 child (the inner square hole)
    child_count = int(np.sum(hierarchy[0][:, 3] != -1))
    c1_ok = (len(ext_simple) == 4 and len(list_simple) == 5 and len(tree_simple) == 5
             and child_count == 1 and len(sq_simple) == 4 and len(sq_none) > 300)
    cases.append(dict(
        name="find_contours_modes_and_approx",
        inputs=dict(shape=[240, 360], modes=["RETR_EXTERNAL", "RETR_LIST", "RETR_TREE"]),
        prerequisites="含 4 个外部几何图形(其中矩形含 1 个内部孔洞)的二值图",
        action="对比 RETR_EXTERNAL/RETR_LIST/RETR_TREE 轮廓数与层次关系,以及 CHAIN_APPROX_SIMPLE 与 CHAIN_APPROX_NONE 的点数压缩。",
        expected=dict(
            external_count=4,
            tree_count=5,
            nested_child_count=1,
            square_simple_points=4,
            square_none_gt_300=True,
        ),
        actual=dict(
            external_count=len(ext_simple),
            tree_count=len(tree_simple),
            nested_child_count=child_count,
            square_simple_points=len(sq_simple),
            square_none_gt_300=len(sq_none) > 300,
        ),
        measurements=dict(
            list_count=len(list_simple),
            square_none_points=len(sq_none),
        ),
        passed=c1_ok,
    ))

    # Case 2: contourArea, arcLength, boundingRect, minAreaRect, minEnclosingCircle
    # Sort external contours cleanly by semantic identity
    circle_c = [c for c in ext_simple if cv2.boundingRect(c)[0] > 250][0]
    tri_c = [c for c in ext_simple if 125 <= cv2.boundingRect(c)[0] <= 145 and cv2.boundingRect(c)[1] < 40][0]
    rot_c = [c for c in ext_simple if cv2.boundingRect(c)[1] > 120][0]

    sq_area = round(float(cv2.contourArea(sq_simple)), 1)
    sq_perim = round(float(cv2.arcLength(sq_simple, True)), 1)
    sq_bbox = list(cv2.boundingRect(sq_simple))

    rot_bbox = cv2.boundingRect(rot_c)
    rot_bbox_area = float(rot_bbox[2] * rot_bbox[3])
    rot_min_rect = cv2.minAreaRect(rot_c)
    rot_min_area = round(float(rot_min_rect[1][0] * rot_min_rect[1][1]), 1)
    rot_box_pts = np.intp(np.round(cv2.boxPoints(rot_min_rect)))

    (cx, cy), radius = cv2.minEnclosingCircle(circle_c)
    circle_center = [round(float(cx), 1), round(float(cy), 1)]
    circle_radius = round(float(radius), 2)

    c2_ok = (sq_area == 6400.0 and sq_perim == 320.0 and sq_bbox == [20, 20, 81, 81]
             and rot_min_area < rot_bbox_area and abs(circle_radius - 36.0) < 1.0)
    cases.append(dict(
        name="contour_geometry_metrics",
        inputs=dict(shapes=["square_80x80", "tilted_rect_90x40_30deg", "circle_r36"]),
        prerequisites="RETR_EXTERNAL 提取的四组外轮廓",
        action="依次调用 contourArea、arcLength、boundingRect、minAreaRect/boxPoints 与 minEnclosingCircle 核对几何特征。",
        expected=dict(
            square_area=6400.0,
            square_perimeter=320.0,
            min_area_rect_tighter_than_bbox=True,
            circle_radius_approx_36=True,
        ),
        actual=dict(
            square_area=sq_area,
            square_perimeter=sq_perim,
            min_area_rect_tighter_than_bbox=rot_min_area < rot_bbox_area,
            circle_radius_approx_36=abs(circle_radius - 36.0) < 1.0,
        ),
        measurements=dict(
            square_bbox=sq_bbox,
            rot_bbox_area=rot_bbox_area,
            rot_min_rect_area=rot_min_area,
            circle_center=circle_center,
            circle_radius=circle_radius,
            box_points_shape=list(rot_box_pts.shape),
        ),
        passed=c2_ok,
    ))

    # Case 3: approxPolyDP polygon approximation & drawContours rendering
    def poly_vertices(c, ratio=0.02):
        eps = ratio * cv2.arcLength(c, True)
        return cv2.approxPolyDP(c, eps, True)

    approx_sq = poly_vertices(sq_simple)
    approx_tri = poly_vertices(tri_c)
    approx_rot = poly_vertices(rot_c)
    approx_cir = poly_vertices(circle_c, ratio=0.015)

    canvas = bgr.copy()
    cv2.drawContours(canvas, tree_simple, -1, (0, 255, 0), 2)
    green_drawn = int(np.count_nonzero((canvas[:, :, 1] == 255) & (canvas[:, :, 0] == 0)))
    c3_ok = (len(approx_tri) == 3 and len(approx_sq) == 4 and len(approx_rot) == 4
             and len(approx_cir) >= 8 and green_drawn > 500)
    cases.append(dict(
        name="approx_polydp_and_draw_contours",
        inputs=dict(epsilon_ratio=0.02, circle_epsilon_ratio=0.015),
        prerequisites="外轮廓点集与空白/原图画布",
        action="使用 cv2.approxPolyDP() 进行多边形逼近分类顶点数,并使用 cv2.drawContours() 绘制全部轮廓。",
        expected=dict(
            triangle_vertices=3,
            square_vertices=4,
            rotated_rect_vertices=4,
            circle_vertices_ge_8=True,
            drawn_green_pixels_gt_500=True,
        ),
        actual=dict(
            triangle_vertices=len(approx_tri),
            square_vertices=len(approx_sq),
            rotated_rect_vertices=len(approx_rot),
            circle_vertices_ge_8=len(approx_cir) >= 8,
            drawn_green_pixels_gt_500=green_drawn > 500,
        ),
        measurements=dict(circle_approx_vertices=len(approx_cir), drawn_green_pixels=green_drawn),
        passed=c3_ok,
    ))

    # Case 4: Matplotlib visualization figure
    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)

        annot = np.full_like(bgr, 24)
        cv2.drawContours(annot, tree_simple, -1, (200, 200, 200), 1)
        # Bounding rect on square (green)
        x, y, w, h = sq_bbox
        cv2.rectangle(annot, (x, y), (x + w, y + h), (0, 220, 80), 2)
        # Approx poly on triangle (cyan)
        cv2.drawContours(annot, [approx_tri], 0, (255, 220, 0), 2)
        # MinAreaRect on rotated rect (red in BGR -> (40,40,240))
        cv2.drawContours(annot, [rot_box_pts], 0, (40, 60, 255), 2)
        # MinEnclosingCircle on circle (blue/orange)
        cv2.circle(annot, (int(round(cx)), int(round(cy))), int(round(radius)), (255, 140, 0), 2)

        fig, axes = plt.subplots(1, 2, figsize=(9.6, 4.1), dpi=140)
        axes[0].imshow(binary, cmap="gray", vmin=0, vmax=255)
        axes[0].set_title(f"输入二值图 (外轮廓={len(ext_simple)}, 树轮廓={len(tree_simple)})", fontsize=10)
        axes[0].axis("off")

        axes[1].imshow(cv2.cvtColor(annot, cv2.COLOR_BGR2RGB))
        axes[1].set_title("外接矩形(绿) / 多边形(青) / 外接圆(蓝) / 最小旋转框(红)", fontsize=9.5)
        axes[1].axis("off")
        fig.suptitle("OpenCV 轮廓提取与几何特征标注实测", fontsize=12)
        fig.tight_layout()
        out_png = fig_dir / "contour-geometry-features.png"
        fig.savefig(out_png)
        plt.close(fig)
        figures["contour-geometry-features.png"] = sha(out_png)
        mpl_ver = matplotlib.__version__

    cases.append(dict(
        name="contour_features_plot",
        inputs=dict(panels=2, figure="contour-geometry-features.png"),
        prerequisites="二值图形与外接矩形、最小旋转矩形、最小外接圆及多边形逼近标注",
        action="输出 1×2 轮廓检测与几何特征可视化图 PNG。",
        expected=dict(panel_count=2, shapes_annotated=4),
        actual=dict(panel_count=2, shapes_annotated=len(ext_simple)),
        measurements=dict(figure_generated="contour-geometry-features.png" in figures),
        passed=len(ext_simple) == 4,
    ))

    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)
预期结果 · 待实际运行核验
  • 核对 RETR_EXTERNAL(4) 与 RETR_TREE(5,含 1 子孔)、CHAIN_APPROX_SIMPLE(4 点) 压缩比、方块面积 6400/周长 320、旋转框面积 3742 < 8019、外接圆半径 36.0 与多边形顶点数。
运行轮廓层次提取、几何特征度量与多边形逼近实验

所需环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。

当前源码 SHA256:1a8ef6faad5dc2dbb2d80d91745b8c97ac2cc89777dba734b41f9475d94873fd

下载本站示例源码

本地运行

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

下载OpenCV 图像轮廓检测实验

所需环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。

ZIP SHA256:b5bd614f2c47fc0c762490d517e1b248fe154c761febe409db3504fd35bfbb96

常见错误与边界

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

练习与解答

在 NumPy 2.x 与新版 OpenCV 环境下,使用 cv2.minAreaRect() 和 cv2.boxPoints() 绘制旋转框时为何不能直接沿用旧写法 np.int0(box)?

展开参考解答

NumPy 2.0 起已正式移除废弃别名 np.int0,继续调用会触发 AttributeError;应改用 np.intp(np.round(box)) 或 box.astype(np.int32) 将浮点角点转为整数坐标。

规范与官方依据