蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。explore-image-contour-detection.py
explore-image-contour-detection.py230 行
"""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)
本例需在 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-contour-detection-lab/explore-image-contour-detection.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-image-contour-detection.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:OpenCV

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

下载课程关联工程包:OpenCV

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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