赞
踩
首先要准备一份xml配置的数据集,数据集打完标注文件如下:
ImageSets中暂为空,再执行【划分训练集、验证集和测试集】 ,划分后如下图:
再将xml格式数据集转为txt文件格式【数据集格式转换xml2txt】:
整合成最终数据集:
images是数据集的所有图片;labels是数据集的所有txt标签数据;train.txt是训练集的所有文件名;
数据集放在mm/datasets下, datasets与mmdetection-master代码同级:
这里是将数据集重新组织为 COCO 格式(JSON格式)。官网:在自定义数据集上进行训练.
整体结构
{
"images": [image],
"annotations": [annotation],
"categories": [category]
}
images
images是包含多个image实例的数组 下面是一个image实例:
{
"file_name": "文件名或文件路径",
"height": 360,
"width": 640,
"id": 1 # image id
}
annotations
annotations是包含多个annotation实例的数组 下面是一个annotation实例:
annotation{
"id": int, # 标注id
"image_id": int, # 图片文件id
"category_id": int, # 类别id
# "segmentation": RLE or [polygon], # iscrowded=0 polygon格式 iscrowded=1 RLE格式
"area": float, # 标注区域的面积
"bbox": [x, y, width, height], # bbox标注 xywh
# "iscrowd": 0 or 1, # iscrowd=0 单个的对象 iscrowd=1 一群对象(比如一群人)
}
categories
categories是包含多个categorie实例的数组 下面是一个categorie实例:
{
"id": int, # 类别id
"name": str, # 类别名
# "supercategory": str, # 类别父类 选填
}
【数据集格式转换txt2json】.用这个脚本将数据集格式从txt转为json格式(COCO格式)
转换后的数据集
imagesets到这一步往后其实没什么用了,可以删去也可以保留。
下面修改相关配置文件,这里以faster-rcnn为例:
faster_rcnn_r50_fpn_1x_pest.py
# Config # 1 model config model = dict( type='FasterRCNN', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), roi_head=dict( type='StandardRoIHead', bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=7, # modify 1: dataset class num bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0))), train_cfg=dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, debug=False), rpn_proposal=dict( nms_pre=2000, max_per_img=1000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, match_low_quality=False, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), pos_weight=-1, debug=False)), test_cfg=dict( rpn=dict( nms_pre=1000, max_per_img=1000, nms=dict(type='nms', iou_threshold=0.7), min_bbox_size=0), rcnn=dict( score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100))) # 2 pipeline config img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1280, 640), keep_ratio=True), # modify img max size and min size dict(type='RandomFlip', flip_ratio=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1280, 640), # modify by yourself img max size and min size flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] # 3 dataset config metainfo= { 'classes': (brown_spot', 'leaf_miner', 'paraleyrodes_pseudonaranjae_martin', 'papilio_polytes', 'chlorococcum', 'canker', 'dark_mildew',) } # modify 2: dataset classes data = dict( samples_per_gpu=2, # batch_size = samples_per_gpu*gpu_num workers_per_gpu=2, # numworks = workers_per_gpu*gpu_num train=dict( type='CocoDataset', # modify 3: dataset type classes=classes, # modify 2: dataset classes data_root='I:\Miniconda\datasets\pest', # modify 4: dataset root ann_file='train.json', # modify 5: dataset json annotation img_prefix='images', # modify 6 dataset image prefix pipeline=[ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1280, 640), keep_ratio=True), # modify 7: img max size and min size dict(type='RandomFlip', flip_ratio=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ]), val=dict( type='CocoDataset', # same with train classes=classes, # same with train data_root='I:\Miniconda\datasets\pest', # same with train ann_file='val.json', # same with train img_prefix='images', # same with train pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1280, 1280), # same with train flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ]), test=dict( type='CocoDataset', # same with train classes=classes, # same with train data_root='I:\Miniconda\datasets\pest', # same with train ann_file='test.json', # same with train img_prefix='images', # same with train pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1280, 1280), # same with train flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ])) # 4 other config # lr default 8 GPU = 0.02 1 GPU = 0.02/8 optimizer = dict(type='SGD', lr=0.02/8, momentum=0.9, weight_decay=0.0001) # modify 8: lr change optimizer_config = dict(grad_clip=None) lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[8, 11]) runner = dict(type='EpochBasedRunner', max_epochs=5) checkpoint_config = dict(interval=1) # save checkpoint per interval log_config = dict(interval=1, hooks=[dict(type='TextLoggerHook')]) # print log per 5 interval custom_hooks = [dict(type='NumClassCheckHook')] dist_params = dict(backend='nccl') log_level = 'INFO' load_from = "checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth" # 9: modify checkpoints root resume_from = None workflow = [('train', 1)] # train: python tools/train.py tests/test_train/faster_rcnn_r50_fpn_1x_pest.py --work-dir work_dir
注意:配置文件中不能有中文字符
文件目录:
单GPU训练指令:
python tools/train.py <config_file> --gpus <gpu_id> --work_dir <work_dir>
example:
python tools/train.py mycode/train_example/pest/faster_rcnn_r50_fpn_1x_pest.py --work-dir mycode/train_example/work_dir
多GPU训练指令:
tools/dist_train.sh <config_file> gpu_num --validate
example:
tools/dist_train.sh mycode/train_example/pest/faster_rcnn_r50_fpn_1x_pest.py 4 --validate
–validate: perform evaluation every k (default=1) epochs during the training.
如下图成功开始训练:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。