目标检测yolov8数据集txt转换、Labelme标注的json解析

一、计算所有json文件里的目标类别及对应数量

import os
import json
from collections import Counter

# 指定包含所有JSON文件的目录路径
json_dir = 'gs_road_json'

# 初始化一个Counter对象来统计标签类型
label_counter = Counter()
# 遍历目录中的所有JSON文件
for filename in os.listdir(json_dir):
    if filename.endswith('.json'):
        filepath = os.path.join(json_dir, filename)
        # 读取JSON文件
        with open(filepath, 'r') as f:
            data = json.load(f)

        # 提取并统计标签
        objects = data.get('outputs', {}).get('object', [])
        for obj in objects:
            label = obj.get('name')
            if label:
                label_counter[label] += 1

# 打印每种标签的数量
for label, count in label_counter.items():
    print(f'Label: {label}, Count: {count}')

二、Labelme标注的json转成yolov8目标检测数据集txt格式

def convert(size, box):
    """
    convert [xmin, xmax, ymin, ymax] to [x_centre, y_centre, w, h]
    """
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)

def LabelMeData2YOLOData():
    SaveDataDir = ""
    # 图像img的路径
    SaveDataDir2 =""
    # txt保存路径

    src_class_names_lib = {'类别':1} 

    json_pths = glob(SaveDataDir + "*.json")

   
    for i in tqdm(range(len(json_pths))):
        json_path = json_pths[i]
        img_path =  SaveDataDir + os.path.basename(json_path).replace(".json", ".jpg")

        txt_file_name = os.path.basename(json_path).replace('.json' ,'.txt')
    
        save_txt_path = SaveDataDir2  + txt_file_name

        if os.path.exists(json_path) and os.path.exists(img_path):
            txt_out_file = open(save_txt_path, "w")

            img = cv2.imread(img_path)
            h, w = img.shape[:2]

            json_file = open(json_path, "r")
            json_data = json.load(json_file)
            
            label_infos = json_data["shapes"]
            for label_info in label_infos:
                label = label_info["label"]
                points = label_info["points"]
                shape_type = label_info["shape_type"]
                if len(points) >= 3:
                    points = np.array(points)
                    print(points.shape)
                    xmin, xmax = max(0, min(np.unique(points[:, 0]))), min(w, max(np.unique(points[:, 0])))
                    ymin, ymax = max(0, min(np.unique(points[:, 1]))), min(h, max(np.unique(points[:, 1])))
                    print("++++", ymin, ymax)
                elif len(points) == 2:
                    x1, y1 = points[0]
                    x2, y2 = points[1]
                    xmin, xmax = min(x1, x2), max(x1, x2)
                    ymin, ymax = min(y1, y2), max(y1, y2)
                else:
                    continue
                    
                bbox = [xmin, xmax, ymin, ymax]
                bbox_ = convert((w, h), bbox)
                if label in src_class_names_lib.keys():
                    # cls_id = class_names.index(label)
                    cls_id = src_class_names_lib[label]
                    txt_out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bbox_]) + '\n')
                else:
                    print(json_path, ' :',label)

            txt_out_file.close()
            json_file.close()

三、yolov8预测后的txt文件转成labelme的json格式

def convert_txt_to_labelme_json(txt_path, image_path, output_dir, image_fmt='.jpg'):
    # txt 转labelme json
    # 将yolo的txt转labelme json
    txts = glob.glob(os.path.join(txt_path, "*.txt"))
    for txt in txts:
        labelme_json = {
            'version': '5.1.1',
            'flags': {},
            'shapes': [],
            'imagePath': None,
            'imageData': None,
            'imageHeight': None,
            'imageWidth': None,
        }
        txt_name = os.path.basename(txt)
        image_name = txt_name.split(".")[0] + image_fmt
        labelme_json['imagePath'] = image_name
        image_name = os.path.join(image_path, image_name)
        if not os.path.exists(image_name):
            raise Exception('txt 文件={},找不到对应的图像={}'.format(txt, image_name))
        image = cv2.imdecode(np.fromfile(image_name, dtype=np.uint8), cv2.IMREAD_COLOR)
        h, w = image.shape[:2]
        labelme_json['imageHeight'] = h
        labelme_json['imageWidth'] = w
        with open(txt, 'r') as t:
            lines = t.readlines()
            for line in lines:
                content = line.split(' ')
                label = content[0]

                label2 = label_id[int(label)]

                object_width = float(content[3])
                object_height = float(content[4])
                top_left_x = (float(content[1]) - object_width / 2) * w
                top_left_y = (float(content[2]) - object_height / 2) * h
                bottom_right_x = (float(content[1]) + object_width / 2) * w
                bottom_right_y = (float(content[2]) + object_height / 2) * h

                try:
                    shape = {
                            'label': str(label2),
                            'score': float(content[5]),
                            'group_id': None,
                            'shape_type': 'rectangle',
                            'flags': {},
                            'points': [
                                [float(top_left_x), float(top_left_y)],
                                [float(bottom_right_x), float(bottom_right_y)]
                            ]
                        }
                except Exception as e:
                        # print(e)
                    shape = {
                            'label': str(label2),
                            'score': float(0.99),
                            'group_id': None,
                            'shape_type': 'rectangle',
                            'flags': {},
                            'points': [
                                [float(top_left_x), float(top_left_y)],
                                [float(bottom_right_x), float(bottom_right_y)]
                            ]
                        }
                    labelme_json['shapes'].append(shape)
            json_name = txt_name.split('.')[0] + '.json'
            json_name_path = os.path.join(output_dir, json_name)
            fd = open(json_name_path, 'w')
            json.dump(labelme_json, fd, indent=4)
            fd.close()
            print("save json={}".format(json_name_path))

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值