COCO2YOLO

该Python脚本用于将包含形状信息的COCO格式标注数据转换为YOLO数据格式。它读取源路径中的.json文件,提取类别和边界框信息,然后按YOLO的格式要求写入目标路径的.txt文件中,包括类索引、中心点坐标和宽高相对于图像的比例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Label打标数据转成YOLO数据格式

# from ultralytics.yolo.data.converter import convert_coco
#
# convert_coco(labels_dir=r'D:\github\ultralytics\111')
import cv2
import json
import os

source_path = r"D:\github\ultralytics\111"

dest_path = r"D:\github\ultralytics\222"
class_list = [ 'cut_corner' ,'with_corner']


for jsonfile in os.listdir(source_path):
    if jsonfile.endswith(".json"):
        with open(source_path + '//' + jsonfile, 'r') as f:    #打开json文件,读取数据
            data = json.load(f)
            #
            class_name = data.get("shapes")[0].get("label")

            points = data.get("shapes")[0].get("points")

            imageHeight = data.get("imageHeight")
            imageWidth = data.get("imageWidth")

            Center_X = float(points[0][0] + points[1][0]) /2
            Center_Y = float(points[0][1] + points[1][1]) /2

            Width = abs(float(points[0][0]) - float(points[1][0]))
            Height = abs(float(points[0][1]) - float(points[1][1]))

            #算出类别、四个点的坐标
            #新建一个txt同名文件
            file = open(dest_path + "\\"+ jsonfile.split(".json")[0] + '.txt', 'a')
            file.write(str(class_list.index(class_name)) + ' ' + str(Center_X / imageWidth) + ' ' + str(Center_Y / imageHeight) + ' ' + str(Width / imageWidth) + ' ' + str(Height / imageHeight))

### 将COCO数据集转换为YOLO格式 为了适应YOLO算法的需求,将COCO数据集转换成YOLO格式是一个常见的预处理步骤。此过程涉及调整标注文件的结构和内容。 #### 数据集标签结构调整 在COCO数据集中,每个图像都有对应的JSON文件来描述对象的位置和其他属性。而YOLO期望的是每张图片对应一个文本文件(.txt),其中每一行代表一个边界框及其类别索引[^2]。 对于每一个目标检测任务,在COCO JSON文件里定义的对象需要被解析并重新写入到相应的TXT文件中去。具体来说: - 图像ID与文件名之间的映射关系; - 类别名称至连续整数编号间的映射表(通常是从0开始); - 边界框坐标(xmin,ymin,xmax,ymax)需转化为中心点位置(center_x,center_y,width,height), 并且这些数值应该相对于整个图像尺寸进行归一化处理[^1]。 以下是Python脚本片段用于实现上述功能: ```python import json from pathlib import Path def coco_to_yolo(coco_annotation_file, output_dir): with open(coco_annotation_file) as f: data = json.load(f) # 创建输出目录如果不存在的话 path_output = Path(output_dir) path_output.mkdir(parents=True, exist_ok=True) categories = {cat['id']: cat['name'] for cat in data['categories']} category_ids = sorted(categories.keys()) class_mapping = {category_id: idx for idx, category_id in enumerate(category_ids)} image_info = {} for img in data["images"]: image_info[img["id"]] = { "file_name": img["file_name"], "width": img["width"], "height": img["height"] } annotations_by_image = {} for ann in data["annotations"]: if ann["image_id"] not in annotations_by_image: annotations_by_image[ann["image_id"]] = [] bbox = [ (ann["bbox"][0] + ann["bbox"][2]/2)/image_info[ann["image_id"]]["width"], # center_x normalized (ann["bbox"][1] + ann["bbox"][3]/2)/image_info[ann["image_id"]]["height"], # center_y normalized ann["bbox"][2]/image_info[ann["image_id"]]["width"], # width normalized ann["bbox"][3]/image_info[ann["image_id"]]["height"] # height normalized ] line = "{} {} {} {} {}\n".format(class_mapping[ann["category_id"]], *bbox) annotations_by_image[ann["image_id"]].append(line) for img_id, lines in annotations_by_image.items(): file_path = str(path_output / Path(image_info[img_id]['file_name']).with_suffix('.txt')) with open(file_path, 'w') as txt_f: txt_f.writelines(lines) if __name__ == "__main__": coco_to_yolo('instances_val2017.json', './yolov3/labels') ``` 这段代码读取了一个标准形式的COCO标注文件,并将其转换成了YOLO所需的格式保存到了指定路径下。注意这里假设输入json位于当前工作目录并且命名为`instances_val2017.json`, 输出则会放在相对路径下的`./yolov3/labels` 文件夹内。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值