当前位置: 首页 > 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 仲裁器。...

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…...

微软PowerBI考试 PL300-选择 Power BI 模型框架【附练习数据】

微软PowerBI考试 PL300-选择 Power BI 模型框架 20 多年来&#xff0c;Microsoft 持续对企业商业智能 (BI) 进行大量投资。 Azure Analysis Services (AAS) 和 SQL Server Analysis Services (SSAS) 基于无数企业使用的成熟的 BI 数据建模技术。 同样的技术也是 Power BI 数据…...

Qt Http Server模块功能及架构

Qt Http Server 是 Qt 6.0 中引入的一个新模块&#xff0c;它提供了一个轻量级的 HTTP 服务器实现&#xff0c;主要用于构建基于 HTTP 的应用程序和服务。 功能介绍&#xff1a; 主要功能 HTTP服务器功能&#xff1a; 支持 HTTP/1.1 协议 简单的请求/响应处理模型 支持 GET…...

C++使用 new 来创建动态数组

问题&#xff1a; 不能使用变量定义数组大小 原因&#xff1a; 这是因为数组在内存中是连续存储的&#xff0c;编译器需要在编译阶段就确定数组的大小&#xff0c;以便正确地分配内存空间。如果允许使用变量来定义数组的大小&#xff0c;那么编译器就无法在编译时确定数组的大…...

JS设计模式(4):观察者模式

JS设计模式(4):观察者模式 一、引入 在开发中&#xff0c;我们经常会遇到这样的场景&#xff1a;一个对象的状态变化需要自动通知其他对象&#xff0c;比如&#xff1a; 电商平台中&#xff0c;商品库存变化时需要通知所有订阅该商品的用户&#xff1b;新闻网站中&#xff0…...

人工智能(大型语言模型 LLMs)对不同学科的影响以及由此产生的新学习方式

今天是关于AI如何在教学中增强学生的学习体验&#xff0c;我把重要信息标红了。人文学科的价值被低估了 ⬇️ 转型与必要性 人工智能正在深刻地改变教育&#xff0c;这并非炒作&#xff0c;而是已经发生的巨大变革。教育机构和教育者不能忽视它&#xff0c;试图简单地禁止学生使…...

uniapp 开发ios, xcode 提交app store connect 和 testflight内测

uniapp 中配置 配置manifest 文档&#xff1a;manifest.json 应用配置 | uni-app官网 hbuilderx中本地打包 下载IOS最新SDK 开发环境 | uni小程序SDK hbulderx 版本号&#xff1a;4.66 对应的sdk版本 4.66 两者必须一致 本地打包的资源导入到SDK 导入资源 | uni小程序SDK …...

第7篇:中间件全链路监控与 SQL 性能分析实践

7.1 章节导读 在构建数据库中间件的过程中&#xff0c;可观测性 和 性能分析 是保障系统稳定性与可维护性的核心能力。 特别是在复杂分布式场景中&#xff0c;必须做到&#xff1a; &#x1f50d; 追踪每一条 SQL 的生命周期&#xff08;从入口到数据库执行&#xff09;&#…...

如何配置一个sql server使得其它用户可以通过excel odbc获取数据

要让其他用户通过 Excel 使用 ODBC 连接到 SQL Server 获取数据&#xff0c;你需要完成以下配置步骤&#xff1a; ✅ 一、在 SQL Server 端配置&#xff08;服务器设置&#xff09; 1. 启用 TCP/IP 协议 打开 “SQL Server 配置管理器”。导航到&#xff1a;SQL Server 网络配…...

HTML中各种标签的作用

一、HTML文件主要标签结构及说明 1. <&#xff01;DOCTYPE html> 作用&#xff1a;声明文档类型&#xff0c;告知浏览器这是 HTML5 文档。 必须&#xff1a;是。 2. <html lang“zh”>. </html> 作用&#xff1a;包裹整个网页内容&#xff0c;lang"z…...