深度学习数据集分割json文件转目标检测txt文件

本文介绍了一种方法,用于将包含多边形标注的JSON文件转换为文本文件,以便于目标检测任务中使用矩形框形式的标注。作者通过Python脚本获取每个多边形的类别、坐标点信息并计算出框选区域,然后保存为txt文件。
摘要由CSDN通过智能技术生成

平时在网上找数据集或者师兄师姐给到的数据集有部分是做分割的数据集,标注是以矩形框的形式进行标注的,而我们现在常用的目标检测所使用的数据集一般是按照矩形框进行标注的,这里给出一种json转txt的方法(需要json转png+txt私聊),整体思路大概是获取多边形标注框的所有坐标点的最大最小坐标,达到框选整个目标的需求。

效果如可以看下图,所有的类别和标注框都正常,右图为json标注效果,左图为转换后txt效果

代码如下

import os
import json

# 定义JSON文件夹路径和输出txt文件夹路径
json_folder = r'f:\111' #修改为json文件夹
output_txt_folder = r'f:\333' #修改为输出txt文件夹

# 类别列表
category_list = ["Tailings Ponds", "Bare Land", "Water Reservoir"] #这里需要修改列出所有标签

# 列出文件夹中的所有JSON文件
json_files = [f for f in os.listdir(json_folder) if f.endswith('.json')]

for json_file in json_files:
    with open(os.path.join(json_folder, json_file), 'r') as f:
        data = json.load(f)

    output_txt_path = os.path.join(output_txt_folder, json_file.replace('.json', '.txt'))

    with open(output_txt_path, 'w') as txt_file:

        for shape in data['shapes']:
            category = category_list.index(shape['label'])
            points = shape['points']
            x_values = [point[0] for point in points]
            y_values = [point[1] for point in points]
            x_min = min(x_values)
            x_max = max(x_values)
            y_min = min(y_values)
            y_max = max(y_values)

            x_center = max(0, (x_min + x_max) / 2.0 / data['imageWidth'])
            y_center = max(0, (y_min + y_max) / 2.0 / data['imageHeight'])
            width = max(0, (x_max - x_min) / data['imageWidth'])
            height = max(0, (y_max - y_min) / data['imageHeight'])
            txt_file.write(f"{category} {x_center} {y_center} {width} {height}\n")

    print(f"Saved normalized coordinates to: {output_txt_path}")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值