You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含多segmentation的JSON条目拆分为单segmentation条目?

实现思路及代码示例

核心逻辑步骤

  • 提取原始条目中的公共字段:image_id、iscrowd、bbox、area、category_id,这些字段在拆分后的所有条目中保持不变。
  • 遍历原始的segmentation列表,每一个子数组对应一个独立的新条目。
  • 为每个新条目生成唯一递增的id:以原始条目的id为起始值,第一个新条目沿用原始id,后续每个条目id依次加1。
  • 每个新条目仅保留当前遍历到的单个segmentation子数组,组合公共字段后形成完整的新条目。

Python 代码实现

假设原始数据已处理为合法的Python字典(若为JSON字符串,先用json.loads()解析):

import json

# 原始数据(已修正JSON格式,移除多余尾逗号)
original_item = {
    "id": 2,
    "image_id": 2,
    "segmentation": [
        [913.0, 659.5, 895.0],
        [658.5, 875.0, 652.5, 659.5]
    ],
    "iscrowd": 0,
    "bbox": [4.5, 406.5, 1098.0, 1096.0],
    "area": 579348.0,
    "category_id": 0
}

# 提取公共字段
common_fields = {
    key: original_item[key]
    for key in ["image_id", "iscrowd", "bbox", "area", "category_id"]
}

# 拆分生成新条目
split_items = []
current_id = original_item["id"]
for seg in original_item["segmentation"]:
    new_item = common_fields.copy()
    new_item["id"] = current_id
    new_item["segmentation"] = [seg]
    split_items.append(new_item)
    current_id += 1

# 输出格式化后的结果
print(json.dumps(split_items, indent=4))

结果说明

运行代码后会得到一个包含所有拆分条目的列表,每个条目仅含单个segmentation子数组,id从原始值递增,其余字段与原条目完全一致,结构与你给出的示例匹配。

内容的提问来源于stack exchange,提问作者Deamoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:15:45