Labelme标注工具安装及使用

该文章已生成可运行项目,

       训练自己的计算机视觉模型,怎么少的了数据标注工具的加持,labelme可用于目标检测、关键点检测等多种视觉任务的数据标注,是一个比较优秀的开源标注工具;接下来我就以关键点标注为例,演示一下labelme从安装到使用的全部流程。

一、安装并运行

       这里我使用的是MacOS系统的电脑,其他系统也是大同小异,Windows的话直接有免安装的exe可执行文件,无需自己安装;

1、创建并激活python虚拟环境

conda create --name labelme python=3.8.0
conda activate labelme

2、 安装labelme

pip install labelme -i https://pypi.tuna.tsinghua.edu.cn/simple

3、运行Labelme 

# 在虚拟环境为labelme的终端中运行
labelme

运行成功会出现如下界面:

二、标注关键点

1、加载预标注图片文件夹:

2、选择Edit,Create Point:

 3、标注完成后点击save,会生成一个和图片名称相同的json文件,该文件就是该图片的标签,在关键点标注任务中,需要特别注意的一个点是:

1)不管你的标签关键点在图片里面是否被遮挡,都要标注出来;

2)标注的关键点不需要有刻板的顺序,但同一批标注的训练数据的关键点标注顺序必须是一致的;

三、标注标签转换

       在yolo系列模型的训练中,yolo模型只能识别自己特定的标签格式,这时就需要将json格式的文件转换为yolo模型可以解析的标签格式,下面就以yolov8的关键点检测格式为例,对标注的json格式标签进行格式转换;

1、yolov8关键点识别模型标签格式解析:

       首先,训练集中每一张图片对应一个同名的txt文件作为标签,标签中每一行代表一组标记实体,格式及含义如下:

2、json格式转为coco格式:

import os
import sys
import glob
import json
import argparse
import numpy as np
from tqdm import tqdm
from labelme import utils


