python 求内轮廓

发布于:2025-05-23 ⋅ 阅读:(16) ⋅ 点赞:(0)

效果图

轮廓检测方法: 

import cv2
import numpy as np

# 创建画布
canvas_size = 500
img = np.zeros((canvas_size, canvas_size, 3), dtype=np.uint8)  # 可视化用彩色图像
binary = np.zeros((canvas_size, canvas_size), dtype=np.uint8)  # 处理用二值图像

# 定义多边形顶点(示例为五边形)
vertices = np.array([[100, 100], [400, 150], [350, 400], [150, 400], [50, 200]], dtype=np.int32)

# 绘制带厚度的白色多边形
cv2.polylines(img, [vertices], isClosed=True, color=(255, 255, 255), thickness=2)
cv2.polylines(binary, [vertices], isClosed=True, color=255, thickness=2)

# 轮廓检测
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# 筛选内轮廓(具有父轮廓的)
inner_contours = []
if hierarchy is not None:
    hierarchy = hierarchy[0]  # 去除外层维度
    for i, (_, _, _, parent_idx) in enumerate(hierarchy):
        if parent_idx != -1:  # 存在父轮廓的即为内轮廓
            inner_contours.append(contours[i])

# 处理找到的第一个内轮廓
if inner_contours:
    # 使用多边形近似算法
    epsilon = 0.01 * cv2.arcLength(inner_contours[0], True)
    approx = cv2.approxPolyDP(inner_contours[0], epsilon, True)

    # 提取顶点坐标
    inner_vertices = approx.reshape(-1, 2)

    # 可视化标记
    for (x, y) in inner_vertices:
        cv2.circle(img, (x, y), 2, (0, 0, 255), -1)  # 红色标记顶点
        cv2.putText(img, f"({x},{y})", (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

# 显示结果
cv2.imshow('Polygon with Inner Vertices', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 输出顶点坐标
if inner_contours:
    print("内轮廓顶点坐标:")
    print(inner_vertices)
else:
    print("未检测到内轮廓")


网站公告

今日签到

点亮在社区的每一天
去签到