YOLO格式数据集转COCO格式

网上找了很久的YOLO格式数据集转COCO格式的代码,但是没有一个成功的,费尽千辛万苦终于找到一个能用的,因此记录一下。

一、首先YOLO格式数据集文件布局

其中lmages和labels 中的内容布局如下,只不过一个存放图片,一个存放标签

二、COCO数据集布局

下面的代码生产生成的是下图的第一个文件夹,存放标注文件json,其他三个文件夹都是图片

三、转换代码

import json
import os
import shutilimport cv2# info,license暂时用不到
info = {"year": 2024"version": '1.0',"date_created": 2024 - 03 - 29
}licenses = {"id": 1,"name": "yiquan","url": "null",
}#自己的标签类别,跟yolo格式的数据集类别要对应好;
categories = [{"id": 0,"name": 'Eating',"supercategory": 'lines',},{"id": 1,"name": 'Raising_a_hand',"supercategory": 'lines',},
{"id": 2,"name": 'Reading',"supercategory": 'lines',},{"id": 3,"name": 'Sleeping_At_a_desk',"supercategory": 'lines',},{"id": 4,"name": 'Writing',"supercategory": 'lines',}]#初始化train,test、val数据字典
# info licenses categories 在train和test,val里面都是一致的;
train_data = {'info': info, 'licenses': licenses, 'categories': categories, 'images': [], 'annotations': []}
test_data = {'info': info, 'licenses': licenses, 'categories': categories, 'images': [], 'annotations': []}# image_path 对应yolo的图像路径,比如images/train;
# label_path 对应yolo的label路径,比如labels/train 跟images要对应;
def v5_covert_coco_format(image_path, label_path):images = []annotations = []for index, img_file in enumerate(os.listdir(image_path)):if img_file.endswith('.jpg'):image_info = {}img = cv2.imread(os.path.join(image_path, img_file))height, width, channel = img.shapeimage_info['id'] = indeximage_info['file_name'] = img_fileimage_info['width'], image_info['height'] = width, heightelse:continueif image_info != {}:images.append(image_info)# 处理label信息-------label_file = os.path.join(label_path, img_file.replace('.jpg', '.txt'))with open(label_file, 'r') as f:for idx, line in enumerate(f.readlines()):info_annotation = {}class_num, xs, ys, ws, hs = line.strip().split(' ')class_id, xc, yc, w, h = int(class_num), float(xs), float(ys), float(ws), float(hs)xmin = (xc - w / 2) * widthymin = (yc - h / 2) * heightxmax = (xc + w / 2) * widthymax = (yc + h / 2) * heightbbox_w = int(width * w)bbox_h = int(height * h)img_copy = img[int(ymin):int(ymax),int(xmin):int(xmax)].copy()info_annotation["category_id"] = class_id  # 类别的idinfo_annotation['bbox'] = [xmin, ymin, bbox_w, bbox_h]  ## bbox的坐标info_annotation['area'] = bbox_h * bbox_w ###areainfo_annotation['image_id'] = index # bbox的idinfo_annotation['id'] = index * 100 + idx  # bbox的id# cv2.imwrite(f"./temp/{info_annotation['id']}.jpg", img_copy)info_annotation['segmentation'] = [[xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax]]  # 四个点的坐标info_annotation['iscrowd'] = 0  # 单例annotations.append(info_annotation)return images, annotations# key == train,test,val
# 对应要生成的json文件,比如instances_train.json,instances_test.json,instances_val.jsondef gen_json_file(yolov5_data_path, coco_format_path, key):# json pathjson_path = os.path.join(coco_format_path, f'annotations/instances_{key}.json')dst_path = os.path.join(coco_format_path, f'{key}')if not os.path.exists(os.path.dirname(json_path)):os.makedirs(os.path.dirname(json_path), exist_ok=True)data_path = os.path.join(yolov5_data_path, f'images/{key}')label_path = os.path.join(yolov5_data_path, f'labels/{key}')images, anns = v5_covert_coco_format(data_path, label_path)if key == 'train':train_data['images'] = imagestrain_data['annotations'] = annswith open(json_path, 'w') as f:json.dump(train_data, f, indent=2)# shutil.copy(data_path,'')elif key == 'val':test_data['images'] = imagestest_data['annotations'] = annswith open(json_path, 'w') as f:json.dump(test_data, f, indent=2)else:print(f'key is {key}')print(f'generate {key} json success!')returnif __name__ == '__main__':yolov5_data_path = 'D:/deep_learn/yolov8_20230701/ClassroomBehavior'  #保存YOLO数据集的目录coco_format_path = 'D:/deep_learn/yolov8_20230701/COCO'               #转换后生成的COCO数据集   json文件gen_json_file(yolov5_data_path, coco_format_path,key='train')gen_json_file(yolov5_data_path, coco_format_path,key='val')gen_json_file(yolov5_data_path, coco_format_path, key='test')

