You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实例分割任务中如何为不同Mask标注填充差异化颜色

实例分割标注的差异化颜色填充解决方案

核心思路

直接基于标注的遍历索引分配唯一颜色,跳过连通域分析工具(比如skimage.morphology.label)。这样不管单个标注内部是否存在非连通区域,同一次循环处理的标注会被填充为同一种颜色,不同标注则用不同颜色,完全匹配你的需求。

具体实现方案

方案1:随机生成唯一颜色(适合标注数量较少的场景)

通过随机生成RGB值,并记录已使用的颜色来避免重复:

import numpy as np
import random

# 假设你的标注集合是masks,每个元素是二值数组(1/True表示目标区域)
masks = [...]  # 替换为你的标注数据
height, width = masks[0].shape

# 初始化空白RGB画布
canvas = np.zeros((height, width, 3), dtype=np.uint8)
used_colors = set()

def get_unique_random_color():
    while True:
        color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
        if color not in used_colors:
            used_colors.add(color)
            return color

# 遍历每个标注填充颜色
for mask in masks:
    color = get_unique_random_color()
    canvas[mask] = color

方案2:基于索引的确定性颜色生成(适合标注数量较多的场景)

利用HSL色彩空间,通过索引计算色相值,生成均匀分布的唯一颜色,避免随机生成的重复风险:

import numpy as np
import colorsys

masks = [...]  # 替换为你的标注数据
height, width = masks[0].shape
canvas = np.zeros((height, width, 3), dtype=np.uint8)
total_masks = len(masks)

def get_color_by_index(idx):
    # 色相随索引线性变化,保证颜色均匀分布
    hue = idx / total_masks
    # 转换为RGB,固定饱和度和亮度保证颜色辨识度
    rgb = colorsys.hsv_to_rgb(hue, 0.9, 0.7)
    return tuple(int(x * 255) for x in rgb)

# 遍历填充
for idx, mask in enumerate(masks):
    color = get_color_by_index(idx)
    canvas[mask] = color

为什么skimage.morphology.label不适用?

该函数的核心是连通域标记,会将单个标注mask中的非连通区域识别为独立对象并分配不同label值。如果用它来映射颜色,同一个标注的不同连通块会被填充成不同颜色,这与你希望同一标注用单一颜色的需求冲突。

内容的提问来源于stack exchange,提问作者Caesar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 14:37:01