当前位置: 首页 > news >正文

划分VOC数据集,以及转换为划分后的COCO数据集格式

1.VOC数据集

    LabelImg是一款广泛应用于图像标注的开源工具,主要用于构建目标检测模型所需的数据集。Visual Object Classes(VOC)数据集作为一种常见的目标检测数据集,通过labelimg工具在图像中标注边界框和类别标签,为训练模型提供了必要的注解信息。VOC数据集源于对PASCAL挑战赛的贡献,涵盖多个物体类别,成为目标检测领域的重要基准之一,推动着算法性能的不断提升。

    使用labelimg标注或者其他VOC标注工具标注后,会得到两个文件夹,如下:

Annotations    ------->>>  存放.xml标注信息文件
JPEGImages     ------->>>  存放图片文件

在这里插入图片描述

2.划分VOC数据集

    如下代码是按照训练集:验证集 = 8:2来划分的,会找出没有对应.xml的图片文件,且划分的时候支持JPEGImages文件夹下有如下图片格式:

['.jpg', '.png', '.gif', '.bmp', '.tiff', '.jpeg', '.webp', '.svg', '.psd', '.cr2', '.nef', '.dng']

整体代码为:

import os
import randomimage_extensions = ['.jpg', '.png', '.gif', '.bmp', '.tiff', '.jpeg', '.webp', '.svg', '.psd', '.cr2', '.nef', '.dng']def split_voc_dataset(dataset_dir, train_ratio, val_ratio):if not (0 < train_ratio + val_ratio <= 1):print("Invalid ratio values. They should sum up to 1.")returnannotations_dir = os.path.join(dataset_dir, 'Annotations')images_dir = os.path.join(dataset_dir, 'JPEGImages')output_dir = os.path.join(dataset_dir, 'ImageSets/Main')if not os.path.exists(output_dir):os.makedirs(output_dir)dict_info = dict()# List all the image files in the JPEGImages directoryfor file in os.listdir(images_dir):if any(ext in file for ext in image_extensions):jpg_files, endwith = os.path.splitext(file)dict_info[jpg_files] = endwith# List all the XML files in the Annotations directoryxml_files = [file for file in os.listdir(annotations_dir) if file.endswith('.xml')]random.shuffle(xml_files)num_samples = len(xml_files)num_train = int(num_samples * train_ratio)num_val = int(num_samples * val_ratio)train_xml_files = xml_files[:num_train]val_xml_files = xml_files[num_train:num_train + num_val]with open(os.path.join(output_dir, 'train_list.txt'), 'w') as train_file:for xml_file in train_xml_files:image_name = os.path.splitext(xml_file)[0]if image_name in dict_info:image_path = os.path.join('JPEGImages', image_name + dict_info[image_name])annotation_path = os.path.join('Annotations', xml_file)train_file.write(f'{image_path} {annotation_path}\n')else:print(f"没有找到图片 {os.path.join(images_dir, image_name)}")with open(os.path.join(output_dir, 'val_list.txt'), 'w') as val_file:for xml_file in val_xml_files:image_name = os.path.splitext(xml_file)[0]if image_name in dict_info:image_path = os.path.join('JPEGImages', image_name + dict_info[image_name])annotation_path = os.path.join('Annotations', xml_file)val_file.write(f'{image_path} {annotation_path}\n')else:print(f"没有找到图片 {os.path.join(images_dir, image_name)}")labels = set()for xml_file in xml_files:annotation_path = os.path.join(annotations_dir, xml_file)with open(annotation_path, 'r') as f:lines = f.readlines()for line in lines:if '<name>' in line:label = line.strip().replace('<name>', '').replace('</name>', '')labels.add(label)with open(os.path.join(output_dir, 'labels.txt'), 'w') as labels_file:for label in labels:labels_file.write(f'{label}\n')if __name__ == "__main__":dataset_dir = 'BirdNest/'train_ratio = 0.8  # Adjust the train-validation split ratio as neededval_ratio = 0.2split_voc_dataset(dataset_dir, train_ratio, val_ratio)

划分好后的截图:
在这里插入图片描述

3.VOC转COCO格式

目前很多框架大多支持的是COCO格式,因为存放与使用起来方便,采用了json文件来代替xml文件。

