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
'''
相关推荐
东莞呵呵7 小时前
从Linear到MLP AI模型的数学本质
人工智能·深度学习·机器学习
SmartBrain7 小时前
Spring Boot 中常用注解总结(AI工程化)
java·人工智能·spring boot·后端
帐篷Li7 小时前
Superpowers:让 AI 编程助手拥有专业级软件开发流程
人工智能·everything
明月照山海-7 小时前
机器学习周报三十七
人工智能·机器学习
TOWE technology7 小时前
从“制造”到“智造”:智能PDU如何成为智慧工厂的电力“神经中枢”
大数据·人工智能·制造·数据中心·电源管理·智能pdu
flying_13147 小时前
图神经网络分享系列-HAN(Heterogeneous Graph Attention Network)(一)
人工智能·深度学习·图神经网络·异构图·han·节点级注意力·语义级注意力
MIka7 小时前
CopilotKit 入门:用 Runtime 和 React Core 搭建真正可用的 AI Copilot
人工智能·typescript·agent
一 铭7 小时前
Agent设计方式-工具调用:从自然语言到工具调用的桥梁
人工智能·大模型
用户4815930195917 小时前
MCP vs Function Calling:两个总被搞混的概念,一次说清楚
人工智能
黄粱梦醒7 小时前
OpenClaw-window安装教程以及通用常用命令
人工智能·llm