按比例划分coco数据集,保存对应的json文件

一、pandas是什么?

经常要对数据集进行按比例划分,因为只有一个完整的coco数据文件,所以编写了这个脚本,可以按比例划分并保存成两个json文件。

二、完整代码

import os
import json
import shutil


def split_and_save_json(input_file, train_output_file, test_output_file, split_ratio=0.8):
    with open(input_file, 'r') as file:
        data = json.load(file)

    total_images = len(data['images'])
    split_index = int(total_images * split_ratio)

    train_data = {
        "info": data["info"],
        "images": data['images'][:split_index],
        "annotations": [ann for ann in data['annotations'] if ann['image_id'] <= data['images'][split_index - 1]['id']],
        "licenses": data["licenses"],
        "categories": data["categories"]
    }

    test_data = {
        "info": data["info"],
        "images": data['images'][split_index:],
        "annotations": [ann for ann in data['annotations'] if ann['image_id'] > data['images'][split_index - 1]['id']],
        "licenses": data["licenses"],
        "categories": data["categories"]
    }

    with open(train_output_file, 'w') as train_outfile:
        json.dump(train_data, train_outfile)

    with open(test_output_file, 'w') as test_outfile:
        json.dump(test_data, test_outfile)

    print(f"已将训练数据保存至 {train_output_file},并将测试数据保存至 {test_output_file}。")

# 调用新的函数,按照8:2划分数据并保存两个json文件
input_coco_file_path = '/codeyard/yolov5_6.0/data_MS_train_val/coco_train.json'
train_output_path = '/codeyard/yolov5_6.0/data_MS_train_val/coco_train.json'
test_output_path = '/codeyard/yolov5_6.0/data_MS_train_val/coco_test.json'
split_ratio = 0.8
split_and_save_json(input_coco_file_path, train_output_path, test_output_path, split_ratio)

首先,导入了 json 模块,该模块用于读取和写入 JSON 数据。

然后,定义了一个名为 split_and_save_json 的函数,它接受四个参数:input_file(输入文件路径)、train_output_file(训练集输出文件路径)、test_output_file(测试集输出文件路径)和可选的 split_ratio(分割比例,默认为 0.8)。

在函数内部,使用 open 函数打开输入文件,并使用 json.load 函数将文件内容加载为 Python 字典形式的数据。

获取图像总数和分割索引,分割索引是根据给定的分割比例计算得出的。

创建 train_data 字典,包含了训练集的信息,如数据集信息、前一部分图像、相应的注释、许可证和类别信息。

创建 test_data 字典,包含了测试集的信息,如数据集信息、后一部分图像、相应的注释、许可证和类别信息。

使用 open 函数分别打开训练集输出文件和测试集输出文件,并使用 json.dump 函数将相应的数据写入文件中。

最后,打印出保存的训练数据和测试数据的文件路径。

### 将COCO数据集JSON文件转换为TXT文件 为了实现这一目的,Python提供了丰富的库支持解析和处理JSON文件。下面是一个具体的例子,展示了如何编写一个简单的Python脚本来完成这个任务。 #### 导入必要的库 首先需要导入`json`模块用于加载JSON文件以及标准输入输出操作所需的库: ```python import json ``` #### 加载并解析JSON文件 接着定义函数来打开指定路径下的JSON文件,并从中提取所需的信息(这里假设是从标注文件中获取图像ID作为基础信息)。这一步骤利用到了Python内置的`with open()`语句安全地读取文件内容[^1]。 ```python def load_json(file_path): with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) return data['images'] # 假设只关心'images'字段内的信息 ``` #### 提取消息到列表 随后遍历上述得到的对象数组,收集所有感兴趣的条目至一个新的列表里。对于本案例而言,则是指向每一张图片对应的唯一标识符(ID)或者是其文件名去除扩展部分后的字符串表示形式[^3]。 ```python def extract_info(images_data): info_list = [] for image in images_data: file_name_without_extension = '.'.join(image["file_name"].split('.')[:-1]) info_list.append(file_name_without_extension) return info_list ``` #### 输出到TXT文件 最后通过循环访问之前准备好的列表项,依次写入新的文本文件当中去。注意设置合适的编码方式以确保字符能够被正确保存下来。 ```python def write_to_txt(info_list, output_file): with open(output_file, 'w', encoding='utf-8') as txt_f: for item in info_list: txt_f.write("%s\n" % item) if __name__ == "__main__": coco_json_path = './annotations/instances_train2017.json' result_txt_path = './output/train.txt' images_data = load_json(coco_json_path) extracted_infos = extract_info(images_data) write_to_txt(extracted_infos, result_txt_path) ``` 此段代码实现了从给定的COCO JSON格式的数据集中抽取特定信息,并将其记录在一个`.txt`文档内。这种方式不仅适用于训练集同样也适合于测试集等其他子集合的操作需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张Tt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值