家庭路由器建个人网站,263邮箱个人登录,书画展示网站源码,wordpress爬虫COCO格式转化为YOLOv8格式 目录格式代码 目录格式
yolov8仅支持YOLO格式的标签#xff0c;COCO的默认标签为JSON格式#xff0c;所以需要将COCO格式转换为YOLO格式。
如果训练COCO数据集的话一定要按照这个格式#xff0c;摆放目录images#xff0c;labels这两个目录名不… COCO格式转化为YOLOv8格式 目录格式代码 目录格式
yolov8仅支持YOLO格式的标签COCO的默认标签为JSON格式所以需要将COCO格式转换为YOLO格式。
如果训练COCO数据集的话一定要按照这个格式摆放目录imageslabels这两个目录名不可以改变
因为在内部已经写好了就这么去找数据如果不按照这个规则写就会报错No labels found in
datasets|coco|images|train2017val2017labels|train2017val2017代码
该代码可将COCO格式转换为YOLO格式并保存在labels/下。这里需要运行两次train和val都需要转换。
import os
import json
from tqdm import tqdm
import argparseparser argparse.ArgumentParser()
parser.add_argument(--json_path, default/home/ubuntu/data/coco2017/annotations/instances_train2017.json,typestr, helpinput: coco format(json))
parser.add_argument(--save_path, default/home/ubuntu/data/coco2017/labels/train2017, typestr, helpspecify where to save the output dir of labels)
arg parser.parse_args()def convert(size, box):dw 1. / (size[0])dh 1. / (size[1])x box[0] box[2] / 2.0y box[1] box[3] / 2.0w box[2]h box[3]x x * dww w * dwy y * dhh h * dhreturn (x, y, w, h)if __name__ __main__:json_file arg.json_path # COCO Object Instance 类型的标注ana_txt_save_path arg.save_path # 保存的路径data json.load(open(json_file, r))if not os.path.exists(ana_txt_save_path):os.makedirs(ana_txt_save_path)id_map {} # coco数据集的id不连续重新映射一下再输出for i, category in enumerate(data[categories]): id_map[category[id]] i# 通过事先建表来降低时间复杂度max_id 0for img in data[images]:max_id max(max_id, img[id])# 注意这里不能写作 [[]]*(max_id1)否则列表内的空列表共享地址img_ann_dict [[] for i in range(max_id1)] for i, ann in enumerate(data[annotations]):img_ann_dict[ann[image_id]].append(i)for img in tqdm(data[images]):filename img[file_name]img_width img[width]img_height img[height]img_id img[id]head, tail os.path.splitext(filename)ana_txt_name head .txt # 对应的txt名字与jpg一致f_txt open(os.path.join(ana_txt_save_path, ana_txt_name), w)for ann in data[annotations]:if ann[image_id] img_id:box convert((img_width, img_height), ann[bbox])f_txt.write(%s %s %s %s %s\n % (id_map[ann[category_id]], box[0], box[1], box[2], box[3]))# 这里可以直接查表而无需重复遍历for ann_id in img_ann_dict[img_id]:ann data[annotations][ann_id]box convert((img_width, img_height), ann[bbox])f_txt.write(%s %s %s %s %s\n % (id_map[ann[category_id]], box[0], box[1], box[2], box[3]))f_txt.close()参考文章