EfficientDet 训练自己的数据集_efficientdet训练自己的数据-程序员宅基地

技术标签: python  深度学习  efficientDet  pytorch  json  

EfficientDet训练自己的数据集

项目安装

参考代码:https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch
安装及环境配置可参考作者介绍或者其他博客

数据准备

训练时需要将数据集转换为coco格式的数据集,本人使用的数据集为visdrone数据集,转换过程如下:txt->XML->coco.json

txt->XML

import os
from PIL import Image

# 把下面的路径改成你自己的路径即可
root_dir = "./VisDrone2019-DET-train/"
annotations_dir = root_dir+"annotations/"
image_dir = root_dir + "images/"
xml_dir = root_dir+"Annotations_XML/"
# 下面的类别也换成你自己数据类别,也可适用于其他的数据集转换
class_name = ['ignored regions','pedestrian','people','bicycle','car','van','truck','tricycle','awning-tricycle','bus','motor','others']

for filename in os.listdir(annotations_dir):
    fin = open(annotations_dir+filename, 'r')
    image_name = filename.split('.')[0]
    img = Image.open(image_dir+image_name+".jpg") # 若图像数据是“png”转换成“.png”即可
    xml_name = xml_dir+image_name+'.xml'
    with open(xml_name, 'w') as fout:
        fout.write('<annotation>'+'\n')
        
        fout.write('\t'+'<folder>VOC2007</folder>'+'\n')
        fout.write('\t'+'<filename>'+image_name+'.jpg'+'</filename>'+'\n')
        
        fout.write('\t'+'<source>'+'\n')
        fout.write('\t\t'+'<database>'+'VisDrone2018 Database'+'</database>'+'\n')
        fout.write('\t\t'+'<annotation>'+'VisDrone2018'+'</annotation>'+'\n')
        fout.write('\t\t'+'<image>'+'flickr'+'</image>'+'\n')
        fout.write('\t\t'+'<flickrid>'+'Unspecified'+'</flickrid>'+'\n')
        fout.write('\t'+'</source>'+'\n')
        
        fout.write('\t'+'<owner>'+'\n')
        fout.write('\t\t'+'<flickrid>'+'Haipeng Zhang'+'</flickrid>'+'\n')
        fout.write('\t\t'+'<name>'+'Haipeng Zhang'+'</name>'+'\n')
        fout.write('\t'+'</owner>'+'\n')
        
        fout.write('\t'+'<size>'+'\n')
        fout.write('\t\t'+'<width>'+str(img.size[0])+'</width>'+'\n')
        fout.write('\t\t'+'<height>'+str(img.size[1])+'</height>'+'\n')
        fout.write('\t\t'+'<depth>'+'3'+'</depth>'+'\n')
        fout.write('\t'+'</size>'+'\n')
        
        fout.write('\t'+'<segmented>'+'0'+'</segmented>'+'\n')

        for line in fin.readlines():
            line = line.split(',')
            fout.write('\t'+'<object>'+'\n')
            fout.write('\t\t'+'<name>'+class_name[int(line[5])]+'</name>'+'\n')
            fout.write('\t\t'+'<pose>'+'Unspecified'+'</pose>'+'\n')
            fout.write('\t\t'+'<truncated>'+line[6]+'</truncated>'+'\n')
            fout.write('\t\t'+'<difficult>'+str(int(line[7]))+'</difficult>'+'\n')
            fout.write('\t\t'+'<bndbox>'+'\n')
            fout.write('\t\t\t'+'<xmin>'+line[0]+'</xmin>'+'\n')
            fout.write('\t\t\t'+'<ymin>'+line[1]+'</ymin>'+'\n')
            # pay attention to this point!(0-based)
            fout.write('\t\t\t'+'<xmax>'+str(int(line[0])+int(line[2])-1)+'</xmax>'+'\n')
            fout.write('\t\t\t'+'<ymax>'+str(int(line[1])+int(line[3])-1)+'</ymax>'+'\n')
            fout.write('\t\t'+'</bndbox>'+'\n')
            fout.write('\t'+'</object>'+'\n')
             
        fin.close()
        fout.write('</annotation>')

