对比实验系列:Efficientdet环境配置及训练个人数据集

news/2024/5/2 11:58:26

一、源码下载

可以通过下方链接下载Efficientdet源码

GitHub - zylo117/Yet-Another-EfficientDet-Pytorch: The pytorch re-implement of the official efficientdet with SOTA performance in real time and pretrained weights.The pytorch re-implement of the official efficientdet with SOTA performance in real time and pretrained weights. - zylo117/Yet-Another-EfficientDet-Pytorchicon-default.png?t=N7T8https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch/tree/master

二、环境配置

1、使用anaconda创建环境

conda create -n efficient python==3.8 -y

2、进入环境

conda activate efficient

3、安装依赖包

pip install pycocotools-windows numpy opencv-python tqdm tensorboard tensorboardX pyyaml webcolors

4、安装torch和torchvision

pip install torch==1.9.1+cu111 torchvision==0.10.1+cu111 -f https://download.pytorch.org/whl/torch_stable.html

5、测试配置

5.1预训练权重下载

在源码下载的地方将预训练权重下载下来,这里选择的是Efficientdet-D1版本的预训练权重

在根目录下创建weights文件夹,将预训练权重放在文件夹内

5.2修改参数

在efficientdet_test.py中修改测试图片路径和efficientdet的版本,这里我下的版本是D1,所以就要将compound_coef改为1,如果你下的是其他版本,就将compound_coef改成对应的版本数字。

测试图片官方已经放在test\img.png,修改完之后运行efficientdet_test.py,检测结果保存在test文件夹内。

至此,efficientdet的所有环境配置结束。

三、自己的数据集制作

由于efficientdet使用的是coco格式的数据集,需要将标签转为coco格式,如果使用labelme进行标注,可以直接在labelme中切换成json格式的标签,最后用脚本进行合并,本文介绍的是使用VOC格式(xml)如何转为coco格式数据集。

1、划分验证集和训练集

使用下面的脚本将训练集进行划分:

# 将标签格式为xml的数据集按照8:2的比例划分为训练集和验证集import os
import shutil
import random
from tqdm import tqdmdef split_img(img_path, label_path, split_list):try:  # 创建数据集文件夹Data = 'yourdatasetsname'os.mkdir(Data)train_img_dir = Data + '/images/train'val_img_dir = Data + '/images/val'# test_img_dir = Data + '/images/test'train_label_dir = Data + '/labels/train'val_label_dir = Data + '/labels/val'# test_label_dir = Data + '/labels/test'# 创建文件夹os.makedirs(train_img_dir)os.makedirs(train_label_dir)os.makedirs(val_img_dir)os.makedirs(val_label_dir)# os.makedirs(test_img_dir)# os.makedirs(test_label_dir)except:print('文件目录已存在')train, val = split_listall_img = os.listdir(img_path)all_img_path = [os.path.join(img_path, img) for img in all_img]# all_label = os.listdir(label_path)# all_label_path = [os.path.join(label_path, label) for label in all_label]train_img = random.sample(all_img_path, int(train * len(all_img_path)))train_img_copy = [os.path.join(train_img_dir, img.split('\\')[-1]) for img in train_img]train_label = [toLabelPath(img, label_path) for img in train_img]train_label_copy = [os.path.join(train_label_dir, label.split('\\')[-1]) for label in train_label]for i in tqdm(range(len(train_img)), desc='train2007 ', ncols=80, unit='img'):_copy(train_img[i], train_img_dir)_copy(train_label[i], train_label_dir)all_img_path.remove(train_img[i])val_img = all_img_pathval_label = [toLabelPath(img, label_path) for img in val_img]for i in tqdm(range(len(val_img)), desc='test2007 ', ncols=80, unit='img'):_copy(val_img[i], val_img_dir)_copy(val_label[i], val_label_dir)def _copy(from_path, to_path):shutil.copy(from_path, to_path)def toLabelPath(img_path, label_path):img = img_path.split('\\')[-1]label = img.split('.jpg')[0] + '.xml'return os.path.join(label_path, label)def main():img_path = '/path/to/your/image/folder'label_path = '/path/to/your/xml/folder'split_list = [0.8, 0.2]  # 数据集划分比例[train2007:test2007]split_img(img_path, label_path, split_list)if __name__ == '__main__':main()