运行后生成,至此任务完成。如果帮到你,麻烦帮忙点点赞

 参考文章

代码实现如何将yolov5数据格式转换为coco格式_yolo转coco-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/578711.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

物联网实战--入门篇之(三)嵌入式STM32

目录 一、Keil简介 二、工程结构 三、文件目录 四、STM32简介 五、编码风格 六、总结 一、Keil简介 Keil是一款常用的单片机开发工具,主要包含了编译、仿真、调试和开发界面(IDE),后被ARM公司收购,与其MDK-ARM合并为MDK-ARM Keil软件包…

Github profile Readme实现小游戏[github自述游戏]

Github profile Readme常用于个人主页介绍,将它与action自动化流程结合,可以实现一些小游戏 例如:2048、五子棋 2048实现 losehu (RUBO) GitHub 五子棋 https://github.com/losehu/losehu/tree/main 通过python/C编写可执行文件&#xf…

DSVPN实验报告

一、分析要求 1. 配置R5为ISP,只能进行IP地址配置,所有地址均配为公有IP地址。 - 在R5上,将接口配置为公有IP地址,并确保只进行了IP地址配置。 2. R1和R5之间使用PPP的PAP认证,R5为主认证方;R2于R5之间…

vue+elementUI搭建动态表头的表格

前提:以下代码是vue2项目结合elementUi完成的 数据结构 后端传来的数据是两个list,一个表头的list,一个表格内容的list // 表头 headTableAtts: [{ columnLabel: 姓名, columnName: name },{ columnLabel: 年龄, columnName: age },{ colu…

KT-0855大小鼠Y迷宫——动物行为研究的实验设备

大小鼠Y迷宫视频分析系统是一种专门应用于动物行为研究的实验设备,主要用于评估动物的空间记忆、辨别性学习以及工作记忆等认知功能。该系统通过捕捉和分析动物在迷宫中的行为表现,提供了一系列参数,如进入各臂的次数、时间、正确次数、错误次…

Web APIs知识点讲解(阶段五)

DOM- 网页特效篇 一.课前回顾(手风琴) <!DOCTYPE html> <html><head lang"en"><meta charset"UTF-8"><title>手风琴</title><style>ul {list-style: none;}* {margin: 0;padding: 0;}div {width: 1200px;heig…

LoRA 及其衍生技术总览:An Overview of the LoRA Family

编者按&#xff1a; 对于大语言模型的微调训练来说&#xff0c;传统的全参数微调方法需要处理数百万甚至数十亿级别的参数&#xff0c;计算量和显存占用都非常大。而 LoRA 这种技术方案&#xff0c;通过引入少量的可训练矩阵来调整预训练模型的行为&#xff0c;极大降低了训练所…

Radash一款JavaScript最新的实用工具库,Lodash的平替!

文章目录 Lodash 的痛点进入正题--Radash特点 举例几个常用的api 一说lodash应该大部分前端同学都知道吧&#xff0c;陪伴我们好多年的JavaScript工具库&#xff0c;但是自从 ES6 出现后就慢慢退出前端人的视线&#xff0c;能ES6写的代码绝对不会用Lodash&#xff0c;也不是完全…

C语言数据结构易错知识点(6)(快速排序、归并排序、计数排序)

快速排序属于交换排序&#xff0c;交换排序还有冒泡排序&#xff0c;这个太简单了&#xff0c;这里就不再讲解。 归并排序和快速排序都是采用分治法实现的排序&#xff0c;理解它们对分支思想的感悟会更深。 计数排序属于非比较排序&#xff0c;在数据集中的情况下可以考虑使…

LLM推理入门指南②:深入解析KV缓存

在本系列文章《LLM推理入门指南①&#xff1a;文本生成的初始化与解码阶段》中&#xff0c;作者对Transformer解码器的文本生成算法进行了高层次概述&#xff0c;着重介绍了两个阶段&#xff1a;单步初始化阶段&#xff0c;即提示的处理阶段&#xff0c;和逐个生成补全词元的多…

jetson Orin nano 部署(一)

jetson Orin nano上安装VScode 和 anconda环境配置&#xff0c;在anaconda中安装pytorch、torchvision、tensorrt 安装VScode下载VScode安装VScode 安装anaconda安装pytorh和torchvision&#xff0c;tensorrttrtexec的问题 安装VScode 下载VScode 点击VScode下载链接&#xf…