class Labelme2coco_keypoints():
    def __init__(self, args):       
        self.classname_to_id = {args.class_name: 1}
        self.images = []
        self.annotations = []
        self.categories = []
        self.ann_id = 0
        self.img_id = 0

    def save_coco_json(self, instance, save_path):
        json.dump(instance, open(save_path, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)

    def read_jsonfile(self, path):
        with open(path, "r", encoding='utf-8') as f:
            return json.load(f)

    def _get_box(self, points):
        min_x = min_y = np.inf
        max_x = max_y = 0
        for x, y in points:
            min_x = min(min_x, x)
            min_y = min(min_y, y)
            max_x = max(max_x, x)
            max_y = max(max_y, y)
        return [min_x, min_y, max_x - min_x, max_y - min_y]

    def _get_keypoints(self, points, keypoints, num_keypoints):
        if points[0] == 0 and points[1] == 0:
            visable = 0
        else:
            visable = 1
            num_keypoints += 1
        keypoints.extend([points[0], points[1], visable])
        return keypoints, num_keypoints

    def _image(self, obj, path):
        image = {}

        img_x = utils.img_b64_to_arr(obj['imageData'])  # 获得原始 labelme 标签的 imageData 属性,并通过 labelme 的工具方法转成 array
        image['height'], image['width'] = img_x.shape[:-1]  # 获得图片的宽高

        # self.img_id = int(os.path.basename(path).split(".json")[0])
        self.img_id = self.img_id + 1
        image['id'] = self.img_id

        image['file_name'] = os.path.basename(path).replace(".json", ".jpg")

        return image

    def _annotation(self, bboxes_list, keypoints_list, json_path):
        """
        生成coco标注

        Args:
            bboxes_list: 矩形标注框
            keypoints_list: 关键点
            json_path:json文件路径

        """

        if len(keypoints_list) != args.join_num * len(bboxes_list):
            print('you loss {} keypoint(s) with file {}'.format(args.join_num * len(bboxes_list) - len(keypoints_list), json_path))
            print('Please check !!!')
            sys.exit()
        i = 0
        for object in bboxes_list:
            annotation = {}
            keypoints = []
            num_keypoints = 0

            label = object['label']
            bbox = object['points']
            annotation['id'] = self.ann_id
            annotation['image_id'] = self.img_id
            annotation['category_id'] = int(self.classname_to_id[label])
            annotation['iscrowd'] = 0
            annotation['area'] = 1.0
            annotation['segmentation'] = [np.asarray(bbox).flatten().tolist()]
            annotation['bbox'] = self._get_box(bbox)

            for keypoint in keypoints_list[i * args.join_num: (i + 1) * args.join_num]:
                point = keypoint['points']
                annotation['keypoints'], num_keypoints = self._get_keypoints(point[0], keypoints, num_keypoints)
            annotation['num_keypoints'] = num_keypoints

            i += 1
            self.ann_id += 1
            self.annotations.append(annotation)

    def _init_categories(self):
        """
        初始化 COCO 的 标注类别

        例如:
        "categories": [
            {
                "supercategory": "hand",
                "id": 1,
                "name": "hand",
                "keypoints": [
                    "wrist",
                    "thumb1",
                    "thumb2",
                    ...,
                ],
                "skeleton": [
                ]
            }
        ]
        """

        for name, id in self.classname_to_id.items():
            category = {}

            category['supercategory'] = name
            category['id'] = id
            category['name'] = name
            # 17 个关键点数据
            category['keypoint'] = [str(i + 1) for i in range(args.join_num)]

            self.categories.append(category)

    def to_coco(self, json_path_list):
        """
        Labelme 原始标签转换成 coco 数据集格式,生成的包括标签和图像

        Args:
            json_path_list:原始数据集的目录

        """

        self._init_categories()

        for json_path in tqdm(json_path_list):
            obj = self.read_jsonfile(json_path)  # 解析一个标注文件
            self.images.append(self._image(obj, json_path))  # 解析图片
            shapes = obj['shapes']  # 读取 labelme shape 标注

            bboxes_list, keypoints_list = [], []
            for shape in shapes:
                if shape['shape_type'] == 'rectangle':  # bboxs
                    bboxes_list.append(shape)           # keypoints
                elif shape['shape_type'] == 'point':
                    keypoints_list.append(shape)

            self._annotation(bboxes_list, keypoints_list, json_path)

        keypoints = {}
        keypoints['info'] = {'description': 'Lableme Dataset', 'version': 1.0, 'year': 2021}
        keypoints['license'] = ['BUAA']
        keypoints['images'] = self.images
        keypoints['annotations'] = self.annotations
        keypoints['categories'] = self.categories
        return keypoints


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--class_name", default="IDBox", help="class name", type=str)
    parser.add_argument("--input",  default="./json_dataset", help="json file path (labelme)", type=str)
    parser.add_argument("--output", default="./coco_dataset", help="output file path (coco format)", type=str)
    parser.add_argument("--join_num",  default=4, help="number of join", type=int)
    # parser.add_argument("--ratio", help="train and test split ratio", type=float, default=0.5)
    args = parser.parse_args()

    labelme_path = args.input
    saved_coco_path = args.output

    json_list_path = glob.glob(labelme_path + "/*.json")

    print('{} for json files'.format(len(json_list_path)))
    print('Start transform please wait ...')

    l2c_json = Labelme2coco_keypoints(args)  # 构造数据集生成类

    # 生成coco类型数据
    keypoints = l2c_json.to_coco(json_list_path)
    l2c_json.save_coco_json(keypoints, os.path.join(saved_coco_path, "keypoints.json"))

3、coco转yolo格式:

import os
import json
from tqdm import tqdm
import argparse

parser = argparse.ArgumentParser()
# 这里根据自己的json文件位置,换成自己的就行
parser.add_argument('--json_path',
                    default='coco/keypoints.json', type=str,
                    help="input: coco format(json)")
# 这里设置.txt文件保存位置
parser.add_argument('--save_path', default='txt_dataset', type=str,
                    help="specify where to save the output dir of labels")
arg = parser.parse_args()


def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = box[0] + box[2] / 2.0
    y = box[1] + box[3] / 2.0
    w = box[2]
    h = box[3]

    x = round(x * dw, 6)
    w = round(w * dw, 6)
    y = round(y * dh, 6)
    h = round(h * dh, 6)
    return (x, y, w, h)


if __name__ == '__main__':
    json_file = arg.json_path  # COCO Object Instance 类型的标注
    ana_txt_save_path = arg.save_path  # 保存的路径

    data = json.load(open(json_file, 'r'))
    if not os.path.exists(ana_txt_save_path):
        os.makedirs(ana_txt_save_path)

    id_map = {}  # coco数据集的id不连续!重新映射一下再输出!
    with open(os.path.join(ana_txt_save_path, 'classes.txt'), 'w') as f:
        # 写入classes.txt
        for i, category in enumerate(data['categories']):
            f.write(category['name']+"\n")
            id_map[category['id']] = i
    # print(id_map)
    # 这里需要根据自己的需要,更改写入图像相对路径的文件位置。
    # list_file = open(os.path.join(ana_txt_save_path, 'train2017.txt'), 'w')
    for img in tqdm(data['images']):
        filename = img["file_name"]
        img_width = img["width"]
        img_height = img["height"]
        img_id = img["id"]
        head, tail = os.path.splitext(filename)
        ana_txt_name = head + ".txt"  # 对应的txt名字,与jpg一致
        f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w')
        for ann in data['annotations']:
            if ann['image_id'] == img_id:
                box = convert((img_width, img_height), ann["bbox"])
                f_txt.write("%s %s %s %s %s" % (id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
                counter=0
                for i in range(len(ann["keypoints"])):
                    if ann["keypoints"][i] == 2 or ann["keypoints"][i] == 1 or ann["keypoints"][i] == 0:
                        f_txt.write(" %s " % format(ann["keypoints"][i] + 1,'6f'))
                        counter=0
                    else:
                        if counter==0:
                            f_txt.write(" %s " % round((ann["keypoints"][i] / img_width),6))
                        else:
                            f_txt.write(" %s " % round((ann["keypoints"][i] / img_height),6))
                        counter+=1
        f_txt.write("\n")
        f_txt.close()

本文章已经生成可运行项目
资源下载链接为: https://pan.quark.cn/s/00cceecb854d 在计算机视觉领域,数据标注是关键环节,为机器学习和深度学习模型提供训练数据。LabelMe和LabelImg是两款常用图像标注工具,它们的Windows可执行文件可直接运行,助力用户完成图像对象标注LabelMe由麻省理工学院计算机科学与人工智能实验室开发,是一款开源在线图像注释工具。它支持矩形框、多边形、点和线段等多种图像标注任务,其生成的JSON格式标注数据结构灵活、易于解析,包含图像信息、物体边界框和类别等详细信息,适用于训练目标检测、语义分割等模型。 LabelImg由Tian Qi Chen开发,是Python项目,主要支持XML格式标注文件,这种格式规范,利于在PASCAL VOC等数据集上工作。LabelImg有简单图形用户界面,用户可拖动调整矩形框标注图像物体,并指定类别。其XML文件包含边界框位置、大小和类别标签等信息,可用于训练深度学习模型。 在自动驾驶、无人机导航、人脸识别、图像识别等计算机视觉应用领域,高质量标注数据是模型训练基础。借助这些工具,研究人员和开发者能快速高效地标注大量图像,创建训练数据集,进而用于训练深度神经网络,使模型能理解识别图像特征和物体。 使用LabelMe和LabelImg时,需先下载运行对应.exe文件,打开工具后导入待标注图像,利用工具进行标注操作,如绘制边界框、选择类别等,完成后保存文件,LabelMe生成JSON,LabelImg生成XML。这些标注文件可整合到深度学习框架的数据预处理流程,用于模型训练。 这两个工具适用于学术研究和商业项目,尤其适合大量图像标注任务,无论是物体检测、实例分割还是语义分割模型训练,都能提供高效便捷的标注解决方案。LabelMe的JSON格式在灵活性和可扩展性上占优,LabelImg的XML格式更
<think>我们被要求安装Labelme图像标注工具。根据引用内容,安装Labelme通常需要先安装Anaconda(一个Python发行版),然后使用conda或pip来安装Labelme安装步骤因操作系统而异,主要分为Windows和Ubuntu(Linux)两种。从引用中我们可以总结出以下步骤: 对于Windows系统: 1.下载并安装Anaconda(选择适合的Python版本)。 2.打开AnacondaPrompt(在开始菜单中可以找到)。3.创建一个新的conda环境(可选,但推荐):```condacreate --name=labelmepython=3.6#这里python版本根据自己安装的Anaconda版本选择```4.激活该环境:```activate labelme```5.安装PyQt5(Labelme的依赖):```condainstall pyqt5```或者使用pip:```pip installpyqt5```6.安装labelme:```pipinstall labelme```7.安装完成后,输入以下命令启动labelme:```labelme```对于Ubuntu系统(引用中提供了两种Python版本): -Python2:```sudo apt-get installpython-qt4#安装PyQt4(或者安装PyQt5)sudopip installlabelme``` -Python3:```sudo apt-get installpython3-pyqt5sudopip3install labelme```注意:在Windows系统中,如果遇到网络问题导致安装失败(如超时),可以尝试增加超时时间(如`pip--default-timeout=100install labelme`)或切换网络环境。根据上述引用,我们给出安装步骤: ###安装Labelme图像标注工具####在Windows系统上安装1.**安装Anaconda**如果你还没有安装Anaconda,请先到[Anaconda官网](https://www.anaconda.com/products/individual)下载并安装适合你操作系统的版本。安装时注意选择Python版本(推荐Python3.6或更高版本)。2.**打开Anaconda Prompt**在开始菜单中找到并打开“Anaconda Prompt”。 3. **创建并激活环境(可选但推荐)**为了避免与其他项目环境冲突,建议创建一个独立的环境。在AnacondaPrompt中输入以下命令(以Python3.6为例):```bashconda create--namelabelme python=3.6```然后激活环境:```bashcondaactivate labelme```4.**安装PyQt5**在激活的环境中,输入以下命令安装PyQt5:```bashconda installpyqt5```或者使用pip:```bashpip installpyqt5```5.**安装Labelme**在同一个环境中,使用pip安装Labelme:```bashpip installlabelme``` 6. **启动Labelme**安装完成后,输入以下命令启动Labelme:```bashlabelme```如果出现Labelme的图形界面,则说明安装成功。 ####在Ubuntu系统上安装对于Ubuntu系统(以Python3为例): 1.安装PyQt5:```bashsudo apt-get installpython3-pyqt5```2.安装Labelme:```bashsudo pip3 installlabelme```或者使用`--user`选项安装到用户目录(不需要sudo):```bashpip3install labelme --user```3.启动Labelme:```bashlabelme``` ####常见问题- **网络问题**:如果在安装过程中出现网络超时,可以尝试增加超时时间,例如:```bashpip--default-timeout=100install labelme```或者更换网络环境(如使用手机热点)[^3]。 -**环境变量问题**:在Ubuntu中,如果安装后无法运行`labelme`命令,可能是因为用户安装的脚本目录不在PATH中,可以尝试将`~/.local/bin`添加到PATH中。###相关问题1.如何验证Labelme是否安装成功?2.使用Labelme进行图像标注的基本步骤是什么?3.Labelme支持哪些类型的图像标注?4.如何将Labelme标注的数据转换成其他格式(如COCO)?</think>### 安装Labelme图像标注工具指南 #### 一、Windows系统安装步骤 1. **安装Anaconda** - 下载对应Python版本的Anaconda安装包(推荐Python 3.6+) - 运行安装程序,勾选"Add Anaconda to PATH"选项 2. **创建虚拟环境** 打开`Anaconda Prompt`,执行: ```bash conda create --name=labelme python=3.6 # 创建环境 conda activate labelme # 激活环境 ``` 3. **安装依赖库** ```bash conda install pyqt5 # 安装界面依赖 pip install labelme # 安装Labelme核心 ``` 4. **验证安装** ```bash labelme # 若弹出标注界面即成功 ``` [^2][^4] #### 二、Ubuntu系统安装步骤 ```bash # Python3环境 sudo apt-get install python3-pyqt5 # 安装Qt界面库 sudo pip3 install labelme # 安装Labelme # 验证安装 labelme ``` [^1] #### 三、常见问题解决 1. **网络超时** 安装时添加超时参数: ```bash pip --default-timeout=100 install labelme ``` [^3] 2. **环境冲突** 建议使用虚拟环境(conda或venv)隔离安装 3. **启动失败** 检查PyQt5是否安装成功: ```bash python -c "from PyQt5 import QtWidgets; print('Success')" ``` #### 四、首次使用示例 1. 终端输入`labelme`启动 2. 点击`Open`加载图像 3. 使用多边形工具(Polygon)标注目标 4. 保存生成JSON标注文件 ![标注界面示意图](https://example.com/labelme-ui.png) *标注界面示意图(图源:Labelme官方文档)* > **注意**:标注前建议创建专门的项目目录存放图像和标注文件,避免文件路径混乱[^3]。 ### 相关问题 1. Labelme标注的JSON文件如何转换为COCO数据集格式? 2. 使用Labelme进行语义分割标注时有哪些最佳实践? 3. 如何批量处理Labelme生成的JSON标注文件? 4. Labelme与其他标注工具(如LabelImg)相比有哪些优势? 5. 在无GUI界面的服务器上如何使用Labelme进行标注
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值