labelme标注不同物体显示不同颜色

本文介绍如何修改LabelMe软件,使其能根据不同的物体类别显示特定的RGB颜色,包括修改label.py和json_to_dataset.py文件,以及如何批量处理生成的数据集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

labelme标注不同类别物体显示不同的颜色

1、labelme的版本

labelme版本

2、下载labelme后进行文件修改

由于博主想要的是rgb三通道的彩色图,所以标注出的是三通道的rgb值。
因此本教程适合想要标注的物体是彩色图案的读者,不是灰度图。

2.1 label.py文件的修改
#博主的参考路径为:
C:\ProgramData\Anaconda3\envs\labelme\Lib\site-packages\imgviz

修改如下内容:

import numpy as np

from . import color as color_module
from . import draw as draw_module


def label_colormap(n_label=256, value=None):
    """Label colormap.

    Parameters
    ----------
    n_labels: int
        Number of labels (default: 256).
    value: float or int
        Value scale or value of label color in HSV space.

    Returns
    -------
    cmap: numpy.ndarray, (N, 3), numpy.uint8
        Label id to colormap.

    """

    def bitget(byteval, idx):
        return (byteval & (1 << idx)) != 0

    cmap = np.zeros((n_label, 3), dtype=np.uint8)
    for i in range(0, n_label):
        id = i
        r, g, b = 0, 0, 0
        for j in range(0, 8):
            r = np.bitwise_or(r, (bitget(id, 0) << 7 - j))
            g = np.bitwise_or(g, (bitget(id, 1) << 7 - j))
            b = np.bitwise_or(b, (bitget(id, 2) << 7 - j))
            id = id >> 3
        cmap[i, 0] = r
        cmap[i, 1] = g
        cmap[i, 2] = b
        
    #我认为添加的一段,自己设置不同类别的rgb值
    cmap[0,:] = [255,255,255] #背景的rgb值
    cmap[1,:] = [255,0,0] #车的rgb
    cmap[2,:] = [0,255,0] #人的rgb

    if value is not None:
        hsv = color_module.rgb2hsv(cmap.reshape(1, -1, 3))
        if isinstance(value, float):
            hsv[:, 1:, 2] = hsv[:, 1:, 2].astype(float) * value
        else:
            assert isinstance(value, int)
            hsv[:, 1:, 2] = value
        cmap = color_module.hsv2rgb(hsv).reshape(-1, 3)
    return cmap


