当前位置: 首页 > news >正文

告别手动!用Python脚本一键批量转换Labelme标注的JSON文件(附完整代码)

告别手动!用Python脚本一键批量转换Labelme标注的JSON文件(附完整代码)

在计算机视觉项目中,数据标注是模型训练前的关键步骤。Labelme作为一款流行的图像标注工具,生成的JSON文件需要转换为模型可直接读取的图像和掩码格式。当面对数百个标注文件时,手动操作不仅效率低下,还容易出错。本文将带你开发一个开箱即用的批量转换工具,解决实际工程中的痛点问题。

1. 理解Labelme标注文件的结构

Labelme生成的JSON文件包含以下核心信息:

{ "version": "4.5.6", "flags": {}, "shapes": [ { "label": "cat", "points": [[100, 120], [150, 180]], "shape_type": "polygon" } ], "imagePath": "example.jpg", "imageData": "base64编码的图像数据" }

关键字段说明:

  • shapes:包含所有标注对象的标签和坐标信息
  • imageData:Base64编码的原始图像数据
  • imagePath:原始图像相对路径

提示:当imageData字段为空时,脚本会自动根据imagePath加载原图

2. 环境配置与依赖管理

2.1 创建专用Python环境

推荐使用conda创建独立环境:

conda create -n labelme_converter python=3.8 conda activate labelme_converter

2.2 安装指定版本依赖

版本兼容性至关重要,特别是labelmePillow的版本:

包名称推荐版本作用
labelme3.16.2核心标注工具
Pillow8.3.1图像处理
numpy1.21.2数组运算
pyyaml5.4.1配置文件生成

安装命令:

pip install labelme==3.16.2 Pillow==8.3.1 numpy==1.21.2 pyyaml==5.4.1

3. 开发批量转换脚本

3.1 脚本核心功能设计

完整脚本应包含以下功能模块:

  1. 批量文件处理:自动遍历目录下所有JSON文件
  2. 数据解析:提取标注信息和图像数据
  3. 格式转换:生成图像、掩码和可视化标注
  4. 结果组织:按标准结构保存输出文件

3.2 完整实现代码

创建batch_json_to_dataset.py文件:

import argparse import json import os import os.path as osp import warnings import base64 import numpy as np from PIL import Image import yaml from labelme import utils def process_single_json(json_path, output_dir): """处理单个JSON文件""" with open(json_path) as f: data = json.load(f) # 解析图像数据 if data['imageData']: img = utils.img_b64_to_arr(data['imageData']) else: img_path = osp.join(osp.dirname(json_path), data['imagePath']) img = np.array(Image.open(img_path)) # 创建标签映射 label_name_to_value = {'_background_': 0} for shape in data['shapes']: if shape['label'] not in label_name_to_value: label_name_to_value[shape['label']] = len(label_name_to_value) # 生成标签图像 lbl = utils.shapes_to_label( img.shape, data['shapes'], label_name_to_value) # 准备输出目录 base_name = osp.splitext(osp.basename(json_path))[0] os.makedirs(output_dir, exist_ok=True) # 保存各种输出 Image.fromarray(img).save(osp.join(output_dir, f'{base_name}_img.png')) utils.lblsave(osp.join(output_dir, f'{base_name}_label.png'), lbl) # 保存标签名称 with open(osp.join(output_dir, 'label_names.txt'), 'w') as f: f.write('\n'.join(label_name_to_value.keys())) def batch_process(json_dir, output_root): """批量处理目录下的所有JSON文件""" json_files = [f for f in os.listdir(json_dir) if f.endswith('.json')] for json_file in json_files: json_path = osp.join(json_dir, json_file) output_dir = osp.join(output_root, osp.splitext(json_file)[0]) print(f"Processing {json_file}...") process_single_json(json_path, output_dir) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('json_dir', help='包含JSON文件的目录') parser.add_argument('-o', '--output', default='output', help='输出目录') args = parser.parse_args() os.makedirs(args.output, exist_ok=True) batch_process(args.json_dir, args.output)

4. 实战应用与问题排查

4.1 典型使用场景

假设标注文件存放在~/data/annotations,运行命令:

python batch_json_to_dataset.py ~/data/annotations -o ~/data/dataset

生成的文件结构如下:

dataset/ ├── image1/ │ ├── image1_img.png │ ├── image1_label.png │ └── label_names.txt ├── image2/ │ ├── image2_img.png │ ├── image2_label.png │ └── label_names.txt

4.2 常见问题解决方案

