Mmdetection custom dataset training bug

Hi all !
I am trying to train mmdetection with my custom dataset :
here is my config file :


# The new config inherits a base config to highlight the necessary modification
_base_ = 'mask_rcnn_x101_64x4d_fpn_mstrain-poly_3x_coco.py'

# We also need to change the num_classes in head to match the dataset's annotation
model = dict(
    roi_head=dict(
        bbox_head=dict(num_classes=1),
        mask_head=dict(num_classes=1)))

# Modify dataset related settings
dataset_type = 'COCODataset'
classes = ('foliole_0',)
data = dict(
    train=dict(
        img_prefix='dataset/train/',
        classes=classes,
        ann_file='dataset/train/via_region_data_coco.json'),
    val=dict(
        img_prefix='dataset/val/',
        classes=classes,
        ann_file='dataset/val/via_region_data_coco.json'),
    test=dict(
        img_prefix='dataset/val/',
        classes=classes,
        ann_file='dataset/val/via_region_data_coco.json'))

# We can use the pre-trained Mask RCNN model to obtain higher performance
#load_from = #'checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth'

and the error :

(openmmlab) C:\Users\MASTER\Dropbox\Documents Sylvain\travail avec Boubacar\mmdetection-master>python tools/train.py configs\mask_rcnn\custom.py
'gcc' n’est pas reconnu en tant que commande interne
ou externe, un programme exécutable ou un fichier de commandes.
fatal: not a git repository (or any of the parent directories): .git
2021-12-28 16:20:16,525 - mmdet - INFO - Environment info:
------------------------------------------------------------
sys.platform: win32
Python: 3.7.11 (default, Jul 27 2021, 09:42:29) [MSC v.1916 64 bit (AMD64)]
CUDA available: True
GPU 0: NVIDIA GeForce RTX 3090
CUDA_HOME: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1
NVCC: Build cuda_11.1.relgpu_drvr455TC455_06.29190527_0
GCC: n/a
PyTorch: 1.8.0
PyTorch compiling details: PyTorch built with:
  - C++ Version: 199711
  - MSVC 192829337
  - Intel(R) Math Kernel Library Version 2020.0.0 Product Build 20191125 for Intel(R) 64 architecture applications
  - Intel(R) MKL-DNN v1.7.0 (Git Hash 7aed236906b1f7a05c0917e5257a1af05e9ff683)
  - OpenMP 2019
  - CPU capability usage: AVX2
  - CUDA Runtime 11.1
  - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_61,code=sm_61;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_37,code=compute_37
  - CuDNN 8.0.5
  - Magma 2.5.4
  - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=11.1, CUDNN_VERSION=8.0.5, CXX_COMPILER=C:/cb/pytorch_1000000000000/work/tmp_bin/sccache-cl.exe, CXX_FLAGS=/DWIN32 /D_WINDOWS /GR /EHsc /w /bigobj -DUSE_PTHREADPOOL -openmp:experimental -DNDEBUG -DUSE_FBGEMM -DUSE_XNNPACK, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, TORCH_VERSION=1.8.0, USE_CUDA=ON, USE_CUDNN=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=OFF, USE_NNPACK=OFF, USE_OPENMP=ON,

TorchVision: 0.9.0
OpenCV: 4.5.4
MMCV: 1.4.2
MMCV Compiler: MSVC 192930133
MMCV CUDA Compiler: 11.1
MMDetection: 2.19.1+
------------------------------------------------------------

