DIOR数据集转化为COCO格式

2023-11-08 01:30
文章标签 数据 格式 转化 coco dior

本文主要是介绍DIOR数据集转化为COCO格式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

DIOR数据集转化为COCO格式

为了实验方便,需要将DIOR数据集转化为COCO格式,在此将代码共享,希望能帮助到同样研究方向的人。

解压DIOR数据集的压缩文件之后,你的路径应该是这样的:

第一个参数是你电脑里上图的路径,第二个参数是你想输出COCO格式文件的路径

DIOR缺少很多COCO格式的数据,所以缺少的项都为空,代码如下

import os
import cv2
from tqdm import tqdm
import json
import xml.dom.minidomcategory_list = ['airplane', 'airport', 'baseballfield', 'basketballcourt', 'bridge', 'chimney', 'dam','Expressway-Service-area', 'Expressway-toll-station', 'golffield', 'groundtrackfield', 'harbor','overpass', 'ship', 'stadium', 'storagetank', 'tenniscourt', 'trainstation', 'vehicle', 'windmill']def convert_to_cocodetection(dir, output_dir):"""input:dir:the path to DIOR datasetoutput_dir:the path write the coco form json file"""annotations_path = dirnamelist_path = os.path.join(dir, "Main")trainval_images_path = os.path.join(dir, "JPEGImages-trainval")test_images_path = os.path.join(dir, "JPEGImages-test")id_num = 0categories = [{"id": 0, "name": "Airplane"},{"id": 1, "name": "Airport"},{"id": 2, "name": "Baseball field"},{"id": 3, "name": "Basketball court"},{"id": 4, "name": "Bridge"},{"id": 5, "name": "Chimney"},{"id": 6, "name": "Dam"},{"id": 7, "name": "Expressway service area"},{"id": 8, "name": "Expressway toll station"},{"id": 9, "name": "Golf course"},{"id": 10, "name": "Ground track field"},{"id": 11, "name": "Harbor"},{"id": 12, "name": "Overpass"},{"id": 13, "name": "Ship"},{"id": 14, "name": "Stadium"},{"id": 15, "name": "Storage tank"},{"id": 16, "name": "Tennis court"},{"id": 17, "name": "Train station"},{"id": 18, "name": "Vehicle"},{"id": 19, "name": "Wind mill"},]for mode in ["train", "val"]:images = []annotations = []print(f"start loading {mode} data...")if mode == "train":f = open(namelist_path + "/" + "train.txt", "r")images_path = trainval_images_pathelse:f = open(namelist_path + "/" + "val.txt", "r")images_path = trainval_images_pathfor name in tqdm(f.readlines()):# image partimage = {}name = name.replace("\n", "")image_name = name + ".jpg"annotation_name = name + ".xml"height, width = cv2.imread(images_path + "/" + image_name).shape[:2]image["file_name"] = image_nameimage["height"] = heightimage["width"] = widthimage["id"] = nameimages.append(image)# anno partdom = xml.dom.minidom.parse(dir + "/" + annotation_name)root_data = dom.documentElementfor i in range(len(root_data.getElementsByTagName('name'))):annotation = {}category = root_data.getElementsByTagName('name')[i].firstChild.datatop_left_x = root_data.getElementsByTagName('xmin')[i].firstChild.datatop_left_y = root_data.getElementsByTagName('ymin')[i].firstChild.dataright_bottom_x = root_data.getElementsByTagName('xmax')[i].firstChild.dataright_bottom_y = root_data.getElementsByTagName('ymax')[i].firstChild.databbox = [top_left_x, top_left_y, right_bottom_x, right_bottom_y]bbox = [int(i) for i in bbox]bbox = xyxy_to_xywh(bbox)annotation["image_id"] = nameannotation["bbox"] = bboxannotation["category_id"] = category_list.index(category)annotation["id"] = id_numannotation["iscrowd"] = 0annotation["segmentation"] = []annotation["area"] = bbox[2] * bbox[3]id_num += 1annotations.append(annotation)dataset_dict = {}dataset_dict["images"] = imagesdataset_dict["annotations"] = annotationsdataset_dict["categories"] = categoriesjson_str = json.dumps(dataset_dict)with open(f'{output_dir}/DIOR_{mode}_coco.json', 'w') as json_file:json_file.write(json_str)print("json file write done...")def get_test_namelist(dir, out_dir):full_path = out_dir + "/" + "test.txt"file = open(full_path, 'w')for name in tqdm(os.listdir(dir)):name = name.replace(".txt", "")file.write(name + "\n")file.close()return Nonedef centerxywh_to_xyxy(boxes):"""args:boxes:list of center_x,center_y,width,height,return:boxes:list of x,y,x,y,cooresponding to top left and bottom right"""x_top_left = boxes[0] - boxes[2] / 2y_top_left = boxes[1] - boxes[3] / 2x_bottom_right = boxes[0] + boxes[2] / 2y_bottom_right = boxes[1] + boxes[3] / 2return [x_top_left, y_top_left, x_bottom_right, y_bottom_right]def centerxywh_to_topleftxywh(boxes):"""args:boxes:list of center_x,center_y,width,height,return:boxes:list of x,y,x,y,cooresponding to top left and bottom right"""x_top_left = boxes[0] - boxes[2] / 2y_top_left = boxes[1] - boxes[3] / 2width = boxes[2]height = boxes[3]return [x_top_left, y_top_left, width, height]def xyxy_to_xywh(boxes):width = boxes[2] - boxes[0]height = boxes[3] - boxes[1]return [boxes[0], boxes[1], width, height]def clamp(coord, width, height):if coord[0] < 0:coord[0] = 0if coord[1] < 0:coord[1] = 0if coord[2] > width:coord[2] = widthif coord[3] > height:coord[3] = heightreturn coordif __name__ == '__main__':convert_to_cocodetection(r"path to your DIOR dataset", r"the path you want to write the coco format json file")

 

