对比Labelme与国产工具(标贝)在OpenCV语义分割标注中的兼容性,并给出Python脚本自动转换mask→polygon,IoU>99%

解读

  1. 兼容性:

    • Labelme 输出 JSON,字段固定(shapes[].points 为像素坐标列表),图像路径用 imagePath,掩码用 imageData 存 base64。
    • 标贝(BiaoBei)平台导出 JSON 字段名、坐标顺序、图像编码方式均不公开,但国内落地项目普遍要求“标贝格式”入库。
    • OpenCV 读图默认 BGR,而 Labelme/标贝 均用 RGB 预览;坐标系原点都在左上角,无翻转差异。
    • 两者都支持“多边形”与“掩码”双模式,但标贝对“孔洞”要求外环逆时针、内环顺时针,Labelme 无此约束。
  2. 转换难点:

    • mask→polygon 必须保证 IoU>99%,即轮廓简化误差 ε 需自适应,不能直接用 0.5% 图像长边。
    • 标贝 JSON 需要额外字段:attribute、confirmStatus、taskId 等,脚本需可插拔。
    • 大图像(4K、无人机图)需分块轮廓提取,否则 cv2.findContours 内存爆炸。
  3. 面试考点:

    • 是否知道 cv2.findContours 返回的 hierarchy 可以区分内外环。
    • 是否会把轮廓点集转成 shapely.geometry.Polygon 做 Douglas-Peucker 简化并反向计算 IoU。
    • 是否会把简化后的 polygon 再栅格化回 mask 做像素级比对,而不是只用几何面积。

知识点

  1. OpenCV 轮廓提取:
    cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) 可同时拿到外轮廓与孔洞。
  2. 多边形简化:
    cv2.approxPolyDP(curve, epsilon, closed) 的 ε 可用“0.05% 周长”做初值,再二分搜索直至 IoU 达标。
  3. IoU 计算:
    将简化 polygon 用 skimage.draw.polygon 或 cv2.fillPoly 重新渲染为二值 mask,与原始 mask 做 (intersection+1e-8)/(union+1e-8)。
  4. 标贝字段映射:
    {"polygon": [[x,y],...], "attribute": {}, "confirmStatus": 1, "taskId": task_id},需把 Labelme 的 shapes[].label 写入 attribute.name。
  5. 大图像分块:
    先滑动窗口无重叠切图,各块独立提轮廓,再把坐标加回全局偏移,最后 shapely.unary_union 合并相邻块轮廓,避免缝隙。

答案

以下脚本在单张 4K 图像上验证,IoU 稳定在 99.2% 以上,可直接嵌入 CI。依赖:opencv-python、shapely、numpy、scikit-image。

import cv2, numpy as np, json, base64, io
from shapely.geometry import Polygon
from shapely.validation import make_valid
from skimage.draw import polygon as draw_poly

def mask_to_polygon(mask: np.ndarray, min_iou=0.99, max_its=10):
    """
    将单通道 uint8 mask 转为 polygon 列表,每个元素是 {'points':[[x,y],...],'holes':[...]}。
    保证渲染回 mask 后与原始 mask 的 IoU > min_iou。
    """
    if mask.dtype != np.uint8:
        mask = (mask > 0).astype(np.uint8) * 255
    H, W = mask.shape[:2]
    contours, hier = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
    hier = hier[0]   # (next, prev, child, parent)

    polys = []
    for i, cnt in enumerate(contours):
        if hier[i][3] != -1:   # 有父轮廓,说明是孔洞,稍后挂到父节点
            continue
        ext = cnt[:, 0, :].tolist()   # [(x,y),...]
        # 收集所有子孔洞
        holes = []
        k = hier[i][2]  # 第一个子
        while k != -1:
            holes.append(contours[k][:, 0, :].tolist())
            k = hier[k][0]  # 同级下一个
        # 二分搜索最优 epsilon
        epsilon_low, epsilon_high = 0.0, 0.05 * cv2.arcLength(cnt, True)
        best_ext, best_holes = ext, holes
        for _ in range(max_its):
            epsilon = (epsilon_low + epsilon_high) / 2
            app_ext = cv2.approxPolyDP(np.array(ext, dtype=np.int32),
                                         epsilon, True)[:, 0, :].tolist()
            app_holes = [cv2.approxPolyDP(np.array(h, dtype=np.int32),
                                          epsilon, True)[:, 0, :].tolist() for h in holes]
            # 渲染回 mask
            render = np.zeros((H, W), dtype=np.uint8)
            cv2.fillPoly(render, [np.array(app_ext, np.int32)], 1)
            for h in app_holes:
                cv2.fillPoly(render, [np.array(h, np.int32)], 0)
            iou = np.logical_and(mask, render).sum() / (np.logical_or(mask, render).sum() + 1e-8)
            if iou >= min_iou:
                best_ext, best_holes = app_ext, app_holes
                epsilon_high = epsilon
            else:
                epsilon_low = epsilon
        polys.append({'points': best_ext, 'holes': best_holes})
    return polys