2、移动图片

在数据集根目录下创建datasets文件夹,并创建coco文件夹,在coco文件夹内创建annotations、train2017和val2017文件夹。将上一步划分好的训练集图片放入trian2017文件夹内,验证集图片放入val2017文件夹内。

3、生成json文件

使用下方的脚本分别对验证集和训练集的所有xml文件转为json文件,结果会生成两个json文件。

import xml.etree.ElementTree as ET
import os
import jsoncoco = dict()
coco['images'] = []
coco['type'] = 'instances'
coco['annotations'] = []
coco['categories'] = []category_set = dict()
image_set = set()# category_item_id = -1
# VOC数据集的类别id与coco数据集一样都是从1开始,如果初始设为-1,那么转出来的coco的json文件中category_id和类别id会从0开始,不符合coco标准,在调coco.py的时候会报错list越界
category_item_id = 0
image_id = 20180000000
annotation_id = 0def addCatItem(name):global category_item_idcategory_item = dict()category_item['supercategory'] = 'none'category_item_id += 1category_item['id'] = category_item_idcategory_item['name'] = namecoco['categories'].append(category_item)category_set[name] = category_item_idreturn category_item_iddef addImgItem(file_name, size):global image_idif file_name is None:raise Exception('Could not find filename tag in xml file.')if size['width'] is None:raise Exception('Could not find width tag in xml file.')if size['height'] is None:raise Exception('Could not find height tag in xml file.')image_id += 1image_item = dict()image_item['id'] = image_idimage_item['file_name'] = file_nameimage_item['width'] = size['width']image_item['height'] = size['height']coco['images'].append(image_item)image_set.add(file_name)return image_iddef addAnnoItem(object_name, image_id, category_id, bbox):global annotation_idannotation_item = dict()annotation_item['segmentation'] = []seg = []# bbox[] is x,y,w,h# left_topseg.append(bbox[0])seg.append(bbox[1])# left_bottomseg.append(bbox[0])seg.append(bbox[1] + bbox[3])# right_bottomseg.append(bbox[0] + bbox[2])seg.append(bbox[1] + bbox[3])# right_topseg.append(bbox[0] + bbox[2])seg.append(bbox[1])annotation_item['segmentation'].append(seg)annotation_item['area'] = bbox[2] * bbox[3]annotation_item['iscrowd'] = 0annotation_item['ignore'] = 0annotation_item['image_id'] = image_idannotation_item['bbox'] = bboxannotation_item['category_id'] = category_idannotation_id += 1annotation_item['id'] = annotation_idcoco['annotations'].append(annotation_item)def _read_image_ids(image_sets_file):ids = []with open(image_sets_file) as f:for line in f:ids.append(line.rstrip())return ids"""通过txt文件生成"""
#split ='train' 'va' 'trainval' 'test'
def parseXmlFiles_by_txt(data_dir,json_save_path,split='train'):print("hello")labelfile=split+".txt"image_sets_file = data_dir + "/ImageSets/Main/"+labelfileids=_read_image_ids(image_sets_file)for _id in ids:xml_file=data_dir + f"/Annotations/{_id}.xml"bndbox = dict()size = dict()current_image_id = Nonecurrent_category_id = Nonefile_name = Nonesize['width'] = Nonesize['height'] = Nonesize['depth'] = Nonetree = ET.parse(xml_file)root = tree.getroot()if root.tag != 'annotation':raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))# elem is <folder>, <filename>, <size>, <object>for elem in root:current_parent = elem.tagcurrent_sub = Noneobject_name = Noneif elem.tag == 'folder':continueif elem.tag == 'filename':file_name = elem.textif file_name in category_set:raise Exception('file_name duplicated')# add img item only after parse <size> tagelif current_image_id is None and file_name is not None and size['width'] is not None:if file_name not in image_set:current_image_id = addImgItem(file_name, size)print('add image with {} and {}'.format(file_name, size))else:raise Exception('duplicated image: {}'.format(file_name))# subelem is <width>, <height>, <depth>, <name>, <bndbox>for subelem in elem:bndbox['xmin'] = Nonebndbox['xmax'] = Nonebndbox['ymin'] = Nonebndbox['ymax'] = Nonecurrent_sub = subelem.tagif current_parent == 'object' and subelem.tag == 'name':object_name = subelem.textif object_name not in category_set:current_category_id = addCatItem(object_name)else:current_category_id = category_set[object_name]elif current_parent == 'size':if size[subelem.tag] is not None:raise Exception('xml structure broken at size tag.')size[subelem.tag] = int(subelem.text)# option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>for option in subelem:if current_sub == 'bndbox':if bndbox[option.tag] is not None:raise Exception('xml structure corrupted at bndbox tag.')bndbox[option.tag] = int(option.text)# only after parse the <object> tagif bndbox['xmin'] is not None:if object_name is None:raise Exception('xml structure broken at bndbox tag')if current_image_id is None:raise Exception('xml structure broken at bndbox tag')if current_category_id is None:raise Exception('xml structure broken at bndbox tag')bbox = []# xbbox.append(bndbox['xmin'])# ybbox.append(bndbox['ymin'])# wbbox.append(bndbox['xmax'] - bndbox['xmin'])# hbbox.append(bndbox['ymax'] - bndbox['ymin'])print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,bbox))addAnnoItem(object_name, current_image_id, current_category_id, bbox)json.dump(coco, open(json_save_path, 'w'))"""直接从xml文件夹中生成"""
def parseXmlFiles(xml_path,json_save_path):for f in os.listdir(xml_path):if not f.endswith('.xml'):continue# print(path)bndbox = dict()size = dict()current_image_id = Nonecurrent_category_id = Nonefile_name = Nonesize['width'] = Nonesize['height'] = Nonesize['depth'] = Nonexml_file = os.path.join(xml_path, f)print(xml_file)tree = ET.parse(xml_file)root = tree.getroot()if root.tag != 'annotation':raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))# elem is <folder>, <filename>, <size>, <object>for elem in root:current_parent = elem.tagcurrent_sub = Noneobject_name = Noneif elem.tag == 'folder':continueif elem.tag == 'filename':# 改成与xml文件同名的图片文件file_name = f.split(".")[0] + ".jpg"# file_name = elem.text# if file_name in category_set:#     raise Exception('file_name duplicated')# add img item only after parse <size> tagelif current_image_id is None and file_name is not None and size['width'] is not None:if file_name not in image_set:current_image_id = addImgItem(file_name, size)print('add image with {} and {}'.format(file_name, size))else:raise Exception('duplicated image: {}'.format(file_name))# subelem is <width>, <height>, <depth>, <name>, <bndbox>for subelem in elem:bndbox['xmin'] = Nonebndbox['xmax'] = Nonebndbox['ymin'] = Nonebndbox['ymax'] = Nonecurrent_sub = subelem.tagif current_parent == 'object' and subelem.tag == 'name':object_name = subelem.textif object_name not in category_set:current_category_id = addCatItem(object_name)else:current_category_id = category_set[object_name]elif current_parent == 'size':if size[subelem.tag] is not None:raise Exception('xml structure broken at size tag.')size[subelem.tag] = int(subelem.text)# option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>for option in subelem:if current_sub == 'bndbox':if bndbox[option.tag] is not None:raise Exception('xml structure corrupted at bndbox tag.')bndbox[option.tag] = int(option.text)# only after parse the <object> tagif bndbox['xmin'] is not None:if object_name is None:raise Exception('xml structure broken at bndbox tag')if current_image_id is None:raise Exception('xml structure broken at bndbox tag')if current_category_id is None:raise Exception('xml structure broken at bndbox tag')bbox = []# xbbox.append(bndbox['xmin'])# ybbox.append(bndbox['ymin'])# wbbox.append(bndbox['xmax'] - bndbox['xmin'])# hbbox.append(bndbox['ymax'] - bndbox['ymin'])print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,bbox))addAnnoItem(object_name, current_image_id, current_category_id, bbox)json.dump(coco, open(json_save_path, 'w'))if __name__ == '__main__':#通过txt文件生成# voc_data_dir="E:/VOCdevkit/VOC2007"# json_save_path="E:/VOCdevkit/voc2007trainval.json"# parseXmlFiles_by_txt(voc_data_dir,json_save_path,"trainval")#通过文件夹生成ann_path='/path/to/your/xml/folder'json_save_path="instances_val.json"parseXmlFiles(ann_path,json_save_path)