def label2rgb(
    label,
    img=None,
    alpha=0.5,
    label_names=None,
    font_size=30,
    thresh_suppress=0,
    colormap=None,
    loc="centroid",
):
    """Convert label to rgb.

    Parameters
    ----------
    label: numpy.ndarray, (H, W), int
        Label image.
    img: numpy.ndarray, (H, W, 3), numpy.uint8
        RGB image.
    alpha: float
        Alpha of RGB (default: 0.5).
    label_names: list of string
        Label id to label name.
    font_size: int
        Font size (default: 30).
    thresh_suppress: float
        Threshold of label ratio in the label image.
    colormap: numpy.ndarray, (M, 3), numpy.uint8
        Label id to color.
        By default, :func:`~imgviz.label_colormap` is used.
    loc: string
        Location of legend (default: 'centroid').
        'lt' and 'rb' are supported.

    Returns
    -------
    res: numpy.ndarray, (H, W, 3), numpy.uint8
        Visualized image.

    """
    if colormap is None:
        colormap = label_colormap()

    res = colormap[label]

    random_state = np.random.RandomState(seed=1234)

    mask_unlabeled = label < 0
    res[mask_unlabeled] = random_state.rand(*(mask_unlabeled.sum(), 3)) * 255

    if img is not None:
        if img.ndim == 2:
            img = color_module.gray2rgb(img)
        res = (1 - alpha) * img.astype(float) + alpha * res.astype(float)
        res = np.clip(res.round(), 0, 255).astype(np.uint8)

    if label_names is None:
        return res

    if loc == "centroid":
        for label_i in np.unique(label):
            if label_i == -1:
                continue  # unlabeled

            mask = label == label_i
            if 1.0 * mask.sum() / mask.size < thresh_suppress:
                continue
            y, x = np.array(_center_of_mass(mask), dtype=int)

            if label[y, x] != label_i:
                Y, X = np.where(mask)
                point_index = np.random.randint(0, len(Y))
                y, x = Y[point_index], X[point_index]

            text = label_names[label_i]
            height, width = draw_module.text_size(text, size=font_size)
            color = color_module.get_fg_color(res[y, x])
            res = draw_module.text(
                res,
                yx=(y - height // 2, x - width // 2),
                text=text,
                color=color,
                size=font_size,
            )
    elif loc in ["rb", "lt"]:
        unique_labels = np.unique(label)
        unique_labels = unique_labels[unique_labels != -1]
        text_sizes = np.array(
            [
                draw_module.text_size(label_names[l], font_size)
                for l in unique_labels
            ]
        )
        text_height, text_width = text_sizes.max(axis=0)
        legend_height = text_height * len(unique_labels) + 5
        legend_width = text_width + 40

        height, width = label.shape[:2]
        legend = np.zeros((height, width, 3), dtype=np.uint8)
        if loc == "rb":
            aabb2 = np.array([height - 5, width - 5], dtype=float)
            aabb1 = aabb2 - (legend_height, legend_width)
        elif loc == "lt":
            aabb1 = np.array([5, 5], dtype=float)
            aabb2 = aabb1 + (legend_height, legend_width)
        else:
            raise ValueError("unexpected loc: {}".format(loc))
        legend = draw_module.rectangle(
            legend, aabb1, aabb2, fill=(255, 255, 255)
        )

        alpha = 0.5
        y1, x1 = aabb1.round().astype(int)
        y2, x2 = aabb2.round().astype(int)
        res[y1:y2, x1:x2] = (
            alpha * res[y1:y2, x1:x2] + alpha * legend[y1:y2, x1:x2]
        )

        for i, l in enumerate(unique_labels):
            box_aabb1 = aabb1 + (i * text_height + 5, 5)
            box_aabb2 = box_aabb1 + (text_height - 10, 20)
            res = draw_module.rectangle(
                res, aabb1=box_aabb1, aabb2=box_aabb2, fill=colormap[l]
            )
            res = draw_module.text(
                res,
                yx=aabb1 + (i * text_height, 30),
                text=label_names[l],
                size=font_size,
            )
    else:
        raise ValueError("unsupported loc: {}".format(loc))

    return res


def _center_of_mass(mask):
    assert mask.ndim == 2 and mask.dtype == bool
    mask = 1.0 * mask / mask.sum()
    dx = np.sum(mask, 0)
    dy = np.sum(mask, 1)
    cx = np.sum(dx * np.arange(mask.shape[1]))
    cy = np.sum(dy * np.arange(mask.shape[0]))
    return cy, cx

需要修改的地方博主已经做了注释和说明。

2.2 json_to_dataset.py文件的修改
#博主的参考路径:
C:\ProgramData\Anaconda3\envs\labelme\Lib\site-packages\labelme\cli

修改如下内容:

import argparse
import base64
import json
import os
import os.path as osp

import imgviz
import PIL.Image

from labelme.logger import logger
from labelme import utils


def main():
    logger.warning('This script is aimed to demonstrate how to convert the'
                   'JSON file to a single image dataset, and not to handle'
                   'multiple JSON files to generate a real-use dataset.')

    parser = argparse.ArgumentParser()
    parser.add_argument('json_file')
    parser.add_argument('-o', '--out', default=None)
    args = parser.parse_args()

    json_file = args.json_file

    if args.out is None:
        out_dir = osp.basename(json_file).replace('.', '_')
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(out_dir)

    data = json.load(open(json_file))
    imageData = data.get('imageData')

    if not imageData:
        imagePath = os.path.join(os.path.dirname(json_file), data['imagePath'])
        with open(imagePath, 'rb') as f:
            imageData = f.read()
            imageData = base64.b64encode(imageData).decode('utf-8')
    img = utils.img_b64_to_arr(imageData)

    label_name_to_value = {'_background_': 0,'car':1,'person':2}  #在这一行更改,改成自己的类别数
    for shape in sorted(data['shapes'], key=lambda x: x['label']):
        label_name = shape['label']
        if label_name in label_name_to_value:
            label_value = label_name_to_value[label_name]
        else:
            label_value = len(label_name_to_value)
            label_name_to_value[label_name] = label_value
    lbl, _ = utils.shapes_to_label(
        img.shape, data['shapes'], label_name_to_value
    )

    label_names = [None] * (max(label_name_to_value.values()) + 1)
    for name, value in label_name_to_value.items():
        label_names[value] = name

    lbl_viz = imgviz.label2rgb(
        label=lbl, img=imgviz.asgray(img), label_names=label_names, loc='rb'
    )

    PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
    utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
    PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))

    with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
        for lbl_name in label_names:
            f.write(lbl_name + '\n')

    logger.info('Saved to: {}'.format(out_dir))


if __name__ == '__main__':
    main()

文中需要修改的地方博主已经进行了说明。

3、如何使用修改后的文件

label.py和json_to_dataset.py修改后不用管。
当labelme标注完自己的数据集后,会生成对应的.json文件,此时需要将文件进行批量化生成json文件夹,里面包含了原图,标签,txt等文件。博主弄了一个批量化生成json文件夹的python文件。
此文件博主已经上传到csdn,读者可以免积分下载。
链接:https://download.youkuaiyun.com/download/weixin_44753371/12298864