import json
import os
from xml.etree import ElementTree as ETdef parse_xml(dataset_dir, xml_file):xml_path = os.path.join(dataset_dir, xml_file)tree = ET.parse(xml_path)root = tree.getroot()objects = root.findall('object')annotations = []for obj in objects:bbox = obj.find('bndbox')xmin = int(bbox.find('xmin').text)ymin = int(bbox.find('ymin').text)xmax = int(bbox.find('xmax').text)ymax = int(bbox.find('ymax').text)# Extract label from XML annotationlabel = obj.find('name').textif not label:print(f"Label not found in XML annotation. Skipping annotation.")continueannotations.append({'xmin': xmin,'ymin': ymin,'xmax': xmax,'ymax': ymax,'label': label})return annotationsdef convert_to_coco_format(image_list_file, annotations_dir, output_json_file, dataset_dir):images = []annotations = []categories = []# Load labelswith open(os.path.join(os.path.dirname(image_list_file), 'labels.txt'), 'r') as labels_file:label_lines = labels_file.readlines()categories = [{'id': i + 1, 'name': label.strip()} for i, label in enumerate(label_lines)]# Load image list filewith open(image_list_file, 'r') as image_list:image_lines = image_list.readlines()for i, line in enumerate(image_lines):image_path, annotation_path = line.strip().split(' ')image_id = i + 1image_filename = os.path.basename(image_path)# Extract image size from XML filexml_path = os.path.join(dataset_dir, annotation_path)tree = ET.parse(xml_path)size = tree.find('size')image_height = int(size.find('height').text)image_width = int(size.find('width').text)images.append({'id': image_id,'file_name': image_filename,'height': image_height,'width': image_width,'license': None,'flickr_url': None,'coco_url': None,'date_captured': None})# Load annotations from XML filesxml_annotations = parse_xml(dataset_dir, annotation_path)for xml_annotation in xml_annotations:label = xml_annotation['label']category_id = next((cat['id'] for cat in categories if cat['name'] == label), None)if category_id is None:print(f"Label '{label}' not found in categories. Skipping annotation.")continuebbox = {'xmin': xml_annotation['xmin'],'ymin': xml_annotation['ymin'],'xmax': xml_annotation['xmax'],'ymax': xml_annotation['ymax']}annotations.append({'id': len(annotations) + 1,'image_id': image_id,'category_id': category_id,'bbox': [bbox['xmin'], bbox['ymin'], bbox['xmax'] - bbox['xmin'], bbox['ymax'] - bbox['ymin']],'area': (bbox['xmax'] - bbox['xmin']) * (bbox['ymax'] - bbox['ymin']),'segmentation': [],'iscrowd': 0})coco_data = {'images': images,'annotations': annotations,'categories': categories}with open(output_json_file, 'w') as json_file:json.dump(coco_data, json_file, indent=4)if __name__ == "__main__":# 根据需要调整路径dataset_dir = 'BirdNest/'image_sets_dir = 'BirdNest/ImageSets/Main/'train_list_file = os.path.join(image_sets_dir, 'train_list.txt')val_list_file = os.path.join(image_sets_dir, 'val_list.txt')output_train_json_file = os.path.join(dataset_dir, 'train_coco.json')output_val_json_file = os.path.join(dataset_dir, 'val_coco.json')convert_to_coco_format(train_list_file, image_sets_dir, output_train_json_file, dataset_dir)convert_to_coco_format(val_list_file, image_sets_dir, output_val_json_file, dataset_dir)print("The json file has been successfully generated!!!")

转COCO格式成功截图:
在这里插入图片描述
在这里插入图片描述

相关文章:

划分VOC数据集,以及转换为划分后的COCO数据集格式

1.VOC数据集 LabelImg是一款广泛应用于图像标注的开源工具&#xff0c;主要用于构建目标检测模型所需的数据集。Visual Object Classes&#xff08;VOC&#xff09;数据集作为一种常见的目标检测数据集&#xff0c;通过labelimg工具在图像中标注边界框和类别标签&#xff0c;为…...

JAVA基础8:方法

1.方法概念 方法&#xff08;method)&#xff1a;将具有独立功能的代码块组织成为一个整体&#xff0c;使其具有特殊功能的代码集。 注意事项&#xff1a; 方法必须先创建才可以使用&#xff0c;该过程称为方法定义方法创建后并不是直接运行的&#xff0c;需要手动使用后才执…...

域名反查Api接口——让您轻松查询域名相关信息

在互联网发展的今天&#xff0c;域名作为网站的唯一标识符&#xff0c;已经成为了企业和个人网络营销中不可或缺的一部分。为了方便用户查询所需的域名信息&#xff0c;API接口应运而生。本文将介绍如何使用挖数据平台《域名反查Api接口——让您轻松查询域名相关信息》进行域名…...

果儿科技:打造无代码开发的电商平台、CRM和用户运营系统

连接业务系统&#xff1a;果儿科技与集简云的无代码开发 北京果儿科技有限公司&#xff0c;自2015年成立以来&#xff0c;始终专注于研发创新的企业服务解决方案。其中&#xff0c;集简云无代码集成平台是我们的一项杰出成果&#xff0c;它实现了与近千款软件系统的连接&#…...

C++ 并发编程中condition_variable和future的区别