四、训练

1、创建配置文件

类似于YOLO,efficientdet也需要创建配置文件,直接复制projects文件夹的coco.yml并改名,并根据自己的数据集进行修改。

2、修改训练参数

3、训练

使用下方命令进行训练

python train.py


http://www.mrgr.cn/p/32085355

相关文章

实战指南:使用 xUnit 和 ASP.NET Core 进行集成测试【完整教程】

引言 集成测试可在包含应用支持基础结构(如数据库、文件系统和网络)的级别上确保应用组件功能正常。 ASP.NET Core 通过将单元测试框架与测试 Web 主机和内存中测试服务器结合使用来支持集成测试。 简介 集成测试与单元测试相比,能够在更广泛的级别上评估应用的组件,确认多…

ElasticSearch实战之项目搜索高亮

文章目录 1. 前情配置2、数据操作2.1 操作API2.2 数据入库 3. 高亮搜索3.1 方法封装3.2 高亮搜索 1. 前情配置 为满足ElasticSearch可在项目中实现搜索高亮&#xff0c;我们需要先做一些前情配置 导入ElasticSearch依赖 <dependency><groupId>org.springframewor…

OpenHarmony UI动画-recyclerview_animators

简介 带有添加删除动画效果以及整体动画效果的list组件库 下载安装 ohpm install ohos/recyclerview-animatorsOpenHarmony ohpm 环境配置等更多内容&#xff0c;请参考如何安装OpenHarmony ohpm 包 使用说明 引入组件库 import { RecyclerView } from "ohos/recycler…