XML->coco.json

    # coding=utf-8
import xml.etree.ElementTree as ET
import os
import json


voc_clses = ['aeroplane', 'bicycle', 'bird', 'boat',
    'bottle', 'bus', 'car', 'cat', 'chair',
    'cow', 'diningtable', 'dog', 'horse',
    'motorbike', 'person', 'pottedplant',
    'sheep', 'sofa', 'train', 'tvmonitor']


categories = []
for iind, cat in enumerate(voc_clses):
    cate = {
    }
    cate['supercategory'] = cat
    cate['name'] = cat
    cate['id'] = iind
    categories.append(cate)

def getimages(xmlname, id):
    sig_xml_box = []
    tree = ET.parse(xmlname)
    root = tree.getroot()
    images = {
    }
    for i in root:  # 遍历一级节点
        if i.tag == 'filename':
            file_name = i.text  # 0001.jpg
            # print('image name: ', file_name)
            images['file_name'] = file_name
        if i.tag == 'size':
            for j in i:
                if j.tag == 'width':
                    width = j.text
                    images['width'] = width
                if j.tag == 'height':
                    height = j.text
                    images['height'] = height
        if i.tag == 'object':
            for j in i:
                if j.tag == 'name':
                    cls_name = j.text
                cat_id = voc_clses.index(cls_name) + 1
                if j.tag == 'bndbox':
                    bbox = []
                    xmin = 0
                    ymin = 0
                    xmax = 0
                    ymax = 0
                    for r in j:
                        if r.tag == 'xmin':
                            xmin = eval(r.text)
                        if r.tag == 'ymin':
                            ymin = eval(r.text)
                        if r.tag == 'xmax':
                            xmax = eval(r.text)
                        if r.tag == 'ymax':
                            ymax = eval(r.text)
                    bbox.append(xmin)
                    bbox.append(ymin)
                    bbox.append(xmax - xmin)
                    bbox.append(ymax - ymin)
                    bbox.append(id)   # 保存当前box对应的image_id
                    bbox.append(cat_id)
                    # anno area
                    bbox.append((xmax - xmin) * (ymax - ymin) - 10.0)   # bbox的ares
                    # coco中的ares数值是 < w*h 的, 因为它其实是按segmentation的面积算的,所以我-10.0一下...
                    sig_xml_box.append(bbox)
                    # print('bbox', xmin, ymin, xmax - xmin, ymax - ymin, 'id', id, 'cls_id', cat_id)
    images['id'] = id
    # print ('sig_img_box', sig_xml_box)
    return images, sig_xml_box



def txt2list(txtfile):
    f = open(txtfile)
    l = []
    for line in f:
        l.append(line[:-1])
    return l


# voc2007xmls = 'anns'
voc2007xmls = '/data2/chenjia/data/VOCdevkit/VOC2007/Annotations'
# test_txt = 'voc2007/test.txt'
test_txt = '/data2/chenjia/data/VOCdevkit/VOC2007/ImageSets/Main/test.txt'
xml_names = txt2list(test_txt)
xmls = []
bboxes = []
ann_js = {
    }
for ind, xml_name in enumerate(xml_names):
    xmls.append(os.path.join(voc2007xmls, xml_name + '.xml'))
json_name = 'annotations/instances_voc2007val.json'
images = []
for i_index, xml_file in enumerate(xmls):
    image, sig_xml_bbox = getimages(xml_file, i_index)
    images.append(image)
    bboxes.extend(sig_xml_bbox)
ann_js['images'] = images
ann_js['categories'] = categories
annotations = []
for box_ind, box in enumerate(bboxes):
    anno = {
    }
    anno['image_id'] =  box[-3]
    anno['category_id'] = box[-2]
    anno['bbox'] = box[:-3]
    anno['id'] = box_ind
    anno['area'] = box[-1]
    anno['iscrowd'] = 0
    annotations.append(anno)