2021-12-28 16:20:16,714 - mmdet - INFO - Distributed training: False
2021-12-28 16:20:16,902 - mmdet - INFO - Config:
checkpoint_config = dict(interval=1)
log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
custom_hooks = [dict(type='NumClassCheckHook')]
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
dataset_type = 'COCODataset'
data_root = 'data/coco/'
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,
        with_mask=True,
        poly2mask=False),
    dict(
        type='Resize',
        img_scale=[(1333, 640), (1333, 800)],
        multiscale_mode='range',
        keep_ratio=True),
    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', 'gt_masks'])
]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=(1333, 800),
        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'])
        ])
]
data = dict(
    samples_per_gpu=2,
    workers_per_gpu=2,
    train=dict(
        type='RepeatDataset',
        times=3,
        dataset=dict(
            type='CocoDataset',
            ann_file='data/coco/annotations/instances_train2017.json',
            img_prefix='data/coco/train2017/',
            pipeline=[
                dict(type='LoadImageFromFile'),
                dict(
                    type='LoadAnnotations',
                    with_bbox=True,
                    with_mask=True,
                    poly2mask=False),
                dict(
                    type='Resize',
                    img_scale=[(1333, 640), (1333, 800)],
                    multiscale_mode='range',
                    keep_ratio=True),
                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', 'gt_masks'])
            ]),
        img_prefix='dataset/train/',
        classes=('foliole_0', ),
        ann_file='dataset/train/via_region_data_coco.json'),
    val=dict(
        type='CocoDataset',
        ann_file='dataset/val/via_region_data_coco.json',
        img_prefix='dataset/val/',
        pipeline=[
            dict(type='LoadImageFromFile'),
            dict(
                type='MultiScaleFlipAug',
                img_scale=(1333, 800),
                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'])
                ])
        ],
        classes=('foliole_0', )),
    test=dict(
        type='CocoDataset',
        ann_file='dataset/val/via_region_data_coco.json',
        img_prefix='dataset/val/',
        pipeline=[
            dict(type='LoadImageFromFile'),
            dict(
                type='MultiScaleFlipAug',
                img_scale=(1333, 800),
                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'])
                ])
        ],
        classes=('foliole_0', )))
evaluation = dict(interval=1, metric=['bbox', 'segm'])
optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
lr_config = dict(
    policy='step',
    warmup='linear',
    warmup_iters=500,
    warmup_ratio=0.001,
    step=[9, 11])
runner = dict(type='EpochBasedRunner', max_epochs=12)
model = dict(
    type='MaskRCNN',
    backbone=dict(
        type='ResNeXt',
        depth=101,
        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',
        init_cfg=dict(
            type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d'),
        groups=64,
        base_width=4),
    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=1,
            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)),
        mask_roi_extractor=dict(
            type='SingleRoIExtractor',
            roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0),
            out_channels=256,
            featmap_strides=[4, 8, 16, 32]),
        mask_head=dict(
            type='FCNMaskHead',
            num_convs=4,
            in_channels=256,
            conv_out_channels=256,
            num_classes=1,
            loss_mask=dict(
                type='CrossEntropyLoss', use_mask=True, 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=True,
                ignore_iof_thr=-1),
            sampler=dict(
                type='RandomSampler',
                num=512,
                pos_fraction=0.25,
                neg_pos_ub=-1,
                add_gt_as_proposals=True),
            mask_size=28,
            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,
            mask_thr_binary=0.5)))
classes = ('foliole_0', )
work_dir = './work_dirs\custom'
gpu_ids = range(0, 1)

