极智AI | labelme标注与处理分割数据方法

简介: 大家好,我是极智视界。本文详细介绍了 labelme 标注与处理分割数据的方法。

大家好,我是极智视界。本文详细介绍了 labelme 标注与处理分割数据的方法。

图像分割是计算机视觉任务中常见任务,有实例分割、语义分割、全景分割等之分,在送入分割任务前,需要先对数据做标注处理。大家知道,深度学习中数据的质量对最后的检测效果影响很大,所以数据标注的好坏重要性不言而喻。

下面开始。


1、安装 labelme

不管你是 windows 还是 linux 都可以这么安装:

# 首先安装anaconda,这个这里不多说
# 安装pyqt5
pip install -i https://pypi.douban.com/simple pyqt5
# 安装labelme
pip install -i https://pypi.douban.com/simple labelme
# 打开labelme
./labelme

然后会生成对应图片的json文件,里面会有label和标注的分割掩膜信息,差不多像这样:


2、内置 json to datset

2.1 单图json to dataset

直接执行:

labelme_json_dataset xxx.json

然后会生成:

  • img.png:原图;
  • label.png:掩膜图;
  • label_viz.png:加背景的掩膜图;
  • info.yaml、label_names.txt:标签信息;

2.2 批量json to dataset

找到 cli/json_to_dataset.py 目录,然后:

cd cli
touch json_to_datasetP.py
vim json_to_datasetP.py

加入如下内容:

import argparse
import json
import os
import os.path as osp
import warnings
import PIL.Image
import yaml
from labelme import utils
import base64
def main():
    warnings.warn("This script is aimed to demonstrate how to convert the\n"
                  "JSON file to a single image dataset, and not to handle\n"
                  "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)
    count = os.listdir(json_file) 
    for i in range(0, len(count)):
        path = os.path.join(json_file, count[i])
        if os.path.isfile(path):
            data = json.load(open(path))
            if data['imageData']:
                imageData = data['imageData']
            else:
                imagePath = os.path.join(os.path.dirname(path), 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}
            for shape in data['shapes']:
                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
            # label_values must be dense
            label_values, label_names = [], []
            for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
                label_values.append(lv)
                label_names.append(ln)
            assert label_values == list(range(len(label_values)))
            lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
            captions = ['{}: {}'.format(lv, ln)
                for ln, lv in label_name_to_value.items()]
            lbl_viz = utils.draw_label(lbl, img, captions)
            out_dir = osp.basename(count[i]).replace('.', '_')
            out_dir = osp.join(osp.dirname(count[i]), out_dir)
            if not osp.exists(out_dir):
                os.mkdir(out_dir)
            PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
            #PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.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')
            warnings.warn('info.yaml is being replaced by label_names.txt')
            info = dict(label_names=label_names)
            with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
                yaml.safe_dump(info, f, default_flow_style=False)
            print('Saved to: %s' % out_dir)
if __name__ == '__main__':
    main()

然后批量进行转换:

python path/cli/json_to_datasetP.py path/JPEGImages

若报错:

lbl_viz = utils.draw_label(lbl, img, captions)

AttributeError: module 'labelme.utils' has no attribute 'draw_label'

解决办法:需要更换labelme版本,需要降低labelme 版本到3.16.2 ,方法进入labelme环境中,键入 pip install labelme==3.16.2 就可以自动下载这个版本了,就可以成功了。


3、另一种分割标签制作

若你想生成类似下面这种标签:

原图:

对应标签 (背景为0,圆为1):

此标签为 8 位单通道图像,该方法支持最多 256 种类型。

可以通过以下脚本进行数据集的制作:

import cv2
import numpy as np
import json
import os
#    0     1    2    3   
#  backg  Dog  Cat  Fish     
category_types = ["Background", "Dog", "Cat", "Fish"]
#  获取原始图像尺寸
img = cv2.imread("image.bmp")
h, w = img.shape[:2]
for root,dirs,files in os.walk("data/Annotations"): 
    for file in files: 
        mask = np.zeros([h, w, 1], np.uint8)    # 创建一个大小和原图相同的空白图像
        print(file[:-5])
        jsonPath = "data/Annotations/"
        with open(jsonPath + file, "r") as f:
            label = json.load(f)
        shapes = label["shapes"]
        for shape in shapes:
            category = shape["label"]
            points = shape["points"]
            # 填充
            points_array = np.array(points, dtype=np.int32)
            mask = cv2.fillPoly(mask, [points_array], category_types.index(category))
        imgPath = "data/masks/"
        cv2.imwrite(imgPath + file[:-5] + ".png", mask)

以上是 4 个分类的情况。

到这里就大功告成了。以上分享了 labelme 标注与处理分割数据的方法,希望我的分享能对你的学习有一点帮助。


logo_show.gif

相关文章
|
4月前
|
人工智能 监控 安全
人体姿态[站着、摔倒、坐、深蹲、跑]检测数据集(6000张图片已划分、已标注)| AI训练适用于目标检测
本数据集包含6000张已标注人体姿态图片,覆盖站着、摔倒、坐、深蹲、跑五类动作,按5:1划分训练集与验证集,标注格式兼容YOLO等主流框架,适用于跌倒检测、健身分析、安防监控等AI目标检测任务,开箱即用,助力模型快速训练与部署。
|
4月前
|
人工智能 自然语言处理 物联网
GEO优化方法有哪些?2025企业抢占AI流量必看指南
AI的不断重塑传统的信息入口之际,用户的搜索行为也从单一的百度、抖音的简单的查找答案的模式,逐渐转向了对DeepSeek、豆包、文心一言等一系列的AI对话平台的更加深入的探索和体验。DeepSeek的不断迭代优化同时,目前其月活跃的用户已破1.6亿,全网的AI用户规模也已超过6亿,这无疑为其下一阶段的迅猛发展提供了坚实的基础和广泛的市场空间。
|
4月前
|
人工智能 监控 算法
人群计数、行人检测数据集(9000张图片已划分、已标注) | AI训练适用于目标检测任务
本数据集包含9000张已标注、已划分的行人图像,适用于人群计数与目标检测任务。支持YOLO等主流框架,涵盖街道、商场等多种场景,标注精准,结构清晰,助力AI开发者快速训练高精度模型,应用于智慧安防、人流统计等场景。
人群计数、行人检测数据集(9000张图片已划分、已标注) | AI训练适用于目标检测任务
|
4月前
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
5782 80
|
4月前
|
机器学习/深度学习 人工智能 算法
用于实验室智能识别的目标检测数据集(2500张图片已划分、已标注) | AI训练适用于目标检测任务
本数据集包含2500张已标注实验室设备图片,涵盖空调、灭火器、显示器等10类常见设备,适用于YOLO等目标检测模型训练。数据多样、标注规范,支持智能巡检、设备管理与科研教学,助力AI赋能智慧实验室建设。
用于实验室智能识别的目标检测数据集(2500张图片已划分、已标注) | AI训练适用于目标检测任务
|
4月前
|
机器学习/深度学习 人工智能 监控
面向智慧牧场的牛行为识别数据集(5000张图片已划分、已标注) | AI训练适用于目标检测任务
本数据集包含5000张已标注牛行为图片,涵盖卧、站立、行走三类,适用于YOLO等目标检测模型训练。数据划分清晰,标注规范,场景多样,助力智慧牧场、健康监测与AI科研。
面向智慧牧场的牛行为识别数据集(5000张图片已划分、已标注) | AI训练适用于目标检测任务
|
4月前
|
机器学习/深度学习 人工智能 监控
拔俗AI智能营运分析助手软件系统:企业决策的"数据军师",让经营从"拍脑袋"变"精准导航"
AI智能营运分析助手打破数据孤岛,实时整合ERP、CRM等系统数据,自动生成报表、智能预警与可视化决策建议,助力企业从“经验驱动”迈向“数据驱动”,提升决策效率,降低运营成本,精准把握市场先机。(238字)
176 0
|
4月前
|
传感器 人工智能 监控
拔俗多模态跨尺度大数据AI分析平台:让复杂数据“开口说话”的智能引擎
在数字化时代,多模态跨尺度大数据AI分析平台应运而生,打破数据孤岛,融合图像、文本、视频等多源信息,贯通微观与宏观尺度,实现智能诊断、预测与决策,广泛应用于医疗、制造、金融等领域,推动AI从“看懂”到“会思考”的跃迁。
390 0
|
4月前
|
机器学习/深度学习 人工智能 算法
拔俗AI智能营运分析助手:用技术破解企业“数据焦虑”
AI智能营运分析助手破解企业“数据多却难洞察”难题,通过自动化集成、定制化模型、可视化输出,助力中小企业实现低门槛数据驱动决策,提升营运效率与精准度。
235 0

热门文章

最新文章