ann_js['annotations'] = annotations
json.dump(ann_js, open(json_name, 'w'), indent=4)  # indent=4 更加美观显示               

将生成的json及图片按照一下结构放置,注意修改json文件名称:

  • dadasets
    • visdrone2019
      • train2019
      • val2019
      • annotations
        • instances_train2019.json
        • instances_val2019.json

修改projects下coco.yml内容,按照自己的数据库情况修改

project_name: visdrone2019  # also the folder name of the dataset that under data_path folder
train_set: train2019
val_set: val2019
num_gpus: 1

# mean and std in RGB order, actually this part should remain unchanged as long as your dataset is similar to coco.
mean: [0.373, 0.378, 0.364]
std: [0.191, 0.182, 0.194]

# this is coco anchors, change it if necessary
anchors_scales: '[2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)]'
anchors_ratios: '[(1.0, 1.0), (1.4, 0.7), (0.7, 1.4)]'

# must match your dataset's category_id.
# category_id is one_indexed,
# for example, index of 'car' here is 2, while category_id of is 3
obj_list: ["pedestrian","people","bicycle","car","van","truck","tricycle","awning-tricycle","bus","motor"]

训练

python train.py -c 2 --batch_size 8 --lr 1e-5 --num_epochs 10
–load_weights /path/to/your/weights/efficientdet-d2.pth

提前下载model文件,放置在文件夹中,建议d0,d1,d2(大了显存会溢出),如出现显存溢出情况,调整batch_size大小。
在这里插入图片描述

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/gu891221/article/details/105783719

智能推荐

(防坑笔记)hadoop3.0 (一) 环境部署与伪分布式(hdfs)-程序员宅基地

文章浏览阅读1.3w次,点赞21次,收藏42次。防坑留名:为了避免以后自己遇到什么坑爹的东西,先留脚印给自己。这个hadoop呢,主要是可以让用户可以在不了解分布式底层细节的情况下,开发分布式程序,充分利用集群的威力进行高速运算和存储。这点比较厉害了。它主要是用来做数据分析,支持低端服务器集群(这点美滋滋- - ),先抓取大量数据,利用数据运算分析,获取日志,显示报表~~~~~;_hadoop3.0

编写求立方根函数double cube(double x);函数返回参数的立方根。中国海洋大学03-04年第二学期《C程序设计期中考试》第三题编程题的第三题_double cube(double x);-程序员宅基地

文章浏览阅读801次。题目本题是中国海洋大学03-04年第二学期《C程序设计期中考试》第三题编程题的第三题。题目:编写求立方根函数double cube(double x);函数返回参数的立方根。主函数如下:。main() { double cube(double x); double x; scanf("%lf", &x); printf("cube(%lf)=%lf\n", cube(x));}以下是本篇文章正文内容,欢迎朋友们进行指正,一起探讨,共同进步。——来自考研路上的lwj一、解题_double cube(double x);

和oscp相似的靶机-hackthebox & vulnhub (OSCP-LIKE HACKTHEBOX & VULNHUB)_lnhub hackthebox vulnstack vulntarget-程序员宅基地

文章浏览阅读2.9k次,点赞2次,收藏14次。每台都做一做,然后记录在博客里.供自己和大家一起学习._lnhub hackthebox vulnstack vulntarget

Debian 6 安装小记_linux pardus 6.1.0-17-amd64 #1 smp preempt_dynamic-程序员宅基地

文章浏览阅读1.1k次。Debian 6 安装小记07.31.2011 · Posted in LAMP上个月入手了mac,就把thinkpadr400冷落了蛮久。想着太浪费了,于是想着开始折腾系统。最开始是考虑unix中的freebsd, openbsd, netbsd,后来觉得还是回_linux pardus 6.1.0-17-amd64 #1 smp preempt_dynamic debian 6.1.69-1 (2023-12-