std::condition_variable 和 std::future 的区别&#xff1a; 用途不同&#xff1a; std::condition_variable&#xff1a; 就好比是一把魔法门&#xff0c;有两个小朋友&#xff0c;一个在门这边&#xff0c;一个在门那边。门上贴了一张纸&#xff0c;写着“开心时可以进来…...

【保姆级教程】Linux安装JDK8

本文以centos7为例&#xff0c;一步一步进行jdk1.8的安装。 1. 下载安装 官网下载链接&#xff1a; https://www.oracle.com/cn/java/technologies/downloads/#java8 上传jdk的压缩包到服务器的/usr/local目录下 在当前目录解压jdk压缩包&#xff0c;如果是其它版本&#xf…...

【备忘】ChromeDriver 官方下载地址 Selenium,pyppetter依赖

https://googlechromelabs.github.io/chrome-for-testing/#stable windows系统选择win64版本下载即可...

day08_osi各层协议,子网掩码,ip地址组成与分类

osi各层协议&#xff0c;子网掩码,ip地址组成与分类 一、上节课复习二 今日内容&#xff1a;1、子网划分 来源于http://egonlin.com/。林海峰老师课件 一、上节课复习 1、osi七层与数据传输 2、socketsocket是对传输层以下的封装ipport标识唯一一个基于网络通讯的软件3、tcp与…...

微信小程序:tabbar、事件绑定、数据绑定、模块化、模板语法、尺寸单位

目录 1. tabbar 1.1 什么是tabbar 1.2 配置tabbar 2. 事件绑定 2.1 准备表单 2.2 事件绑定 2.3 冒泡事件及非冒泡事件 3. 数据绑定 3.1 官方文档 4. 关于模块化 5. 模板语法 6. 尺寸单位 1. tabbar 1.1 什么是tabbar 下图中标记出来的部分即为tabbar&#xff1a…...

AR工业眼镜:智能化生产新时代的引领者!!

科技飞速发展&#xff0c;人工智能与增强现实&#xff08;AR&#xff09;技术结合正在改变生活工作方式。AR工业眼镜在生产领域应用广泛&#xff0c;具有实时信息展示、智能导航定位、远程协作培训、智能安全监测等功能&#xff0c;提高生产效率、降低操作风险&#xff0c;为企…...

从0到0.01入门React | 008.精选 React 面试题

🤍 前端开发工程师(主业)、技术博主(副业)、已过CET6 🍨 阿珊和她的猫_CSDN个人主页 🕠 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 🍚 蓝桥云课签约作者、已在蓝桥云课上架的前后端实战课程《Vue.js 和 Egg.js 开发企业级健康管理项目》、《带你从入…...

PP-YOLO: An Effective and Efficient Implementation of Object Detector(2020.8)

文章目录 Abstract1. Introduction先介绍了一堆前人的work自己的workexpect 2. Related Work先介绍别人的work与我们的区别 3.Method3.1. ArchitectureBackboneDetection NeckDetection Head 3.2. Selection of TricksLarger Batch SizeEMADropBlockIoULossIoU AwareGrid Sensi…...

4、创建第一个鸿蒙应用

一、创建项目 此处以空模板为例来创建一个鸿蒙应用。在创建项目前请保持网页的畅通。 1、在欢迎页面点击“Create Project”。 2、左侧默认为“Application”&#xff0c;在“Template Market”中选择空模板&#xff08;Empty Ability&#xff09;&#xff0c;点击“Next” 3…...

Docker - DockerFile

Docker - DockerFile DockerFile 描述 dockerfile 是用来构建docker镜像的文件&#xff01;命令参数脚本&#xff01; 构建步骤&#xff1a; 编写一个dockerfile 文件docker build 构建成为一个镜像docker run 运行脚本docker push 发布镜像&#xff08;dockerhub&#xff0…...

2311rust模式匹配

原文 在Rust中混合匹配,改变和移动 结构模式匹配:极大的改进了C或Java风格的switch语句. Match包含命令式和函数式编程风格:可继续使用break语句,赋值等,不必面向表达式. 按需匹配"借用"或"移动",:Rust鼓励开发者仔细考虑所有权和借用.设计匹配时仅支持…...

Linux系统软件安装方式

Linux系统软件安装方式 1. 绿色安装2. yum安装3. rpm安装3.1 rpm常用命令 4. 源码安装4.1 安装依赖包4.2 执行configure脚本4.3 编译、安装4.4 安装4.5 操作nginx4.6 创建服务器 1. 绿色安装 Compressed Archive压缩文档包&#xff0c;如Java软件的压缩文档包&#xff0c;只需…...

React + Antd 自定义Select选择框 全选、清空功能

