Repository: open-mmlab/mmdetection

Issue:
TypeError: argument of type 'NoneType' is not iterable
When I use my own datasets to train faster-rcnn,I meet this question,the following are environment infomation and logs:



sys.platform: linux
Python: 3.7.9 | packaged by conda-forge | (default, Dec  9 2020, 21:08:20) [GCC 9.3.0]
CUDA available: True
GPU 0,1,2,3,4,5,6,7: GeForce GTX 1080 Ti
CUDA_HOME: /usr/local/cuda
NVCC: Cuda compilation tools, release 10.2, V10.2.89
GCC: gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
PyTorch: 1.5.0
PyTorch compiling details: PyTorch built with:
  - GCC 7.3
  - C++ Version: 201402
  - Intel(R) Math Kernel Library Version 2020.0.2 Product Build 20200624 for Intel(R) 64 architecture applications
  - Intel(R) MKL-DNN v0.21.1 (Git Hash 7d2fd500bc78936d1d648ca713b901012f470dbc)
  - OpenMP 201511 (a.k.a. OpenMP 4.5)
  - NNPACK is enabled
  - CPU capability usage: AVX2
  - CUDA Runtime 10.2
  - 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_6
1;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_37,code=compute_37  - CuDNN 7.6.5
  - Magma 2.5.2
  - Build settings: BLAS=MKL, BUILD_TYPE=Release, CXX_FLAGS= -Wno-deprecated -fvisibility-inlines-hidden -fopenmp -DNDEBUG -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK
 -DUSE_XNNPACK -DUSE_INTERNAL_THREADPOOL_IMPL -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-unused-result -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, USE_CUDA=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=ON, USE_NNPACK=ON, USE_OPENMP=ON, USE_STATIC_DISPATCH=OFF, 
TorchVision: 0.6.0a0+82fd1c8
OpenCV: 4.4.0
MMCV: 1.2.4
MMCV Compiler: GCC 7.3
MMCV CUDA Compiler: 10.2
MMDetection: 2.8.0+
------------------------------------------------------------

2021-01-31 22:13:23,946 - mmdet - INFO - Distributed training: False
2021-01-31 22:13:26,538 - mmdet - INFO - Config:
model = dict(
    type='FasterRCNN',
    pretrained='torchvision://resnet50',
    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=232,
            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_across_levels=False,
            nms_pre=2000,
            nms_post=1000,
            max_num=1000,
            nms_thr=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_across_levels=False,
            nms_pre=1000,
            nms_post=1000,
            max_num=1000,
            nms_thr=0.7,
            min_bbox_size=0),
        rcnn=dict(
            score_thr=0.05,
            nms=dict(type='nms', iou_threshold=0.5),
            max_per_img=100)))
dataset_type = 'VOCDataset'
data_root = '/home/chengyuhong/mmdetection/data/tt100k_2021/'
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=(1000, 600), 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'])
]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=(1000, 600),
        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='VOCDataset',
            ann_file=[
                '/home/chengyuhong/mmdetection/data/tt100k_2021/VOC2007/ImageSets/Main/trainval.txt'
            ],
            img_prefix=[
                '/home/chengyuhong/mmdetection/data/tt100k_2021/VOC2007/'
            ],
            pipeline=[
                dict(type='LoadImageFromFile'),
                dict(type='LoadAnnotations', with_bbox=True),
                dict(type='Resize', img_scale=(1000, 600), 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'])
            ])),
    val=dict(
        type='VOCDataset',
        ann_file=
        '/home/chengyuhong/mmdetection/data/tt100k_2021/VOC2007/ImageSets/Main/test.txt',
        img_prefix='/home/chengyuhong/mmdetection/data/tt100k_2021/VOC2007/',
        pipeline=[
            dict(type='LoadImageFromFile'),
            dict(
                type='MultiScaleFlipAug',
                img_scale=(1000, 600),
                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='VOCDataset',
        ann_file=
        '/home/chengyuhong/mmdetection/data/tt100k_2021/VOC2007/ImageSets/Main/test.txt',
        img_prefix='/home/chengyuhong/mmdetection/data/tt100k_2021/VOC2007/',
        pipeline=[
            dict(type='LoadImageFromFile'),
            dict(
                type='MultiScaleFlipAug',
                img_scale=(1000, 600),
                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'])
                ])
        ]))
evaluation = dict(interval=1, metric='mAP')
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)]
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
lr_config = dict(policy='step', step=[3])
total_epochs = 4
work_dir = './work_dirs/faster_rcnn_r50_fpn_1x_voc0712'
gpu_ids = range(0, 1)

2021-01-31 22:13:27,410 - mmdet - INFO - load model from: torchvision://resnet50
2021-01-31 22:13:27,935 - mmdet - WARNING - The model and loaded state dict do not match exactly

unexpected key in source state_dict: fc.weight, fc.bias

