Mmdetection: yolox训练自己的VOC数据集

本次使用的mmdetection版本为:
在这里插入图片描述

1.数据集准备

VOC数据集格式
Annotations 存放所有xml标签,JPEGImages存放所有图像,ImageSet用来划分数据集。
在这里插入图片描述
xml文件命名为:图像名.xml 包含图像后缀,这里主要是因为数据集设计多种格式的图像,以图像文件名来直接划分到txt中,方便之后索引到相应的地址。xml内容示例:
在这里插入图片描述

在data目录下新建train_val.py:

import random
import os

trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'Annotations'
txtsavepath = r'ImageSets\Main'
total_xml = os.listdir(xmlfilepath)

num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)

ftrainval = open('ImageSets/Main/trainval.txt', 'w')
ftest = open('ImageSets/Main/test.txt', 'w')
ftrain = open('ImageSets/Main/train.txt', 'w')
fval = open('ImageSets/Main/val.txt', 'w')

for i in list:
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        ftrainval.write(name)
        if i in train:
            fval.write(name)
        else:
            ftest.write(name)
    else:
        ftrain.write(name)

ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

并执行,划分好的数据存在ImageSet/Main/ 下。
在这里插入图片描述

2.创建环境

conda create -n openmmlab python=3.6
conda activate openmmlab

根据自己的设备安装相应的pytorch,官网版本查询

conda install pytorch==1.7.0 torchvision==0.8.0 torchaudio==0.7.0 cudatoolkit=10.2 -c pytorch
pip install -U openmim
mim install mmcv-full
git clone https://github.com/open-mmlab/mmdetection.git
cd mmdetection
pip install -v -e .

过程中其余依赖项自己pip安装……

3.修改配置参数

mmdetection/mmdet/datasets/voc.py
设置自己的数据集class; 取消年份版本选择(我们的数据集没有按年份设置文件夹)

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

mmdetection/mmdet/core/evaluation/class_names.py
在这里插入图片描述
只有一个类别的话需要改mmdetection/mmdet/datasets/xml_style.py:
在这里插入图片描述

detect/mmdetection/configs/yolox/yolox_s_8x8_300e_coco.py
修改训练参数:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

detect/mmdetection/mmdet/datasets/pipelines/loading.py
这里是因为我们的图像后缀有jpg,JPG,png,bmp……所以在一开始创建数据txt时候就直接存了文件名,在这一步的时候把后面填充的.jpg去掉。
在这里插入图片描述

增加训练指标:
参考:MMdetection增加评估指标precision
mmdetection/mmdet/core/evaluation/mean_ap.py
在这里插入图片描述
在这里插入图片描述

4.训练

python ./tools/train.py ./configs/yolox/yolox_s_8x8_300e_coco.py 

训练后会在mmdetection/work_dirs/yolox_s_8x8_300e_coco/ 下生成训练结果
在这里插入图片描述
在这里插入图片描述
其中,yolox_s_8x8_300e_coco.py为训练模型的配置文件;20220705_155440.log 终端log文件;20220705_155440.log.json json版本,主要是之后可视化训练过程参数使用。

若中途中断训练,可接上次训练结果继续训练,或从之前某个epoch的模型直接开始训练:

python ./tools/train.py ./work_dirs/yolox_s_8x8_300e_coco/yolox_s_8x8_300e_coco.py --auto-resume 
python ./tools/train.py ./work_dirs/yolox_s_8x8_300e_coco/yolox_s_8x8_300e_coco.py --resume-from ./work_dirs/yolox_s_8x8_300e_coco/epoch_100.pth

在这里插入图片描述
在这里插入图片描述
多单机多卡训练(最后参数:[gpu_num]):

./tools/dist_train.sh ./configs/yolox/yolox_s_8x8_300e_coco.py 8

5.测试

修改:detect/mmdetection/mmdet/models/detectors/base.py
在这里插入图片描述
运行测试脚本,将test.txt中的图像拿来测试效果:image_test.py:

from argparse import ArgumentParser
import os
from mmdet.apis import inference_detector, init_detector 
import cv2

def show_result_pyplot(model, img, result, score_thr=0.3, fig_size=(15, 10)):
    """Visualize the detection results on the image.
    Args:
        model (nn.Module): The loaded detector.
        img (str or np.ndarray): Image filename or loaded image.
        result (tuple[list] or list): The detection result, can be either
            (bbox, segm) or just bbox.
        score_thr (float): The threshold to visualize the bboxes and masks.
        fig_size (tuple): Figure size of the pyplot figure.
    """
    if hasattr(model, 'module'):
        model = model.module
    img = model.show_result(img, result, score_thr=score_thr, show=False)
    return img

def main():
    # config文件
    config_file = '[path]/mmdetection/work_dirs/yolox_s_8x8_300e_coco/yolox_s_8x8_300e_coco.py'
    # 训练好的模型
    checkpoint_file = '[path]/mmdetection/work_dirs/yolox_s_8x8_300e_coco/epoch_100.pth'

    # model = init_detector(config_file, checkpoint_file)
    model = init_detector(config_file, checkpoint_file, device='cuda:0',)

    # 图片路径
    img_dir = '[path]/data/JPEGImages/'
    # 检测后存放图片路径
    out_dir = '[path]/mmdetection/work_dirs/yolox_s_8x8_300e_coco/images_test_result/'

    if not os.path.exists(out_dir):
        os.mkdir(out_dir)
    
    # 测试集的图片名称txt
    test_path = '[path]/data/ImageSets/Main/test.txt'
    fp = open(test_path, 'r')
    test_list = fp.readlines()
    count = 0
    for test in test_list:
        test = test.replace('\n', '')
        test2=test[:-4]
        name = img_dir + test + '.jpg'
    
        count += 1
        print('model is processing the {}/{} images.'.format(count, len(test_list)))
        result = inference_detector(model, name)
        img = show_result_pyplot(model, name, result)
        cv2.imwrite("{}/{}.jpg".format(out_dir, test2), img)

if __name__ == '__main__':
    main()

在这里插入图片描述
在这里插入图片描述

6.可视化

1.可视化训练过程参数:

python ./tools/analysis_tools/analyze_logs.py plot_curve ./work_dirs/yolox_s_8x8_300e_coco/20220705_155440.log.json --keys mAP  --out out2.jpg --eval-interval 10

在这里插入图片描述

python ./tools/analysis_tools/analyze_logs.py plot_curve ./work_dirs/yolox_s_8x8_300e_coco/20220705_155440.log.json --keys loss loss_cls loss_obj  --out out1.jpg

在这里插入图片描述

2.可视化数据增强处理流程的结果:

python ./tools/misc/browse_dataset.py  --output-dir ./work_dirs/yolox_s_8x8_300e_coco/vis_pipeline/ ./work_dirs/yolox_s_8x8_300e_coco/yolox_s_8x8_300e_coco.py 

在这里插入图片描述
在这里插入图片描述

3.开启tensorboard实时查看训练参数变化:

mmdetection/configs/base/default_runtime.py
打开下面注释:
在这里插入图片描述
终端:tensorboard --logdir=work_dirs/yolox_s_8x8_300e_coco/
在这里插入图片描述
在这里插入图片描述

  • 9
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小屋*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值