实现代码 import React, { useState, useEffect } from react; import { Select, Space, Divider, Button } from antd;export default function AllSelect (props) {const {fieldNames, // 自定义节点labbel、value、options、grouLabeloptions, // 数据化配置选项内容&#…...

阿里云国际站:应用实时监控服务

文章目录 一、阿里云应用实时监控服务的概念 二、阿里云应用实时监控服务的优势 三、阿里云应用实时监控服务的功能 四、写在最后 一、阿里云应用实时监控服务的概念 应用实时监控服务 (Application Real-Time Monitoring Service) 作为一款云原生可观测产品平台&#xff…...

专题知识点-二叉树-(非常有意义的一篇文章)

这里写目录标题 二叉树的基础知识知识点一(二叉树性质 )树与二叉树的相互转换二叉树的遍历层次优先遍历树的深度和广度优先遍历中序线索二叉树二叉树相关遍历代码顺序存储和链式存储二叉树的遍历二叉树的相关例题左右两边表达式求值求树的深度找数找第k个数二叉树非递归遍历代码…...

多路数据写入DDR3/DDR4的两种方法

1.官方IP实现&#xff1b; 2.手写Axi 仲裁器。...

内存分配函数malloc kmalloc vmalloc

内存分配函数malloc kmalloc vmalloc malloc实现步骤: 1)请求大小调整:首先,malloc 需要调整用户请求的大小,以适应内部数据结构(例如,可能需要存储额外的元数据)。通常,这包括对齐调整,确保分配的内存地址满足特定硬件要求(如对齐到8字节或16字节边界)。 2)空闲…...

DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径

目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...

Golang 面试经典题:map 的 key 可以是什么类型?哪些不可以?

Golang 面试经典题&#xff1a;map 的 key 可以是什么类型&#xff1f;哪些不可以&#xff1f; 在 Golang 的面试中&#xff0c;map 类型的使用是一个常见的考点&#xff0c;其中对 key 类型的合法性 是一道常被提及的基础却很容易被忽视的问题。本文将带你深入理解 Golang 中…...

爬虫基础学习day2

# 爬虫设计领域 工商&#xff1a;企查查、天眼查短视频&#xff1a;抖音、快手、西瓜 ---> 飞瓜电商&#xff1a;京东、淘宝、聚美优品、亚马逊 ---> 分析店铺经营决策标题、排名航空&#xff1a;抓取所有航空公司价格 ---> 去哪儿自媒体&#xff1a;采集自媒体数据进…...

网络编程(UDP编程)

思维导图 UDP基础编程&#xff08;单播&#xff09; 1.流程图 服务器&#xff1a;短信的接收方 创建套接字 (socket)-----------------------------------------》有手机指定网络信息-----------------------------------------------》有号码绑定套接字 (bind)--------------…...

3-11单元格区域边界定位(End属性)学习笔记

返回一个Range 对象&#xff0c;只读。该对象代表包含源区域的区域上端下端左端右端的最后一个单元格。等同于按键 End 向上键(End(xlUp))、End向下键(End(xlDown))、End向左键(End(xlToLeft)End向右键(End(xlToRight)) 注意&#xff1a;它移动的位置必须是相连的有内容的单元格…...

Web 架构之 CDN 加速原理与落地实践

文章目录 一、思维导图二、正文内容&#xff08;一&#xff09;CDN 基础概念1. 定义2. 组成部分 &#xff08;二&#xff09;CDN 加速原理1. 请求路由2. 内容缓存3. 内容更新 &#xff08;三&#xff09;CDN 落地实践1. 选择 CDN 服务商2. 配置 CDN3. 集成到 Web 架构 &#xf…...

Webpack性能优化:构建速度与体积优化策略

一、构建速度优化 1、​​升级Webpack和Node.js​​ ​​优化效果​​&#xff1a;Webpack 4比Webpack 3构建时间降低60%-98%。​​原因​​&#xff1a; V8引擎优化&#xff08;for of替代forEach、Map/Set替代Object&#xff09;。默认使用更快的md4哈希算法。AST直接从Loa…...

Web后端基础(基础知识)

BS架构&#xff1a;Browser/Server&#xff0c;浏览器/服务器架构模式。客户端只需要浏览器&#xff0c;应用程序的逻辑和数据都存储在服务端。 优点&#xff1a;维护方便缺点&#xff1a;体验一般 CS架构&#xff1a;Client/Server&#xff0c;客户端/服务器架构模式。需要单独…...

通过 Ansible 在 Windows 2022 上安装 IIS Web 服务器

拓扑结构 这是一个用于通过 Ansible 部署 IIS Web 服务器的实验室拓扑。 前提条件&#xff1a; 在被管理的节点上安装WinRm 准备一张自签名的证书 开放防火墙入站tcp 5985 5986端口 准备自签名证书 PS C:\Users\azureuser> $cert New-SelfSignedCertificate -DnsName &…...