目标检测标签格式转化——JSON格式转YOLO格式

说明

在目标检测数据集处理中,我们经常会遇到标签之间不同格式的转化,以下介绍JSON格式的标签转YOLO格式。

格式

json格式标签是通过labelme软件进行标注,实现转为txt格式,即保存归一化后的中心点坐标和归一化后检测框长和宽。

代码

import os
import json

# labelme标注的json标签文件目录和保存生成的txt标签的文件夹
dir_json = r'F:\文件B_数集文件\B_葡萄数据\07-230612葡萄\00-标注文件/'
dir_txt = r'F:\文件B_数集文件\B_葡萄数据\07-230612葡萄\00-标注文件/txt/' # txt存储目录
os.mkdir(dir_txt)

def json2txt(path_json, path_txt):  # 可修改生成格式
    with open(path_json, 'r',encoding='utf-8') as path_json:
        jsonx = json.load(path_json)
        with open(path_txt, 'w+') as ftxt:
            shapes = jsonx['shapes']
            #获取图片长和宽
            width=jsonx['imageWidth']
            height=jsonx['imageHeight']
            for shape in shapes:
               #获取矩形框两个角点坐标
                x1 = shape['points'][0][0]
                y1 = shape['points'][0][1]
                x2 = shape['points'][1][0]
                y2 = shape['points'][1][1]
                if shape['label']=='grape': # 对应类别转为数字代号
                    cat=0
                else:
                    cat=1
                #对结果进行归一化
                dw = 1. / width
                dh = 1. / height
                x=dw *(x1+x2)/2
                y=dh *(y1+y2)/2
                w=dw *abs(x2-x1)
                h = dh * abs(y2 - y1)
                yolo = f"{cat} {x} {y} {w} {h} \n"
                ftxt.writelines(yolo)

list_json = os.listdir(dir_json)
for cnt, json_name in enumerate(list_json):
    if os.path.splitext(json_name)[-1] == ".json":
        path_json = dir_json + json_name
        path_txt = dir_txt + json_name.replace('.json', '.txt')
        json2txt(path_json, path_txt)

txt标签可视化

import cv2
import numpy as np

# 定义可视化函数
def visualize(image_path, label_path, class_names):
    # 读取图片
    image = cv2.imread(image_path)

    # 获取图片的大小
    height, width, _ = image.shape

    # 读取标签文件
    with open(label_path, "r") as f:
        lines = f.readlines()

    # 遍历每个标签
    for line in lines:
        # 解析标签
        class_id, x, y, w, h = map(float, line.split())
        class_name = class_names[int(class_id)]

        # 计算 bounding box 的坐标
        left = int((x - w / 2) * width)
        top = int((y - h / 2) * height)
        right = int((x + w / 2) * width)
        bottom = int((y + h / 2) * height)

        # 绘制 bounding box
        cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)

        # 绘制类别名称
        text_size, _ = cv2.getTextSize(class_name, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2)
        cv2.putText(image, class_name, (left, top - text_size[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    # 显示图片
    cv2.imshow("visualization", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# 调用函数,可视化 YOLO 标签(请替换为你的图片路径、标签路径和类别名称列表)
visualize(r"F:\文件B_数集文件\B_葡萄数据\07-230612葡萄\01-标注文件六月第三周\0620_2_1.png", r"F:\文件B_数集文件\B_葡萄数据\07-230612葡萄\0620_2_1.txt", ["类别1", "类别2", "类别3"])


  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JSON换为YOLO格式标签需要经过以下步骤: 1. 将JSON文件加载到Python中。 2. 对于每个图像,将其宽度和高度读入。 3. 对于每个对象,将其类别ID换为YOLO格式。 4. 计算每个对象的中心点坐标和宽度高度。 5. 将所有对象的YOLO格式标签写入一个文本文件。 下面是一个示例Python代码来实现这个换: ``` import json # 加载JSON文件 with open('annotations.json', 'r') as f: data = json.load(f) # 获取图像宽度和高度 width, height = data['imageWidth'], data['imageHeight'] # 换每个对象的类别ID为YOLO格式 class_map = {'cat': 0, 'dog': 1} # 假设类别ID为0和1 yolo_labels = [] for obj in data['annotations']: class_id = class_map[obj['label']] x_min, y_min, x_max, y_max = obj['BoundingBox'] x_center = (x_min + x_max) / 2 / width y_center = (y_min + y_max) / 2 / height w = (x_max - x_min) / width h = (y_max - y_min) / height yolo_labels.append(f"{class_id} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}") # 写入YOLO格式标签文件 with open('labels.txt', 'w') as f: f.write('\n'.join(yolo_labels)) ``` 在这个例子中,我们假设JSON文件包含一个名为`annotations.json`的图像注释文件,其中类别ID为`cat`和`dog`。我们还假设图像的宽度和高度可以在JSON文件中找到,并且我们将YOLO格式标签写入名为`labels.txt`的文件中。最后,我们使用`join()`方法将所有标签连接为单个字符串,并将其写入文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值