语义分割json转mask批量转换代码
时间: 2025-03-28 08:11:36 浏览: 68
### 批量转换语义分割 JSON 文件到 MASK 格式的代码
为了实现将语义分割的 JSON 文件批量转换为 MASK 格式的功能,可以编写一个 Python 脚本。该脚本会读取 JSON 文件中的标注数据,并将其转化为对应的二进制掩码图像(MASK)。以下是完整的解决方案:
#### 解决方案描述
1. **输入**: 假设 JSON 文件遵循 COCO 数据集的标准格式,其中包含 `annotations` 和 `categories` 字段。
2. **输出**: 对于每张图片生成一张或多张 MASK 图像,具体取决于类别数量。
以下是一个基于上述假设的代码示例[^3]:
```python
import os
import json
from PIL import Image
import numpy as np
def convert_json_to_mask(json_file_path, output_dir):
"""
将单个 JSON 文件转换为 MASK 格式。
:param json_file_path: 输入的 JSON 文件路径
:param output_dir: 输出 MASK 的目录
"""
with open(json_file_path, 'r') as f:
data = json.load(f)
image_info = {img['id']: img for img in data['images']}
category_info = {cat['id']: cat['name'] for cat in data['categories']}
for annotation in data['annotations']:
image_id = annotation['image_id']
category_id = annotation['category_id']
# 获取对应图片的信息
image_name = image_info[image_id]['file_name'].split('.')[0]
height = image_info[image_id]['height']
width = image_info[image_id]['width']
# 创建空白掩码
mask = np.zeros((height, width), dtype=np.uint8)
# 处理多边形坐标并填充掩码
polygons = annotation.get('segmentation', [])
if not isinstance(polygons[0], list): # 如果只有一个对象,则解包
polygons = [polygons]
for polygon in polygons:
flattened_polygon = []
for i in range(0, len(polygon), 2):
x = int(polygon[i])
y = int(polygon[i + 1])
flattened_polygon.extend([x, y])
# 使用 PIL 绘制多边形区域
img = Image.new('L', (width, height), 0)
ImageDraw.Draw(img).polygon(flattened_polygon, outline=1, fill=1)
mask += np.array(img)
# 存储掩码文件
category_name = category_info[category_id].replace(' ', '_')
mask_filename = f"{image_name}_{category_name}.png"
mask_filepath = os.path.join(output_dir, mask_filename)
Image.fromarray(mask * 255).save(mask_filepath)
def batch_convert(directory_with_jsons, output_directory):
"""
批量处理指定目录下的所有 JSON 文件。
:param directory_with_jsons: 包含多个 JSON 文件的目录
:param output_directory: 输出 MASK 的总目录
"""
if not os.path.exists(output_directory):
os.makedirs(output_directory)
for filename in os.listdir(directory_with_jsons):
if filename.endswith('.json'):
json_file_path = os.path.join(directory_with_jsons, filename)
sub_output_dir = os.path.join(output_directory, filename.split('.')[0])
if not os.path.exists(sub_output_dir):
os.makedirs(sub_output_dir)
convert_json_to_mask(json_file_path, sub_output_dir)
if __name__ == "__main__":
input_directory = './input/json_files' # 替换为实际的 JSON 文件所在目录
output_directory = './output/masks' # 替换为目标存储 MASK 的目录
batch_convert(input_directory, output_directory)
```
此代码实现了从 JSON 到 MASK 的批量转换功能。它通过解析 JSON 中的 `segmentation` 字段来提取多边形信息,并利用 Pillow 库绘制这些多边形作为掩码。
---
### 关键技术点说明
- **JSON 结构解析**:COCO 数据集中通常有 `annotations`, `images`, 和 `categories` 等字段。`annotations` 下的 `segmentation` 提供了目标物体的边界框或轮廓线信息[^3]。
- **Pillow 库的应用**:用于高效地创建和保存掩码图像。
- **批量化操作**:支持一次性处理整个目录下的所有 JSON 文件,自动按类别分类保存掩码。
---
阅读全文
相关推荐

















