Python解析labelme生成的json文件(bbox标注)

本文介绍了一种将JSON格式的图像标注数据转换为YOLO格式的方法,通过Python脚本实现,适用于目标检测任务的数据预处理。具体步骤包括读取JSON文件、解析标注信息、转换坐标到YOLO标准格式,并保存为文本文件。
部署运行你感兴趣的模型镜像

json文件

{
  "version": "3.16.7",
  "imageWidth": 1024,
  "lineColor": [
    0,
    255,
    0,
    128
  ],
  "flags": {},
  "fillColor": [
    255,
    0,
    0,
    128
  ],
  "imageData": "/9j/4AAQSkZJRgABAQAAAQABAAD
  "imagePath": "../airplane/0a7cbe64b71d8026.jpg",
  "shapes": [
    {
      "fill_color": null,
      "line_color": null,
      "flags": {},
      "shape_type": "rectangle",
      "points": [
        [
          639.5679012345679,
          327.8641975308642
        ],
        [
          746.9753086419753,
          403.1728395061728
        ]
      ],
      "label": "cargo"
    }
  ],
  "imageHeight": 678
}

 

解析代码(生成yolo的标签文件)

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import json
import os
           
def convert(img_size, box):
    dw = 1./(img_size[0])
    dh = 1./(img_size[1])
    x = (box[0] + box[2])/2.0 - 1
    y = (box[1] + box[3])/2.0 - 1
    w = box[2] - box[0]
    h = box[3] - box[1]
    x = x*dw
    w = w*dw
    y = y*dh
    h = h*dh
    return (x,y,w,h)


def decode_json(json_floder_path,json_name):

    txt_name = '/home/deepnorth/A_codeTest/txt_label/' + json_name[0:-5] + '.txt'
    txt_file = open(txt_name, 'w')

    json_path = os.path.join(json_floder_path, json_name)
    data = json.load(open(json_path, 'r', encoding='utf-8'))

    img_w = data['imageWidth']
    img_h = data['imageHeight']

    for i in data['shapes']:
        
        if (i['shape_type'] == 'rectangle' and i['label'] == 'cargo'):

            x1 = int(i['points'][0][0])
            y1 = int(i['points'][0][1])
            x2 = int(i['points'][1][0])
            y2 = int(i['points'][1][1])

            bb = (x1,y1,x2,y2)
            bbox = convert((img_w,img_h),bb)
            txt_file.write( '0' + " " + " ".join([str(a) for a in bbox]) + '\n')


    
if __name__ == "__main__":
    
    json_floder_path = '/home/deepnorth/A_codeTest/label'
    json_names = os.listdir(json_floder_path)
    for json_name in json_names:
        decode_json(json_floder_path,json_name)

 

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

当然可以,首先你需要安装必要的库,如`yolov5`, `pycocotools`等。以下是一个简单的Python脚本示例,用于读取LabelMe JSON文件使用YOLOv8模型进行物体检测,然后将检测结果添加到原始JSON中: ```python import json from PIL import Image import requests from io import BytesIO from pycocotools.coco import COCO from yolov5.yolov5 import YOLOv5 # 首先安装YOLOv5(如果还没有安装) !pip install -qr https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt # 初始化YOLOv5模型 model = YOLOv5('yolov8') # 指定YOLOv8模型路径,例如'yolov8.pt' def detect_labels_from_json(json_path): with open(json_path) as f: data = json.load(f) annotations = [] for img in data['images']: img_path = img['file_name'] # 下载图片 response = requests.get(img_path) img_data = BytesIO(response.content) image = Image.open(img_data).convert('RGB') # 进行预测 results = model.detect(image=image) # 将预测结果转换为LabelMe格式的注释 bboxes = [r['bbox'] + [img['width'], img['height']] for r in results] labels = [r['class'] for r in results] # 创建新的annots对象 annots = [{'image_id': img['id'], 'bbox': bbox.tolist(), 'category_id': label} for bbox, label in zip(bboxes, labels)] # 添加到原有数据中 data['annotations'].extend(annots) # 保存更新后的JSON文件 new_json_path = "annotated_" + json_path with open(new_json_path, 'w') as f: json.dump(data, f, indent=2) print(f"Annotations saved to {new_json_path}") # 替换为你实际的LabelMe JSON文件路径 json_file = 'path_to_your_labelme_json.json' detect_labels_from_json(json_file)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值