2021-12-28 16:20:16,904 - mmdet - INFO - Set random seed to 335105629, deterministic: False
2021-12-28 16:20:17,458 - mmdet - INFO - initialize ResNeXt with init_cfg {'type': 'Pretrained', 'checkpoint': 'open-mmlab://resnext101_64x4d'}
2021-12-28 16:20:17,458 - mmcv - INFO - load model from: open-mmlab://resnext101_64x4d
2021-12-28 16:20:17,459 - mmcv - INFO - load checkpoint from openmmlab path: open-mmlab://resnext101_64x4d
2021-12-28 16:20:17,636 - mmdet - INFO - initialize FPN with init_cfg {'type': 'Xavier', 'layer': 'Conv2d', 'distribution': 'uniform'}
2021-12-28 16:20:17,648 - mmdet - INFO - initialize RPNHead with init_cfg {'type': 'Normal', 'layer': 'Conv2d', 'std': 0.01}
2021-12-28 16:20:17,651 - mmdet - INFO - initialize Shared2FCBBoxHead with init_cfg [{'type': 'Normal', 'std': 0.01, 'override': {'name': 'fc_cls'}}, {'type': 'Normal', 'std': 0.001, 'override': {'name': 'fc_reg'}}, {'type': 'Xavier', 'distribution': 'uniform', 'override': [{'name': 'shared_fcs'}, {'name': 'cls_fcs'}, {'name': 'reg_fcs'}]}]
loading annotations into memory...
Traceback (most recent call last):
  File "C:\Users\MASTER\.conda\envs\openmmlab\lib\site-packages\mmcv\utils\registry.py", line 52, in build_from_cfg
    return obj_cls(**args)
  File "C:\Users\MASTER\.conda\envs\openmmlab\lib\site-packages\mmdet\datasets\custom.py", line 92, in __init__
    self.data_infos = self.load_annotations(local_path)
  File "C:\Users\MASTER\.conda\envs\openmmlab\lib\site-packages\mmdet\datasets\coco.py", line 50, in load_annotations
    self.coco = COCO(ann_file)
  File "C:\Users\MASTER\.conda\envs\openmmlab\lib\site-packages\mmdet\datasets\api_wrappers\coco_api.py", line 23, in __init__
    super().__init__(annotation_file=annotation_file)
  File "C:\Users\MASTER\.conda\envs\openmmlab\lib\site-packages\pycocotools\coco.py", line 81, in __init__
    with open(annotation_file, 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data/coco/annotations/instances_train2017.json'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "tools/train.py", line 185, in <module>
    main()
  File "tools/train.py", line 161, in main
    datasets = [build_dataset(cfg.data.train)]
  File "C:\Users\MASTER\.conda\envs\openmmlab\lib\site-packages\mmdet\datasets\builder.py", line 69, in build_dataset
    build_dataset(cfg['dataset'], default_args), cfg['times'])
  File "C:\Users\MASTER\.conda\envs\openmmlab\lib\site-packages\mmdet\datasets\builder.py", line 81, in build_dataset
    dataset = build_from_cfg(cfg, DATASETS, default_args)
  File "C:\Users\MASTER\.conda\envs\openmmlab\lib\site-packages\mmcv\utils\registry.py", line 55, in build_from_cfg
    raise type(e)(f'{obj_cls.__name__}: {e}')
FileNotFoundError: CocoDataset: [Errno 2] No such file or directory: 'data/coco/annotations/instances_train2017.json'

(openmmlab) C:\Users\MASTER\Dropbox\Documents Sylvain\travail avec Boubacar\mmdetection-master>pause
Appuyez sur une touche pour continuer...

thank you for helping me !
Kind regards !

1 Like

the code is here : GitHub - open-mmlab/mmdetection: OpenMMLab Detection Toolbox and Benchmark

The error seems to be raised due to a missing file:

FileNotFoundError: [Errno 2] No such file or directory: 'data/coco/annotations/instances_train2017.json'

I know it is looking for ‘data/coco/annotations/instances_train2017.json’ but it shouldn’t because I told it to look in ‘dataset/trai /via_region_data_coco.json’! in my config file. Indeed it is a custom dataset and not the default coco dataset !

1 Like

In your config file you need to use this:

data = dict(
    train=dict(
        dataset=dict(
            img_prefix='dataset/train/',
            classes=classes,
            ann_file='dataset/train/via_region_data_coco.json')
    ),
    val=dict(
        img_prefix='dataset/val/',
        classes=classes,
        ann_file='dataset/val/via_region_data_coco.json'),
    test=dict(
        img_prefix='dataset/val/',
        classes=classes,
        ann_file='dataset/val/via_region_data_coco.json'))

There is an extra keyword called “dataset” inside the dict “train”.

The thing I learned from this error is that we have to search in the log-error for information, because in this case the log-error have such structure with the extra keyword “dataset”.