图像分割时很多模型给出的都是mask图像,为了方便转换为ROI,这里提供一段python代码基于mask提取contour坐标。

import cv2
import numpy as np

def get_outlines(masks):
    outpix = []
    for n in np.unique(masks)[1:]:
        mn = masks == n
        if mn.sum() > 0:
            contours = cv2.findContours(mn.astype(np.uint8), mode=cv2.RETR_EXTERNAL,
                                        method=cv2.CHAIN_APPROX_NONE)
            contours = contours[-2]
            cmax = np.argmax([c.shape[0] for c in contours])
            pix = contours[cmax].astype(int).squeeze()
            if len(pix) > 4:
                outpix.append(pix)
            else:
                outpix.append(np.zeros((0, 2)))
    return outpix
最后修改:2025 年 05 月 21 日
请大力赞赏以支持本站持续运行!