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()
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安装……
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
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
./tools/dist_train.sh ./configs/yolox/yolox_s_8x8_300e_coco.py 8
修改: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()
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
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
mmdetection/configs/base/default_runtime.py
打开下面注释:
终端:tensorboard --logdir=work_dirs/yolox_s_8x8_300e_coco/