这篇关于DIOR数据集转化为COCO格式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/367133

相关文章

MySQL快速复制一张表的四种核心方法(包括表结构和数据)

《MySQL快速复制一张表的四种核心方法(包括表结构和数据)》本文详细介绍了四种复制MySQL表(结构+数据)的方法,并对每种方法进行了对比分析,适用于不同场景和数据量的复制需求,特别是针对超大表(1... 目录一、mysql 复制表(结构+数据)的 4 种核心方法(面试结构化回答)方法 1:CREATE

详解C++ 存储二进制数据容器的几种方法

《详解C++存储二进制数据容器的几种方法》本文主要介绍了详解C++存储二进制数据容器,包括std::vector、std::array、std::string、std::bitset和std::ve... 目录1.std::vector<uint8_t>(最常用)特点:适用场景:示例:2.std::arra

C#中DateTime的格式符的实现示例

《C#中DateTime的格式符的实现示例》本文介绍了C#中DateTime格式符的使用方法,分为预定义格式和自定义格式两类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录DateTime的格式符1.核心概念2.预定义格式(快捷方案,直接复用)3.自定义格式(灵活可控

MySQL中的DELETE删除数据及注意事项

《MySQL中的DELETE删除数据及注意事项》MySQL的DELETE语句是数据库操作中不可或缺的一部分,通过合理使用索引、批量删除、避免全表删除、使用TRUNCATE、使用ORDERBY和LIMI... 目录1. 基本语法单表删除2. 高级用法使用子查询删除删除多表3. 性能优化策略使用索引批量删除避免

MySQL 数据库进阶之SQL 数据操作与子查询操作大全

《MySQL数据库进阶之SQL数据操作与子查询操作大全》本文详细介绍了SQL中的子查询、数据添加(INSERT)、数据修改(UPDATE)和数据删除(DELETE、TRUNCATE、DROP)操作... 目录一、子查询:嵌套在查询中的查询1.1 子查询的基本语法1.2 子查询的实战示例二、数据添加:INSE

Linux服务器数据盘移除并重新挂载的全过程

《Linux服务器数据盘移除并重新挂载的全过程》:本文主要介绍在Linux服务器上移除并重新挂载数据盘的整个过程,分为三大步:卸载文件系统、分离磁盘和重新挂载,每一步都有详细的步骤和注意事项,确保... 目录引言第一步:卸载文件系统第二步:分离磁盘第三步:重新挂载引言在 linux 服务器上移除并重新挂p

使用MyBatis TypeHandler实现数据加密与解密的具体方案

《使用MyBatisTypeHandler实现数据加密与解密的具体方案》在我们日常的开发工作中,经常会遇到一些敏感数据需要存储,比如用户的手机号、身份证号、银行卡号等,为了保障数据安全,我们通常会对... 目录1. 核心概念:什么是 TypeHandler?2. 实战场景3. 代码实现步骤步骤 1:定义 E

使用C#导出Excel数据并保存多种格式的完整示例

《使用C#导出Excel数据并保存多种格式的完整示例》在现代企业信息化管理中,Excel已经成为最常用的数据存储和分析工具,从员工信息表、销售数据报表到财务分析表,几乎所有部门都离不开Excel,本文... 目录引言1. 安装 Spire.XLS2. 创建工作簿和填充数据3. 保存为不同格式4. 效果展示5

Python多任务爬虫实现爬取图片和GDP数据

《Python多任务爬虫实现爬取图片和GDP数据》本文主要介绍了基于FastAPI开发Web站点的方法,包括搭建Web服务器、处理图片资源、实现多任务爬虫和数据可视化,同时,还简要介绍了Python爬... 目录一. 基于FastAPI之Web站点开发1. 基于FastAPI搭建Web服务器2. Web服务

MySQL 批量插入的原理和实战方法(快速提升大数据导入效率)

《MySQL批量插入的原理和实战方法(快速提升大数据导入效率)》在日常开发中,我们经常需要将大量数据批量插入到MySQL数据库中,本文将介绍批量插入的原理、实现方法,并结合Python和PyMySQ... 目录一、批量插入的优势二、mysql 表的创建示例三、python 实现批量插入1. 安装 PyMyS