import os
path = 'D:/Image_Segmentic/Semantic-Segmentation-master/dataset2/label'  # path为json文件存放的路径
json_file = os.listdir(path)
os.system("activate labelme") # 博主labelme所在的环境名就叫labelme,读者应修改成activate [自己labelme所在的环境名]
for file in json_file: 
    os.system("labelme_json_to_dataset.exe %s"%(path + '/' + file))

使用方法:
使用操作
在虚拟空间建立labelme,要进入到labelme的虚拟空间。尽管会提示警告,但可以进行批量化处理,因为labelme的本意是演示单个文件的标注,所以本身不支持批量化处理。

本文的参考博客:
1
2

<think>好的,用户遇到了Labelme显示标注的问题,我需要根据提供的引用资料来找出可能的原因和解决方案。首先,用户提到已经尝试过很多方法,但问题依然存在,显示找不到Labelme,尽管它确实在文件夹里。这可能涉及到安装问题或者路径配置错误。 首先,查看引用[5]提到安装过程中setuptools版本过高可能导致问题,需要降级。虽然用户的问题不是安装失败,但版本兼容性问题可能影响Labelme的正常运行,包括标注显示。可能需要检查依赖库的版本是否正确。 然后,引用[2]指出不同物体标注颜色显示问题,解决方案是升级Labelme版本。这说明版本过旧可能导致显示异常,包括标注显示。建议用户升级到最新版本,可能修复了相关bug。 引用[3]和[4]提到路径错误的问题,如果标注文件的路径不正确,Labelme可能无法加载标注数据,导致不显示。需要确认标注文件的路径是否正确,或者是否有中文/特殊字符,这可能导致读取失败。 另外,用户可能没有正确保存标注文件,或者在打开时选择了错误的文件。需要检查标注文件是否存在,格式是否正确,比如JSON文件是否完整。 还有可能是图像文件被移动或删除,导致Labelme无法找到对应的图像,从而不显示标注。需要确保图像文件的位置与标注文件中记录的一致。 综合以上可能的原因,解决方案应包括检查Labelme版本、验证标注文件路径、确保依赖库版本正确、检查图像文件是否存在,以及查看文件权限和特殊字符问题。此外,重新安装或升级Labelme可能解决潜在的软件缺陷。</think>### Labelme显示标注的原因及解决方案 #### 一、软件版本问题 1. **Labelme版本过旧** 早期版本的Labelme可能存在标注显示兼容性问题,例如标注颜色异常或渲染失败[^2]。 **解决方案**: ```bash pip install labelme --upgrade ``` 2. **依赖库版本冲突** 例如`setuptools`版本过高可能导致功能异常[^5]。 **解决方案**: ```bash pip uninstall setuptools pip install setuptools==58.0.4 ``` #### 二、标注文件问题 1. **标注文件路径错误** 如果标注文件(JSON)与图像文件路径不匹配,或文件被移动/删除,会导致标注无法加载[^3]。 **解决方案**: - 检查JSON文件中`imagePath`字段是否指向正确的图像路径 - 避免使用中文或特殊字符命名路径 2. **标注文件格式损坏** 手动修改JSON文件可能导致语法错误,例如缺少引号或括号。 **解决方案**: - 使用Labelme重新保存标注 - 使用JSON验证工具(如`jsonlint`)检查文件完整性 #### 三、显示配置问题 1. **标注颜色与背景色相同** 如果标注颜色设置为透明或与背景色接近,可能导致视觉上的“不显示”。 **解决方案**: - 在Labelme设置中调整标注颜色(`Edit -> Preferences`) - 确保标注透明度未设置为0% 2. **图层渲染异常** 显卡驱动或GUI库(如Qt)的兼容性问题可能导致渲染失败。 **解决方案**: - 更新显卡驱动 - 重装Qt依赖: ```bash pip install PyQt5 --force-reinstall ``` #### 四、操作问题 1. **未正确加载标注文件** 直接打开图像文件而非JSON文件会导致标注显示。 **正确操作流程**: - 启动Labelme后点击`Open`选择JSON文件 - 或通过命令行指定文件: ```bash labelme --nodata image.jpg ``` 2. **标注被意外隐藏** 可能误触快捷键关闭标注显示(如`Ctrl+H`)。 **解决方案**: - 按`Ctrl+0`重置视图 - 在菜单栏勾选`View -> Show Labels` #### 五、系统环境问题 1. **文件权限限制** 无读取权限会导致标注加载失败(常见于Linux/macOS)。 **解决方案**: ```bash chmod 644 /path/to/your/label.json ``` 2. **Python环境污染** 多版本Python或虚拟环境配置错误可能导致依赖混乱[^5]。 **解决方案**: - 创建干净的虚拟环境: ```bash python -m venv labelme_env source labelme_env/bin/activate # Linux/macOS labelme_env\Scripts\activate.bat # Windows pip install labelme ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值