idea查看UML类图_idea社区版查看类图-程序员宅基地

文章浏览阅读1.5k次。idea查看UML类图_idea社区版查看类图

oj开发 第一周_oj 平台开发 比较-程序员宅基地

文章浏览阅读771次。自上周六至今天已经一个星期了,总结一下!这一阶段:周六、周日下组讨论暂时确定了需求,画出了思维导图和用例图;周四确定了需求,得出了可用的用例图,然后前后台开始了正式的工作。给前台培训了bootstarp 的基本用法,展示了liteoj前台的代码。然后前台开始画原型图。后台演示了django入门的四个part 也开始进入了django入门阶段。_oj 平台开发 比较

随便推点

宏定义中的可变参数 __VA_ARGS__ 用法 与 #和##的用法_##__va_args__-程序员宅基地

文章浏览阅读1.1k次,点赞2次,收藏3次。首先了解一下可变参数#include <stdio.h> #define DEBUG(fmt, ...) printf(fmt, __VA_ARGS__)int main(){ DEBUG("you know i am handsome%d,%f,%d", 1000, 1.1, 10); return 0;}输出:you know i am handsome1000,1.100000,10这里的__VA_ARGS__其实就是指代…三个省略号的内容了,这_##__va_args__

高德地图+echarts实现飞线图_import echartsamap from "echarts-amap";-程序员宅基地

文章浏览阅读9.3k次。下面是vue实现,原生html后续贴上来前期准备:引入amap、echarts、echarts-amap依赖,vue的话需要npm安装一下By using script tag<!--引入高德地图JSAPI --> <script src="//webapi.amap.com/maps?v=1.4.15&key=ab99f68b8f9eac7a5287f..._import echartsamap from "echarts-amap";

Flowable 6.6.0表单 - 1.配置 - 1.2 FormEngineConfiguration bean_form engine is not initialized-程序员宅基地

文章浏览阅读574次。The flowable.form.cfg.xml must contain a bean that has the id ‘formEngineConfiguration’.这个flowable.form.cfg.xml必须包含id为“formEngineConfiguration”的bean。 <bean id="formEngineConfiguration" class="org.flowable.form.engine.impl.cfg.StandaloneFormEngineConfi_form engine is not initialized

yocto依赖关系小结_yocto depends-程序员宅基地

文章浏览阅读4.6k次,点赞2次,收藏12次。首先说明,yocto中的依赖本质上是任务之间的依赖,即使是使用DEPENDS或者RDEPENDS定义的两个recipe之间的依赖关系,但实际上在yocto运行时依赖关系还是会体现在这两个recipe中的task之间,即在运行时,yocto会将recipe之间的依赖解析成task之间的依赖。task之间的依赖关系可以分为两种:属于同一个recipe的task之间的依赖或者属于不同recipe的ta..._yocto depends

亿级Web系统搭建:单机到分布式集群-程序员宅基地

文章浏览阅读162次。当一个Web系统从日访问量10万逐步增长到1000万,甚至超过1亿的过程中,Web系统承受的压力会越来越大,在这个过程中,我们会遇到很多的问题。为了解决这些性能压力带来问题,我们需要在Web系统架构层面搭建多个层次的缓存机制。在不同的压力阶段,我们会遇到不同的问题,通过搭建不同的服务和架构来解决。Web负载均衡Web负载均衡(Load Balan

计算机网络之IP篇_ip csdn-程序员宅基地

文章浏览阅读2.9k次,点赞38次,收藏53次。首先这是个 IPv4 地址,IPv4 地址有 32 位,一个字节有 8 位,共 4 个字节。其中 127 开头的都属于回环地址,也是 IPv4 的特殊地址,没什么道理,就是人为规定的。而 127.0.0.1 是众多回环地址的一个。之所以不是 127.0.0.2 ,而是 127.0.0.1 ,是因为源码里就是这个定义的,也没什么道理。_ip csdn

推荐文章

热门文章

相关标签