txt转coco数据集

python txt转coco数据集代码

在这里插入代码片
```"""
YOLO 格式的数据集转化为 COCO 格式的数据集
--root_dir 输入根路径
--save_path 保存文件的名字(没有random_split时使用)
--random_split 有则会随机划分数据集,然后再分别保存为3个文件。
--split_by_file 按照 ./train.txt ./val.txt ./test.txt 来对数据集进行划分。
"""

import os
import cv2
import json
from tqdm import tqdm
from sklearn.model_selection import train_test_split
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--root_dir', default='./data', type=str,
                    help="root path of images and labels, include ./images and ./labels and classes.txt")
parser.add_argument('--save_path', type=str, default='./train.json',
                    help="if not split the dataset, give a path to a json file")
parser.add_argument('--random_split', action='store_true', help="random split the dataset, default ratio is 8:1:1")
parser.add_argument('--split_by_file', action='store_true',
                    help="define how to split the dataset, include ./train.txt ./val.txt ./test.txt ")

arg = parser.parse_args()


def train_test_val_split_random(img_paths, ratio_train=0.8, ratio_test=0.1, ratio_val=0.1):
    # 这里可以修改数据集划分的比例。
    assert int(ratio_train + ratio_test + ratio_val) == 1
    train_img, middle_img =
### 将YOLO格式数据集换为COCO格式 #### 数据结构概述 YOLO格式的数据集中,标签文件(.txt)与图像文件(.jpg)一一对应并分别存放在各自的子目录下。而COCO格式则采用JSON文件来存储所有的标注信息以及图片元数据。 #### 换过程详解 为了实现从YOLO到COCO格式的换,需执行如下操作: 创建一个新的Python脚本用于处理此任务。该脚本会读取所有`.txt`文件中的边界框坐标,并将其化为适合写入JSON文档的形式。对于每张图片,在最终生成的大规模JSON对象里都会有一个条目描述其宽度、高度和其他属性;同时也会有相应的注解记录物体的位置和类别ID[^2]。 编写具体的解析逻辑时需要注意YOLO格式下的归一化坐标系——即位置参数是以相对整个图像尺寸的比例给出而不是绝对像素值。因此在保存至COCO JSON之前要先反向计算回实际大小。 ```python import json from pathlib import Path def yolo_to_coco(yolo_dir, coco_json_path): images = [] annotations = [] categories = [{"id": 1, "name": 'object'}] # 假设只有一个类名为'object' image_id = 0 annotation_id = 0 for txt_file in (yolo_dir / 'labels').glob('**/*.txt'): img_filename = str(txt_file).replace('/labels/', '/images/').rsplit('.', 1)[0] + '.jpg' with open(img_filename, 'rb') as f: from PIL import Image im = Image.open(f) width, height = im.size images.append({ "file_name": Path(img_filename).name, "height": height, "width": width, "id": image_id }) with open(str(txt_file), 'r') as file: lines = file.readlines() for line in lines: parts = list(map(float, line.strip().split())) category_id = int(parts[0]) + 1 # 类别索引调整 center_x = float(parts[1]) center_y = float(parts[2]) bbox_width = float(parts[3]) bbox_height = float(parts[4]) x_min = max((center_x - bbox_width / 2.) * width, 0.) y_min = max((center_y - bbox_height / 2.) * height, 0.) converted_bbox = [ round(x_min), round(y_min), min(round(bbox_width * width), width - x_min), min(round(bbox_height * height), height - y_min) ] annotations.append({ "area": converted_bbox[2]*converted_bbox[3], "bbox": converted_bbox, "category_id": category_id, "id": annotation_id, "image_id": image_id, "iscrowd": 0, "segmentation": [[x_min, y_min, x_min + converted_bbox[2], y_min, x_min + converted_bbox[2], y_min + converted_bbox[3], x_min, y_min + converted_bbox[3]]] }) annotation_id += 1 image_id += 1 data = { "info": {}, "licenses": [], "categories": categories, "images": images, "annotations": annotations } with open(coco_json_path, 'w', encoding='utf8') as output_file: json.dump(data, output_file) if __name__ == '__main__': yolo_directory = './path/to/yolo_dataset/' target_json = './output/coco_format_annotations.json' yolo_to_coco(Path(yolo_directory), target_json) ``` 上述代码片段展示了如何遍历YOLO风格的文本标记文件(`.txt`)并将它们的内容按照COCO标准重新组织成单个大型JSON文件的过程。注意这里假设输入数据只包含一类目标(编号为0),如果有多种类别,则需要额外映射表将原始类别编码换为目标检测挑战赛所使用的连续整数形式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值