AR地图导览小程序是怎么开发出来的?

在移动互联网时代&#xff0c;AR技术的发展为地图导览提供了全新的可能性。AR地图导览小程序结合了虚拟现实技术和地图导航功能&#xff0c;为用户提供了更加沉浸式、直观的导览体验。本文将从专业性和思考深度两个方面&#xff0c;探讨AR地图导览小程序的开发方案。 编辑搜图 …

【Linux驱动层】iTOP-RK3568学习之路(二):vscode中设置头文件路径-完成代码自动补全

在Ubuntu下用vscode写Linux驱动层的时候&#xff0c;需要添加头文件&#xff1a; #include<linux/module.h> #include<linux/init.h> #include<linux/kernel.h>但vscode没有智能提示&#xff0c;因此需要我们手动添加自己的头文件路径&#xff1a; topeetu…

算法部署 | 使用TensorRT在Jetson-Xavier-AGX上部署YOLOv4目标检测算法

项目应用场景 面向 NVIDIA Jetson Xavier AGX 平台部署 YOLOv4 目标检测算法场景&#xff0c;项目采用 TensorRT 进行 GPU 算法加速推理。 项目效果 项目细节 > 具体参见项目 README.md (1) 安装依赖 Install pycuda (takes awhile) $ cd ${HOME}/catkin_ws/src/yolov4_tr…

不需要GPU就可以玩转模型,同时支持本地化部署

简单一款不需要GPU就可以在Win 机器跑的模型&#xff1a;Ollama&#xff1b;用于本地运行和部署大型语言模型&#xff08;LLMs&#xff09;的开源工具 关于Ollama的简要介绍 平台兼容性&#xff1a;Ollama支持多种操作系统&#xff0c;包括macOS、Linux和Windows&#xff0c;…

【QT+OpenCV】车牌号检测 学习记录 遇到的问题

【QTOpenCV】车牌号检测 学习记录 首先在QT里面配置好OpenCV .pro文件中加入&#xff1a; INCLUDEPATH G:/opencv/build/include LIBS -L"G:/opencv/build/x64/vc14/lib"\-lopencv_core \-lopencv_imgproc \-lopencv_highgui \-lopencv_ml \-lopencv_video \-lo.c…

前端三大件速成 01 HTML

文章目录 一、前端基础知识二、标签1、什么是标签2、标签的属性3、常用标签&#xff08;1&#xff09;声明&#xff08;2&#xff09;注释&#xff08;3&#xff09;html 根标签&#xff08;3&#xff09;head标签&#xff08;4&#xff09;body标签 三、特殊字符四、其他标签1…

Nacos—配置管理

