mask_color_map.json丢失,导致分割标签.png无法导入X-Anylabeling的解决办法

最近在接手前人的分割任务时遇到了一个问题,即仅知道数据集可能有多少类,但是类名、具体的类个数、以及对应的色彩映射标签全都不清楚。而缺少这些会导致无法继续开展标注,所以当前撰写了一个脚本,通过读取部分的.png标签,从而猜测该数据集的色彩种类以及具体的映射色彩,进而生成mask_color_mapu.json导入X-Anylabeling。

具体的代码:

由于处理图片的过程较慢,当前直接固定读取100张图片进行猜测。第一次执行由于不知道类别个数和类别对应的色彩,所以仅输出'索引x: 255,170,0...'这样的标签。

复制代码
import os
import cv2
import numpy as np
import json

# ================= 配置区域 =================
# 你的标签文件夹路径 (请修改这里)
label_dir = r'D:\datasets\xxx\labels' 

# 想要保存生成的 json 文件路径
output_json_path = 'mask_color_map.json'
# ===========================================

def get_unique_colors(label_dir):
    print(f"正在扫描文件夹: {label_dir} ...")
    unique_colors = set()
    
    files = [f for f in os.listdir(label_dir) if f.endswith('.png')]
    if not files:
        print("未找到 PNG 文件!")
        return None

    # 为了节省时间,我们不需要遍历每一张图的每一个像素
    # 但为了防止遗漏,建议至少扫描一部分图片,或者全部扫描
    count = 0
    for file in files:
        file_path = os.path.join(label_dir, file)
        
        # 读取图片 (OpenCV 读取的是 BGR 格式)
        img = cv2.imread(file_path)
        if img is None:
            continue
            
        # 将 BGR 转为 RGB (因为 JSON 通常使用 RGB)
        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        
        # 将二维图像展平为像素列表,并获取唯一值
        # reshape(-1, 3) 把 (H, W, 3) 变成 (N, 3)
        colors = np.unique(img_rgb.reshape(-1, 3), axis=0)
        
        for c in colors:
            # 将 numpy 数组转为 tuple 以便放入 set 去重,并转为 int 类型以支持 JSON
            unique_colors.add(tuple(int(x) for x in c))
            
        count += 1
        print(f"已处理 {count} 张图片...")
            
        if count == 101:
            break

    return sorted(list(unique_colors))

# 1. 提取颜色
found_colors = get_unique_colors(label_dir)

if found_colors:
    print("\n扫描完成!发现了以下颜色 (RGB):")
    print("-" * 30)
    for idx, color in enumerate(found_colors):
        print(f"索引 {idx}: RGB{color}")
    print("-" * 30)
    
    # 2. 这里需要你根据上面的输出进行手动填写!
    color_map = {}
    
    # === 请根据打印结果修改下面的逻辑 ===
    print("\n请在代码中修改映射逻辑,然后再次运行生成 JSON。")
    print("假设映射如下(示例):")
    
    for color in found_colors:
        # 将 tuple 转回 list (确保元素为 int)
        c_list = [int(x) for x in color]
        
        # 逻辑判断:YGBR 映射
        if c_list == [0, 0, 0]:
            class_name = "_background_"
        elif c_list == [0, 170, 255]:
            class_name = "Blue"
        elif c_list == [160, 180, 0]:
            class_name = "Green"
        elif c_list == [244, 108, 59]:
            class_name = "Red"
        elif c_list == [255, 170, 0]:
            class_name = "Yellow"
        else:
            # 如果有未知的杂色,先给个临时名字
            class_name = f"unknown_{c_list}"
            
        color_map[class_name] = c_list

    # 3. 保存 JSON
    with open(output_json_path, 'w') as f:
        json.dump(color_map, f, indent=4)
        
    print(f"\n成功生成: {output_json_path}")
    print("内容预览:")
    print(json.dumps(color_map, indent=4))

else:
    print("未发现有效颜色。")
    
'''
    python ./recover_colormap.py
'''
相关推荐
道友可好1 天前
让 AI 自己验收,等于让学生自己批卷
前端·人工智能·后端
美团技术团队1 天前
美团海报生成 AIGC 技术创新与实践
人工智能
冬哥聊AI1 天前
放弃 Spring AI?这 3 个开源框架,才是让 SpringBoot 玩转 AI Agent 的正解
人工智能
小爷毛毛_卓寿杰1 天前
当 max_tokens=1 遇上 reasoning 模型:从 Xagent 一次“测试连接“按钮的失败说起
人工智能
用户5191495848451 天前
Flex QR Code Generator 漏洞利用工具 CVE-2025-10041
人工智能·aigc
蝎子莱莱爱打怪1 天前
AI Agent 相关知识扫盲:16 个概念+11张图+38个开源项目推荐
人工智能·github·agent
甲维斯1 天前
Fable+Codex 《坦克大战3D》双端发布了!
人工智能·ai编程·游戏开发
掘金一周1 天前
企业中要做智能体,最佳的方案是什么? | 沸点周刊 6.18
前端·人工智能·ai编程
雪隐1 天前
个人电脑玩AI-04让5060 Ti给你打工——本地claude code编程助理
人工智能·后端