问题1AttributeError: module 'labelme.utils' has no attribute 'draw_label'

解决方法

pip uninstall labelme pip install labelme==3.16.2

问题2:生成的掩码图像全黑

检查步骤

  1. 确认标注时是否设置了非背景标签
  2. 检查JSON文件中shapes数组是否非空
  3. 验证label_name_to_value字典是否正确生成

问题3:内存不足处理大图

优化方案

# 在process_single_json函数中添加 del img # 及时释放内存 del lbl

5. 高级功能扩展

5.1 支持多类别语义分割

修改标签生成逻辑,为不同类别分配固定ID:

CLASS_MAPPING = { 'person': 1, 'car': 2, 'road': 3 } def shapes_to_label_custom(shape, img_shape, class_mapping): lbl = np.zeros(img_shape[:2], dtype=np.uint8) for shape in shapes: label = class_mapping.get(shape['label'], 0) utils.draw_shape(lbl, shape, label) return lbl

5.2 添加进度显示

使用tqdm显示处理进度:

from tqdm import tqdm def batch_process(json_dir, output_root): json_files = [f for f in os.listdir(json_dir) if f.endswith('.json')] for json_file in tqdm(json_files, desc='Processing'): json_path = osp.join(json_dir, json_file) output_dir = osp.join(output_root, osp.splitext(json_file)[0]) process_single_json(json_path, output_dir)

5.3 并行处理加速

利用多进程提高处理速度:

from multiprocessing import Pool def parallel_process(json_dir, output_root, workers=4): json_files = [f for f in os.listdir(json_dir) if f.endswith('.json')] with Pool(workers) as p: args = [(osp.join(json_dir, f), osp.join(output_root, osp.splitext(f)[0])) for f in json_files] p.starmap(process_single_json, args)

在实际项目中,这个脚本帮助我将标注数据处理时间从8小时缩短到15分钟。特别是在处理2000+张街景图像时,稳定的批量处理能力显著提升了项目迭代速度。

http://www.jsqmd.com/news/502691/

相关文章:

  • 销售类书籍汗牛充栋,只有这些称得上是必读!
  • STM32Modbus RTU包:主从机源码,支持多寄存器写入读取,代码注释详细可读
  • 终极游戏加速指南:如何使用OpenSpeedy开源工具提升游戏体验
  • 复试
  • 打破计量孤岛,告别能耗盲区,实现能耗可视可控
  • 这五本人才管理书籍适合不同阶段的管理者和HR读
  • ChatGPT PC端下载与安装指南:从零开始到高效使用
  • ControlNet-v1-1 FP16终极指南:从零到精通的完整解决方案
  • 工程实录:如何在多模型混用架构中解决“接口碎片化”难题——DMXAPI
  • VXE-Table 中自定义图标的三种实现方式与最佳实践
  • Qt文件操作实战:QFile读写本地文件的5种常见场景与代码示例
  • 关于 Redhat - 9 下 postfix 的安装配置 与 mail 命令发送邮件
  • MapLibre GL Native:构建跨平台移动地图应用的开源利器
  • OpenUAV:如何用12k轨迹数据集破解无人机‘听懂人话’导航的三大现实难题
  • 智驾端到端模型Flow Matching与Diffusion选型及机器人场景差异解析
  • AI普及74%,仍超6成团队陷延期?|2025年 IT行业项目管理全景报告
  • 前端图表革命:Mermaid 与 Markdown 的完美结合
  • 云主机安全加固:从系统、网络到应用的零信任配置
  • PyCharm高效配置Gitee全攻略
  • 重塑丰盈,遇见更美:河北美胸品牌“卓养女王”的科学养护之道 - 中媒介
  • DAMO-YOLO在农业领域的创新应用:作物病虫害检测
  • Mirage Flow大模型Java开发指南:SpringBoot集成实战
  • 基于分布式电源与电动汽车接入的配电网潮流计算方法——考虑风光电动汽车出力时序特性并基于IEEE...
  • DeerFlow智能招聘系统:基于NLP的简历筛选应用
  • Vue2项目实战:5分钟搞定天地图API集成(附完整代码)
  • 这家全球领先的氨糖生物肥制造商,正在用生物科技重新定义绿色农业 - 中媒介
  • Python 基础教学
  • 3个高效策略深度解析:VS Code R扩展在数据科学工作流中的核心价值
  • 小白也能上手的GTE文本向量:中文文本分类与问答系统快速搭建
  • Git Credential anager 账号和密码是什么