简介&#xff1a; Nacos是阿里巴巴开发的&#xff0c;它旨在帮助用户更敏捷和容易地构建、交付和管理微服务平台。Nacos的主要功能和特性包括&#xff1a; 动态服务发现。Nacos支持基于DNS和RPC的服务发现&#xff0c;允许服务提供者和消费者之间的高效交互。动态配置管理。…

Mac下brew安装php7.4

这里作者挂了梯子&#xff0c;所以很流畅&#xff01; brew的下载&#xff0c;可参考另外一篇博文&#xff5e;Homebrew 安装与卸载 1、将第三方仓库加入brew brew tap shivammathur/php2、安装指定版本的PHP brew install php7.43、替换Mac自带PHP环境并刷新环境变量 -> …

transformer架构详细详解

一、transformer的贡献 transformer架构的贡献&#xff1a;该架构只使用自注意力机制&#xff0c;没有使用RNN或卷积网络。且可以实现并行计算&#xff0c;加快模型训练速度。 &#xff08;将所有的循环层全部换成&#xff1a;multi-headed self-attention&#xff09; 二、t…

HTML5+JavaScript实现本地视频/音频播放器

HTML5JavaScript实现本地视频/音频播放器 HTML5 提供了本地视频和音频播放器的支持&#xff0c;通过 <video> 和 <audio> 标签&#xff0c;这些标签支持多种媒体格式&#xff0c;并且可以通过 JavaScript 进行控制&#xff0c;实现功能比较完整的本地视频音频播放器…

在 Linux 终端中创建目录

目录 ⛳️推荐 前言 在 Linux 中创建一个新目录 创建多个新目录 创建多个嵌套的子目录 测试你的知识 ⛳️推荐 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站 前言 在本系列的这一部…

Objective-C网络数据捕获:使用MWFeedParser库下载Stack Overflow示例

概述 Objective-C开发中&#xff0c;网络数据捕获是一项常见而关键的任务&#xff0c;特别是在处理像RSS源这样的实时网络数据流时。MWFeedParser库作为一个优秀的解析工具&#xff0c;提供了简洁而强大的解决方案。本文将深入介绍如何利用MWFeedParser库&#xff0c;以高效、…

读所罗门的密码笔记21_读后总结与感想兼导读

读所罗门的密码笔记21_读后总结与感想兼导读1. 基本信息 所罗门的密码:AI时代的价值、权力与信任 Solomons Code 奥拉夫格罗思 马克尼兹伯格 著 中信出版社,2022年5月出版 1.1. 读薄率 书籍总字数257千字,笔记总字数37780字。 读薄率37780257000≈14.7% 1.2. 读厚方向千脑智能…

浅写个登录(无js文件)

全部代码如下&#xff0c;无需编写wxss文件&#xff0c;渲染都在style里面&#xff1a; <view style"height: 250rpx;width: 100%;"> <!-- 背景图片 --><view style"position: absolute; background-color: antiquewhite; height: 250rpx;width…

遥感卫星:探索地球的科技之旅

遥感卫星是人类探索地球、理解地球、保护地球的重要工具&#xff0c;其发展历程承载了人类对地球的探索与认知的历程。从最初的概念到如今的高科技应用&#xff0c;遥感卫星技术的发展见证了人类科技的不断进步与创新。 初心萌芽&#xff1a; 遥感卫星的发展始于20世纪中叶&…

Linux debian gdb dump

1.开发背景 记录 debian 下应用程序崩溃调试方法 2.开发需求 程序越界可以定位到越界的位置附近 3.开发环境 debian 操作系统&#xff0c;如果不支持需要查看是否存在对应的可执行文件 4.实现步骤 4.1 设置 dump 输出大小 ulimit -c unlimited # 设置输出大小 生成core 文…

【opencv】dnn示例-speech_recognition.cpp 使用DNN模块结合音频信号处理技术实现的英文语音识别...

模型下载地址&#xff1a; https://drive.google.com/drive/folders/1wLtxyao4ItAg8tt4Sb63zt6qXzhcQoR6 终端输出&#xff1a;&#xff08;audio6.mp3 、audio10.mp3&#xff09; [ERROR:00.002] global cap_ffmpeg_impl.hpp:1112 open VIDEOIO/FFMPEG: unsupported parameter…