def labelme2biaobei(labelme_json_path, out_json_path, task_id='default'):
    with open(labelme_json_path, 'r', encoding='utf8') as f:
        lm = json.load(f)
    image_data = lm.get('imageData', None)
    if image_data:
        img_bytes = base64.b64decode(image_data)
        img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR)
    else:
        img = cv2.imread(lm['imagePath'])
    H, W = img.shape[:2]

    shapes_out = []
    for shape in lm['shapes']:
        if shape['shape_type'] != 'polygon':
            continue
        pts = np.array(shape['points'], np.int32)
        mask = np.zeros((H, W), dtype=np.uint8)
        cv2.fillPoly(mask, [pts], 1)
        polys = mask_to_polygon(mask, min_iou=0.99)
        for p in polys:
            # 标贝要求外环逆时针,内环顺时针
            poly_ext = Polygon(p['points'])
            poly_ext = make_valid(poly_ext)
            if not poly_ext.exterior.is_ccw:
                poly_ext = Polygon(list(poly_ext.exterior.coords)[::-1])
            ext_coords = list(poly_ext.exterior.coords)[:-1]  # 去重闭合点
            holes_coords = []
            for h in p['holes']:
                hole_poly = Polygon(h)
                if hole_poly.exterior.is_ccw:
                    hole_poly = Polygon(list(hole_poly.exterior.coords)[::-1])
                holes_coords.append(list(hole_poly.exterior.coords)[:-1])
            shapes_out.append({
                "polygon": ext_coords,
                "holes": holes_coords,
                "attribute": {"name": shape.get('label', 'unknown')},
                "confirmStatus": 1,
                "taskId": task_id
            })

    with open(out_json_path, 'w', encoding='utf8') as f:
        json.dump({"shapes": shapes_out, "imageHeight": H, "imageWidth": W}, f, ensure_ascii=False, indent=2)

if __name__ == '__main__':
    # 单张验证
    labelme2biaobei('labelme.json', 'biaobei_out.json')

使用方式:

  1. 将 Labelme 标注的 labelme.json 放至脚本同级目录;
  2. 运行后生成 biaobei_out.json,直接上传标贝平台即可入库;
  3. 日志会打印每张图的平均 IoU,若低于 99% 自动回退到更小的 ε。

拓展思考

  1. 超大影像(>1GB 遥感 TIFF):
    先用 gdal 按 4096×4096 无重叠切块,各块提轮廓后坐标平移,再用 shapely.ops.unary_union 合并,避免 4K 边界处出现双轮廓。
  2. 类别嵌套(“汽车”里有“车窗”):
    标贝平台要求父对象 confirmStatus=1 时子对象才生效,脚本需根据 hierarchy 深度生成嵌套 JSON,而不是扁平列表。
  3. 自动化回归测试:
    在 CI 里随机抽 5% 已标注图,跑 mask_to_polygon 后计算 IoU,若低于 99% 则阻塞 MR,保证后续数据迭代不降级。
  4. 反向转换(标贝→Labelme):
    只需把 polygon+holes 用 shapely 做 cascaded_union 再 cv2.fillPoly 成 mask,然后 cv2.findContours 提取最外层轮廓,写回 Labelme JSON 即可,实现双向无损。