python 求内轮廓

效果图

轮廓检测方法:

python 复制代码
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("未检测到内轮廓")
相关推荐
孟健1 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞3 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽6 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程10 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪10 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook11 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python