opencv系列:获取闭环轮廓坐标信息

opencv系列:获取闭环轮廓坐标信息

示例代码

import numpy as np
import cv2

def get_contour_closed_coord_info(mask):
    # 找到轮廓,这里使用RETR_TREE以检索所有轮廓和它们的层次结构
    contours, hierarchy = cv2.findContours(
        mask, 
        cv2.RETR_TREE, 
        cv2.CHAIN_APPROX_NONE # 获取所有轮廓点
    )
    contour_closed_coord_dict = {}
    # 遍历所有轮廓
    for i, contour in enumerate(contours):
        # 检查轮廓是否为内部轮廓(即闭环部分)
        if hierarchy[0][i][3] != -1:
            # 轮廓是闭环的,可能是内部轮廓或子轮廓
            # 获取闭环的坐标点信息
            closed_contour_points = contour.reshape(-1, 2)
            contour_closed_coord_dict[i] = closed_contour_points

    return contour_closed_coord_dict

if __name__ == "__main__":
    mask_path = ".test.png"
    # 读取图像
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
    # 根据需要设置
    # mask = cv2.inRange(mask, 100, 255)
    # 社区版python-opencv才行
    mask = cv2.ximgproc.thinning(
        mask,
        # thinningType=cv2.ximgproc.THINNING_ZHANGSUEN
        thinningType=cv2.ximgproc.THINNING_GUOHALL,
    )
    contour_closed_coord_dict = get_contour_closed_coord_info(mask)
    mask_contour_closed = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
    mask_visual_path = "./test_visual.png"
    for i, contour_points in contour_closed_coord_dict.items():
        mask_contour_closed[contour_points[:, 1], contour_points[:, 0]] = (255, 255, 0)
    cv2.imwrite(mask_visual_path, mask_contour_closed)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值