Traceback (most recent call last):
  File "./tools/train.py", line 187, in <module>
    main()
  File "./tools/train.py", line 163, in main
    datasets = [build_dataset(cfg.data.train)]
  File "/home/chengyuhong/TT100K/mmdet/datasets/builder.py", line 64, in build_dataset
    build_dataset(cfg['dataset'], default_args), cfg['times'])
  File "/home/chengyuhong/TT100K/mmdet/datasets/builder.py", line 69, in build_dataset
    dataset = _concat_dataset(cfg, default_args)
  File "/home/chengyuhong/TT100K/mmdet/datasets/builder.py", line 48, in _concat_dataset
    datasets.append(build_dataset(data_cfg, default_args))
  File "/home/chengyuhong/TT100K/mmdet/datasets/builder.py", line 71, in build_dataset
    dataset = build_from_cfg(cfg, DATASETS, default_args)
  File "/home/chengyuhong/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/mmcv/utils/registry.py", line 171, in build_from_cfg
    return obj_cls(**args)
  File "/home/chengyuhong/TT100K/mmdet/datasets/voc.py", line 32, in __init__
    super(VOCDataset, self).__init__(**kwargs)
  File "/home/chengyuhong/TT100K/mmdet/datasets/xml_style.py", line 23, in __init__
    super(XMLDataset, self).__init__(**kwargs)
  File "/home/chengyuhong/TT100K/mmdet/datasets/custom.py", line 96, in __init__
    valid_inds = self._filter_imgs()
  File "/home/chengyuhong/TT100K/mmdet/datasets/xml_style.py", line 75, in _filter_imgs
    if name in self.CLASSES:
TypeError: argument of type 'NoneType' is not iterable




Discussion:

Resolving patch:
diff --git a/mmdet/datasets/xml_style.py b/mmdet/datasets/xml_style.py
--- a/mmdet/datasets/xml_style.py
+++ b/mmdet/datasets/xml_style.py
@@ -20,6 +20,8 @@ class XMLDataset(CustomDataset):
     """
 
     def __init__(self, min_size=None, **kwargs):
+        assert self.CLASSES or kwargs.get(
+            'classes', None), 'CLASSES in `XMLDataset` can not be None.'
         super(XMLDataset, self).__init__(**kwargs)
         self.cat2label = {cat: i for i, cat in enumerate(self.CLASSES)}
         self.min_size = min_size
@@ -43,8 +45,6 @@ def load_annotations(self, ann_file):
             tree = ET.parse(xml_path)
             root = tree.getroot()
             size = root.find('size')
-            width = 0
-            height = 0
             if size is not None:
                 width = int(size.find('width').text)
                 height = int(size.find('height').text)


Test patch:
diff --git a/tests/data/VOCdevkit/VOC2007/Annotations/000001.xml b/tests/data/VOCdevkit/VOC2007/Annotations/000001.xml
new file mode 100644
--- /dev/null
+++ b/tests/data/VOCdevkit/VOC2007/Annotations/000001.xml
@@ -0,0 +1,44 @@
+<annotation>
+	<folder>VOC2007</folder>
+	<filename>000001.jpg</filename>
+	<source>
+		<database>The VOC2007 Database</database>
+		<annotation>PASCAL VOC2007</annotation>
+		<image>flickr</image>
+		<flickrid>341012865</flickrid>
+	</source>
+	<owner>
+		<flickrid>Fried Camels</flickrid>
+		<name>Jinky the Fruit Bat</name>
+	</owner>
+	<size>
+		<width>353</width>
+		<height>500</height>
+		<depth>3</depth>
+	</size>
+	<segmented>0</segmented>
+	<object>
+		<name>dog</name>
+		<pose>Left</pose>
+		<truncated>1</truncated>
+		<difficult>0</difficult>
+		<bndbox>
+			<xmin>48</xmin>
+			<ymin>240</ymin>
+			<xmax>195</xmax>
+			<ymax>371</ymax>
+		</bndbox>
+	</object>
+	<object>
+		<name>person</name>
+		<pose>Left</pose>
+		<truncated>1</truncated>
+		<difficult>0</difficult>
+		<bndbox>
+			<xmin>8</xmin>
+			<ymin>12</ymin>
+			<xmax>352</xmax>
+			<ymax>498</ymax>
+		</bndbox>
+	</object>
+</annotation>
diff --git a/tests/data/VOCdevkit/VOC2007/ImageSets/Main/test.txt b/tests/data/VOCdevkit/VOC2007/ImageSets/Main/test.txt
new file mode 100644
--- /dev/null
+++ b/tests/data/VOCdevkit/VOC2007/ImageSets/Main/test.txt
@@ -0,0 +1 @@
+000001
diff --git a/tests/data/VOCdevkit/VOC2007/ImageSets/Main/trainval.txt b/tests/data/VOCdevkit/VOC2007/ImageSets/Main/trainval.txt
new file mode 100644
--- /dev/null
+++ b/tests/data/VOCdevkit/VOC2007/ImageSets/Main/trainval.txt
@@ -0,0 +1 @@
+000001
diff --git a/tests/data/VOCdevkit/VOC2007/JPEGImages/000001.jpg b/tests/data/VOCdevkit/VOC2007/JPEGImages/000001.jpg
new file mode 100644
Binary files /dev/null and b/tests/data/VOCdevkit/VOC2007/JPEGImages/000001.jpg differ
diff --git a/tests/data/VOCdevkit/VOC2012/Annotations/000001.xml b/tests/data/VOCdevkit/VOC2012/Annotations/000001.xml
new file mode 100644
--- /dev/null
+++ b/tests/data/VOCdevkit/VOC2012/Annotations/000001.xml
@@ -0,0 +1,32 @@
+<annotation>
+	<folder>VOC2007</folder>
+	<filename>000002.jpg</filename>
+	<source>
+		<database>The VOC2007 Database</database>
+		<annotation>PASCAL VOC2007</annotation>
+		<image>flickr</image>
+		<flickrid>329145082</flickrid>
+	</source>
+	<owner>
+		<flickrid>hiromori2</flickrid>
+		<name>Hiroyuki Mori</name>
+	</owner>
+	<size>
+		<width>335</width>
+		<height>500</height>
+		<depth>3</depth>
+	</size>
+	<segmented>0</segmented>
+	<object>
+		<name>train</name>
+		<pose>Unspecified</pose>
+		<truncated>0</truncated>
+		<difficult>0</difficult>
+		<bndbox>
+			<xmin>139</xmin>
+			<ymin>200</ymin>
+			<xmax>207</xmax>
+			<ymax>301</ymax>
+		</bndbox>
+	</object>
+</annotation>
diff --git a/tests/data/VOCdevkit/VOC2012/ImageSets/Main/test.txt b/tests/data/VOCdevkit/VOC2012/ImageSets/Main/test.txt
new file mode 100644
--- /dev/null
+++ b/tests/data/VOCdevkit/VOC2012/ImageSets/Main/test.txt
@@ -0,0 +1 @@
+000001
diff --git a/tests/data/VOCdevkit/VOC2012/ImageSets/Main/trainval.txt b/tests/data/VOCdevkit/VOC2012/ImageSets/Main/trainval.txt
new file mode 100644
--- /dev/null
+++ b/tests/data/VOCdevkit/VOC2012/ImageSets/Main/trainval.txt
@@ -0,0 +1 @@
+000001
diff --git a/tests/data/VOCdevkit/VOC2012/JPEGImages/000001.jpg b/tests/data/VOCdevkit/VOC2012/JPEGImages/000001.jpg
new file mode 100644
Binary files /dev/null and b/tests/data/VOCdevkit/VOC2012/JPEGImages/000001.jpg differ
diff --git a/tests/test_data/test_dataset.py b/tests/test_data/test_dataset.py
--- a/tests/test_data/test_dataset.py
+++ b/tests/test_data/test_dataset.py
@@ -1,6 +1,8 @@
 import bisect
+import copy
 import logging
 import math
+import os
 import os.path as osp
 import tempfile
 from collections import defaultdict
@@ -104,6 +106,41 @@ def _create_dummy_results():
     return [boxes]
 
 
+def test_xml_dataset():
+    dataconfig = {
+        'ann_file': 'data/VOCdevkit/VOC2007/ImageSets/Main/test.txt',
+        'img_prefix': 'data/VOCdevkit/VOC2007/',
+        'pipeline': [{
+            'type': 'LoadImageFromFile'
+        }]
+    }
+    XMLDataset = DATASETS.get('XMLDataset')
+
+    class XMLDatasetSubClass(XMLDataset):
+        CLASSES = None
+
+    # get_ann_info and _filter_imgs of XMLDataset
+    # would use self.CLASSES, we added CLASSES not NONE
+    with pytest.raises(AssertionError):
+        XMLDatasetSubClass(**dataconfig)
+
+
+@pytest.mark.parametrize('config_path',
+                         ['./configs/_base_/datasets/voc0712.py'])
+def test_dataset_init(config_path):
+    if not os.path.exists('./data'):
+        os.symlink('./tests/data', './data')
+    data_config = mmcv.Config.fromfile(config_path)
+    if 'data' not in data_config:
+        return
+    stage_names = ['train', 'val', 'test']
+    for stage_name in stage_names:
+        dataset_config = copy.deepcopy(data_config.data.get(stage_name))
+        dataset = build_dataset(dataset_config)
+        dataset[0]
+    os.unlink('./data')
+
+
 def test_dataset_evaluation():
     tmp_dir = tempfile.TemporaryDirectory()
     # create dummy data