labelme语义分割json转mask
时间: 2025-07-04 13:29:35 浏览: 14
### 将 Labelme JSON 文件转换为 Mask 格式的 Python 实现
以下是实现 `Labelme` 的 `.json` 文件到语义分割训练所需 `Mask` 标签的 Python 工具代码。此代码能够读取由 `Labelme` 生成的标注文件并将其转换为像素级的二值掩码或多类掩码。
#### 功能描述
该脚本支持以下特性:
- 支持单类别和多类别的语义分割任务。
- 自动生成对应的彩色掩码图像以便可视化验证。
- 输出路径可配置,便于集成到更大的数据预处理流程中。
```python
import os
import cv2
import numpy as np
from labelme import utils
import json
import imgviz
def json_to_dataset(json_file, out_jpgs_path, out_mask_path):
"""
Convert a single Labelme .json file into an image and its corresponding mask.
Parameters:
json_file (str): Path to the input .json file generated by Labelme.
out_jpgs_path (str): Directory where original images will be saved.
out_mask_path (str): Directory where masks will be saved.
Returns:
None
"""
# Load data from .json file
with open(json_file) as f:
data = json.load(f)
# Extract shapes and image information
imageData = data.get("imageData", None)
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)
# Create label masks based on annotations
lbl, _ = utils.shapes_to_label(
img.shape,
data['shapes'],
{shape['label']: i for i, shape in enumerate(data['shapes'], start=1)}
)
# Save original image
jpg_filename = os.path.splitext(os.path.basename(json_file))[0] + ".jpg"
jpg_filepath = os.path.join(out_jpgs_path, jpg_filename)
cv2.imwrite(jpg_filepath, img[:, :, ::-1]) # RGB -> BGR conversion for OpenCV
# Generate colored mask visualization
mask_colored = imgviz.label2rgb(lbl, imgviz.asgray(img), label_names=None, loc="upper_left")
mask_filename = os.path.splitext(os.path.basename(json_file))[0] + "_mask.png"
mask_filepath = os.path.join(out_mask_path, mask_filename)
cv2.imwrite(mask_filepath, mask_colored)
if __name__ == "__main__":
# Example usage
json_dir = "./path/to/json/files/"
output_images_dir = "./output/images/"
output_masks_dir = "./output/masks/"
# Ensure directories exist
os.makedirs(output_images_dir, exist_ok=True)
os.makedirs(output_masks_dir, exist_ok=True)
# Process all .json files in directory
for filename in os.listdir(json_dir):
if filename.endswith(".json"):
json_to_dataset(os.path.join(json_dir, filename), output_images_dir, output_masks_dir)
```
#### 关键说明
1. **输入参数解释**
- `json_file`: 输入的 `.json` 文件路径,通常是由 `Labelme` 导出的标注文件。
- `out_jpgs_path`: 原始图片保存目录。
- `out_mask_path`: 掩码图片保存目录。
2. **核心逻辑**
- 使用 `utils.shapes_to_label()` 方法将 `Labelme` 中定义的形状(polygon 或 rectangle)解析为逐像素分类标签矩阵。
- 利用 `imgviz.label2rgb()` 函数生成带有颜色编码的掩码图,方便后续检查和调试。
3. **依赖库安装**
如果尚未安装必要的库,请运行以下命令进行安装:
```bash
pip install labelme imgviz opencv-python-headless numpy
```
通过以上方法可以高效地完成从 `Labelme` 注解文件到语义分割训练所需的 `Mask` 数据集的转换过程[^1]。
---
####
阅读全文
相关推荐

















