diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_instance.py b/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..57f657aa67f34830515f410425eccc96cb065af4 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_instance.py @@ -0,0 +1,53 @@ +# dataset settings +dataset_type = 'ADE20KInstanceDataset' +data_root = 'data/ADEChallengeData2016/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/ADEChallengeData2016/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2560, 640), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='ade20k_instance_val.json', + data_prefix=dict(img='images/validation'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'ade20k_instance_val.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_panoptic.py b/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..7be5ddd7f0732193f4f92bc49e52493602928162 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_panoptic.py @@ -0,0 +1,38 @@ +# dataset settings +dataset_type = 'ADE20KPanopticDataset' +data_root = 'data/ADEChallengeData2016/' + +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2560, 640), keep_ratio=True), + dict(type='LoadPanopticAnnotations', backend_args=backend_args), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=0, + persistent_workers=False, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='ade20k_panoptic_val.json', + data_prefix=dict(img='images/validation/', seg='ade20k_panoptic_val/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoPanopticMetric', + ann_file=data_root + 'ade20k_panoptic_val.json', + seg_prefix=data_root + 'ade20k_panoptic_val/', + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_semantic.py b/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..522a775704182ededaa36f318cd1eb185784918f --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/ade20k_semantic.py @@ -0,0 +1,48 @@ +dataset_type = 'ADE20KSegDataset' +data_root = 'data/ADEChallengeData2016/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/ADEChallengeData2016/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2048, 512), keep_ratio=True), + dict( + type='LoadAnnotations', + with_bbox=False, + with_mask=False, + with_seg=True, + reduce_zero_label=True), + dict( + type='PackDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='images/validation', + seg_map_path='annotations/validation'), + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +val_evaluator = dict(type='SemSegMetric', iou_metrics=['mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/cityscapes_detection.py b/mmdet_code/SR-TOD/configs/_base_/datasets/cityscapes_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..caeba6bfcd26d8954fc9d499446e93323e372959 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/cityscapes_detection.py @@ -0,0 +1,84 @@ +# dataset settings +dataset_type = 'CityscapesDataset' +data_root = 'data/cityscapes/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/segmentation/cityscapes/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/segmentation/', +# 'data/': 's3://openmmlab/datasets/segmentation/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomResize', + scale=[(2048, 800), (2048, 1024)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2048, 1024), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=8, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instancesonly_filtered_gtFine_train.json', + data_prefix=dict(img='leftImg8bit/train/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instancesonly_filtered_gtFine_val.json', + data_prefix=dict(img='leftImg8bit/val/'), + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instancesonly_filtered_gtFine_val.json', + metric='bbox', + backend_args=backend_args) + +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/cityscapes_instance.py b/mmdet_code/SR-TOD/configs/_base_/datasets/cityscapes_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..136403136c67a6726662832b66f56701ff5aba8a --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/cityscapes_instance.py @@ -0,0 +1,113 @@ +# dataset settings +dataset_type = 'CityscapesDataset' +data_root = 'data/cityscapes/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/segmentation/cityscapes/' + +# Method 2: Use backend_args, file_client_args in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/segmentation/', +# 'data/': 's3://openmmlab/datasets/segmentation/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', + scale=[(2048, 800), (2048, 1024)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2048, 1024), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=8, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instancesonly_filtered_gtFine_train.json', + data_prefix=dict(img='leftImg8bit/train/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instancesonly_filtered_gtFine_val.json', + data_prefix=dict(img='leftImg8bit/val/'), + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = [ + dict( + type='CocoMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + metric=['bbox', 'segm'], + backend_args=backend_args), + dict( + type='CityScapesMetric', + seg_prefix=data_root + 'gtFine/val', + outfile_prefix='./work_dirs/cityscapes_metric/instance', + backend_args=backend_args) +] + +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file='annotations/instancesonly_filtered_gtFine_test.json', +# data_prefix=dict(img='leftImg8bit/test/'), +# test_mode=True, +# filter_cfg=dict(filter_empty_gt=True, min_size=32), +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CityScapesMetric', +# format_only=True, +# outfile_prefix='./work_dirs/cityscapes_metric/test') diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_caption.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_caption.py new file mode 100644 index 0000000000000000000000000000000000000000..a1bd898313927e4fca336dfa10f05e78b9fb7162 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_caption.py @@ -0,0 +1,60 @@ +# data settings + +dataset_type = 'CocoCaptionDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +test_pipeline = [ + dict( + type='LoadImageFromFile', + imdecode_backend='pillow', + backend_args=backend_args), + dict( + type='Resize', + scale=(224, 224), + interpolation='bicubic', + backend='pillow'), + dict(type='PackInputs', meta_keys=['image_id']), +] + +# ann_file download from +# train dataset: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_train.json # noqa +# val dataset: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val.json # noqa +# test dataset: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test.json # noqa +# val evaluator: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val_gt.json # noqa +# test evaluator: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test_gt.json # noqa +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/coco_karpathy_val.json', + pipeline=test_pipeline, + )) + +val_evaluator = dict( + type='COCOCaptionMetric', + ann_file=data_root + 'annotations/coco_karpathy_val_gt.json', +) + +# # If you want standard test, please manually configure the test dataset +test_dataloader = val_dataloader +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_aitod.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_aitod.py new file mode 100644 index 0000000000000000000000000000000000000000..a6cdf3e69534512bb18ed70d2b1ad7cceb59a520 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_aitod.py @@ -0,0 +1,96 @@ +# dataset settings +dataset_type = 'AITODDataset' +data_root = '/root/nas-resource-linkdata/AI-TOD/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(800, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(800, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'annotations/aitod_trainval_v1.json', + data_prefix=dict(img='trainval/images/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'annotations/aitod_test_v1.json', + data_prefix=dict(img='test/images/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + #type='CocoMetric', + type='AITODMetric', + ann_file=data_root + 'annotations/aitod_test_v1.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoMetric', +# metric='bbox', +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_detection/test') diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_dota.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_dota.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec10024ab7bba149e435997af054982074c78ee --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_dota.py @@ -0,0 +1,96 @@ +# dataset settings +dataset_type = 'DOTADataset' +data_root = "/root/nas-resource-tju/Dataset/DOTA/DOTA_split/" + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1024, 1024), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1024, 1024), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'train/DOTA_train1024.json', + data_prefix=dict(img='train/images/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'val/DOTA_val1024.json', + data_prefix=dict(img='val/images/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + #type='CocoMetric', + type='AITODMetric', + ann_file=data_root + 'val/DOTA_val1024.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoMetric', +# metric='bbox', +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_detection/test') diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_drones.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_drones.py new file mode 100644 index 0000000000000000000000000000000000000000..dab6348aa279354b4e4289434b5c6c44dd8b2c10 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_drones.py @@ -0,0 +1,96 @@ +# dataset settings +dataset_type = 'DronesDataset' +data_root = '/root/nas-public-linkdata/dataset/Drones/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1920, 1080), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1920, 1080), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'train/train.json', + data_prefix=dict(img='train/JPEGImages/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'test/test.json', + data_prefix=dict(img='test/JPEGImages/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + #type='CocoMetric', + type='AITODMetric', + ann_file=data_root + 'test/test.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoMetric', +# metric='bbox', +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_detection/test') diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_visdrone.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_visdrone.py new file mode 100644 index 0000000000000000000000000000000000000000..458c01cc050e66439d592e63afe3596f26db9604 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_detection_visdrone.py @@ -0,0 +1,96 @@ +# dataset settings +dataset_type = 'VisDroneDataset' +data_root = '/root/nas-resource-linkdata/VisDrone-DET2019/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1280, 1280), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1280, 1280), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'VisDrone2019-DET-train/visdrone_train_coco.json', + data_prefix=dict(img='VisDrone2019-DET-train/images/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'VisDrone2019-DET-val/visdrone_val_coco.json', + data_prefix=dict(img='VisDrone2019-DET-val/images/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + #type='CocoMetric', + type='AITODMetric', + ann_file=data_root + 'VisDrone2019-DET-val/visdrone_val_coco.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoMetric', +# metric='bbox', +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_detection/test') diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_instance.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..e91cb354038db4df3b990b307a5da9d77f341a88 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_instance.py @@ -0,0 +1,95 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoMetric', +# metric=['bbox', 'segm'], +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_instance/test') diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_instance_semantic.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_instance_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..cc961863306690c056e564b542d518c0ebfbb7e2 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_instance_semantic.py @@ -0,0 +1,78 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict( + type='LoadAnnotations', with_bbox=True, with_mask=True, with_seg=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict( + type='LoadAnnotations', with_bbox=True, with_mask=True, with_seg=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/', seg='stuffthingmaps/train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_panoptic.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..0b95b619e68ed531d361bbd11a2382852c13446e --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_panoptic.py @@ -0,0 +1,94 @@ +# dataset settings +dataset_type = 'CocoPanopticDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadPanopticAnnotations', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadPanopticAnnotations', backend_args=backend_args), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/panoptic_train2017.json', + data_prefix=dict( + img='train2017/', seg='annotations/panoptic_train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/panoptic_val2017.json', + data_prefix=dict(img='val2017/', seg='annotations/panoptic_val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoPanopticMetric', + ann_file=data_root + 'annotations/panoptic_val2017.json', + seg_prefix=data_root + 'annotations/panoptic_val2017/', + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=1, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file='annotations/panoptic_image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoPanopticMetric', +# format_only=True, +# ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_panoptic/test') diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/coco_semantic.py b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..944bbbaeaeb6f10f0946bd1fc828bb01ea6c1fc3 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/coco_semantic.py @@ -0,0 +1,78 @@ +# dataset settings +dataset_type = 'CocoSegDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict( + type='LoadAnnotations', + with_bbox=False, + with_label=False, + with_seg=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_bbox=False, + with_label=False, + with_seg=True), + dict( + type='PackDetInputs', + meta_keys=('img_path', 'ori_shape', 'img_shape', 'scale_factor')) +] + +# For stuffthingmaps_semseg, please refer to +# `docs/en/user_guides/dataset_prepare.md` +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='train2017/', + seg_map_path='stuffthingmaps_semseg/train2017/'), + pipeline=train_pipeline)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='val2017/', + seg_map_path='stuffthingmaps_semseg/val2017/'), + pipeline=test_pipeline)) + +test_dataloader = val_dataloader + +val_evaluator = dict(type='SemSegMetric', iou_metrics=['mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/deepfashion.py b/mmdet_code/SR-TOD/configs/_base_/datasets/deepfashion.py new file mode 100644 index 0000000000000000000000000000000000000000..a93dc7152f7a2e28ab726c79f9398a1034b7b4a1 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/deepfashion.py @@ -0,0 +1,95 @@ +# dataset settings +dataset_type = 'DeepFashionDataset' +data_root = 'data/DeepFashion/In-shop/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='Resize', scale=(750, 1101), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(750, 1101), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=2, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='Anno/segmentation/DeepFashion_segmentation_train.json', + data_prefix=dict(img='Img/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='Anno/segmentation/DeepFashion_segmentation_query.json', + data_prefix=dict(img='Img/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='Anno/segmentation/DeepFashion_segmentation_gallery.json', + data_prefix=dict(img='Img/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + + 'Anno/segmentation/DeepFashion_segmentation_query.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = dict( + type='CocoMetric', + ann_file=data_root + + 'Anno/segmentation/DeepFashion_segmentation_gallery.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/dsdl.py b/mmdet_code/SR-TOD/configs/_base_/datasets/dsdl.py new file mode 100644 index 0000000000000000000000000000000000000000..1f19e5e498b18a404f3c4e6419316b5f9981e811 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/dsdl.py @@ -0,0 +1,62 @@ +dataset_type = 'DSDLDetDataset' +data_root = 'path to dataset folder' +train_ann = 'path to train yaml file' +val_ann = 'path to val yaml file' + +backend_args = None +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': "s3://open_data/", +# 'data/': "s3://open_data/" +# })) + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'instances')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=train_ann, + filter_cfg=dict(filter_empty_gt=True, min_size=32, bbox_min_size=32), + pipeline=train_pipeline)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=val_ann, + test_mode=True, + pipeline=test_pipeline)) + +test_dataloader = val_dataloader + +val_evaluator = dict(type='CocoMetric', metric='bbox') +# val_evaluator = dict(type='VOCMetric', metric='mAP', eval_mode='11points') +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/isaid_instance.py b/mmdet_code/SR-TOD/configs/_base_/datasets/isaid_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..09ddcab02bdd52374d5093d446abb0e34751f7a3 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/isaid_instance.py @@ -0,0 +1,59 @@ +# dataset settings +dataset_type = 'iSAIDDataset' +data_root = 'data/iSAID/' +backend_args = None + +# Please see `projects/iSAID/README.md` for data preparation +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='Resize', scale=(800, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(800, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='train/instancesonly_filtered_train.json', + data_prefix=dict(img='train/images/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='val/instancesonly_filtered_val.json', + data_prefix=dict(img='val/images/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'val/instancesonly_filtered_val.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/lvis_v0.5_instance.py b/mmdet_code/SR-TOD/configs/_base_/datasets/lvis_v0.5_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ca44efb6d31aae5f6426a1c8b89d2e9be2104f --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/lvis_v0.5_instance.py @@ -0,0 +1,79 @@ +# dataset settings +dataset_type = 'LVISV05Dataset' +data_root = 'data/lvis_v0.5/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/lvis_v0.5/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomChoiceResize', + scales=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='ClassBalancedDataset', + oversample_thr=1e-3, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/lvis_v0.5_train.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/lvis_v0.5_val.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='LVISMetric', + ann_file=data_root + 'annotations/lvis_v0.5_val.json', + metric=['bbox', 'segm'], + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/lvis_v1_instance.py b/mmdet_code/SR-TOD/configs/_base_/datasets/lvis_v1_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..0413f370a2b635362a60c20881769064bac9a603 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/lvis_v1_instance.py @@ -0,0 +1,22 @@ +# dataset settings +_base_ = 'lvis_v0.5_instance.py' +dataset_type = 'LVISV1Dataset' +data_root = 'data/lvis_v1/' + +train_dataloader = dict( + dataset=dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/lvis_v1_train.json', + data_prefix=dict(img='')))) +val_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/lvis_v1_val.json', + data_prefix=dict(img=''))) +test_dataloader = val_dataloader + +val_evaluator = dict(ann_file=data_root + 'annotations/lvis_v1_val.json') +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge.py b/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge.py new file mode 100644 index 0000000000000000000000000000000000000000..ce2828ef70a34c123792d252bf992f423049d065 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge.py @@ -0,0 +1,90 @@ +# dataset settings +dataset_type = 'MOTChallengeDataset' +data_root = 'data/MOT17/' +img_scale = (1088, 1088) + +backend_args = None +# data pipeline +train_pipeline = [ + dict( + type='UniformRefFrameSample', + num_ref_imgs=1, + frame_range=10, + filter_key_img=True), + dict( + type='TransformBroadcaster', + share_random_params=True, + transforms=[ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadTrackAnnotations'), + dict( + type='RandomResize', + scale=img_scale, + ratio_range=(0.8, 1.2), + keep_ratio=True, + clip_object_border=False), + dict(type='PhotoMetricDistortion') + ]), + dict( + type='TransformBroadcaster', + # different cropped positions for different frames + share_random_params=False, + transforms=[ + dict( + type='RandomCrop', crop_size=img_scale, bbox_clip_border=False) + ]), + dict( + type='TransformBroadcaster', + share_random_params=True, + transforms=[ + dict(type='RandomFlip', prob=0.5), + ]), + dict(type='PackTrackInputs') +] + +test_pipeline = [ + dict( + type='TransformBroadcaster', + transforms=[ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=img_scale, keep_ratio=True), + dict(type='LoadTrackAnnotations') + ]), + dict(type='PackTrackInputs') +] + +# dataloader +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='TrackImgSampler'), # image-based sampling + dataset=dict( + type=dataset_type, + data_root=data_root, + visibility_thr=-1, + ann_file='annotations/half-train_cocoformat.json', + data_prefix=dict(img_path='train'), + metainfo=dict(classes=('pedestrian', )), + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + # Now we support two ways to test, image_based and video_based + # if you want to use video_based sampling, you can use as follows + # sampler=dict(type='DefaultSampler', shuffle=False, round_up=False), + sampler=dict(type='TrackImgSampler'), # image-based sampling + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/half-val_cocoformat.json', + data_prefix=dict(img_path='train'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# evaluator +val_evaluator = dict( + type='MOTChallengeMetric', metric=['HOTA', 'CLEAR', 'Identity']) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge_det.py b/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge_det.py new file mode 100644 index 0000000000000000000000000000000000000000..a988572c3837eb2a8a6bf7b9eca06f3d82abdfda --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge_det.py @@ -0,0 +1,66 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/MOT17/' + +backend_args = None +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args, to_float32=True), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomResize', + scale=(1088, 1088), + ratio_range=(0.8, 1.2), + keep_ratio=True, + clip_object_border=False), + dict(type='PhotoMetricDistortion'), + dict(type='RandomCrop', crop_size=(1088, 1088), bbox_clip_border=False), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1088, 1088), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/half-train_cocoformat.json', + data_prefix=dict(img='train/'), + metainfo=dict(classes=('pedestrian', )), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/half-val_cocoformat.json', + data_prefix=dict(img='train/'), + metainfo=dict(classes=('pedestrian', )), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/half-val_cocoformat.json', + metric='bbox', + format_only=False) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge_reid.py b/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge_reid.py new file mode 100644 index 0000000000000000000000000000000000000000..57a95b531f3591e60daaabc5eea6f11c7424215b --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/mot_challenge_reid.py @@ -0,0 +1,61 @@ +# dataset settings +dataset_type = 'ReIDDataset' +data_root = 'data/MOT17/' + +backend_args = None +# data pipeline +train_pipeline = [ + dict( + type='TransformBroadcaster', + share_random_params=False, + transforms=[ + dict( + type='LoadImageFromFile', + backend_args=backend_args, + to_float32=True), + dict( + type='Resize', + scale=(128, 256), + keep_ratio=False, + clip_object_border=False), + dict(type='RandomFlip', prob=0.5, direction='horizontal'), + ]), + dict(type='PackReIDInputs', meta_keys=('flip', 'flip_direction')) +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args, to_float32=True), + dict(type='Resize', scale=(128, 256), keep_ratio=False), + dict(type='PackReIDInputs') +] + +# dataloader +train_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + dataset=dict( + type=dataset_type, + data_root=data_root, + triplet_sampler=dict(num_ids=8, ins_per_id=4), + data_prefix=dict(img_path='reid/imgs'), + ann_file='reid/meta/train_80.txt', + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + triplet_sampler=None, + data_prefix=dict(img_path='reid/imgs'), + ann_file='reid/meta/val_20.txt', + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# evaluator +val_evaluator = dict(type='ReIDMetrics', metric=['mAP', 'CMC']) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/objects365v1_detection.py b/mmdet_code/SR-TOD/configs/_base_/datasets/objects365v1_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..ee398698608543e13188452a816283e9a2563390 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/objects365v1_detection.py @@ -0,0 +1,74 @@ +# dataset settings +dataset_type = 'Objects365V1Dataset' +data_root = 'data/Objects365/Obj365_v1/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/objects365_train.json', + data_prefix=dict(img='train/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/objects365_val.json', + data_prefix=dict(img='val/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/objects365_val.json', + metric='bbox', + sort_categories=True, + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/objects365v2_detection.py b/mmdet_code/SR-TOD/configs/_base_/datasets/objects365v2_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..b25a7ba901befa8d61e3cdae8a7c68fb8a9c5aef --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/objects365v2_detection.py @@ -0,0 +1,73 @@ +# dataset settings +dataset_type = 'Objects365V2Dataset' +data_root = 'data/Objects365/Obj365_v2/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/zhiyuan_objv2_train.json', + data_prefix=dict(img='train/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/zhiyuan_objv2_val.json', + data_prefix=dict(img='val/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/zhiyuan_objv2_val.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/openimages_detection.py b/mmdet_code/SR-TOD/configs/_base_/datasets/openimages_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..129661b405c70d3e2d0d2c4741e3a59333dd960c --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/openimages_detection.py @@ -0,0 +1,81 @@ +# dataset settings +dataset_type = 'OpenImagesDataset' +data_root = 'data/OpenImages/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1024, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1024, 800), keep_ratio=True), + # avoid bboxes being resized + dict(type='LoadAnnotations', with_bbox=True), + # TODO: find a better way to collect image_level_labels + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'instances', 'image_level_labels')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=0, # workers_per_gpu > 0 may occur out of memory + persistent_workers=False, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/oidv6-train-annotations-bbox.csv', + data_prefix=dict(img='OpenImages/train/'), + label_file='annotations/class-descriptions-boxable.csv', + hierarchy_file='annotations/bbox_labels_600_hierarchy.json', + meta_file='annotations/train-image-metas.pkl', + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=0, + persistent_workers=False, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/validation-annotations-bbox.csv', + data_prefix=dict(img='OpenImages/validation/'), + label_file='annotations/class-descriptions-boxable.csv', + hierarchy_file='annotations/bbox_labels_600_hierarchy.json', + meta_file='annotations/validation-image-metas.pkl', + image_level_ann_file='annotations/validation-' + 'annotations-human-imagelabels-boxable.csv', + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='OpenImagesMetric', + iou_thrs=0.5, + ioa_thrs=0.5, + use_group_of=True, + get_supercategory=True) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/refcoco+.py b/mmdet_code/SR-TOD/configs/_base_/datasets/refcoco+.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0278ddf6c30fda6e4fb42aed1cb1b9a55109ec --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/refcoco+.py @@ -0,0 +1,55 @@ +# dataset settings +dataset_type = 'RefCocoDataset' +data_root = 'data/coco/' + +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_mask=True, + with_bbox=False, + with_seg=False, + with_label=False), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'gt_masks', 'text')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcoco+/instances.json', + split_file='refcoco+/refs(unc).p', + split='val', + text_mode='select_first', + pipeline=test_pipeline)) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcoco+/instances.json', + split_file='refcoco+/refs(unc).p', + split='testA', # or 'testB' + text_mode='select_first', + pipeline=test_pipeline)) + +val_evaluator = dict(type='RefSegMetric', metric=['cIoU', 'mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/refcoco.py b/mmdet_code/SR-TOD/configs/_base_/datasets/refcoco.py new file mode 100644 index 0000000000000000000000000000000000000000..7b6caefa9a4bbfabdb49689588821f99d882a80f --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/refcoco.py @@ -0,0 +1,55 @@ +# dataset settings +dataset_type = 'RefCocoDataset' +data_root = 'data/coco/' + +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_mask=True, + with_bbox=False, + with_seg=False, + with_label=False), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'gt_masks', 'text')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcoco/instances.json', + split_file='refcoco/refs(unc).p', + split='val', + text_mode='select_first', + pipeline=test_pipeline)) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcoco/instances.json', + split_file='refcoco/refs(unc).p', + split='testA', # or 'testB' + text_mode='select_first', + pipeline=test_pipeline)) + +val_evaluator = dict(type='RefSegMetric', metric=['cIoU', 'mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/refcocog.py b/mmdet_code/SR-TOD/configs/_base_/datasets/refcocog.py new file mode 100644 index 0000000000000000000000000000000000000000..19dbeef1cde79fcb2aa80bb9936a60cc30089963 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/refcocog.py @@ -0,0 +1,55 @@ +# dataset settings +dataset_type = 'RefCocoDataset' +data_root = 'data/coco/' + +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_mask=True, + with_bbox=False, + with_seg=False, + with_label=False), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'gt_masks', 'text')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcocog/instances.json', + split_file='refcocog/refs(umd).p', + split='val', + text_mode='select_first', + pipeline=test_pipeline)) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcocog/instances.json', + split_file='refcocog/refs(umd).p', + split='test', + text_mode='select_first', + pipeline=test_pipeline)) + +val_evaluator = dict(type='RefSegMetric', metric=['cIoU', 'mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/semi_coco_detection.py b/mmdet_code/SR-TOD/configs/_base_/datasets/semi_coco_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..694f25f841e06dbb59a699dfe13c18e34dbdce9f --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/semi_coco_detection.py @@ -0,0 +1,178 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +color_space = [ + [dict(type='ColorTransform')], + [dict(type='AutoContrast')], + [dict(type='Equalize')], + [dict(type='Sharpness')], + [dict(type='Posterize')], + [dict(type='Solarize')], + [dict(type='Color')], + [dict(type='Contrast')], + [dict(type='Brightness')], +] + +geometric = [ + [dict(type='Rotate')], + [dict(type='ShearX')], + [dict(type='ShearY')], + [dict(type='TranslateX')], + [dict(type='TranslateY')], +] + +scale = [(1333, 400), (1333, 1200)] + +branch_field = ['sup', 'unsup_teacher', 'unsup_student'] +# pipeline used to augment labeled data, +# which will be sent to student model for supervised training. +sup_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict( + type='MultiBranch', + branch_field=branch_field, + sup=dict(type='PackDetInputs')) +] + +# pipeline used to augment unlabeled data weakly, +# which will be sent to teacher model for predicting pseudo instances. +weak_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data strongly, +# which will be sent to student model for unsupervised training. +strong_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomOrder', + transforms=[ + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='RandAugment', aug_space=geometric, aug_num=1), + ]), + dict(type='RandomErasing', n_patches=(1, 5), ratio=(0, 0.2)), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data into different views +unsup_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadEmptyAnnotations'), + dict( + type='MultiBranch', + branch_field=branch_field, + unsup_teacher=weak_pipeline, + unsup_student=strong_pipeline, + ) +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +batch_size = 5 +num_workers = 5 +# There are two common semi-supervised learning settings on the coco dataset: +# (1) Divide the train2017 into labeled and unlabeled datasets +# by a fixed percentage, such as 1%, 2%, 5% and 10%. +# The format of labeled_ann_file and unlabeled_ann_file are +# instances_train2017.{fold}@{percent}.json, and +# instances_train2017.{fold}@{percent}-unlabeled.json +# `fold` is used for cross-validation, and `percent` represents +# the proportion of labeled data in the train2017. +# (2) Choose the train2017 as the labeled dataset +# and unlabeled2017 as the unlabeled dataset. +# The labeled_ann_file and unlabeled_ann_file are +# instances_train2017.json and image_info_unlabeled2017.json +# We use this configuration by default. +labeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=sup_pipeline, + backend_args=backend_args) + +unlabeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_unlabeled2017.json', + data_prefix=dict(img='unlabeled2017/'), + filter_cfg=dict(filter_empty_gt=False), + pipeline=unsup_pipeline, + backend_args=backend_args) + +train_dataloader = dict( + batch_size=batch_size, + num_workers=num_workers, + persistent_workers=True, + sampler=dict( + type='GroupMultiSourceSampler', + batch_size=batch_size, + source_ratio=[1, 4]), + dataset=dict( + type='ConcatDataset', datasets=[labeled_dataset, unlabeled_dataset])) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/voc0712.py b/mmdet_code/SR-TOD/configs/_base_/datasets/voc0712.py new file mode 100644 index 0000000000000000000000000000000000000000..47f5e6563b7f47dd6cfec02248d4c8decd32afe4 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/voc0712.py @@ -0,0 +1,92 @@ +# dataset settings +dataset_type = 'VOCDataset' +data_root = 'data/VOCdevkit/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically Infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/segmentation/VOCdevkit/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/segmentation/', +# 'data/': 's3://openmmlab/datasets/segmentation/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1000, 600), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1000, 600), keep_ratio=True), + # avoid bboxes being resized + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=3, + dataset=dict( + type='ConcatDataset', + # VOCDataset will add different `dataset_type` in dataset.metainfo, + # which will get error if using ConcatDataset. Adding + # `ignore_keys` can avoid this error. + ignore_keys=['dataset_type'], + datasets=[ + dict( + type=dataset_type, + data_root=data_root, + ann_file='VOC2007/ImageSets/Main/trainval.txt', + data_prefix=dict(sub_data_root='VOC2007/'), + filter_cfg=dict( + filter_empty_gt=True, min_size=32, bbox_min_size=32), + pipeline=train_pipeline, + backend_args=backend_args), + dict( + type=dataset_type, + data_root=data_root, + ann_file='VOC2012/ImageSets/Main/trainval.txt', + data_prefix=dict(sub_data_root='VOC2012/'), + filter_cfg=dict( + filter_empty_gt=True, min_size=32, bbox_min_size=32), + pipeline=train_pipeline, + backend_args=backend_args) + ]))) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='VOC2007/ImageSets/Main/test.txt', + data_prefix=dict(sub_data_root='VOC2007/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +# Pascal VOC2007 uses `11points` as default evaluate mode, while PASCAL +# VOC2012 defaults to use 'area'. +val_evaluator = dict(type='VOCMetric', metric='mAP', eval_mode='11points') +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/wider_face.py b/mmdet_code/SR-TOD/configs/_base_/datasets/wider_face.py new file mode 100644 index 0000000000000000000000000000000000000000..7042bc46e877ed899969730325143307e15adf64 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/wider_face.py @@ -0,0 +1,73 @@ +# dataset settings +dataset_type = 'WIDERFaceDataset' +data_root = 'data/WIDERFace/' +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/cityscapes/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +img_scale = (640, 640) # VGA resolution + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=img_scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=img_scale, keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='train.txt', + data_prefix=dict(img='WIDER_train'), + filter_cfg=dict(filter_empty_gt=True, bbox_min_size=17, min_size=32), + pipeline=train_pipeline)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='val.txt', + data_prefix=dict(img='WIDER_val'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +val_evaluator = dict( + # TODO: support WiderFace-Evaluation for easy, medium, hard cases + type='VOCMetric', + metric='mAP', + eval_mode='11points') +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/configs/_base_/datasets/youtube_vis.py b/mmdet_code/SR-TOD/configs/_base_/datasets/youtube_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..ece07cc3879e512082e302c2e3f76108c57a0234 --- /dev/null +++ b/mmdet_code/SR-TOD/configs/_base_/datasets/youtube_vis.py @@ -0,0 +1,66 @@ +dataset_type = 'YouTubeVISDataset' +data_root = 'data/youtube_vis_2019/' +dataset_version = data_root[-5:-1] # 2019 or 2021 + +backend_args = None + +# dataset settings +train_pipeline = [ + dict( + type='UniformRefFrameSample', + num_ref_imgs=1, + frame_range=100, + filter_key_img=True), + dict( + type='TransformBroadcaster', + share_random_params=True, + transforms=[ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadTrackAnnotations', with_mask=True), + dict(type='Resize', scale=(640, 360), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + ]), + dict(type='PackTrackInputs') +] + +test_pipeline = [ + dict( + type='TransformBroadcaster', + transforms=[ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(640, 360), keep_ratio=True), + dict(type='LoadTrackAnnotations', with_mask=True), + ]), + dict(type='PackTrackInputs') +] + +# dataloader +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + # sampler=dict(type='TrackImgSampler'), # image-based sampling + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='TrackAspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + dataset_version=dataset_version, + ann_file='annotations/youtube_vis_2019_train.json', + data_prefix=dict(img_path='train/JPEGImages'), + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False, round_up=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + dataset_version=dataset_version, + ann_file='annotations/youtube_vis_2019_valid.json', + data_prefix=dict(img_path='valid/JPEGImages'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader diff --git a/mmdet_code/SR-TOD/docs/en/Makefile b/mmdet_code/SR-TOD/docs/en/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d4bb2cbb9eddb1bb1b4f366623044af8e4830919 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/mmdet_code/SR-TOD/docs/en/_static/css/readthedocs.css b/mmdet_code/SR-TOD/docs/en/_static/css/readthedocs.css new file mode 100644 index 0000000000000000000000000000000000000000..57ed0ad084827ae75f5c58d3799ff5cfa6e40600 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/_static/css/readthedocs.css @@ -0,0 +1,6 @@ +.header-logo { + background-image: url("../image/mmdet-logo.png"); + background-size: 156px 40px; + height: 40px; + width: 156px; +} diff --git a/mmdet_code/SR-TOD/docs/en/_static/image/mmdet-logo.png b/mmdet_code/SR-TOD/docs/en/_static/image/mmdet-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..da0b5a3f01ba8ba79c63189e09b4689f3fe25472 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/_static/image/mmdet-logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3cbc8783587b4c1edd6300c8026007514b8fee8298d2a7cfa48a53936f47610 +size 32181 diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/conventions.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/conventions.md new file mode 100644 index 0000000000000000000000000000000000000000..da159ac699f741d07bf89c15bee5a79740a2315c --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/conventions.md @@ -0,0 +1,111 @@ +# Conventions + +Please check the following conventions if you would like to modify MMDetection as your own project. + +## About the order of image shape + +In OpenMMLab 2.0, to be consistent with the input argument of OpenCV, the argument about image shape in the data transformation pipeline is always in the `(width, height)` order. On the contrary, for computation convenience, the order of the field going through the data pipeline and the model is `(height, width)`. Specifically, in the results processed by each data transform pipeline, the fields and their value meaning is as below: + +- img_shape: (height, width) +- ori_shape: (height, width) +- pad_shape: (height, width) +- batch_input_shape: (height, width) + +As an example, the initialization arguments of `Mosaic` are as below: + +```python +@TRANSFORMS.register_module() +class Mosaic(BaseTransform): + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + center_ratio_range: Tuple[float, float] = (0.5, 1.5), + bbox_clip_border: bool = True, + pad_val: float = 114.0, + prob: float = 1.0) -> None: + ... + + # img_scale order should be (width, height) + self.img_scale = img_scale + + def transform(self, results: dict) -> dict: + ... + + results['img'] = mosaic_img + # (height, width) + results['img_shape'] = mosaic_img.shape[:2] +``` + +## Loss + +In MMDetection, a `dict` containing losses and metrics will be returned by `model(**data)`. + +For example, in bbox head, + +```python +class BBoxHead(nn.Module): + ... + def loss(self, ...): + losses = dict() + # classification loss + losses['loss_cls'] = self.loss_cls(...) + # classification accuracy + losses['acc'] = accuracy(...) + # bbox regression loss + losses['loss_bbox'] = self.loss_bbox(...) + return losses +``` + +`bbox_head.loss()` will be called during model forward. +The returned dict contains `'loss_bbox'`, `'loss_cls'`, `'acc'` . +Only `'loss_bbox'`, `'loss_cls'` will be used during back propagation, +`'acc'` will only be used as a metric to monitor training process. + +By default, only values whose keys contain `'loss'` will be back propagated. +This behavior could be changed by modifying `BaseDetector.train_step()`. + +## Empty Proposals + +In MMDetection, We have added special handling and unit test for empty proposals of two-stage. We need to deal with the empty proposals of the entire batch and single image at the same time. For example, in CascadeRoIHead, + +```python +# simple_test method +... +# There is no proposal in the whole batch +if rois.shape[0] == 0: + bbox_results = [[ + np.zeros((0, 5), dtype=np.float32) + for _ in range(self.bbox_head[-1].num_classes) + ]] * num_imgs + if self.with_mask: + mask_classes = self.mask_head[-1].num_classes + segm_results = [[[] for _ in range(mask_classes)] + for _ in range(num_imgs)] + results = list(zip(bbox_results, segm_results)) + else: + results = bbox_results + return results +... + +# There is no proposal in the single image +for i in range(self.num_stages): + ... + if i < self.num_stages - 1: + for j in range(num_imgs): + # Handle empty proposal + if rois[j].shape[0] > 0: + bbox_label = cls_score[j][:, :-1].argmax(dim=1) + refine_roi = self.bbox_head[i].regress_by_class( + rois[j], bbox_label, bbox_pred[j], img_metas[j]) + refine_roi_list.append(refine_roi) +``` + +If you have customized `RoIHead`, you can refer to the above method to deal with empty proposals. + +## Coco Panoptic Dataset + +In MMDetection, we have supported COCO Panoptic dataset. We clarify a few conventions about the implementation of `CocoPanopticDataset` here. + +1. For mmdet\<=2.16.0, the range of foreground and background labels in semantic segmentation are different from the default setting of MMDetection. The label `0` stands for `VOID` label and the category labels start from `1`. + Since mmdet=2.17.0, the category labels of semantic segmentation start from `0` and label `255` stands for `VOID` for consistency with labels of bounding boxes. + To achieve that, the `Pad` pipeline supports setting the padding value for `seg`. +2. In the evaluation, the panoptic result is a map with the same shape as the original image. Each value in the result map has the format of `instance_id * INSTANCE_OFFSET + category_id`. diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_dataset.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_dataset.md new file mode 100644 index 0000000000000000000000000000000000000000..3d63d12c61a436563f7318e766089b6ce48dda79 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_dataset.md @@ -0,0 +1,433 @@ +# Customize Datasets + +## Support new data format + +To support a new data format, you can either convert them to existing formats (COCO format or PASCAL format) or directly convert them to the middle format. You could also choose to convert them offline (before training by a script) or online (implement a new dataset and do the conversion at training). In MMDetection, we recommend to convert the data into COCO formats and do the conversion offline, thus you only need to modify the config's data annotation paths and classes after the conversion of your data. + +### Reorganize new data formats to existing format + +The simplest way is to convert your dataset to existing dataset formats (COCO or PASCAL VOC). + +The annotation JSON files in COCO format has the following necessary keys: + +```python +'images': [ + { + 'file_name': 'COCO_val2014_000000001268.jpg', + 'height': 427, + 'width': 640, + 'id': 1268 + }, + ... +], + +'annotations': [ + { + 'segmentation': [[192.81, + 247.09, + ... + 219.03, + 249.06]], # If you have mask labels, and it is in polygon XY point coordinate format, you need to ensure that at least 3 point coordinates are included. Otherwise, it is an invalid polygon. + 'area': 1035.749, + 'iscrowd': 0, + 'image_id': 1268, + 'bbox': [192.81, 224.8, 74.73, 33.43], + 'category_id': 16, + 'id': 42986 + }, + ... +], + +'categories': [ + {'id': 0, 'name': 'car'}, + ] +``` + +There are three necessary keys in the JSON file: + +- `images`: contains a list of images with their information like `file_name`, `height`, `width`, and `id`. +- `annotations`: contains the list of instance annotations. +- `categories`: contains the list of categories names and their ID. + +After the data pre-processing, there are two steps for users to train the customized new dataset with existing format (e.g. COCO format): + +1. Modify the config file for using the customized dataset. +2. Check the annotations of the customized dataset. + +Here we give an example to show the above two steps, which uses a customized dataset of 5 classes with COCO format to train an existing Cascade Mask R-CNN R50-FPN detector. + +#### 1. Modify the config file for using the customized dataset + +There are two aspects involved in the modification of config file: + +1. The `data` field. Specifically, you need to explicitly add the `metainfo=dict(classes=classes)` fields in `train_dataloader.dataset`, `val_dataloader.dataset` and `test_dataloader.dataset` and `classes` must be a tuple type. +2. The `num_classes` field in the `model` part. Explicitly over-write all the `num_classes` from default value (e.g. 80 in COCO) to your classes number. + +In `configs/my_custom_config.py`: + +```python + +# the new config inherits the base configs to highlight the necessary modification +_base_ = './cascade_mask_rcnn_r50_fpn_1x_coco.py' + +# 1. dataset settings +dataset_type = 'CocoDataset' +classes = ('a', 'b', 'c', 'd', 'e') +data_root='path/to/your/' + +train_dataloader = dict( + batch_size=2, + num_workers=2, + dataset=dict( + type=dataset_type, + # explicitly add your class names to the field `metainfo` + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='train/annotation_data', + data_prefix=dict(img='train/image_data') + ) + ) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + dataset=dict( + type=dataset_type, + test_mode=True, + # explicitly add your class names to the field `metainfo` + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='val/annotation_data', + data_prefix=dict(img='val/image_data') + ) + ) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + dataset=dict( + type=dataset_type, + test_mode=True, + # explicitly add your class names to the field `metainfo` + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='test/annotation_data', + data_prefix=dict(img='test/image_data') + ) + ) + +# 2. model settings + +# explicitly over-write all the `num_classes` field from default 80 to 5. +model = dict( + roi_head=dict( + bbox_head=[ + dict( + type='Shared2FCBBoxHead', + # explicitly over-write all the `num_classes` field from default 80 to 5. + num_classes=5), + dict( + type='Shared2FCBBoxHead', + # explicitly over-write all the `num_classes` field from default 80 to 5. + num_classes=5), + dict( + type='Shared2FCBBoxHead', + # explicitly over-write all the `num_classes` field from default 80 to 5. + num_classes=5)], + # explicitly over-write all the `num_classes` field from default 80 to 5. + mask_head=dict(num_classes=5))) +``` + +#### 2. Check the annotations of the customized dataset + +Assuming your customized dataset is COCO format, make sure you have the correct annotations in the customized dataset: + +1. The length for `categories` field in annotations should exactly equal the tuple length of `classes` fields in your config, meaning the number of classes (e.g. 5 in this example). +2. The `classes` fields in your config file should have exactly the same elements and the same order with the `name` in `categories` of annotations. MMDetection automatically maps the uncontinuous `id` in `categories` to the continuous label indices, so the string order of `name` in `categories` field affects the order of label indices. Meanwhile, the string order of `classes` in config affects the label text during visualization of predicted bounding boxes. +3. The `category_id` in `annotations` field should be valid, i.e., all values in `category_id` should belong to `id` in `categories`. + +Here is a valid example of annotations: + +```python + +'annotations': [ + { + 'segmentation': [[192.81, + 247.09, + ... + 219.03, + 249.06]], # if you have mask labels + 'area': 1035.749, + 'iscrowd': 0, + 'image_id': 1268, + 'bbox': [192.81, 224.8, 74.73, 33.43], + 'category_id': 16, + 'id': 42986 + }, + ... +], + +# MMDetection automatically maps the uncontinuous `id` to the continuous label indices. +'categories': [ + {'id': 1, 'name': 'a'}, {'id': 3, 'name': 'b'}, {'id': 4, 'name': 'c'}, {'id': 16, 'name': 'd'}, {'id': 17, 'name': 'e'}, + ] +``` + +We use this way to support CityScapes dataset. The script is in [cityscapes.py](../../../tools/dataset_converters/cityscapes.py) and we also provide the finetuning [configs](../../../configs/cityscapes). + +**Note** + +1. For instance segmentation datasets, **MMDetection only supports evaluating mask AP of dataset in COCO format for now**. +2. It is recommended to convert the data offline before training, thus you can still use `CocoDataset` and only need to modify the path of annotations and the training classes. + +### Reorganize new data format to middle format + +It is also fine if you do not want to convert the annotation format to COCO or PASCAL format. +Actually, we define a simple annotation format in MMEninge's [BaseDataset](https://github.com/open-mmlab/mmengine/blob/main/mmengine/dataset/base_dataset.py#L116) and all existing datasets are +processed to be compatible with it, either online or offline. + +The annotation of the dataset must be in `json` or `yaml`, `yml` or `pickle`, `pkl` format; the dictionary stored in the annotation file must contain two fields `metainfo` and `data_list`. The `metainfo` is a dictionary, which contains the metadata of the dataset, such as class information; `data_list` is a list, each element in the list is a dictionary, the dictionary defines the raw data of one image, and each raw data contains a or several training/testing samples. + +Here is an example. + +```python +{ + 'metainfo': + { + 'classes': ('person', 'bicycle', 'car', 'motorcycle'), + ... + }, + 'data_list': + [ + { + "img_path": "xxx/xxx_1.jpg", + "height": 604, + "width": 640, + "instances": + [ + { + "bbox": [0, 0, 10, 20], + "bbox_label": 1, + "ignore_flag": 0 + }, + { + "bbox": [10, 10, 110, 120], + "bbox_label": 2, + "ignore_flag": 0 + } + ] + }, + { + "img_path": "xxx/xxx_2.jpg", + "height": 320, + "width": 460, + "instances": + [ + { + "bbox": [10, 0, 20, 20], + "bbox_label": 3, + "ignore_flag": 1, + } + ] + }, + ... + ] +} +``` + +Some datasets may provide annotations like crowd/difficult/ignored bboxes, we use `ignore_flag`to cover them. + +After obtaining the above standard data annotation format, you can directly use [BaseDetDataset](../../../mmdet/datasets/base_det_dataset.py#L13) of MMDetection in the configuration , without conversion. + +### An example of customized dataset + +Assume the annotation is in a new format in text files. +The bounding boxes annotations are stored in text file `annotation.txt` as the following + +``` +# +000001.jpg +1280 720 +2 +10 20 40 60 1 +20 40 50 60 2 +# +000002.jpg +1280 720 +3 +50 20 40 60 2 +20 40 30 45 2 +30 40 50 60 3 +``` + +We can create a new dataset in `mmdet/datasets/my_dataset.py` to load the data. + +```python +import mmengine + +from mmdet.base_det_dataset import BaseDetDataset +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class MyDataset(BaseDetDataset): + + METAINFO = { + 'classes': ('person', 'bicycle', 'car', 'motorcycle'), + 'palette': [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230)] + } + + def load_data_list(self, ann_file): + ann_list = mmengine.list_from_file(ann_file) + + data_infos = [] + for i, ann_line in enumerate(ann_list): + if ann_line != '#': + continue + + img_shape = ann_list[i + 2].split(' ') + width = int(img_shape[0]) + height = int(img_shape[1]) + bbox_number = int(ann_list[i + 3]) + + instances = [] + for anns in ann_list[i + 4:i + 4 + bbox_number]: + instance = {} + instance['bbox'] = [float(ann) for ann in anns.split(' ')[:4]] + instance['bbox_label']=int(anns[4]) + instances.append(instance) + + data_infos.append( + dict( + img_path=ann_list[i + 1], + img_id=i, + width=width, + height=height, + instances=instances + )) + + return data_infos +``` + +Then in the config, to use `MyDataset` you can modify the config as the following + +```python +dataset_A_train = dict( + type='MyDataset', + ann_file = 'image_list.txt', + pipeline=train_pipeline +) +``` + +## Customize datasets by dataset wrappers + +MMEngine also supports many dataset wrappers to mix the dataset or modify the dataset distribution for training. +Currently it supports to three dataset wrappers as below: + +- `RepeatDataset`: simply repeat the whole dataset. +- `ClassBalancedDataset`: repeat dataset in a class balanced manner. +- `ConcatDataset`: concat datasets. + +For detailed usage, see [MMEngine Dataset Wrapper](#TODO). + +## Modify Dataset Classes + +With existing dataset types, we can modify the metainfo of them to train subset of the annotations. +For example, if you want to train only three classes of the current dataset, +you can modify the classes of dataset. +The dataset will filter out the ground truth boxes of other classes automatically. + +```python +classes = ('person', 'bicycle', 'car') +train_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +val_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +test_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +``` + +**Note**: + +- Before MMDetection v2.5.0, the dataset will filter out the empty GT images automatically if the classes are set and there is no way to disable that through config. This is an undesirable behavior and introduces confusion because if the classes are not set, the dataset only filter the empty GT images when `filter_empty_gt=True` and `test_mode=False`. After MMDetection v2.5.0, we decouple the image filtering process and the classes modification, i.e., the dataset will only filter empty GT images when `filter_cfg=dict(filter_empty_gt=True)` and `test_mode=False`, no matter whether the classes are set. Thus, setting the classes only influences the annotations of classes used for training and users could decide whether to filter empty GT images by themselves. +- When directly using `BaseDataset` in MMEngine or `BaseDetDataset` in MMDetection, users cannot filter images without GT by modifying the configuration, but it can be solved in an offline way. +- Please remember to modify the `num_classes` in the head when specifying `classes` in dataset. We implemented [NumClassCheckHook](../../../mmdet/engine/hooks/num_class_check_hook.py) to check whether the numbers are consistent since v2.9.0(after PR#4508). + +## COCO Panoptic Dataset + +Now we support COCO Panoptic Dataset, the format of panoptic annotations is different from COCO format. +Both the foreground and the background will exist in the annotation file. +The annotation json files in COCO Panoptic format has the following necessary keys: + +```python +'images': [ + { + 'file_name': '000000001268.jpg', + 'height': 427, + 'width': 640, + 'id': 1268 + }, + ... +] + +'annotations': [ + { + 'filename': '000000001268.jpg', + 'image_id': 1268, + 'segments_info': [ + { + 'id':8345037, # One-to-one correspondence with the id in the annotation map. + 'category_id': 51, + 'iscrowd': 0, + 'bbox': (x1, y1, w, h), # The bbox of the background is the outer rectangle of its mask. + 'area': 24315 + }, + ... + ] + }, + ... +] + +'categories': [ # including both foreground categories and background categories + {'id': 0, 'name': 'person'}, + ... + ] +``` + +Moreover, the `seg` must be set to the path of the panoptic annotation images. + +```python +dataset_type = 'CocoPanopticDataset' +data_root='path/to/your/' + +train_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='train/image_data/', seg='train/panoptic/image_annotation_data/') + ) +) +val_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='val/image_data/', seg='val/panoptic/image_annotation_data/') + ) +) +test_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='test/image_data/', seg='test/panoptic/image_annotation_data/') + ) +) +``` diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_losses.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_losses.md new file mode 100644 index 0000000000000000000000000000000000000000..3120dc01ffe4b11e75eb1e43632cbbfe6f1b05c8 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_losses.md @@ -0,0 +1,126 @@ +# Customize Losses + +MMDetection provides users with different loss functions. But the default configuration may be not applicable for different datasets or models, so users may want to modify a specific loss to adapt the new situation. + +This tutorial first elaborate the computation pipeline of losses, then give some instructions about how to modify each step. The modification can be categorized as tweaking and weighting. + +## Computation pipeline of a loss + +Given the input prediction and target, as well as the weights, a loss function maps the input tensor to the final loss scalar. The mapping can be divided into five steps: + +1. Set the sampling method to sample positive and negative samples. + +2. Get **element-wise** or **sample-wise** loss by the loss kernel function. + +3. Weighting the loss with a weight tensor **element-wisely**. + +4. Reduce the loss tensor to a **scalar**. + +5. Weighting the loss with a **scalar**. + +## Set sampling method (step 1) + +For some loss functions, sampling strategies are needed to avoid imbalance between positive and negative samples. + +For example, when using `CrossEntropyLoss` in RPN head, we need to set `RandomSampler` in `train_cfg` + +```python +train_cfg=dict( + rpn=dict( + sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False)) +``` + +For some other losses which have positive and negative sample balance mechanism such as Focal Loss, GHMC, and QualityFocalLoss, the sampler is no more necessary. + +## Tweaking loss + +Tweaking a loss is more related with step 2, 4, 5, and most modifications can be specified in the config. +Here we take [Focal Loss (FL)](../../../mmdet/models/losses/focal_loss.py) as an example. +The following code sniper are the construction method and config of FL respectively, they are actually one to one correspondence. + +```python +@LOSSES.register_module() +class FocalLoss(nn.Module): + + def __init__(self, + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + reduction='mean', + loss_weight=1.0): +``` + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0) +``` + +### Tweaking hyper-parameters (step 2) + +`gamma` and `beta` are two hyper-parameters in the Focal Loss. Say if we want to change the value of `gamma` to be 1.5 and `alpha` to be 0.5, then we can specify them in the config as follows: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=1.5, + alpha=0.5, + loss_weight=1.0) +``` + +### Tweaking the way of reduction (step 3) + +The default way of reduction is `mean` for FL. Say if we want to change the reduction from `mean` to `sum`, we can specify it in the config as follows: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0, + reduction='sum') +``` + +### Tweaking loss weight (step 5) + +The loss weight here is a scalar which controls the weight of different losses in multi-task learning, e.g. classification loss and regression loss. Say if we want to change to loss weight of classification loss to be 0.5, we can specify it in the config as follows: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=0.5) +``` + +## Weighting loss (step 3) + +Weighting loss means we re-weight the loss element-wisely. To be more specific, we multiply the loss tensor with a weight tensor which has the same shape. As a result, different entries of the loss can be scaled differently, and so called element-wisely. +The loss weight varies across different models and highly context related, but overall there are two kinds of loss weights, `label_weights` for classification loss and `bbox_weights` for bbox regression loss. You can find them in the `get_target` method of the corresponding head. Here we take [ATSSHead](../../../mmdet/models/dense_heads/atss_head.py#L322) as an example, which inherit [AnchorHead](../../../mmdet/models/dense_heads/anchor_head.py) but overwrite its `get_targets` method which yields different `label_weights` and `bbox_weights`. + +``` +class ATSSHead(AnchorHead): + + ... + + def get_targets(self, + anchor_list, + valid_flag_list, + gt_bboxes_list, + img_metas, + gt_bboxes_ignore_list=None, + gt_labels_list=None, + label_channels=1, + unmap_outputs=True): +``` diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_models.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_models.md new file mode 100644 index 0000000000000000000000000000000000000000..1779aeb1aa1f347fa27cd71bf214dc0b298f6b43 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_models.md @@ -0,0 +1,412 @@ +# Customize Models + +We basically categorize model components into 5 types. + +- backbone: usually an FCN network to extract feature maps, e.g., ResNet, MobileNet. +- neck: the component between backbones and heads, e.g., FPN, PAFPN. +- head: the component for specific tasks, e.g., bbox prediction and mask prediction. +- roi extractor: the part for extracting RoI features from feature maps, e.g., RoI Align. +- loss: the component in head for calculating losses, e.g., FocalLoss, L1Loss, and GHMLoss. + +## Develop new components + +### Add a new backbone + +Here we show how to develop new components with an example of MobileNet. + +#### 1. Define a new backbone (e.g. MobileNet) + +Create a new file `mmdet/models/backbones/mobilenet.py`. + +```python +import torch.nn as nn + +from mmdet.registry import MODELS + + +@MODELS.register_module() +class MobileNet(nn.Module): + + def __init__(self, arg1, arg2): + pass + + def forward(self, x): # should return a tuple + pass +``` + +#### 2. Import the module + +You can either add the following line to `mmdet/models/backbones/__init__.py` + +```python +from .mobilenet import MobileNet +``` + +or alternatively add + +```python +custom_imports = dict( + imports=['mmdet.models.backbones.mobilenet'], + allow_failed_imports=False) +``` + +to the config file to avoid modifying the original code. + +#### 3. Use the backbone in your config file + +```python +model = dict( + ... + backbone=dict( + type='MobileNet', + arg1=xxx, + arg2=xxx), + ... +``` + +### Add new necks + +#### 1. Define a neck (e.g. PAFPN) + +Create a new file `mmdet/models/necks/pafpn.py`. + +```python +import torch.nn as nn + +from mmdet.registry import MODELS + +@MODELS.register_module() +class PAFPN(nn.Module): + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False): + pass + + def forward(self, inputs): + # implementation is ignored + pass +``` + +#### 2. Import the module + +You can either add the following line to `mmdet/models/necks/__init__.py`, + +```python +from .pafpn import PAFPN +``` + +or alternatively add + +```python +custom_imports = dict( + imports=['mmdet.models.necks.pafpn'], + allow_failed_imports=False) +``` + +to the config file and avoid modifying the original code. + +#### 3. Modify the config file + +```python +neck=dict( + type='PAFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5) +``` + +### Add new heads + +Here we show how to develop a new head with the example of [Double Head R-CNN](https://arxiv.org/abs/1904.06493) as the following. + +First, add a new bbox head in `mmdet/models/roi_heads/bbox_heads/double_bbox_head.py`. +Double Head R-CNN implements a new bbox head for object detection. +To implement a bbox head, basically we need to implement three functions of the new module as the following. + +```python +from typing import Tuple + +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule, ModuleList +from torch import Tensor + +from mmdet.models.backbones.resnet import Bottleneck +from mmdet.registry import MODELS +from mmdet.utils import ConfigType, MultiConfig, OptConfigType, OptMultiConfig +from .bbox_head import BBoxHead + +@MODELS.register_module() +class DoubleConvFCBBoxHead(BBoxHead): + r"""Bbox head used in Double-Head R-CNN + + .. code-block:: none + + /-> cls + /-> shared convs -> + \-> reg + roi features + /-> cls + \-> shared fc -> + \-> reg + """ # noqa: W605 + + def __init__(self, + num_convs: int = 0, + num_fcs: int = 0, + conv_out_channels: int = 1024, + fc_out_channels: int = 1024, + conv_cfg: OptConfigType = None, + norm_cfg: ConfigType = dict(type='BN'), + init_cfg: MultiConfig = dict( + type='Normal', + override=[ + dict(type='Normal', name='fc_cls', std=0.01), + dict(type='Normal', name='fc_reg', std=0.001), + dict( + type='Xavier', + name='fc_branch', + distribution='uniform') + ]), + **kwargs) -> None: + kwargs.setdefault('with_avg_pool', True) + super().__init__(init_cfg=init_cfg, **kwargs) + + def forward(self, x_cls: Tensor, x_reg: Tensor) -> Tuple[Tensor]: + +``` + +Second, implement a new RoI Head if it is necessary. We plan to inherit the new `DoubleHeadRoIHead` from `StandardRoIHead`. We can find that a `StandardRoIHead` already implements the following functions. + +```python +from typing import List, Optional, Tuple + +import torch +from torch import Tensor + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.structures import DetDataSample +from mmdet.structures.bbox import bbox2roi +from mmdet.utils import ConfigType, InstanceList +from ..task_modules.samplers import SamplingResult +from ..utils import empty_instances, unpack_gt_instances +from .base_roi_head import BaseRoIHead + + +@MODELS.register_module() +class StandardRoIHead(BaseRoIHead): + """Simplest base roi head including one bbox head and one mask head.""" + + def init_assigner_sampler(self) -> None: + + def init_bbox_head(self, bbox_roi_extractor: ConfigType, + bbox_head: ConfigType) -> None: + + def init_mask_head(self, mask_roi_extractor: ConfigType, + mask_head: ConfigType) -> None: + + def forward(self, x: Tuple[Tensor], + rpn_results_list: InstanceList) -> tuple: + + def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, + batch_data_samples: List[DetDataSample]) -> dict: + + def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict: + + def bbox_loss(self, x: Tuple[Tensor], + sampling_results: List[SamplingResult]) -> dict: + + def mask_loss(self, x: Tuple[Tensor], + sampling_results: List[SamplingResult], bbox_feats: Tensor, + batch_gt_instances: InstanceList) -> dict: + + def _mask_forward(self, + x: Tuple[Tensor], + rois: Tensor = None, + pos_inds: Optional[Tensor] = None, + bbox_feats: Optional[Tensor] = None) -> dict: + + def predict_bbox(self, + x: Tuple[Tensor], + batch_img_metas: List[dict], + rpn_results_list: InstanceList, + rcnn_test_cfg: ConfigType, + rescale: bool = False) -> InstanceList: + + def predict_mask(self, + x: Tuple[Tensor], + batch_img_metas: List[dict], + results_list: InstanceList, + rescale: bool = False) -> InstanceList: + +``` + +Double Head's modification is mainly in the `bbox_forward` logic, and it inherits other logics from the `StandardRoIHead`. In the `mmdet/models/roi_heads/double_roi_head.py`, we implement the new RoI Head as the following: + +```python +from typing import Tuple + +from torch import Tensor + +from mmdet.registry import MODELS +from .standard_roi_head import StandardRoIHead + + +@MODELS.register_module() +class DoubleHeadRoIHead(StandardRoIHead): + """RoI head for `Double Head RCNN `_. + + Args: + reg_roi_scale_factor (float): The scale factor to extend the rois + used to extract the regression features. + """ + + def __init__(self, reg_roi_scale_factor: float, **kwargs): + super().__init__(**kwargs) + self.reg_roi_scale_factor = reg_roi_scale_factor + + def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict: + """Box head forward function used in both training and testing. + + Args: + x (tuple[Tensor]): List of multi-level img features. + rois (Tensor): RoIs with the shape (n, 5) where the first + column indicates batch id of each RoI. + + Returns: + dict[str, Tensor]: Usually returns a dictionary with keys: + + - `cls_score` (Tensor): Classification scores. + - `bbox_pred` (Tensor): Box energies / deltas. + - `bbox_feats` (Tensor): Extract bbox RoI features. + """ + bbox_cls_feats = self.bbox_roi_extractor( + x[:self.bbox_roi_extractor.num_inputs], rois) + bbox_reg_feats = self.bbox_roi_extractor( + x[:self.bbox_roi_extractor.num_inputs], + rois, + roi_scale_factor=self.reg_roi_scale_factor) + if self.with_shared_head: + bbox_cls_feats = self.shared_head(bbox_cls_feats) + bbox_reg_feats = self.shared_head(bbox_reg_feats) + cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats) + + bbox_results = dict( + cls_score=cls_score, + bbox_pred=bbox_pred, + bbox_feats=bbox_cls_feats) + return bbox_results +``` + +Last, the users need to add the module in +`mmdet/models/bbox_heads/__init__.py` and `mmdet/models/roi_heads/__init__.py` thus the corresponding registry could find and load them. + +Alternatively, the users can add + +```python +custom_imports=dict( + imports=['mmdet.models.roi_heads.double_roi_head', 'mmdet.models.roi_heads.bbox_heads.double_bbox_head']) +``` + +to the config file and achieve the same goal. + +The config file of Double Head R-CNN is as the following + +```python +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + roi_head=dict( + type='DoubleHeadRoIHead', + reg_roi_scale_factor=1.3, + bbox_head=dict( + _delete_=True, + type='DoubleConvFCBBoxHead', + num_convs=4, + num_fcs=2, + in_channels=256, + conv_out_channels=1024, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=80, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[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=2.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=2.0)))) + +``` + +Since MMDetection 2.0, the config system supports to inherit configs such that the users can focus on the modification. +The Double Head R-CNN mainly uses a new `DoubleHeadRoIHead` and a new `DoubleConvFCBBoxHead `, the arguments are set according to the `__init__` function of each module. + +### Add new loss + +Assume you want to add a new loss as `MyLoss`, for bounding box regression. +To add a new loss function, the users need implement it in `mmdet/models/losses/my_loss.py`. +The decorator `weighted_loss` enable the loss to be weighted for each element. + +```python +import torch +import torch.nn as nn + +from mmdet.registry import MODELS +from .utils import weighted_loss + +@weighted_loss +def my_loss(pred, target): + assert pred.size() == target.size() and target.numel() > 0 + loss = torch.abs(pred - target) + return loss + +@MODELS.register_module() +class MyLoss(nn.Module): + + def __init__(self, reduction='mean', loss_weight=1.0): + super(MyLoss, self).__init__() + self.reduction = reduction + self.loss_weight = loss_weight + + def forward(self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None): + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + loss_bbox = self.loss_weight * my_loss( + pred, target, weight, reduction=reduction, avg_factor=avg_factor) + return loss_bbox +``` + +Then the users need to add it in the `mmdet/models/losses/__init__.py`. + +```python +from .my_loss import MyLoss, my_loss + +``` + +Alternatively, you can add + +```python +custom_imports=dict( + imports=['mmdet.models.losses.my_loss']) +``` + +to the config file and achieve the same goal. + +To use it, modify the `loss_xxx` field. +Since MyLoss is for regression, you need to modify the `loss_bbox` field in the head. + +```python +loss_bbox=dict(type='MyLoss', loss_weight=1.0)) +``` diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_runtime.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_runtime.md new file mode 100644 index 0000000000000000000000000000000000000000..e6ce740a492b9e655536fc06aa365cd5421c81c2 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_runtime.md @@ -0,0 +1,391 @@ +# Customize Runtime Settings + +## Customize optimization settings + +Optimization related configuration is now all managed by `optim_wrapper` which usually has three fields: `optimizer`, `paramwise_cfg`, `clip_grad`, refer to [OptimWrapper](https://mmengine.readthedocs.io/en/latest/tutorials/optim_wrapper.md) for more detail. See the example below, where `Adamw` is used as an `optimizer`, the learning rate of the backbone is reduced by a factor of 10, and gradient clipping is added. + +```python +optim_wrapper = dict( + type='OptimWrapper', + # optimizer + optimizer=dict( + type='AdamW', + lr=0.0001, + weight_decay=0.05, + eps=1e-8, + betas=(0.9, 0.999)), + + # Parameter-level learning rate and weight decay settings + paramwise_cfg=dict( + custom_keys={ + 'backbone': dict(lr_mult=0.1, decay_mult=1.0), + }, + norm_decay_mult=0.0), + + # gradient clipping + clip_grad=dict(max_norm=0.01, norm_type=2)) +``` + +### Customize optimizer supported by Pytorch + +We already support to use all the optimizers implemented by PyTorch, and the only modification is to change the `optimizer` field in `optim_wrapper` field of config files. For example, if you want to use `ADAM` (note that the performance could drop a lot), the modification could be as the following. + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='Adam', lr=0.0003, weight_decay=0.0001)) +``` + +To modify the learning rate of the model, the users only need to modify the `lr` in `optimizer`. The users can directly set arguments following the [API doc](https://pytorch.org/docs/stable/optim.html?highlight=optim#module-torch.optim) of PyTorch. + +### Customize self-implemented optimizer + +#### 1. Define a new optimizer + +A customized optimizer could be defined as following. + +Assume you want to add a optimizer named `MyOptimizer`, which has arguments `a`, `b`, and `c`. +You need to create a new directory named `mmdet/engine/optimizers`. And then implement the new optimizer in a file, e.g., in `mmdet/engine/optimizers/my_optimizer.py`: + +```python +from mmdet.registry import OPTIMIZERS +from torch.optim import Optimizer + + +@OPTIMIZERS.register_module() +class MyOptimizer(Optimizer): + + def __init__(self, a, b, c) + +``` + +#### 2. Add the optimizer to registry + +To find the above module defined above, this module should be imported into the main namespace at first. There are two options to achieve it. + +- Modify `mmdet/engine/optimizers/__init__.py` to import it. + + The newly defined module should be imported in `mmdet/engine/optimizers/__init__.py` so that the registry will find the new module and add it: + +```python +from .my_optimizer import MyOptimizer +``` + +- Use `custom_imports` in the config to manually import it + +```python +custom_imports = dict(imports=['mmdet.engine.optimizers.my_optimizer'], allow_failed_imports=False) +``` + +The module `mmdet.engine.optimizers.my_optimizer` will be imported at the beginning of the program and the class `MyOptimizer` is then automatically registered. +Note that only the package containing the class `MyOptimizer` should be imported. +`mmdet.engine.optimizers.my_optimizer.MyOptimizer` **cannot** be imported directly. + +Actually users can use a totally different file directory structure using this importing method, as long as the module root can be located in `PYTHONPATH`. + +#### 3. Specify the optimizer in the config file + +Then you can use `MyOptimizer` in `optimizer` field in `optim_wrapper` field of config files. In the configs, the optimizers are defined by the field `optimizer` like the following: + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) +``` + +To use your own optimizer, the field can be changed to + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='MyOptimizer', a=a_value, b=b_value, c=c_value)) +``` + +### Customize optimizer wrapper constructor + +Some models may have some parameter-specific settings for optimization, e.g. weight decay for BatchNorm layers. +The users can do those fine-grained parameter tuning through customizing optimizer wrapper constructor. + +```python +from mmengine.optim import DefaultOptiWrapperConstructor + +from mmdet.registry import OPTIM_WRAPPER_CONSTRUCTORS +from .my_optimizer import MyOptimizer + + +@OPTIM_WRAPPER_CONSTRUCTORS.register_module() +class MyOptimizerWrapperConstructor(DefaultOptimWrapperConstructor): + + def __init__(self, + optim_wrapper_cfg: dict, + paramwise_cfg: Optional[dict] = None): + + def __call__(self, model: nn.Module) -> OptimWrapper: + + return optim_wrapper + +``` + +The default optimizer wrapper constructor is implemented [here](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/optimizer/default_constructor.py#L18), which could also serve as a template for the new optimizer wrapper constructor. + +### Additional settings + +Tricks not implemented by the optimizer should be implemented through optimizer wrapper constructor (e.g., set parameter-wise learning rates) or hooks. We list some common settings that could stabilize the training or accelerate the training. Feel free to create PR, issue for more settings. + +- __Use gradient clip to stabilize training__: + Some models need gradient clip to clip the gradients to stabilize the training process. An example is as below: + + ```python + optim_wrapper = dict( + _delete_=True, clip_grad=dict(max_norm=35, norm_type=2)) + ``` + + If your config inherits the base config which already sets the `optim_wrapper`, you might need `_delete_=True` to override the unnecessary settings. See the [config documentation](../user_guides/config.md) for more details. + +- __Use momentum schedule to accelerate model convergence__: + We support momentum scheduler to modify model's momentum according to learning rate, which could make the model converge in a faster way. + Momentum scheduler is usually used with LR scheduler, for example, the following config is used in [3D detection](https://github.com/open-mmlab/mmdetection3d/blob/dev-1.x/configs/_base_/schedules/cyclic-20e.py) to accelerate convergence. + For more details, please refer to the implementation of [CosineAnnealingLR](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py#L43) and [CosineAnnealingMomentum](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/momentum_scheduler.py#L71). + + ```python + param_scheduler = [ + # learning rate scheduler + # During the first 8 epochs, learning rate increases from 0 to lr * 10 + # during the next 12 epochs, learning rate decreases from lr * 10 to lr * 1e-4 + dict( + type='CosineAnnealingLR', + T_max=8, + eta_min=lr * 10, + begin=0, + end=8, + by_epoch=True, + convert_to_iter_based=True), + dict( + type='CosineAnnealingLR', + T_max=12, + eta_min=lr * 1e-4, + begin=8, + end=20, + by_epoch=True, + convert_to_iter_based=True), + # momentum scheduler + # During the first 8 epochs, momentum increases from 0 to 0.85 / 0.95 + # during the next 12 epochs, momentum increases from 0.85 / 0.95 to 1 + dict( + type='CosineAnnealingMomentum', + T_max=8, + eta_min=0.85 / 0.95, + begin=0, + end=8, + by_epoch=True, + convert_to_iter_based=True), + dict( + type='CosineAnnealingMomentum', + T_max=12, + eta_min=1, + begin=8, + end=20, + by_epoch=True, + convert_to_iter_based=True) + ] + ``` + +## Customize training schedules + +By default we use step learning rate with 1x schedule, this calls [MultiStepLR](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py#L139) in MMEngine. +We support many other learning rate schedule [here](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py), such as `CosineAnnealingLR` and `PolyLR` schedule. Here are some examples + +- Poly schedule: + + ```python + param_scheduler = [ + dict( + type='PolyLR', + power=0.9, + eta_min=1e-4, + begin=0, + end=8, + by_epoch=True)] + ``` + +- ConsineAnnealing schedule: + + ```python + param_scheduler = [ + dict( + type='CosineAnnealingLR', + T_max=8, + eta_min=lr * 1e-5, + begin=0, + end=8, + by_epoch=True)] + + ``` + +## Customize train loop + +By default, `EpochBasedTrainLoop` is used in `train_cfg` and validation is done after every train epoch, as follows. + +```python +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_begin=1, val_interval=1) +``` + +Actually, both [`IterBasedTrainLoop`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py#L183%5D) and [`EpochBasedTrainLoop`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py#L18) support dynamical interval, see the following example. + +```python +# Before 365001th iteration, we do evaluation every 5000 iterations. +# After 365000th iteration, we do evaluation every 368750 iterations, +# which means that we do evaluation at the end of training. + +interval = 5000 +max_iters = 368750 +dynamic_intervals = [(max_iters // interval * interval + 1, max_iters)] +train_cfg = dict( + type='IterBasedTrainLoop', + max_iters=max_iters, + val_interval=interval, + dynamic_intervals=dynamic_intervals) +``` + +## Customize hooks + +### Customize self-implemented hooks + +#### 1. Implement a new hook + +MMEngine provides many useful [hooks](https://mmengine.readthedocs.io/en/latest/tutorials/hooks.html), but there are some occasions when the users might need to implement a new hook. MMDetection supports customized hooks in training in v3.0 . Thus the users could implement a hook directly in mmdet or their mmdet-based codebases and use the hook by only modifying the config in training. +Here we give an example of creating a new hook in mmdet and using it in training. + +```python +from mmengine.hooks import Hook +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class MyHook(Hook): + + def __init__(self, a, b): + + def before_run(self, runner) -> None: + + def after_run(self, runner) -> None: + + def before_train(self, runner) -> None: + + def after_train(self, runner) -> None: + + def before_train_epoch(self, runner) -> None: + + def after_train_epoch(self, runner) -> None: + + def before_train_iter(self, + runner, + batch_idx: int, + data_batch: DATA_BATCH = None) -> None: + + def after_train_iter(self, + runner, + batch_idx: int, + data_batch: DATA_BATCH = None, + outputs: Optional[dict] = None) -> None: +``` + +Depending on the functionality of the hook, the users need to specify what the hook will do at each stage of the training in `before_run`, `after_run`, `before_train`, `after_train` , `before_train_epoch`, `after_train_epoch`, `before_train_iter`, and `after_train_iter`. There are more points where hooks can be inserted, refer to [base hook class](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/hook.py#L9) for more detail. + +#### 2. Register the new hook + +Then we need to make `MyHook` imported. Assuming the file is in `mmdet/engine/hooks/my_hook.py` there are two ways to do that: + +- Modify `mmdet/engine/hooks/__init__.py` to import it. + + The newly defined module should be imported in `mmdet/engine/hooks/__init__.py` so that the registry will find the new module and add it: + +```python +from .my_hook import MyHook +``` + +- Use `custom_imports` in the config to manually import it + +```python +custom_imports = dict(imports=['mmdet.engine.hooks.my_hook'], allow_failed_imports=False) +``` + +#### 3. Modify the config + +```python +custom_hooks = [ + dict(type='MyHook', a=a_value, b=b_value) +] +``` + +You can also set the priority of the hook by adding key `priority` to `'NORMAL'` or `'HIGHEST'` as below + +```python +custom_hooks = [ + dict(type='MyHook', a=a_value, b=b_value, priority='NORMAL') +] +``` + +By default the hook's priority is set as `NORMAL` during registration. + +### Use hooks implemented in MMDetection + +If the hook is already implemented in MMDectection, you can directly modify the config to use the hook as below + +#### Example: `NumClassCheckHook` + +We implement a customized hook named [NumClassCheckHook](../../../mmdet/engine/hooks/num_class_check_hook.py) to check whether the `num_classes` in head matches the length of `classes` in the metainfo of `dataset`. + +We set it in [default_runtime.py](../../../configs/_base_/default_runtime.py). + +```python +custom_hooks = [dict(type='NumClassCheckHook')] +``` + +### Modify default runtime hooks + +There are some common hooks that are registered through `default_hooks`, they are + +- `IterTimerHook`: A hook that logs 'data_time' for loading data and 'time' for a model train step. +- `LoggerHook`: A hook that Collect logs from different components of `Runner` and write them to terminal, JSON file, tensorboard and wandb .etc. +- `ParamSchedulerHook`: A hook to update some hyper-parameters in optimizer, e.g., learning rate and momentum. +- `CheckpointHook`: A hook that saves checkpoints periodically. +- `DistSamplerSeedHook`: A hook that sets the seed for sampler and batch_sampler. +- `DetVisualizationHook`: A hook used to visualize validation and testing process prediction results. + +`IterTimerHook`, `ParamSchedulerHook` and `DistSamplerSeedHook` are simple and no need to be modified usually, so here we reveals how what we can do with `LoggerHook`, `CheckpointHook` and `DetVisualizationHook`. + +#### CheckpointHook + +Except saving checkpoints periodically, [`CheckpointHook`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py#L19) provides other options such as `max_keep_ckpts`, `save_optimizer` and etc. The users could set `max_keep_ckpts` to only save small number of checkpoints or decide whether to store state dict of optimizer by `save_optimizer`. More details of the arguments are [here](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py#L19) + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + interval=1, + max_keep_ckpts=3, + save_optimizer=True)) +``` + +#### LoggerHook + +The `LoggerHook` enables to set intervals. And the detail usages can be found in the [docstring](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/logger_hook.py#L18). + +```python +default_hooks = dict(logger=dict(type='LoggerHook', interval=50)) +``` + +#### DetVisualizationHook + +`DetVisualizationHook` use `DetLocalVisualizer` to visualize prediction results, and `DetLocalVisualizer` current supports different backends, e.g., `TensorboardVisBackend` and `WandbVisBackend` (see [docstring](https://github.com/open-mmlab/mmengine/blob/main/mmengine/visualization/vis_backend.py) for more detail). The users could add multi backbends to do visualization, as follows. + +```python +default_hooks = dict( + visualization=dict(type='DetVisualizationHook', draw=True)) + +vis_backends = [dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +``` diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_transforms.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_transforms.md new file mode 100644 index 0000000000000000000000000000000000000000..5fe84e9f7c9fdac45db6210e2be9176b53e74536 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/customize_transforms.md @@ -0,0 +1,49 @@ +# Customize Data Pipelines + +1. Write a new transform in a file, e.g., in `my_pipeline.py`. It takes a dict as input and returns a dict. + + ```python + import random + from mmcv.transforms import BaseTransform + from mmdet.registry import TRANSFORMS + + + @TRANSFORMS.register_module() + class MyTransform(BaseTransform): + """Add your transform + + Args: + p (float): Probability of shifts. Default 0.5. + """ + + def __init__(self, prob=0.5): + self.prob = prob + + def transform(self, results): + if random.random() > self.prob: + results['dummy'] = True + return results + ``` + +2. Import and use the pipeline in your config file. + Make sure the import is relative to where your train script is located. + + ```python + custom_imports = dict(imports=['path.to.my_pipeline'], allow_failed_imports=False) + + train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='MyTransform', prob=0.2), + dict(type='PackDetInputs') + ] + ``` + +3. Visualize the output of your transforms pipeline + + To visualize the output of your transforms pipeline, `tools/misc/browse_dataset.py` + can help the user to browse a detection dataset (both images and bounding box annotations) + visually, or save the image to a designated directory. More details can refer to + [visualization documentation](../user_guides/visualization.md) diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/data_flow.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/data_flow.md new file mode 100644 index 0000000000000000000000000000000000000000..59e7ca329422c749a7f07b52e891a42cb5e0ae81 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/data_flow.md @@ -0,0 +1 @@ +# Data Flow diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/datasets.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/datasets.md new file mode 100644 index 0000000000000000000000000000000000000000..157ea3aad83c802540cb7a1c7a914592ef6d8ab7 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/datasets.md @@ -0,0 +1 @@ +# Datasets diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/engine.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/engine.md new file mode 100644 index 0000000000000000000000000000000000000000..eaa55b0c8c47f49fce4a2e827cc58af5212c3433 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/engine.md @@ -0,0 +1 @@ +# Engine diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/evaluation.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..b394c7690c4c67638ff6cf79becf0e139e1e7b1c --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/evaluation.md @@ -0,0 +1 @@ +# Evaluation diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/how_to.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/how_to.md new file mode 100644 index 0000000000000000000000000000000000000000..7eb41ceeb7a99a8539457689138b6f21273bd402 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/how_to.md @@ -0,0 +1,222 @@ +This tutorial collects answers to any `How to xxx with MMDetection`. Feel free to update this doc if you meet new questions about `How to` and find the answers! + +# Use backbone network through MMPretrain + +The model registry in MMDet, MMPreTrain, MMSeg all inherit from the root registry in MMEngine. This allows these repositories to directly use the modules already implemented by each other. Therefore, users can use backbone networks from MMPretrain in MMDetection without implementing a network that already exists in MMPretrain. + +## Use backbone network implemented in MMPretrain + +Suppose you want to use `MobileNetV3-small` as the backbone network of `RetinaNet`, the example config is as the following. + +```python +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict(imports=['mmpretrain.models'], allow_failed_imports=False) +pretrained = 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v3/convert/mobilenet_v3_small-8427ecf0.pth' +model = dict( + backbone=dict( + _delete_=True, # Delete the backbone field in _base_ + type='mmpretrain.MobileNetV3', # Using MobileNetV3 from mmpretrain + arch='small', + out_indices=(3, 8, 11), # Modify out_indices + init_cfg=dict( + type='Pretrained', + checkpoint=pretrained, + prefix='backbone.')), # The pre-trained weights of backbone network in mmpretrain have prefix='backbone.'. The prefix in the keys will be removed so that these weights can be normally loaded. + # Modify in_channels + neck=dict(in_channels=[24, 48, 96], start_level=0)) +``` + +## Use backbone network in TIMM through MMPretrain + +MMPretrain also provides a wrapper for the PyTorch Image Models (timm) backbone network, users can directly use the backbone network in timm through MMPretrain. Suppose you want to use [EfficientNet-B1](../../../configs/timm_example/retinanet_timm-efficientnet-b1_fpn_1x_coco.py) as the backbone network of RetinaNet, the example config is as the following. + +```python +# https://github.com/open-mmlab/mmdetection/blob/main/configs/timm_example/retinanet_timm-efficientnet-b1_fpn_1x_coco.py + +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict(imports=['mmpretrain.models'], allow_failed_imports=False) +model = dict( + backbone=dict( + _delete_=True, # Delete the backbone field in _base_ + type='mmpretrain.TIMMBackbone', # Using timm from mmpretrain + model_name='efficientnet_b1', + features_only=True, + pretrained=True, + out_indices=(1, 2, 3, 4)), # Modify out_indices + neck=dict(in_channels=[24, 40, 112, 320])) # Modify in_channels + +optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) +``` + +`type='mmpretrain.TIMMBackbone'` means use the `TIMMBackbone` class from MMPretrain in MMDetection, and the model used is `EfficientNet-B1`, where `mmpretrain` means the MMPretrain repo and `TIMMBackbone` means the TIMMBackbone wrapper implemented in MMPretrain. + +For the principle of the Hierarchy Registry, please refer to the [MMEngine document](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/config.md). For how to use other backbones in MMPretrain, you can refer to the [MMPretrain document](https://mmpretrain.readthedocs.io/en/latest/user_guides/config.html). + +# Use Mosaic augmentation + +If you want to use `Mosaic` in training, please make sure that you use `MultiImageMixDataset` at the same time. Taking the 'Faster R-CNN' algorithm as an example, you should modify the values of `train_pipeline` and `train_dataset` in the config as below: + +```python +# Open configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py directly and add the following fields +data_root = 'data/coco/' +dataset_type = 'CocoDataset' +img_scale=(1333, 800) + +train_pipeline = [ + dict(type='Mosaic', img_scale=img_scale, pad_val=114.0), + dict( + type='RandomAffine', + scaling_ratio_range=(0.1, 2), + border=(-img_scale[0] // 2, -img_scale[1] // 2)), # The image will be enlarged by 4 times after Mosaic processing,so we use affine transformation to restore the image size. + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +train_dataset = dict( + _delete_ = True, # remove unnecessary Settings + type='MultiImageMixDataset', + dataset=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=[ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True) + ], + filter_empty_gt=False, + ), + pipeline=train_pipeline + ) + +data = dict( + train=train_dataset + ) +``` + +# Unfreeze backbone network after freezing the backbone in the config + +If you have freezed the backbone network in the config and want to unfreeze it after some epoches, you can write a hook function to do it. Taking the Faster R-CNN with the resnet backbone as an example, you can freeze one stage of the backbone network and add a `custom_hooks` in the config as below: + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +model = dict( + # freeze one stage of the backbone network. + backbone=dict(frozen_stages=1), +) +custom_hooks = [dict(type="UnfreezeBackboneEpochBasedHook", unfreeze_epoch=1)] +``` + +Meanwhile write the hook class `UnfreezeBackboneEpochBasedHook` in `mmdet/core/hook/unfreeze_backbone_epoch_based_hook.py` + +```python +from mmengine.model import is_model_wrapper +from mmengine.hooks import Hook +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class UnfreezeBackboneEpochBasedHook(Hook): + """Unfreeze backbone network Hook. + + Args: + unfreeze_epoch (int): The epoch unfreezing the backbone network. + """ + + def __init__(self, unfreeze_epoch=1): + self.unfreeze_epoch = unfreeze_epoch + + def before_train_epoch(self, runner): + # Unfreeze the backbone network. + # Only valid for resnet. + if runner.epoch == self.unfreeze_epoch: + model = runner.model + if is_model_wrapper(model): + model = model.module + backbone = model.backbone + if backbone.frozen_stages >= 0: + if backbone.deep_stem: + backbone.stem.train() + for param in backbone.stem.parameters(): + param.requires_grad = True + else: + backbone.norm1.train() + for m in [backbone.conv1, backbone.norm1]: + for param in m.parameters(): + param.requires_grad = True + + for i in range(1, backbone.frozen_stages + 1): + m = getattr(backbone, f'layer{i}') + m.train() + for param in m.parameters(): + param.requires_grad = True +``` + +# Get the channels of a new backbone + +If you want to get the channels of a new backbone, you can build this backbone alone and input a pseudo image to get each stage output. + +Take `ResNet` as an example: + +```python +from mmdet.models import ResNet +import torch +self = ResNet(depth=18) +self.eval() +inputs = torch.rand(1, 3, 32, 32) +level_outputs = self.forward(inputs) +for level_out in level_outputs: + print(tuple(level_out.shape)) + +``` + +Output of the above script is as below: + +```python +(1, 64, 8, 8) +(1, 128, 4, 4) +(1, 256, 2, 2) +(1, 512, 1, 1) +``` + +Users can get the channels of the new backbone by Replacing the `ResNet(depth=18)` in this script with their customized backbone. + +# Use Detectron2 Model in MMDetection + +Users can use Detectron2Wrapper to run Detectron2's model in MMDetection. We provide examples of [Faster R-CNN](../../../configs/misc/d2_faster-rcnn_r50-caffe_fpn_ms-90k_coco.py), +[Mask R-CNN](../../../configs/misc/d2_mask-rcnn_r50-caffe_fpn_ms-90k_coco.py), and [RetinaNet](../../../configs/misc/d2_retinanet_r50-caffe_fpn_ms-90k_coco.py) in MMDetection. + +The algorithm components in config file should be the same as those of in Detectron2. During setup, we will first initialize the default settings, which can be found in [Detectron2](https://github.com/facebookresearch/detectron2/blob/main/detectron2/config/defaults.py). +Then, the settings in config file will overwrite the default settings and the model will be built with these settings. +The input data will first convert to Detectron2's type and feed into Detectron2's model. +During inference the results calculate from Detectron2's model will reconvert back to the MMDetection's type. + +## Use Detectron2's pre-trained weights + +The weight initialization in `Detectron2Wrapper` will not use the logic of MMDetection. Users can set `model.d2_detector.weights=xxx` to load pre-trained weights. +For example, we can use `model.d2_detector.weights='detectron2://ImageNetPretrained/MSRA/R-50.pkl'` to load the pre-trained ResNet-50 or use +`model.d2_detector.weights='detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/137260431/model_final_a54504.pkl'` to load the pre-trained Mask R-CNN weights proposed in Detectron2. + +**Note:** Detectron2's pretrained model cannot be loaded directly by using `load_from`, it should be first converted via `tools/model_converters/detectron2_to_mmdet.py` + +For inference of released detectron2 checkpoints, users should first use `tools/model_converters/detectron2_to_mmdet.py` to convert Detectron2 checkpoint to MMDetection. + +```shell +python tools/model_converters/detectron2_to_mmdet.py ${Detectron2 ckpt path} ${MMDetectron ckpt path} +``` diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/index.rst b/mmdet_code/SR-TOD/docs/en/advanced_guides/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..20d8177498222efbc568a14a5f6e691a2a360a90 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/index.rst @@ -0,0 +1,34 @@ +Basic Concepts +*************** + +.. toctree:: + :maxdepth: 1 + + data_flow.md + structures.md + models.md + datasets.md + transforms.md + evaluation.md + engine.md + conventions.md + +Component Customization +************************ + +.. toctree:: + :maxdepth: 1 + + customize_models.md + customize_losses.md + customize_dataset.md + customize_transforms.md + customize_runtime.md + +How to +************************ + +.. toctree:: + :maxdepth: 1 + + how_to.md diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/models.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/models.md new file mode 100644 index 0000000000000000000000000000000000000000..91361720ebfffda1ff30f500879c18dafe084dc9 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/models.md @@ -0,0 +1 @@ +# Models diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/structures.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/structures.md new file mode 100644 index 0000000000000000000000000000000000000000..985286177db39812a8d39c77d365d7aade4ae08f --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/structures.md @@ -0,0 +1 @@ +# Structures diff --git a/mmdet_code/SR-TOD/docs/en/advanced_guides/transforms.md b/mmdet_code/SR-TOD/docs/en/advanced_guides/transforms.md new file mode 100644 index 0000000000000000000000000000000000000000..4db036ae5c2433df3dfdf6a704827aaa13cad667 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/advanced_guides/transforms.md @@ -0,0 +1,42 @@ +# Data Transforms (Need to update) + +## Design of Data transforms pipeline + +Following typical conventions, we use `Dataset` and `DataLoader` for data loading +with multiple workers. `Dataset` returns a dict of data items corresponding +the arguments of models' forward method. + +The data transforms pipeline and the dataset is decomposed. Usually a dataset +defines how to process the annotations and a data transforms pipeline defines all the steps to prepare a data dict. +A pipeline consists of a sequence of data transforms. Each operation takes a dict as input and also output a dict for the next transform. + +We present a classical pipeline in the following figure. The blue blocks are pipeline operations. With the pipeline going on, each operator can add new keys (marked as green) to the result dict or update the existing keys (marked as orange). +![pipeline figure](../../../resources/data_pipeline.png) + +Here is a pipeline example for Faster R-CNN. + +```python +train_pipeline = [ # Training data processing pipeline + dict(type='LoadImageFromFile', backend_args=backend_args), # First pipeline to load images from file path + dict( + type='LoadAnnotations', # Second pipeline to load annotations for current image + with_bbox=True), # Whether to use bounding box, True for detection + dict( + type='Resize', # Pipeline that resize the images and their annotations + scale=(1333, 800), # The largest scale of image + keep_ratio=True # Whether to keep the ratio between height and width + ), + dict( + type='RandomFlip', # Augmentation pipeline that flip the images and their annotations + prob=0.5), # The probability to flip + dict(type='PackDetInputs') # Pipeline that formats the annotation data and decides which keys in the data should be packed into data_samples +] +test_pipeline = [ # Testing data processing pipeline + dict(type='LoadImageFromFile', backend_args=backend_args), # First pipeline to load images from file path + dict(type='Resize', scale=(1333, 800), keep_ratio=True), # Pipeline that resize the images + dict( + type='PackDetInputs', # Pipeline that formats the annotation data and decides which keys in the data should be packed into data_samples + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +``` diff --git a/mmdet_code/SR-TOD/docs/en/api.rst b/mmdet_code/SR-TOD/docs/en/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..1b1273219e8ac7af1a9e2e27a3f80d6a18c630e5 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/api.rst @@ -0,0 +1,161 @@ +mmdet.apis +-------------- +.. automodule:: mmdet.apis + :members: + +mmdet.datasets +-------------- + +datasets +^^^^^^^^^^ +.. automodule:: mmdet.datasets + :members: + +api_wrappers +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.datasets.api_wrappers + :members: + +samplers +^^^^^^^^^^ +.. automodule:: mmdet.datasets.samplers + :members: + +transforms +^^^^^^^^^^^^ +.. automodule:: mmdet.datasets.transforms + :members: + +mmdet.engine +-------------- + +hooks +^^^^^^^^^^ +.. automodule:: mmdet.engine.hooks + :members: + +optimizers +^^^^^^^^^^^^^^^ +.. automodule:: mmdet.engine.optimizers + :members: + +runner +^^^^^^^^^^ +.. automodule:: mmdet.engine.runner + :members: + +schedulers +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.engine.schedulers + :members: + +mmdet.evaluation +-------------------- + +functional +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.evaluation.functional + :members: + +metrics +^^^^^^^^^^ +.. automodule:: mmdet.evaluation.metrics + :members: + + +mmdet.models +-------------- + +backbones +^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.backbones + :members: + +data_preprocessors +^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.data_preprocessors + :members: + +dense_heads +^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.dense_heads + :members: + +detectors +^^^^^^^^^^ +.. automodule:: mmdet.models.detectors + :members: + +layers +^^^^^^^^^^ +.. automodule:: mmdet.models.layers + :members: + +losses +^^^^^^^^^^ +.. automodule:: mmdet.models.losses + :members: + +necks +^^^^^^^^^^^^ +.. automodule:: mmdet.models.necks + :members: + +roi_heads +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.roi_heads + :members: + +seg_heads +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.seg_heads + :members: + +task_modules +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.task_modules + :members: + +test_time_augs +^^^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.test_time_augs + :members: + +utils +^^^^^^^^^^ +.. automodule:: mmdet.models.utils + :members: + + +mmdet.structures +-------------------- + +structures +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.structures + :members: + +bbox +^^^^^^^^^^ +.. automodule:: mmdet.structures.bbox + :members: + +mask +^^^^^^^^^^ +.. automodule:: mmdet.structures.mask + :members: + +mmdet.testing +---------------- +.. automodule:: mmdet.testing + :members: + +mmdet.visualization +-------------------- +.. automodule:: mmdet.visualization + :members: + +mmdet.utils +-------------- +.. automodule:: mmdet.utils + :members: diff --git a/mmdet_code/SR-TOD/docs/en/conf.py b/mmdet_code/SR-TOD/docs/en/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..d2beaf1e5c1ca9708d3556476ee3a5073dfdfc5b --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/conf.py @@ -0,0 +1,116 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/main/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import subprocess +import sys + +import pytorch_sphinx_theme + +sys.path.insert(0, os.path.abspath('../..')) + +# -- Project information ----------------------------------------------------- + +project = 'MMDetection' +copyright = '2018-2021, OpenMMLab' +author = 'MMDetection Authors' +version_file = '../../mmdet/version.py' + + +def get_version(): + with open(version_file, 'r') as f: + exec(compile(f.read(), version_file, 'exec')) + return locals()['__version__'] + + +# The full version, including alpha/beta/rc tags +release = get_version() + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.napoleon', + 'sphinx.ext.viewcode', + 'myst_parser', + 'sphinx_markdown_tables', + 'sphinx_copybutton', +] + +myst_enable_extensions = ['colon_fence'] +myst_heading_anchors = 3 + +autodoc_mock_imports = [ + 'matplotlib', 'pycocotools', 'terminaltables', 'mmdet.version', 'mmcv.ops' +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +source_suffix = { + '.rst': 'restructuredtext', + '.md': 'markdown', +} + +# The main toctree document. +master_doc = 'index' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +# html_theme = 'sphinx_rtd_theme' +html_theme = 'pytorch_sphinx_theme' +html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()] + +html_theme_options = { + 'menu': [ + { + 'name': 'GitHub', + 'url': 'https://github.com/open-mmlab/mmdetection' + }, + ], + # Specify the language of shared menu + 'menu_lang': + 'en' +} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] +html_css_files = ['css/readthedocs.css'] + +# -- Extension configuration ------------------------------------------------- +# Ignore >>> when copying code +copybutton_prompt_text = r'>>> |\.\.\. ' +copybutton_prompt_is_regexp = True + + +def builder_inited_handler(app): + subprocess.run(['./stat.py']) + + +def setup(app): + app.connect('builder-inited', builder_inited_handler) diff --git a/mmdet_code/SR-TOD/docs/en/dataset_zoo.md b/mmdet_code/SR-TOD/docs/en/dataset_zoo.md new file mode 100644 index 0000000000000000000000000000000000000000..c35cc220bc001f20f02421ac892efe9e6bb7c925 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/dataset_zoo.md @@ -0,0 +1 @@ +# Dataset Zoo diff --git a/mmdet_code/SR-TOD/docs/en/get_started.md b/mmdet_code/SR-TOD/docs/en/get_started.md new file mode 100644 index 0000000000000000000000000000000000000000..c00eb96b76c68b0db3f70697c601428ac2766595 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/get_started.md @@ -0,0 +1,297 @@ +# GET STARTED + +## Prerequisites + +In this section, we demonstrate how to prepare an environment with PyTorch. + +MMDetection works on Linux, Windows, and macOS. It requires Python 3.7+, CUDA 9.2+, and PyTorch 1.8+. + +```{note} +If you are experienced with PyTorch and have already installed it, just skip this part and jump to the [next section](#installation). Otherwise, you can follow these steps for the preparation. +``` + +**Step 0.** Download and install Miniconda from the [official website](https://docs.conda.io/en/latest/miniconda.html). + +**Step 1.** Create a conda environment and activate it. + +```shell +conda create --name openmmlab python=3.8 -y +conda activate openmmlab +``` + +**Step 2.** Install PyTorch following [official instructions](https://pytorch.org/get-started/locally/), e.g. + +On GPU platforms: + +```shell +conda install pytorch torchvision -c pytorch +``` + +On CPU platforms: + +```shell +conda install pytorch torchvision cpuonly -c pytorch +``` + +## Installation + +We recommend that users follow our best practices to install MMDetection. However, the whole process is highly customizable. See [Customize Installation](#customize-installation) section for more information. + +### Best Practices + +**Step 0.** Install [MMEngine](https://github.com/open-mmlab/mmengine) and [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim). + +```shell +pip install -U openmim +mim install mmengine +mim install "mmcv>=2.0.0" +``` + +**Note:** In MMCV-v2.x, `mmcv-full` is rename to `mmcv`, if you want to install `mmcv` without CUDA ops, you can use `mim install "mmcv-lite>=2.0.0rc1"` to install the lite version. + +**Step 1.** Install MMDetection. + +Case a: If you develop and run mmdet directly, install it from source: + +```shell +git clone https://github.com/open-mmlab/mmdetection.git +cd mmdetection +pip install -v -e . +# "-v" means verbose, or more output +# "-e" means installing a project in editable mode, +# thus any local modifications made to the code will take effect without reinstallation. +``` + +Case b: If you use mmdet as a dependency or third-party package, install it with MIM: + +```shell +mim install mmdet +``` + +## Verify the installation + +To verify whether MMDetection is installed correctly, we provide some sample codes to run an inference demo. + +**Step 1.** We need to download config and checkpoint files. + +```shell +mim download mmdet --config rtmdet_tiny_8xb32-300e_coco --dest . +``` + +The downloading will take several seconds or more, depending on your network environment. When it is done, you will find two files `rtmdet_tiny_8xb32-300e_coco.py` and `rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth` in your current folder. + +**Step 2.** Verify the inference demo. + +Case a: If you install MMDetection from source, just run the following command. + +```shell +python demo/image_demo.py demo/demo.jpg rtmdet_tiny_8xb32-300e_coco.py --weights rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --device cpu +``` + +You will see a new image `demo.jpg` on your `./outputs/vis` folder, where bounding boxes are plotted on cars, benches, etc. + +Case b: If you install MMDetection with MIM, open your python interpreter and copy&paste the following codes. + +```python +from mmdet.apis import init_detector, inference_detector + +config_file = 'rtmdet_tiny_8xb32-300e_coco.py' +checkpoint_file = 'rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth' +model = init_detector(config_file, checkpoint_file, device='cpu') # or device='cuda:0' +inference_detector(model, 'demo/demo.jpg') +``` + +You will see a list of `DetDataSample`, and the predictions are in the `pred_instance`, indicating the detected bounding boxes, labels, and scores. + +## Tracking Installation + +We recommend that users follow our best practices to install MMDetection for for tracking task. + +### Best Practices + +**Step 0.** Install [MMEngine](https://github.com/open-mmlab/mmengine) and [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim). + +```shell +pip install -U openmim +mim install mmengine +mim install "mmcv>=2.0.0" +``` + +**Step 1.** Install MMDetection. + +Case a: If you develop and run mmdet directly, install it from source: + +```shell +git clone https://github.com/open-mmlab/mmdetection.git +cd mmdetection +pip install -v -e . -r requirements/tracking.txt +# "-v" means verbose, or more output +# "-e" means installing a project in editable mode, +# thus any local modifications made to the code will take effect without reinstallation. +``` + +Case b: If you use mmdet as a dependency or third-party package, install it with MIM: + +```shell +mim install mmdet[tracking] +``` + +**Step 2.** Install TrackEval. + +```shell +pip install git+https://github.com/JonathonLuiten/TrackEval.git +``` + +## Verify the installation + +To verify whether MMDetection is installed correctly, we provide some sample codes to run an inference demo. + +**Step 1.** We need to download config and checkpoint files. + +```shell +mim download mmdet --config bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval --dest . +``` + +The downloading will take several seconds or more, depending on your network environment. When it is done, you will find two files `bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py` and `bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500-1985c9f0.pth` in your current folder. + +**Step 2.** Verify the inference demo. + +Case a: If you install MMDetection from source, just run the following command. + +```shell +python demo/mot_demo.py demo/demo_mot.mp4 bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py --checkpoint bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500-1985c9f0.pth --out mot.mp4 +``` + +You will see a new video `mot.mp4` on your folder, where bounding boxes are plotted on person. + +Case b: If you install MMDetection with MIM, open your python interpreter and demo/mot_demo.py, then run it like Case a. + +### Customize Installation + +#### CUDA versions + +When installing PyTorch, you need to specify the version of CUDA. If you are not clear on which to choose, follow our recommendations: + +- For Ampere-based NVIDIA GPUs, such as GeForce 30 series and NVIDIA A100, CUDA 11 is a must. +- For older NVIDIA GPUs, CUDA 11 is backward compatible, but CUDA 10.2 offers better compatibility and is more lightweight. + +Please make sure the GPU driver satisfies the minimum version requirements. See [this table](https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cuda-major-component-versions__table-cuda-toolkit-driver-versions) for more information. + +```{note} +Installing CUDA runtime libraries is enough if you follow our best practices, because no CUDA code will be compiled locally. However, if you hope to compile MMCV from source or develop other CUDA operators, you need to install the complete CUDA toolkit from NVIDIA's [website](https://developer.nvidia.com/cuda-downloads), and its version should match the CUDA version of PyTorch. i.e., the specified version of cudatoolkit in the `conda install` command. +``` + +#### Install MMEngine without MIM + +To install MMEngine with pip instead of MIM, please follow [MMEngine installation guides](https://mmengine.readthedocs.io/en/latest/get_started/installation.html). + +For example, you can install MMEngine by the following command. + +```shell +pip install mmengine +``` + +#### Install MMCV without MIM + +MMCV contains C++ and CUDA extensions, thus depending on PyTorch in a complex way. MIM solves such dependencies automatically and makes the installation easier. However, it is not a must. + +To install MMCV with pip instead of MIM, please follow [MMCV installation guides](https://mmcv.readthedocs.io/en/2.x/get_started/installation.html). This requires manually specifying a find-url based on the PyTorch version and its CUDA version. + +For example, the following command installs MMCV built for PyTorch 1.12.x and CUDA 11.6. + +```shell +pip install "mmcv>=2.0.0" -f https://download.openmmlab.com/mmcv/dist/cu116/torch1.12.0/index.html +``` + +#### Install on CPU-only platforms + +MMDetection can be built for CPU-only environments. In CPU mode you can train (requires MMCV version >= 2.0.0rc1), test, or infer a model. + +However, some functionalities are gone in this mode: + +- Deformable Convolution +- Modulated Deformable Convolution +- ROI pooling +- Deformable ROI pooling +- CARAFE +- SyncBatchNorm +- CrissCrossAttention +- MaskedConv2d +- Temporal Interlace Shift +- nms_cuda +- sigmoid_focal_loss_cuda +- bbox_overlaps + +If you try to train/test/infer a model containing the above ops, an error will be raised. +The following table lists affected algorithms. + +| Operator | Model | +| :-----------------------------------------------------: | :--------------------------------------------------------------------------------------: | +| Deformable Convolution/Modulated Deformable Convolution | DCN、Guided Anchoring、RepPoints、CentripetalNet、VFNet、CascadeRPN、NAS-FCOS、DetectoRS | +| MaskedConv2d | Guided Anchoring | +| CARAFE | CARAFE | +| SyncBatchNorm | ResNeSt | + +#### Install on Google Colab + +[Google Colab](https://colab.research.google.com/) usually has PyTorch installed, +thus we only need to install MMEngine, MMCV, and MMDetection with the following commands. + +**Step 1.** Install [MMEngine](https://github.com/open-mmlab/mmengine) and [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim). + +```shell +!pip3 install openmim +!mim install mmengine +!mim install "mmcv>=2.0.0,<2.1.0" +``` + +**Step 2.** Install MMDetection from the source. + +```shell +!git clone https://github.com/open-mmlab/mmdetection.git +%cd mmdetection +!pip install -e . +``` + +**Step 3.** Verification. + +```python +import mmdet +print(mmdet.__version__) +# Example output: 3.0.0, or an another version. +``` + +```{note} +Within Jupyter, the exclamation mark `!` is used to call external executables and `%cd` is a [magic command](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-cd) to change the current working directory of Python. +``` + +#### Use MMDetection with Docker + +We provide a [Dockerfile](../../docker/Dockerfile) to build an image. Ensure that your [docker version](https://docs.docker.com/engine/install/) >=19.03. + +```shell +# build an image with PyTorch 1.9, CUDA 11.1 +# If you prefer other versions, just modified the Dockerfile +docker build -t mmdetection docker/ +``` + +Run it with + +```shell +docker run --gpus all --shm-size=8g -it -v {DATA_DIR}:/mmdetection/data mmdetection +``` + +### Troubleshooting + +If you have some issues during the installation, please first view the [FAQ](notes/faq.md) page. +You may [open an issue](https://github.com/open-mmlab/mmdetection/issues/new/choose) on GitHub if no solution is found. + +### Use Multiple Versions of MMDetection in Development + +Training and testing scripts have already been modified in `PYTHONPATH` in order to make sure the scripts are using their own versions of MMDetection. + +To install the default version of MMDetection in your environment, you can exclude the follow code in the relative scripts: + +```shell +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH +``` diff --git a/mmdet_code/SR-TOD/docs/en/index.rst b/mmdet_code/SR-TOD/docs/en/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..32c5952a4ae438b491a7408f61b9d833e54f1b68 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/index.rst @@ -0,0 +1,63 @@ +Welcome to MMDetection's documentation! +======================================= + +.. toctree:: + :maxdepth: 1 + :caption: Get Started + + overview.md + get_started.md + +.. toctree:: + :maxdepth: 2 + :caption: User Guides + + user_guides/index.rst + +.. toctree:: + :maxdepth: 2 + :caption: Advanced Guides + + advanced_guides/index.rst + +.. toctree:: + :maxdepth: 1 + :caption: Migration + + migration/migration.md + +.. toctree:: + :maxdepth: 1 + :caption: API Reference + + api.rst + +.. toctree:: + :maxdepth: 1 + :caption: Model Zoo + + model_zoo.md + +.. toctree:: + :maxdepth: 1 + :caption: Notes + + notes/contribution_guide.md + notes/projects.md + notes/changelog.md + notes/changelog_v2.x.md + notes/faq.md + notes/compatibility.md + +.. toctree:: + :caption: Switch Language + + switch_language.md + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`search` diff --git a/mmdet_code/SR-TOD/docs/en/make.bat b/mmdet_code/SR-TOD/docs/en/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..922152e96a04a242e6fc40f124261d74890617d8 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/mmdet_code/SR-TOD/docs/en/migration.md b/mmdet_code/SR-TOD/docs/en/migration.md new file mode 100644 index 0000000000000000000000000000000000000000..689e8d24e45c578b273836d48697610cf63f7115 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/migration.md @@ -0,0 +1 @@ +# Migration diff --git a/mmdet_code/SR-TOD/docs/en/migration/api_and_registry_migration.md b/mmdet_code/SR-TOD/docs/en/migration/api_and_registry_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..72bfd3aec8e34136acf16c2313c1eecad9cfb461 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/migration/api_and_registry_migration.md @@ -0,0 +1 @@ +# Migrate API and Registry from MMDetection 2.x to 3.x diff --git a/mmdet_code/SR-TOD/docs/en/migration/config_migration.md b/mmdet_code/SR-TOD/docs/en/migration/config_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..0a390b67bb2fd20d363b1bfea83561aeb7e90b99 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/migration/config_migration.md @@ -0,0 +1,819 @@ +# Migrate Configuration File from MMDetection 2.x to 3.x + +The configuration file of MMDetection 3.x has undergone significant changes in comparison to the 2.x version. This document explains how to migrate 2.x configuration files to 3.x. + +In the previous tutorial [Learn about Configs](../user_guides/config.md), we used Mask R-CNN as an example to introduce the configuration file structure of MMDetection 3.x. Here, we will follow the same structure to demonstrate how to migrate 2.x configuration files to 3.x. + +## Model Configuration + +There have been no major changes to the model configuration in 3.x compared to 2.x. For the model's backbone, neck, head, as well as train_cfg and test_cfg, the parameters remain the same as in version 2.x. + +On the other hand, we have added the `DataPreprocessor` module in MMDetection 3.x. The configuration for the `DataPreprocessor` module is located in `model.data_preprocessor`. It is used to preprocess the input data, such as normalizing input images and padding images of different sizes into batches, and loading images from memory to VRAM. This configuration replaces the `Normalize` and `Pad` modules in `train_pipeline` and `test_pipeline` of the earlier version. + + + + + + + + + +
2.x Config + +```python +# Image normalization parameters +img_norm_cfg = dict( + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True) +pipeline=[ + ..., + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), # Padding the image to multiples of 32 + ... +] +``` + +
3.x Config + +```python +model = dict( + data_preprocessor=dict( + type='DetDataPreprocessor', + # Image normalization parameters + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + # Image padding parameters + pad_mask=True, # In instance segmentation, the mask needs to be padded + pad_size_divisor=32) # Padding the image to multiples of 32 +) + +``` + +
+ +## Dataset and Evaluator Configuration + +The dataset and evaluator configurations have undergone major changes compared to version 2.x. We will introduce how to migrate from version 2.x to version 3.x from three aspects: Dataloader and Dataset, Data transform pipeline, and Evaluator configuration. + +### Dataloader and Dataset Configuration + +In the new version, we set the data loading settings consistent with PyTorch's official DataLoader, +making it easier for users to understand and get started with. +We put the data loading settings for training, validation, and testing separately in `train_dataloader`, `val_dataloader`, and `test_dataloader`. +Users can set different parameters for these dataloaders. +The input parameters are basically the same as those required by [PyTorch DataLoader](https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader). + +This way, we put the unconfigurable parameters in version 2.x, such as `sampler`, `batch_sampler`, and `persistent_workers`, in the configuration file, so that users can set dataloader parameters more flexibly. + +Users can set the dataset configuration through `train_dataloader.dataset`, `val_dataloader.dataset`, and `test_dataloader.dataset`, which correspond to `data.train`, `data.val`, and `data.test` in version 2.x. + + + + + + + + + +
2.x Config + +```python +data = dict( + samples_per_gpu=2, + workers_per_gpu=2, + train=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=train_pipeline), + val=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline), + test=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline)) +``` + +
3.x Config + +```python +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, # Avoid recreating subprocesses after each iteration + sampler=dict(type='DefaultSampler', shuffle=True), # Default sampler, supports both distributed and non-distributed training + batch_sampler=dict(type='AspectRatioBatchSampler'), # Default batch_sampler, used to ensure that images in the batch have similar aspect ratios, so as to better utilize graphics memory + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline)) +# In version 3.x, validation and test dataloaders can be configured independently +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader # The configuration of the testing dataloader is the same as that of the validation dataloader, which is omitted here + +``` + +
+ +### Data Transform Pipeline Configuration + +As mentioned earlier, we have separated the normalization and padding configurations for images from the `train_pipeline` and `test_pipeline`, and have placed them in `model.data_preprocessor` instead. Hence, in the 3.x version of the pipeline, we no longer require the `Normalize` and `Pad` transforms. + +At the same time, we have also refactored the transform responsible for packing the data format, and have merged the `Collect` and `DefaultFormatBundle` transforms into `PackDetInputs`. This transform is responsible for packing the data from the data pipeline into the input format of the model. For more details on the input format conversion, please refer to the [data flow documentation](../advanced_guides/data_flow.md). + +Below, we will use the `train_pipeline` of Mask R-CNN as an example, to demonstrate how to migrate from the 2.x configuration to the 3.x configuration: + + + + + + + + + +
2.x Config + +```python +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=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', flip_ratio=0.5), + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='DefaultFormatBundle'), + dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), +] +``` + +
3.x Config + +```python +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +``` + +
+ +For the `test_pipeline`, apart from removing the `Normalize` and `Pad` transforms, we have also separated the data augmentation for testing (TTA) from the normal testing process, and have removed `MultiScaleFlipAug`. For more information on how to use the new TTA version, please refer to the [TTA documentation](../advanced_guides/tta.md). + +Below, we will again use the `test_pipeline` of Mask R-CNN as an example, to demonstrate how to migrate from the 2.x configuration to the 3.x configuration: + + + + + + + + + +
2.x Config + +```python +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', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='ImageToTensor', keys=['img']), + dict(type='Collect', keys=['img']), + ]) +] +``` + +
3.x Config + +```python +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +``` + +
+ +In addition, we have also refactored some data augmentation transforms. The following table lists the mapping between the transforms used in the 2.x version and the 3.x version: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name2.x Config3.x Config
Resize + +```python +dict(type='Resize', + img_scale=(1333, 800), + keep_ratio=True) +``` + + + +```python +dict(type='Resize', + scale=(1333, 800), + keep_ratio=True) +``` + +
RandomResize + +```python +dict( + type='Resize', + img_scale=[ + (1333, 640), (1333, 800)], + multiscale_mode='range', + keep_ratio=True) +``` + + + +```python +dict( + type='RandomResize', + scale=[ + (1333, 640), (1333, 800)], + keep_ratio=True) +``` + +
RandomChoiceResize + +```python +dict( + type='Resize', + img_scale=[ + (1333, 640), (1333, 672), + (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + multiscale_mode='value', + keep_ratio=True) +``` + + + +```python +dict( + type='RandomChoiceResize', + scales=[ + (1333, 640), (1333, 672), + (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True) +``` + +
RandomFlip + +```python +dict(type='RandomFlip', flip_ratio=0.5) +``` + + + +```python +dict(type='RandomFlip', prob=0.5) +``` + +
+ +### 评测器配置 + +In version 3.x, model accuracy evaluation is no longer tied to the dataset, but is instead accomplished through the use of an Evaluator. +The Evaluator configuration is divided into two parts: `val_evaluator` and `test_evaluator`. The `val_evaluator` is used for validation dataset evaluation, while the `test_evaluator` is used for testing dataset evaluation. +This corresponds to the `evaluation` field in version 2.x. + +The following table shows the corresponding relationship between Evaluators in version 2.x and 3.x. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Metric Name2.x Config3.x Config
COCO + +```python +data = dict( + val=dict( + type='CocoDataset', + ann_file=data_root + 'annotations/instances_val2017.json')) +evaluation = dict(metric=['bbox', 'segm']) +``` + + + +```python +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False) +``` + +
Pascal VOC + +```python +data = dict( + val=dict( + type=dataset_type, + ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt')) +evaluation = dict(metric='mAP') +``` + + + +```python +val_evaluator = dict( + type='VOCMetric', + metric='mAP', + eval_mode='11points') +``` + +
OpenImages + +```python +data = dict( + val=dict( + type='OpenImagesDataset', + ann_file=data_root + 'annotations/validation-annotations-bbox.csv', + img_prefix=data_root + 'OpenImages/validation/', + label_file=data_root + 'annotations/class-descriptions-boxable.csv', + hierarchy_file=data_root + + 'annotations/bbox_labels_600_hierarchy.json', + meta_file=data_root + 'annotations/validation-image-metas.pkl', + image_level_ann_file=data_root + + 'annotations/validation-annotations-human-imagelabels-boxable.csv')) +evaluation = dict(interval=1, metric='mAP') +``` + + + +```python +val_evaluator = dict( + type='OpenImagesMetric', + iou_thrs=0.5, + ioa_thrs=0.5, + use_group_of=True, + get_supercategory=True) +``` + +
CityScapes + +```python +data = dict( + val=dict( + type='CityScapesDataset', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + img_prefix=data_root + 'leftImg8bit/val/', + pipeline=test_pipeline)) +evaluation = dict(metric=['bbox', 'segm']) +``` + + + +```python +val_evaluator = [ + dict( + type='CocoMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + metric=['bbox', 'segm']), + dict( + type='CityScapesMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + seg_prefix=data_root + '/gtFine/val', + outfile_prefix='./work_dirs/cityscapes_metric/instance') +] +``` + +
+ +## Configuration for Training and Testing + + + + + + + + + +
2.x Config + +```python +runner = dict( + type='EpochBasedRunner', # Type of training loop + max_epochs=12) # Maximum number of training epochs +evaluation = dict(interval=2) # Interval for evaluation, check the performance every 2 epochs +``` + +
3.x Config + +```python +train_cfg = dict( + type='EpochBasedTrainLoop', # Type of training loop, please refer to https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py + max_epochs=12, # Maximum number of training epochs + val_interval=2) # Interval for validation, check the performance every 2 epochs +val_cfg = dict(type='ValLoop') # Type of validation loop +test_cfg = dict(type='TestLoop') # Type of testing loop +``` + +
+ +## Optimization Configuration + +The configuration for optimizer and gradient clipping is moved to the `optim_wrapper` field. +The following table shows the correspondences for optimizer configuration between 2.x version and 3.x version: + + + + + + + + + +
2.x Config + +```python +optimizer = dict( + type='SGD', # Optimizer: Stochastic Gradient Descent + lr=0.02, # Base learning rate + momentum=0.9, # SGD with momentum + weight_decay=0.0001) # Weight decay +optimizer_config = dict(grad_clip=None) # Configuration for gradient clipping, set to None to disable +``` + +
3.x Config + +```python +optim_wrapper = dict( # Configuration for the optimizer wrapper + type='OptimWrapper', # Type of optimizer wrapper, you can switch to AmpOptimWrapper to enable mixed precision training + optimizer=dict( # Optimizer configuration, supports various PyTorch optimizers, please refer to https://pytorch.org/docs/stable/optim.html#algorithms + type='SGD', # SGD + lr=0.02, # Base learning rate + momentum=0.9, # SGD with momentum + weight_decay=0.0001), # Weight decay + clip_grad=None, # Configuration for gradient clipping, set to None to disable. For usage, please see https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html + ) +``` + +
+ +The configuration for learning rate is also moved from the `lr_config` field to the `param_scheduler` field. The `param_scheduler` configuration is more similar to PyTorch's learning rate scheduler and more flexible. The following table shows the correspondences for learning rate configuration between 2.x version and 3.x version: + + + + + + + + + +
2.x Config + +```python +lr_config = dict( + policy='step', # Use multi-step learning rate strategy during training + warmup='linear', # Use linear learning rate warmup + warmup_iters=500, # End warmup at iteration 500 + warmup_ratio=0.001, # Coefficient for learning rate warmup + step=[8, 11], # Learning rate decay at which epochs + gamma=0.1) # Learning rate decay coefficient + +``` + +
3.x Config + +```python +param_scheduler = [ + dict( + type='LinearLR', # Use linear learning rate warmup + start_factor=0.001, # Coefficient for learning rate warmup + by_epoch=False, # Update the learning rate during warmup at each iteration + begin=0, # Starting from the first iteration + end=500), # End at the 500th iteration + dict( + type='MultiStepLR', # Use multi-step learning rate strategy during training + by_epoch=True, # Update the learning rate at each epoch + begin=0, # Starting from the first epoch + end=12, # Ending at the 12th epoch + milestones=[8, 11], # Learning rate decay at which epochs + gamma=0.1) # Learning rate decay coefficient +] + +``` + +
+ +For information on how to migrate other learning rate adjustment policies, please refer to the [learning rate migration document of MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/migration/param_scheduler.html). + +## Migration of Other Configurations + +### Configuration for Saving Checkpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Function2.x Config3.x Config
Set Save Interval + +```python +checkpoint_config = dict( + interval=1) +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + interval=1)) +``` + +
Save Best Model + +```python +evaluation = dict( + save_best='auto') +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + save_best='auto')) +``` + +
Keep Latest Model + +```python +checkpoint_config = dict( + max_keep_ckpts=3) +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + max_keep_ckpts=3)) +``` + +
+ +### Logging Configuration + +In MMDetection 3.x, the logging and visualization of the log are carried out respectively by the logger and visualizer in MMEngine. The following table shows the comparison between the configuration of printing logs and visualizing logs in MMDetection 2.x and 3.x. + + + + + + + + + + + + + + + + + + + + + + + + +
Function2.x Config3.x Config
Set Log Printing Interval + +```python +log_config = dict(interval=50) +``` + + + +```python +default_hooks = dict( + logger=dict(type='LoggerHook', interval=50)) +# Optional: set moving average window size +log_processor = dict( + type='LogProcessor', window_size=50) +``` + +
Use TensorBoard or WandB to visualize logs + +```python +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook'), + dict(type='MMDetWandbHook', + init_kwargs={ + 'project': 'mmdetection', + 'group': 'maskrcnn-r50-fpn-1x-coco' + }, + interval=50, + log_checkpoint=True, + log_checkpoint_metadata=True, + num_eval_images=100) + ]) +``` + + + +```python +vis_backends = [ + dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend'), + dict(type='WandbVisBackend', + init_kwargs={ + 'project': 'mmdetection', + 'group': 'maskrcnn-r50-fpn-1x-coco' + }) +] +visualizer = dict( + type='DetLocalVisualizer', + vis_backends=vis_backends, + name='visualizer') +``` + +
+ +For visualization-related tutorials, please refer to [Visualization Tutorial](../user_guides/visualization.md) of MMDetection. + +### Runtime Configuration + +The runtime configuration fields in version 3.x have been adjusted, and the specific correspondence is as follows: + + + + + + + + + + + + + + + + +
2.x Config3.x Config
+ +```python +cudnn_benchmark = False +opencv_num_threads = 0 +mp_start_method = 'fork' +dist_params = dict(backend='nccl') +log_level = 'INFO' +load_from = None +resume_from = None + + +``` + + + +```python +env_cfg = dict( + cudnn_benchmark=False, + mp_cfg=dict(mp_start_method='fork', + opencv_num_threads=0), + dist_cfg=dict(backend='nccl')) +log_level = 'INFO' +load_from = None +resume = False +``` + +
diff --git a/mmdet_code/SR-TOD/docs/en/migration/dataset_migration.md b/mmdet_code/SR-TOD/docs/en/migration/dataset_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..75d093298e0e751203614d8c5008bc774ebfd93e --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/migration/dataset_migration.md @@ -0,0 +1 @@ +# Migrate dataset from MMDetection 2.x to 3.x diff --git a/mmdet_code/SR-TOD/docs/en/migration/migration.md b/mmdet_code/SR-TOD/docs/en/migration/migration.md new file mode 100644 index 0000000000000000000000000000000000000000..ec6a2f891b15182b033d34e95c9710d701478e21 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/migration/migration.md @@ -0,0 +1,12 @@ +# Migrating from MMDetection 2.x to 3.x + +MMDetection 3.x is a significant update that includes many changes to API and configuration files. This document aims to help users migrate from MMDetection 2.x to 3.x. +We divided the migration guide into the following sections: + +- [Configuration file migration](./config_migration.md) +- [API and Registry migration](./api_and_registry_migration.md) +- [Dataset migration](./dataset_migration.md) +- [Model migration](./model_migration.md) +- [Frequently Asked Questions](./migration_faq.md) + +If you encounter any problems during the migration process, feel free to raise an issue. We also welcome contributions to this document. diff --git a/mmdet_code/SR-TOD/docs/en/migration/migration_faq.md b/mmdet_code/SR-TOD/docs/en/migration/migration_faq.md new file mode 100644 index 0000000000000000000000000000000000000000..a6e3c356c275a9306532d41ac1cb552b714a463a --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/migration/migration_faq.md @@ -0,0 +1 @@ +# Migration FAQ diff --git a/mmdet_code/SR-TOD/docs/en/migration/model_migration.md b/mmdet_code/SR-TOD/docs/en/migration/model_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..04e280879fca1b251f5e32e0d3eafae58af5dab1 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/migration/model_migration.md @@ -0,0 +1 @@ +# Migrate models from MMDetection 2.x to 3.x diff --git a/mmdet_code/SR-TOD/docs/en/model_zoo.md b/mmdet_code/SR-TOD/docs/en/model_zoo.md new file mode 100644 index 0000000000000000000000000000000000000000..15dd7b2fb5b2f890de78d036746b3c8371f0ddf3 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/model_zoo.md @@ -0,0 +1,358 @@ +# Benchmark and Model Zoo + +## Mirror sites + +We only use aliyun to maintain the model zoo since MMDetection V2.0. The model zoo of V1.x has been deprecated. + +## Common settings + +- All models were trained on `coco_2017_train`, and tested on the `coco_2017_val`. +- We use distributed training. +- All pytorch-style pretrained backbones on ImageNet are from PyTorch model zoo, caffe-style pretrained backbones are converted from the newly released model from detectron2. +- For fair comparison with other codebases, we report the GPU memory as the maximum value of `torch.cuda.max_memory_allocated()` for all 8 GPUs. Note that this value is usually less than what `nvidia-smi` shows. +- We report the inference time as the total time of network forwarding and post-processing, excluding the data loading time. Results are obtained with the script [benchmark.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/benchmark.py) which computes the average time on 2000 images. + +## ImageNet Pretrained Models + +It is common to initialize from backbone models pre-trained on ImageNet classification task. All pre-trained model links can be found at [open_mmlab](https://github.com/open-mmlab/mmcv/blob/master/mmcv/model_zoo/open_mmlab.json). According to `img_norm_cfg` and source of weight, we can divide all the ImageNet pre-trained model weights into some cases: + +- TorchVision: Corresponding to torchvision weight, including ResNet50, ResNet101. The `img_norm_cfg` is `dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)`. +- Pycls: Corresponding to [pycls](https://github.com/facebookresearch/pycls) weight, including RegNetX. The `img_norm_cfg` is `dict( mean=[103.530, 116.280, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False)`. +- MSRA styles: Corresponding to [MSRA](https://github.com/KaimingHe/deep-residual-networks) weights, including ResNet50_Caffe and ResNet101_Caffe. The `img_norm_cfg` is `dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)`. +- Caffe2 styles: Currently only contains ResNext101_32x8d. The `img_norm_cfg` is `dict(mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395], to_rgb=False)`. +- Other styles: E.g SSD which corresponds to `img_norm_cfg` is `dict(mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True)` and YOLOv3 which corresponds to `img_norm_cfg` is `dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True)`. + +The detailed table of the commonly used backbone models in MMDetection is listed below : + +| model | source | link | description | +| ---------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| ResNet50 | TorchVision | [torchvision's ResNet-50](https://download.pytorch.org/models/resnet50-19c8e357.pth) | From [torchvision's ResNet-50](https://download.pytorch.org/models/resnet50-19c8e357.pth). | +| ResNet101 | TorchVision | [torchvision's ResNet-101](https://download.pytorch.org/models/resnet101-5d3b4d8f.pth) | From [torchvision's ResNet-101](https://download.pytorch.org/models/resnet101-5d3b4d8f.pth). | +| RegNetX | Pycls | [RegNetX_3.2gf](https://download.openmmlab.com/pretrain/third_party/regnetx_3.2gf-c2599b0f.pth), [RegNetX_800mf](https://download.openmmlab.com/pretrain/third_party/regnetx_800mf-1f4be4c7.pth). etc. | From [pycls](https://github.com/facebookresearch/pycls). | +| ResNet50_Caffe | MSRA | [MSRA's ResNet-50](https://download.openmmlab.com/pretrain/third_party/resnet50_caffe-788b5fa3.pth) | Converted copy of [Detectron2's R-50.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-50.pkl) model. The original weight comes from [MSRA's original ResNet-50](https://github.com/KaimingHe/deep-residual-networks). | +| ResNet101_Caffe | MSRA | [MSRA's ResNet-101](https://download.openmmlab.com/pretrain/third_party/resnet101_caffe-3ad79236.pth) | Converted copy of [Detectron2's R-101.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-101.pkl) model. The original weight comes from [MSRA's original ResNet-101](https://github.com/KaimingHe/deep-residual-networks). | +| ResNext101_32x8d | Caffe2 | [Caffe2 ResNext101_32x8d](https://download.openmmlab.com/pretrain/third_party/resnext101_32x8d-1516f1aa.pth) | Converted copy of [Detectron2's X-101-32x8d.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/FAIR/X-101-32x8d.pkl) model. The ResNeXt-101-32x8d model trained with Caffe2 at FB. | + +## Baselines + +### RPN + +Please refer to [RPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/rpn) for details. + +### Faster R-CNN + +Please refer to [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn) for details. + +### Mask R-CNN + +Please refer to [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn) for details. + +### Fast R-CNN (with pre-computed proposals) + +Please refer to [Fast R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/fast_rcnn) for details. + +### RetinaNet + +Please refer to [RetinaNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/retinanet) for details. + +### Cascade R-CNN and Cascade Mask R-CNN + +Please refer to [Cascade R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/cascade_rcnn) for details. + +### Hybrid Task Cascade (HTC) + +Please refer to [HTC](https://github.com/open-mmlab/mmdetection/blob/main/configs/htc) for details. + +### SSD + +Please refer to [SSD](https://github.com/open-mmlab/mmdetection/blob/main/configs/ssd) for details. + +### Group Normalization (GN) + +Please refer to [Group Normalization](https://github.com/open-mmlab/mmdetection/blob/main/configs/gn) for details. + +### Weight Standardization + +Please refer to [Weight Standardization](https://github.com/open-mmlab/mmdetection/blob/main/configs/gn+ws) for details. + +### Deformable Convolution v2 + +Please refer to [Deformable Convolutional Networks](https://github.com/open-mmlab/mmdetection/blob/main/configs/dcn) for details. + +### CARAFE: Content-Aware ReAssembly of FEatures + +Please refer to [CARAFE](https://github.com/open-mmlab/mmdetection/blob/main/configs/carafe) for details. + +### Instaboost + +Please refer to [Instaboost](https://github.com/open-mmlab/mmdetection/blob/main/configs/instaboost) for details. + +### Libra R-CNN + +Please refer to [Libra R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/libra_rcnn) for details. + +### Guided Anchoring + +Please refer to [Guided Anchoring](https://github.com/open-mmlab/mmdetection/blob/main/configs/guided_anchoring) for details. + +### FCOS + +Please refer to [FCOS](https://github.com/open-mmlab/mmdetection/blob/main/configs/fcos) for details. + +### FoveaBox + +Please refer to [FoveaBox](https://github.com/open-mmlab/mmdetection/blob/main/configs/foveabox) for details. + +### RepPoints + +Please refer to [RepPoints](https://github.com/open-mmlab/mmdetection/blob/main/configs/reppoints) for details. + +### FreeAnchor + +Please refer to [FreeAnchor](https://github.com/open-mmlab/mmdetection/blob/main/configs/free_anchor) for details. + +### Grid R-CNN (plus) + +Please refer to [Grid R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/grid_rcnn) for details. + +### GHM + +Please refer to [GHM](https://github.com/open-mmlab/mmdetection/blob/main/configs/ghm) for details. + +### GCNet + +Please refer to [GCNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/gcnet) for details. + +### HRNet + +Please refer to [HRNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/hrnet) for details. + +### Mask Scoring R-CNN + +Please refer to [Mask Scoring R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/ms_rcnn) for details. + +### Train from Scratch + +Please refer to [Rethinking ImageNet Pre-training](https://github.com/open-mmlab/mmdetection/blob/main/configs/scratch) for details. + +### NAS-FPN + +Please refer to [NAS-FPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/nas_fpn) for details. + +### ATSS + +Please refer to [ATSS](https://github.com/open-mmlab/mmdetection/blob/main/configs/atss) for details. + +### FSAF + +Please refer to [FSAF](https://github.com/open-mmlab/mmdetection/blob/main/configs/fsaf) for details. + +### RegNetX + +Please refer to [RegNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/regnet) for details. + +### Res2Net + +Please refer to [Res2Net](https://github.com/open-mmlab/mmdetection/blob/main/configs/res2net) for details. + +### GRoIE + +Please refer to [GRoIE](https://github.com/open-mmlab/mmdetection/blob/main/configs/groie) for details. + +### Dynamic R-CNN + +Please refer to [Dynamic R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/dynamic_rcnn) for details. + +### PointRend + +Please refer to [PointRend](https://github.com/open-mmlab/mmdetection/blob/main/configs/point_rend) for details. + +### DetectoRS + +Please refer to [DetectoRS](https://github.com/open-mmlab/mmdetection/blob/main/configs/detectors) for details. + +### Generalized Focal Loss + +Please refer to [Generalized Focal Loss](https://github.com/open-mmlab/mmdetection/blob/main/configs/gfl) for details. + +### CornerNet + +Please refer to [CornerNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/cornernet) for details. + +### YOLOv3 + +Please refer to [YOLOv3](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolo) for details. + +### PAA + +Please refer to [PAA](https://github.com/open-mmlab/mmdetection/blob/main/configs/paa) for details. + +### SABL + +Please refer to [SABL](https://github.com/open-mmlab/mmdetection/blob/main/configs/sabl) for details. + +### CentripetalNet + +Please refer to [CentripetalNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/centripetalnet) for details. + +### ResNeSt + +Please refer to [ResNeSt](https://github.com/open-mmlab/mmdetection/blob/main/configs/resnest) for details. + +### DETR + +Please refer to [DETR](https://github.com/open-mmlab/mmdetection/blob/main/configs/detr) for details. + +### Deformable DETR + +Please refer to [Deformable DETR](https://github.com/open-mmlab/mmdetection/blob/main/configs/deformable_detr) for details. + +### AutoAssign + +Please refer to [AutoAssign](https://github.com/open-mmlab/mmdetection/blob/main/configs/autoassign) for details. + +### YOLOF + +Please refer to [YOLOF](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolof) for details. + +### Seesaw Loss + +Please refer to [Seesaw Loss](https://github.com/open-mmlab/mmdetection/blob/main/configs/seesaw_loss) for details. + +### CenterNet + +Please refer to [CenterNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/centernet) for details. + +### YOLOX + +Please refer to [YOLOX](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolox) for details. + +### PVT + +Please refer to [PVT](https://github.com/open-mmlab/mmdetection/blob/main/configs/pvt) for details. + +### SOLO + +Please refer to [SOLO](https://github.com/open-mmlab/mmdetection/blob/main/configs/solo) for details. + +### QueryInst + +Please refer to [QueryInst](https://github.com/open-mmlab/mmdetection/blob/main/configs/queryinst) for details. + +### PanopticFPN + +Please refer to [PanopticFPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/panoptic_fpn) for details. + +### MaskFormer + +Please refer to [MaskFormer](https://github.com/open-mmlab/mmdetection/blob/main/configs/maskformer) for details. + +### DyHead + +Please refer to [DyHead](https://github.com/open-mmlab/mmdetection/blob/main/configs/dyhead) for details. + +### Mask2Former + +Please refer to [Mask2Former](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask2former) for details. + +### Efficientnet + +Please refer to [Efficientnet](https://github.com/open-mmlab/mmdetection/blob/main/configs/efficientnet) for details. + +### Other datasets + +We also benchmark some methods on [PASCAL VOC](https://github.com/open-mmlab/mmdetection/blob/main/configs/pascal_voc), [Cityscapes](https://github.com/open-mmlab/mmdetection/blob/main/configs/cityscapes), [OpenImages](https://github.com/open-mmlab/mmdetection/blob/main/configs/openimages) and [WIDER FACE](https://github.com/open-mmlab/mmdetection/blob/main/configs/wider_face). + +### Pre-trained Models + +We also train [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn) and [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn) using ResNet-50 and [RegNetX-3.2G](https://github.com/open-mmlab/mmdetection/blob/main/configs/regnet) with multi-scale training and longer schedules. These models serve as strong pre-trained models for downstream tasks for convenience. + +## Speed benchmark + +### Training Speed benchmark + +We provide [analyze_logs.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/analyze_logs.py) to get average time of iteration in training. You can find examples in [Log Analysis](https://mmdetection.readthedocs.io/en/latest/useful_tools.html#log-analysis). + +We compare the training speed of Mask R-CNN with some other popular frameworks (The data is copied from [detectron2](https://github.com/facebookresearch/detectron2/blob/main/docs/notes/benchmarks.md/)). +For mmdetection, we benchmark with [mask-rcnn_r50-caffe_fpn_poly-1x_coco_v1.py](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn/mask-rcnn_r50-caffe_fpn_poly-1x_coco_v1.py), which should have the same setting with [mask_rcnn_R_50_FPN_noaug_1x.yaml](https://github.com/facebookresearch/detectron2/blob/main/configs/Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x.yaml) of detectron2. +We also provide the [checkpoint](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug_compare_20200518-10127928.pth) and [training log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug_20200518_105755.log.json) for reference. The throughput is computed as the average throughput in iterations 100-500 to skip GPU warmup time. + +| Implementation | Throughput (img/s) | +| -------------------------------------------------------------------------------------- | ------------------ | +| [Detectron2](https://github.com/facebookresearch/detectron2) | 62 | +| [MMDetection](https://github.com/open-mmlab/mmdetection) | 61 | +| [maskrcnn-benchmark](https://github.com/facebookresearch/maskrcnn-benchmark/) | 53 | +| [tensorpack](https://github.com/tensorpack/tensorpack/tree/master/examples/FasterRCNN) | 50 | +| [simpledet](https://github.com/TuSimple/simpledet/) | 39 | +| [Detectron](https://github.com/facebookresearch/Detectron) | 19 | +| [matterport/Mask_RCNN](https://github.com/matterport/Mask_RCNN/) | 14 | + +### Inference Speed Benchmark + +We provide [benchmark.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/benchmark.py) to benchmark the inference latency. +The script benchmarkes the model with 2000 images and calculates the average time ignoring first 5 times. You can change the output log interval (defaults: 50) by setting `LOG-INTERVAL`. + +```shell +python tools/benchmark.py ${CONFIG} ${CHECKPOINT} [--log-interval $[LOG-INTERVAL]] [--fuse-conv-bn] +``` + +The latency of all models in our model zoo is benchmarked without setting `fuse-conv-bn`, you can get a lower latency by setting it. + +## Comparison with Detectron2 + +We compare mmdetection with [Detectron2](https://github.com/facebookresearch/detectron2.git) in terms of speed and performance. +We use the commit id [185c27e](https://github.com/facebookresearch/detectron2/tree/185c27e4b4d2d4c68b5627b3765420c6d7f5a659)(30/4/2020) of detectron. +For fair comparison, we install and run both frameworks on the same machine. + +### Hardware + +- 8 NVIDIA Tesla V100 (32G) GPUs +- Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz + +### Software environment + +- Python 3.7 +- PyTorch 1.4 +- CUDA 10.1 +- CUDNN 7.6.03 +- NCCL 2.4.08 + +### Performance + +| Type | Lr schd | Detectron2 | mmdetection | Download | +| ------------------------------------------------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_ms-1x_coco.py) | 1x | [37.9](https://github.com/facebookresearch/detectron2/blob/main/configs/COCO-Detection/faster_rcnn_R_50_FPN_1x.yaml) | 38.0 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco-5324cff8.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco_20200429_234554.log.json) | +| [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_coco.py) | 1x | [38.6 & 35.2](https://github.com/facebookresearch/detectron2/blob/main/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml) | 38.8 & 35.4 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco-dbecf295.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco_20200430_054239.log.json) | +| [Retinanet](https://github.com/open-mmlab/mmdetection/blob/main/configs/retinanet/retinanet_r50-caffe_fpn_ms-1x_coco.py) | 1x | [36.5](https://github.com/facebookresearch/detectron2/blob/master/configs/COCO-Detection/retinanet_R_50_FPN_1x.yaml) | 37.0 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/retinanet_r50_caffe_fpn_mstrain_1x_coco/retinanet_r50_caffe_fpn_mstrain_1x_coco-586977a0.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/retinanet_r50_caffe_fpn_mstrain_1x_coco/retinanet_r50_caffe_fpn_mstrain_1x_coco_20200430_014748.log.json) | + +### Training Speed + +The training speed is measure with s/iter. The lower, the better. + +| Type | Detectron2 | mmdetection | +| ------------ | ---------- | ----------- | +| Faster R-CNN | 0.210 | 0.216 | +| Mask R-CNN | 0.261 | 0.265 | +| Retinanet | 0.200 | 0.205 | + +### Inference Speed + +The inference speed is measured with fps (img/s) on a single GPU, the higher, the better. +To be consistent with Detectron2, we report the pure inference speed (without the time of data loading). +For Mask R-CNN, we exclude the time of RLE encoding in post-processing. +We also include the officially reported speed in the parentheses, which is slightly higher +than the results tested on our server due to differences of hardwares. + +| Type | Detectron2 | mmdetection | +| ------------ | ----------- | ----------- | +| Faster R-CNN | 25.6 (26.3) | 22.2 | +| Mask R-CNN | 22.5 (23.3) | 19.6 | +| Retinanet | 17.8 (18.2) | 20.6 | + +### Training memory + +| Type | Detectron2 | mmdetection | +| ------------ | ---------- | ----------- | +| Faster R-CNN | 3.0 | 3.8 | +| Mask R-CNN | 3.4 | 3.9 | +| Retinanet | 3.9 | 3.4 | diff --git a/mmdet_code/SR-TOD/docs/en/notes/changelog.md b/mmdet_code/SR-TOD/docs/en/notes/changelog.md new file mode 100644 index 0000000000000000000000000000000000000000..88dfe98145f6b33d4669c9a899e3d28dce348a40 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/notes/changelog.md @@ -0,0 +1,535 @@ +# Changelog of v3.x + +## v3.1.0 (30/6/2023) + +### Highlights + +- Supports tracking algorithms including multi-object tracking (MOT) algorithms SORT, DeepSORT, StrongSORT, OCSORT, ByteTrack, QDTrack, and video instance segmentation (VIS) algorithm MaskTrackRCNN, Mask2Former-VIS. +- Support [ViTDet](../../../projects/ViTDet) +- Supports inference and evaluation of multimodal algorithms [GLIP](../../../configs/glip) and [XDecoder](../../../projects/XDecoder), and also supports datasets such as COCO semantic segmentation, COCO Caption, ADE20k general segmentation, and RefCOCO. GLIP fine-tuning will be supported in the future. +- Provides a [gradio demo](https://github.com/open-mmlab/mmdetection/blob/dev-3.x/projects/gradio_demo/README.md) for image type tasks of MMDetection, making it easy for users to experience. + +### New Features + +- Support DSDL Dataset (#9801) +- Support iSAID dataset (#10028) +- Support VISION dataset (#10530) +- Release SoftTeacher checkpoints (#10119) +- Release `centernet-update_r50-caffe_fpn_ms-1x_coco` checkpoints (#10327) +- Support SIoULoss (#10290) +- Support Eqlv2 loss (#10120) +- Support CopyPaste when mask is not available (#10509) +- Support MIM to download ODL dataset (#10460) +- Support new config (#10566) + +### Bug Fixes + +- Fix benchmark scripts error in windows (#10128) +- Fix error of `YOLOXModeSwitchHook` does not switch the mode when resumed from the checkpoint after switched (#10116) +- Fix pred and weight dims unmatch in SmoothL1Loss (#10423) + +### Improvements + +- Update MMDet_Tutorial.ipynb (#10081) +- Support to hide inference progress (#10519) +- Replace mmcls with mmpretrain (#10545) + +### Contributors + +A total of 29 developers contributed to this release. + +Thanks @lovelykite, @minato-ellie, @freepoet, @wufan-tb, @yalibian, @keyakiluo, @gihanjayatilaka, @i-aki-y, @xin-li-67, @RangeKing, @JingweiZhang12, @MambaWong, @lucianovk, @tall-josh, @xiuqhou, @jamiechoi1995, @YQisme, @yechenzhi, @bjzhb666, @xiexinch, @jamiechoi1995, @yarkable, @Renzhihan, @nijkah, @amaizr, @Lum1104, @zwhus, @Czm369, @hhaAndroid + +## v3.0.0 (6/4/2023) + +### Highlights + +- Support Semi-automatic annotation Base [Label-Studio](../../../projects/LabelStudio) (#10039) +- Support [EfficientDet](../../../projects/EfficientDet) in projects (#9810) + +### New Features + +- File I/O migration and reconstruction (#9709) +- Release DINO Swin-L 36e model (#9927) + +### Bug Fixes + +- Fix benchmark script (#9865) +- Fix the crop method of PolygonMasks (#9858) +- Fix Albu augmentation with the mask shape (#9918) +- Fix `RTMDetIns` prior generator device error (#9964) +- Fix `img_shape` in data pipeline (#9966) +- Fix cityscapes import error (#9984) +- Fix `solov2_r50_fpn_ms-3x_coco.py` config error (#10030) +- Fix Conditional DETR AP and Log (#9889) +- Fix accepting an unexpected argument local-rank in PyTorch 2.0 (#10050) +- Fix `common/ms_3x_coco-instance.py` config error (#10056) +- Fix compute flops error (#10051) +- Delete `data_root` in `CocoOccludedSeparatedMetric` to fix bug (#9969) +- Unifying metafile.yml (#9849) + +### Improvements + +- Added BoxInst r101 config (#9967) +- Added config migration guide (#9960) +- Added more social networking links (#10021) +- Added RTMDet config introduce (#10042) +- Added visualization docs (#9938, #10058) +- Refined data_prepare docs (#9935) +- Added support for setting the cache_size_limit parameter of dynamo in PyTorch 2.0 (#10054) +- Updated coco_metric.py (#10033) +- Update type hint (#10040) + +### Contributors + +A total of 19 developers contributed to this release. + +Thanks @IRONICBo, @vansin, @RangeKing, @Ghlerrix, @okotaku, @JosonChan1998, @zgzhengSE, @bobo0810, @yechenzh, @Zheng-LinXiao, @LYMDLUT, @yarkable, @xiejiajiannb, @chhluo, @BIGWangYuDong, @RangiLy, @zwhus, @hhaAndroid, @ZwwWayne + +## v3.0.0rc6 (24/2/2023) + +### Highlights + +- Support [Boxinst](../../../configs/boxinst), [Objects365 Dataset](../../../configs/objects365), and [Separated and Occluded COCO metric](../user_guides/useful_tools.md#COCO-Separated-&-Occluded-Mask-Metric) +- Support [ConvNeXt-V2](../../../projects/ConvNeXt-V2), [DiffusionDet](../../../projects/DiffusionDet), and inference of [EfficientDet](../../../projects/EfficientDet) and [Detic](../../../projects/Detic) in `Projects` +- Refactor [DETR](../../../configs/detr) series and support [Conditional-DETR](../../../configs/conditional_detr), [DAB-DETR](../../../configs/dab_detr), and [DINO](../../../configs/detr) +- Support `DetInferencer` for inference, Test Time Augmentation, and automatically importing modules from registry +- Support RTMDet-Ins ONNXRuntime and TensorRT [deployment](../../../configs/rtmdet/README.md#deployment-tutorial) +- Support [calculating FLOPs of detectors](../user_guides/useful_tools.md#Model-Complexity) + +### New Features + +- Support [Boxinst](https://arxiv.org/abs/2012.02310) (#9525) +- Support [Objects365 Dataset](https://openaccess.thecvf.com/content_ICCV_2019/papers/Shao_Objects365_A_Large-Scale_High-Quality_Dataset_for_Object_Detection_ICCV_2019_paper.pdf) (#9600) +- Support [ConvNeXt-V2](http://arxiv.org/abs/2301.00808) in `Projects` (#9619) +- Support [DiffusionDet](https://arxiv.org/abs/2211.09788) in `Projects` (#9639, #9768) +- Support [Detic](http://arxiv.org/abs/2201.02605) inference in `Projects` (#9645) +- Support [EfficientDet](https://arxiv.org/abs/1911.09070) inference in `Projects` (#9645) +- Support [Separated and Occluded COCO metric](https://arxiv.org/abs/2210.10046) (#9710) +- Support auto import modules from registry (#9143) +- Refactor DETR series and support Conditional-DETR, DAB-DETR and DINO (#9646) +- Support `DetInferencer` for inference (#9561) +- Support Test Time Augmentation (#9452) +- Support calculating FLOPs of detectors (#9777) + +### Bug Fixes + +- Fix deprecating old type alias due to new version of numpy (#9625, #9537) +- Fix VOC metrics (#9784) +- Fix the wrong link of RTMDet-x log (#9549) +- Fix RTMDet link in README (#9575) +- Fix MMDet get flops error (#9589) +- Fix `use_depthwise` in RTMDet (#9624) +- Fix `albumentations` augmentation post process with masks (#9551) +- Fix DETR series Unit Test (#9647) +- Fix `LoadPanopticAnnotations` bug (#9703) +- Fix `isort` CI (#9680) +- Fix amp pooling overflow (#9670) +- Fix docstring about noise in DINO (#9747) +- Fix potential bug in `MultiImageMixDataset` (#9764) + +### Improvements + +- Replace NumPy transpose with PyTorch permute to speed-up (#9762) +- Deprecate `sklearn` (#9725) +- Add RTMDet-Ins deployment guide (#9823) +- Update RTMDet config and README (#9603) +- Replace the models used in the tutorial document with RTMDet (#9843) +- Adjust the minimum supported python version to 3.7 (#9602) +- Support modifying palette through configuration (#9445) +- Update README document in `Project` (#9599) +- Replace `github` with `gitee` in `.pre-commit-config-zh-cn.yaml` file (#9586) +- Use official `isort` in `.pre-commit-config.yaml` file (#9701) +- Change MMCV minimum version to `2.0.0rc4` for `dev-3.x` (#9695) +- Add Chinese version of single_stage_as_rpn.md and test_results_submission.md (#9434) +- Add OpenDataLab download link (#9605, #9738) +- Add type hints of several layers (#9346) +- Add typehint for `DarknetBottleneck` (#9591) +- Add dockerfile (#9659) +- Add twitter, discord, medium, and youtube link (#9775) +- Prepare for merging refactor-detr (#9656) +- Add metafile to ConditionalDETR, DABDETR and DINO (#9715) +- Support to modify `non_blocking` parameters (#9723) +- Comment repeater visualizer register (#9740) +- Update user guide: `finetune.md` and `inference.md` (#9578) + +### New Contributors + +- @NoFish-528 made their first contribution in +- @137208 made their first contribution in +- @lyviva made their first contribution in +- @zwhus made their first contribution in +- @zylo117 made their first contribution in +- @chg0901 made their first contribution in +- @DanShouzhu made their first contribution in https://github.com/open-mmlab/mmdetection/pull/9578 + +### Contributors + +A total of 27 developers contributed to this release. + +Thanks @JosonChan1998, @RangeKing, @NoFish-528, @likyoo, @Xiangxu-0103, @137208, @PeterH0323, @tianleiSHI, @wufan-tb, @lyviva, @zwhus, @jshilong, @Li-Qingyun, @sanbuphy, @zylo117, @triple-Mu, @KeiChiTse, @LYMDLUT, @nijkah, @chg0901, @DanShouzhu, @zytx121, @vansin, @BIGWangYuDong, @hhaAndroid, @RangiLyu, @ZwwWayne + +## v3.0.0rc5 (26/12/2022) + +### Highlights + +- Support [RTMDet](https://arxiv.org/abs/2212.07784) instance segmentation models. The technical report of RTMDet is on [arxiv](https://arxiv.org/abs/2212.07784) +- Support SSHContextModule in paper [SSH: Single Stage Headless Face Detector](https://arxiv.org/abs/1708.03979). + +### New Features + +- Support [RTMDet](https://arxiv.org/abs/2212.07784) instance segmentation models and improve RTMDet test config (#9494) +- Support SSHContextModule in paper [SSH: Single Stage Headless Face Detector](https://arxiv.org/abs/1708.03979) (#8953) +- Release [CondInst](https://arxiv.org/abs/2003.05664) pre-trained model (#9406) + +### Bug Fixes + +- Fix CondInst predict error when `batch_size` is greater than 1 in inference (#9400) +- Fix the bug of visualization when the dtype of the pipeline output image is not uint8 in browse dataset (#9401) +- Fix `analyze_logs.py` to plot mAP and calculate train time correctly (#9409) +- Fix backward inplace error with `PAFPN` (#9450) +- Fix config import links in model converters (#9441) +- Fix `DeformableDETRHead` object has no attribute `loss_single` (#9477) +- Fix the logic of pseudo bboxes predicted by teacher model in SemiBaseDetector (#9414) +- Fix demo API in instance segmentation tutorial (#9226) +- Fix `analyze_results` (#9380) +- Fix the error that Readthedocs API cannot be displayed (#9510) +- Fix the error when there are no prediction results and support visualize the groundtruth of TTA (#9840) + +### Improvements + +- Remove legacy `builder.py` (#9479) +- Make sure the pipeline argument shape is in `(width, height)` order (#9324) +- Add `.pre-commit-config-zh-cn.yaml` file (#9388) +- Refactor dataset metainfo to lowercase (#9469) +- Add PyTorch 1.13 checking in CI (#9478) +- Adjust `FocalLoss` and `QualityFocalLoss` to allow different kinds of targets (#9481) +- Refactor `setup.cfg` (#9370) +- Clip saturation value to valid range `[0, 1]` (#9391) +- Only keep meta and state_dict when publishing model (#9356) +- Add segm evaluator in ms-poly_3x_coco_instance config (#9524) +- Update deployment guide (#9527) +- Update zh_cn `faq.md` (#9396) +- Update `get_started` (#9480) +- Update the zh_cn user_guides of `useful_tools.md` and `useful_hooks.md` (#9453) +- Add type hints for `bfp` and `channel_mapper` (#9410) +- Add type hints of several losses (#9397) +- Add type hints and update docstring for task modules (#9468) + +### New Contributors + +- @lihua199710 made their first contribution in +- @twmht made their first contribution in +- @tianleiSHI made their first contribution in +- @kitecats made their first contribution in +- @QJC123654 made their first contribution in + +### Contributors + +A total of 20 developers contributed to this release. + +Thanks @liuyanyi, @RangeKing, @lihua199710, @MambaWong, @sanbuphy, @Xiangxu-0103, @twmht, @JunyaoHu, @Chan-Sun, @tianleiSHI, @zytx121, @kitecats, @QJC123654, @JosonChan1998, @lvhan028, @Czm369, @BIGWangYuDong, @RangiLyu, @hhaAndroid, @ZwwWayne + +## v3.0.0rc4 (23/11/2022) + +### Highlights + +- Support [CondInst](https://arxiv.org/abs/2003.05664) +- Add `projects/` folder, which will be a place for some experimental models/features. +- Support [SparseInst](https://arxiv.org/abs/2203.12827) in [`projects`](./projects/SparseInst/README.md) + +### New Features + +- Support [CondInst](https://arxiv.org/abs/2003.05664) (#9223) +- Add `projects/` folder, which will be a place for some experimental models/features (#9341) +- Support [SparseInst](https://arxiv.org/abs/2203.12827) in [`projects`](./projects/SparseInst/README.md) (#9377) + +### Bug Fixes + +- Fix `pixel_decoder_type` discrimination in MaskFormer Head. (#9176) +- Fix wrong padding value in cached MixUp (#9259) +- Rename `utils/typing.py` to `utils/typing_utils.py` to fix `collect_env` error (#9265) +- Fix resume arg conflict (#9287) +- Fix the configs of Faster R-CNN with caffe backbone (#9319) +- Fix torchserve and update related documentation (#9343) +- Fix bbox refine bug with sigmooid activation (#9538) + +### Improvements + +- Update the docs of GIoU Loss in README (#8810) +- Handle dataset wrapper in `inference_detector` (#9144) +- Update the type of `counts` in COCO’s compressed RLE (#9274) +- Support saving config file in `print_config` (#9276) +- Update docs about video inference (#9305) +- Update guide about model deployment (#9344) +- Fix doc typos of useful tools (#9177) +- Allow to resume from specific checkpoint in CLI (#9284) +- Update FAQ about windows installation issues of pycocotools (#9292) + +### New Contributors + +- @Daa98 made their first contribution in +- @lvhan028 made their first contribution in + +### Contributors + +A total of 12 developers contributed to this release. + +Thanks @sanbuphy, @Czm369, @Daa98, @jbwang1997, @BIGWangYuDong, @JosonChan1998, @lvhan028, @RunningLeon, @RangiLyu, @Daa98, @ZwwWayne, @hhaAndroid + +## v3.0.0rc3 (4/11/2022) + +Upgrade the minimum version requirement of MMEngine to 0.3.0 to use `ignore_key` of `ConcatDataset` for training VOC datasets (#9058) + +### Highlights + +- Support [CrowdDet](https://arxiv.org/abs/2003.09163) and [EIoU Loss](https://ieeexplore.ieee.org/document/9429909) +- Support training detection models in Detectron2 +- Refactor Fast R-CNN + +### New Features + +- Support [CrowdDet](https://arxiv.org/abs/2003.09163) (#8744) +- Support training detection models in Detectron2 with examples of Mask R-CNN, Faster R-CNN, and RetinaNet (#8672) +- Support [EIoU Loss](https://ieeexplore.ieee.org/document/9429909) (#9086) + +### Bug Fixes + +- Fix `XMLDataset` image size error (#9216) +- Fix bugs of empty_instances when predicting without nms in roi_head (#9015) +- Fix the config file of DETR (#9158) +- Fix SOLOv2 cannot dealing with empty gt image (#9192) +- Fix inference demo (#9153) +- Add `ignore_key` in VOC `ConcatDataset` (#9058) +- Fix dumping results issue in test scripts. (#9241) +- Fix configs of training coco subsets on MMDet 3.x (#9225) +- Fix corner2hbox of HorizontalBoxes for supporting empty bboxes (#9140) + +### Improvements + +- Refactor Fast R-CNN (#9132) +- Clean requirements of mmcv-full due to SyncBN (#9207) +- Support training detection models in detectron2 (#8672) +- Add `box_type` support for `DynamicSoftLabelAssigner` (#9179) +- Make scipy as a default dependency in runtime (#9187) +- Update eval_metric (#9062) +- Add `seg_map_suffix` in `BaseDetDataset` (#9088) + +### New Contributors + +- @Wwupup made their first contribution in +- @sanbuphy made their first contribution in +- @cxiang26 made their first contribution in +- @JosonChan1998 made their first contribution in + +### Contributors + +A total of 13 developers contributed to this release. + +Thanks @wanghonglie, @Wwupup, @sanbuphy, @BIGWangYuDong, @liuyanyi, @cxiang26, @jbwang1997, @ZwwWayne, @yuyoujiang, @RangiLyu, @hhaAndroid, @JosonChan1998, @Czm369 + +## v3.0.0rc2 (21/10/2022) + +### Highlights + +- Support [imagenet pre-training](configs/rtmdet/cspnext_imagenet_pretrain) for RTMDet's backbone + +### New Features + +- Support [imagenet pre-training](configs/rtmdet/cspnext_imagenet_pretrain) for RTMDet's backbone (#8887) +- Add `CrowdHumanDataset` and Metric (#8430) +- Add `FixShapeResize` to support resize of fixed shape (#8665) + +### Bug Fixes + +- Fix `ConcatDataset` Import Error (#8909) +- Fix `CircleCI` and `readthedoc` build failed (#8980, #8963) +- Fix bitmap mask translate when `out_shape` is different (#8993) +- Fix inconsistency in `Conv2d` weight channels (#8948) +- Fix bugs when plotting loss curve by analyze_logs.py (#8944) +- Fix type change of labels in `albumentations` (#9074) +- Fix some docs and types error (#8818) +- Update memory occupation of `RTMDet` in metafile (#9098) +- Fix wrong arguments of `OpenImageMetrics` in the config (#9061) + +### Improvements + +- Refactor standard roi head with `box type` (#8658) +- Support mask concatenation in `BitmapMasks` and `PolygonMasks` (#9006) +- Update PyTorch and dependencies' version in dockerfile (#8845) +- Update `robustness_eval.py` and `print_config` (#8452) +- Make compatible with `ConfigDict` and `dict` in `dense_heads` (#8942) +- Support logging coco metric copypaste (#9012) +- Remove `Normalize` transform (#8913) +- Support jittering the color of different instances of the same class (#8988) +- Add assertion for missing key in `PackDetInputs` (#8982) + +### New Contributors + +- @Chan-Sun made their first contribution in +- @MambaWong made their first contribution in +- @yuyoujiang made their first contribution in +- @sltlls made their first contribution in +- @Nioolek made their first contribution in +- @wufan-tb made their first contribution in + +### Contributors + +A total of 13 developers contributed to this release. + +Thanks @RangiLyu, @jbwang1997, @wanghonglie, @Chan-Sun, @RangeKing, @chhluo, @MambaWong, @yuyoujiang, @hhaAndroid, @sltlls, @Nioolek, @ZwwWayne, @wufan-tb + +## v3.0.0rc1 (26/9/2022) + +### Highlights + +- Release a high-precision, low-latency single-stage object detector [RTMDet](configs/rtmdet). + +### Bug Fixes + +- Fix UT to be compatible with PyTorch 1.6 (#8707) +- Fix `NumClassCheckHook` bug when model is wrapped (#8794) +- Update the right URL of R-50-FPN with BoundedIoULoss (#8805) +- Fix potential bug of indices in RandAugment (#8826) +- Fix some types and links (#8839, #8820, #8793, #8868) +- Fix incorrect background fill values in `FSAF` and `RepPoints` Head (#8813) + +### Improvements + +- Refactored anchor head and base head with `box type` (#8625) +- Refactored `SemiBaseDetector` and `SoftTeacher` (#8786) +- Add list to dict keys to avoid modify loss dict (#8828) +- Update `analyze_results.py` , `analyze_logs.py` and `loading.py` (#8430, #8402, #8784) +- Support dump results in `test.py` (#8814) +- Check empty predictions in `DetLocalVisualizer._draw_instances` (#8830) +- Fix `floordiv` warning in `SOLO` (#8738) + +### Contributors + +A total of 16 developers contributed to this release. + +Thanks @ZwwWayne, @jbwang1997, @Czm369, @ice-tong, @Zheng-LinXiao, @chhluo, @RangiLyu, @liuyanyi, @wanghonglie, @levan92, @JiayuXu0, @nye0, @hhaAndroid, @xin-li-67, @shuxp, @zytx121 + +## v3.0.0rc0 (31/8/2022) + +We are excited to announce the release of MMDetection 3.0.0rc0. MMDet 3.0.0rc0 is the first version of MMDetection 3.x, a part of the OpenMMLab 2.0 projects. Built upon the new [training engine](https://github.com/open-mmlab/mmengine), MMDet 3.x unifies the interfaces of the dataset, models, evaluation, and visualization with faster training and testing speed. It also provides a general semi-supervised object detection framework and strong baselines. + +### Highlights + +1. **New engine**. MMDet 3.x is based on [MMEngine](https://github.com/open-mmlab/mmengine), which provides a universal and powerful runner that allows more flexible customizations and significantly simplifies the entry points of high-level interfaces. + +2. **Unified interfaces**. As a part of the OpenMMLab 2.0 projects, MMDet 3.x unifies and refactors the interfaces and internal logic of training, testing, datasets, models, evaluation, and visualization. All the OpenMMLab 2.0 projects share the same design in those interfaces and logic to allow the emergence of multi-task/modality algorithms. + +3. **Faster speed**. We optimize the training and inference speed for common models and configurations, achieving a faster or similar speed than [Detection2](https://github.com/facebookresearch/detectron2/). Model details of benchmark will be updated in [this note](./benchmark.md#comparison-with-detectron2). + +4. **General semi-supervised object detection**. Benefitting from the unified interfaces, we support a general semi-supervised learning framework that works with all the object detectors supported in MMDet 3.x. Please refer to [semi-supervised object detection](../user_guides/semi_det.md) for details. + +5. **Strong baselines**. We release strong baselines of many popular models to enable fair comparisons among state-of-the-art models. + +6. **New features and algorithms**: + + - Enable all the single-stage detectors to serve as region proposal networks + - [SoftTeacher](https://arxiv.org/abs/2106.09018) + - [the updated CenterNet](https://arxiv.org/abs/2103.07461) + +7. **More documentation and tutorials**. We add a bunch of documentation and tutorials to help users get started more smoothly. Read it [here](https://mmdetection.readthedocs.io/en/3.x/). + +### Breaking Changes + +MMDet 3.x has undergone significant changes for better design, higher efficiency, more flexibility, and more unified interfaces. +Besides the changes in API, we briefly list the major breaking changes in this section. +We will update the [migration guide](../migration.md) to provide complete details and migration instructions. +Users can also refer to the [API doc](https://mmdetection.readthedocs.io/en/3.x/) for more details. + +#### Dependencies + +- MMDet 3.x runs on PyTorch>=1.6. We have deprecated the support of PyTorch 1.5 to embrace mixed precision training and other new features since PyTorch 1.6. Some models can still run on PyTorch 1.5, but the full functionality of MMDet 3.x is not guaranteed. +- MMDet 3.x relies on MMEngine to run. MMEngine is a new foundational library for training deep learning models of OpenMMLab and is the core dependency of OpenMMLab 2.0 projects. The dependencies of file IO and training are migrated from MMCV 1.x to MMEngine. +- MMDet 3.x relies on MMCV>=2.0.0rc0. Although MMCV no longer maintains the training functionalities since 2.0.0rc0, MMDet 3.x relies on the data transforms, CUDA operators, and image processing interfaces in MMCV. Note that the package `mmcv` is the version that provides pre-built CUDA operators and `mmcv-lite` does not since MMCV 2.0.0rc0, while `mmcv-full` has been deprecated since 2.0.0rc0. + +#### Training and testing + +- MMDet 3.x uses Runner in [MMEngine](https://github.com/open-mmlab/mmengine) rather than that in MMCV. The new Runner implements and unifies the building logic of the dataset, model, evaluation, and visualizer. Therefore, MMDet 3.x no longer maintains the building logic of those modules in `mmdet.train.apis` and `tools/train.py`. Those codes have been migrated into [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/runner.py). Please refer to the [migration guide of Runner in MMEngine](https://mmengine.readthedocs.io/en/latest/migration/runner.html) for more details. +- The Runner in MMEngine also supports testing and validation. The testing scripts are also simplified, which has similar logic to that in training scripts to build the runner. +- The execution points of hooks in the new Runner have been enriched to allow more flexible customization. Please refer to the [migration guide of Hook in MMEngine](https://mmengine.readthedocs.io/en/latest/migration/hook.html) for more details. +- Learning rate and momentum schedules have been migrated from Hook to [Parameter Scheduler in MMEngine](https://mmengine.readthedocs.io/en/latest/tutorials/param_scheduler.html). Please refer to the [migration guide of Parameter Scheduler in MMEngine](https://mmengine.readthedocs.io/en/latest/migration/param_scheduler.html) for more details. + +#### Configs + +- The [Runner in MMEngine](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/runner.py) uses a different config structure to ease the understanding of the components in the runner. Users can read the [config example of MMDet 3.x](../user_guides/config.md) or refer to the [migration guide in MMEngine](https://mmengine.readthedocs.io/en/latest/migration/runner.html) for migration details. +- The file names of configs and models are also refactored to follow the new rules unified across OpenMMLab 2.0 projects. The names of checkpoints are not updated for now as there is no BC-breaking of model weights between MMDet 3.x and 2.x. We will progressively replace all the model weights with those trained in MMDet 3.x. Please refer to the [user guides of config](../user_guides/config.md) for more details. + +#### Dataset + +The Dataset classes implemented in MMDet 3.x all inherit from the `BaseDetDataset`, which inherits from the [BaseDataset in MMEngine](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/basedataset.html). In addition to the changes in interfaces, there are several changes in Dataset in MMDet 3.x. + +- All the datasets support serializing the internal data list to reduce the memory when multiple workers are built for data loading. +- The internal data structure in the dataset is changed to be self-contained (without losing information like class names in MMDet 2.x) while keeping simplicity. +- The evaluation functionality of each dataset has been removed from the dataset so that some specific evaluation metrics like COCO AP can be used to evaluate the prediction on other datasets. + +#### Data Transforms + +The data transforms in MMDet 3.x all inherits from `BaseTransform` in MMCV>=2.0.0rc0, which defines a new convention in OpenMMLab 2.0 projects. +Besides the interface changes, there are several changes listed below: + +- The functionality of some data transforms (e.g., `Resize`) are decomposed into several transforms to simplify and clarify the usages. +- The format of data dict processed by each data transform is changed according to the new data structure of dataset. +- Some inefficient data transforms (e.g., normalization and padding) are moved into data preprocessor of model to improve data loading and training speed. +- The same data transforms in different OpenMMLab 2.0 libraries have the same augmentation implementation and the logic given the same arguments, i.e., `Resize` in MMDet 3.x and MMSeg 1.x will resize the image in the exact same manner given the same arguments. + +#### Model + +The models in MMDet 3.x all inherit from `BaseModel` in MMEngine, which defines a new convention of models in OpenMMLab 2.0 projects. +Users can refer to [the tutorial of the model in MMengine](https://mmengine.readthedocs.io/en/latest/tutorials/model.html) for more details. +Accordingly, there are several changes as the following: + +- The model interfaces, including the input and output formats, are significantly simplified and unified following the new convention in MMDet 3.x. + Specifically, all the input data in training and testing are packed into `inputs` and `data_samples`, where `inputs` contains model inputs like a list of image tensors, and `data_samples` contains other information of the current data sample such as ground truths, region proposals, and model predictions. In this way, different tasks in MMDet 3.x can share the same input arguments, which makes the models more general and suitable for multi-task learning and some flexible training paradigms like semi-supervised learning. +- The model has a data preprocessor module, which is used to pre-process the input data of the model. In MMDet 3.x, the data preprocessor usually does the necessary steps to form the input images into a batch, such as padding. It can also serve as a place for some special data augmentations or more efficient data transformations like normalization. +- The internal logic of the model has been changed. In MMdet 2.x, model uses `forward_train`, `forward_test`, `simple_test`, and `aug_test` to deal with different model forward logics. In MMDet 3.x and OpenMMLab 2.0, the forward function has three modes: 'loss', 'predict', and 'tensor' for training, inference, and tracing or other purposes, respectively. + The forward function calls `self.loss`, `self.predict`, and `self._forward` given the modes 'loss', 'predict', and 'tensor', respectively. + +#### Evaluation + +The evaluation in MMDet 2.x strictly binds with the dataset. In contrast, MMDet 3.x decomposes the evaluation from dataset so that all the detection datasets can evaluate with COCO AP and other metrics implemented in MMDet 3.x. +MMDet 3.x mainly implements corresponding metrics for each dataset, which are manipulated by [Evaluator](https://mmengine.readthedocs.io/en/latest/design/evaluator.html) to complete the evaluation. +Users can build an evaluator in MMDet 3.x to conduct offline evaluation, i.e., evaluate predictions that may not produce in MMDet 3.x with the dataset as long as the dataset and the prediction follow the dataset conventions. More details can be found in the [tutorial in mmengine](https://mmengine.readthedocs.io/en/latest/tutorials/evaluation.html). + +#### Visualization + +The functions of visualization in MMDet 2.x are removed. Instead, in OpenMMLab 2.0 projects, we use [Visualizer](https://mmengine.readthedocs.io/en/latest/design/visualization.html) to visualize data. MMDet 3.x implements `DetLocalVisualizer` to allow visualization of ground truths, model predictions, feature maps, etc., at any place. It also supports sending the visualization data to any external visualization backends such as Tensorboard. + +### Improvements + +- Optimized training and testing speed of FCOS, RetinaNet, Faster R-CNN, Mask R-CNN, and Cascade R-CNN. The training speed of those models with some common training strategies is also optimized, including those with synchronized batch normalization and mixed precision training. +- Support mixed precision training of all the models. However, some models may get undesirable performance due to some numerical issues. We will update the documentation and list the results (accuracy of failure) of mixed precision training. +- Release strong baselines of some popular object detectors. Their accuracy and pre-trained checkpoints will be released. + +### Bug Fixes + +- DeepFashion dataset: the config and results have been updated. + +### New Features + +1. Support a general semi-supervised learning framework that works with all the object detectors supported in MMDet 3.x. Please refer to [semi-supervised object detection](../user_guides/semi_det.md) for details. +2. Enable all the single-stage detectors to serve as region proposal networks. We give [an example of using FCOS as RPN](../user_guides/single_stage_as_rpn.md). +3. Support a semi-supervised object detection algorithm: [SoftTeacher](https://arxiv.org/abs/2106.09018). +4. Support [the updated CenterNet](https://arxiv.org/abs/2103.07461). +5. Support data structures `HorizontalBoxes` and `BaseBoxes` to encapsulate different kinds of bounding boxes. We are migrating to use data structures of boxes to replace the use of pure tensor boxes. This will unify the usages of different kinds of bounding boxes in MMDet 3.x and MMRotate 1.x to simplify the implementation and reduce redundant codes. + +### Planned changes + +We list several planned changes of MMDet 3.0.0rc0 so that the community could more comprehensively know the progress of MMDet 3.x. Feel free to create a PR, issue, or discussion if you are interested, have any suggestions and feedback, or want to participate. + +1. Test-time augmentation: which is supported in MMDet 2.x, is not implemented in this version due to the limited time slot. We will support it in the following releases with a new and simplified design. +2. Inference interfaces: unified inference interfaces will be supported in the future to ease the use of released models. +3. Interfaces of useful tools that can be used in Jupyter Notebook or Colab: more useful tools that are implemented in the `tools` directory will have their python interfaces so that they can be used in Jupyter Notebook, Colab, and downstream libraries. +4. Documentation: we will add more design docs, tutorials, and migration guidance so that the community can deep dive into our new design, participate the future development, and smoothly migrate downstream libraries to MMDet 3.x. +5. Wandb visualization: MMDet 2.x supports data visualization since v2.25.0, which has not been migrated to MMDet 3.x for now. Since WandB provides strong visualization and experiment management capabilities, a `DetWandBVisualizer` and maybe a hook are planned to fully migrate those functionalities from MMDet 2.x. +6. Full support of WiderFace dataset (#8508) and Fast R-CNN: we are verifying their functionalities and will fix related issues soon. +7. Migrate DETR-series algorithms (#8655, #8533) and YOLOv3 on IPU (#8552) from MMDet 2.x. + +### Contributors + +A total of 11 developers contributed to this release. +Thanks @shuxp, @wanghonglie, @Czm369, @BIGWangYuDong, @zytx121, @jbwang1997, @chhluo, @jshilong, @RangiLyu, @hhaAndroid, @ZwwWayne diff --git a/mmdet_code/SR-TOD/docs/en/notes/changelog_v2.x.md b/mmdet_code/SR-TOD/docs/en/notes/changelog_v2.x.md new file mode 100644 index 0000000000000000000000000000000000000000..2b3a230c0d94687e644c8ef15899781c079d5e1c --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/notes/changelog_v2.x.md @@ -0,0 +1,1681 @@ +# Changelog v2.x + +### v2.25.0 (31/5/2022) + +#### Highlights + +- Support dedicated `WandbLogger` hook +- Support [ConvNeXt](configs/convnext), [DDOD](configs/ddod), [SOLOv2](configs/solov2) +- Support [Mask2Former](configs/mask2former) for instance segmentation +- Rename [config files of Mask2Former](configs/mask2former) + +#### Backwards incompatible changes + +- Rename [config files of Mask2Former](configs/mask2former) (#7571) + + + + + + + + + + + +
before v2.25.0after v2.25.0
+ + - `mask2former_xxx_coco.py` represents config files for **panoptic segmentation**. + + + + - `mask2former_xxx_coco.py` represents config files for **instance segmentation**. + - `mask2former_xxx_coco-panoptic.py` represents config files for **panoptic segmentation**. + +
+ +#### New Features + +- Support [ConvNeXt](https://arxiv.org/abs/2201.03545) (#7281) +- Support [DDOD](https://arxiv.org/abs/2107.02963) (#7279) +- Support [SOLOv2](https://arxiv.org/abs/2003.10152) (#7441) +- Support [Mask2Former](https://arxiv.org/abs/2112.01527) for instance segmentation (#7571, #8032) + +#### Bug Fixes + +- Enable YOLOX training on different devices (#7912) +- Fix the log plot error when evaluation with `interval != 1` (#7784) +- Fix RuntimeError of HTC (#8083) + +#### Improvements + +- Support dedicated `WandbLogger` hook (#7459) + + Users can set + + ```python + cfg.log_config.hooks = [ + dict(type='MMDetWandbHook', + init_kwargs={'project': 'MMDetection-tutorial'}, + interval=10, + log_checkpoint=True, + log_checkpoint_metadata=True, + num_eval_images=10)] + ``` + + in the config to use `MMDetWandbHook`. Example can be found in this [colab tutorial](https://colab.research.google.com/drive/1RCSXHZwDZvakFh3eo9RuNrJbCGqD0dru?usp=sharing#scrollTo=WTEdPDRaBz2C) + +- Add `AvoidOOM` to avoid OOM (#7434, #8091) + + Try to use `AvoidCUDAOOM` to avoid GPU out of memory. It will first retry after calling `torch.cuda.empty_cache()`. If it still fails, it will then retry by converting the type of inputs to FP16 format. If it still fails, it will try to copy inputs from GPUs to CPUs to continue computing. Try AvoidOOM in code to make the code continue to run when GPU memory runs out: + + ```python + from mmdet.utils import AvoidCUDAOOM + + output = AvoidCUDAOOM.retry_if_cuda_oom(some_function)(input1, input2) + ``` + + Users can also try `AvoidCUDAOOM` as a decorator to make the code continue to run when GPU memory runs out: + + ```python + from mmdet.utils import AvoidCUDAOOM + + @AvoidCUDAOOM.retry_if_cuda_oom + def function(*args, **kwargs): + ... + return xxx + ``` + +- Support reading `gpu_collect` from `cfg.evaluation.gpu_collect` (#7672) + +- Speedup the Video Inference by Accelerating data-loading Stage (#7832) + +- Support replacing the `${key}` with the value of `cfg.key` (#7492) + +- Accelerate result analysis in `analyze_result.py`. The evaluation time is speedup by 10 ~ 15 times and only tasks 10 ~ 15 minutes now. (#7891) + +- Support to set `block_dilations` in `DilatedEncoder` (#7812) + +- Support panoptic segmentation result analysis (#7922) + +- Release DyHead with Swin-Large backbone (#7733) + +- Documentations updating and adding + + - Fix wrong default type of `act_cfg` in `SwinTransformer` (#7794) + - Fix text errors in the tutorials (#7959) + - Rewrite the [installation guide](docs/en/get_started.md) (#7897) + - [Useful hooks](docs/en/tutorials/useful_hooks.md) (#7810) + - Fix heading anchor in documentation (#8006) + - Replace `markdownlint` with `mdformat` for avoiding installing ruby (#8009) + +#### Contributors + +A total of 20 developers contributed to this release. + +Thanks @ZwwWayne, @DarthThomas, @solyaH, @LutingWang, @chenxinfeng4, @Czm369, @Chenastron, @chhluo, @austinmw, @Shanyaliux @hellock, @Y-M-Y, @jbwang1997, @hhaAndroid, @Irvingao, @zhanggefan, @BIGWangYuDong, @Keiku, @PeterVennerstrom, @ayulockin + +### v2.24.0 (26/4/2022) + +#### Highlights + +- Support [Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation](https://arxiv.org/abs/2012.07177) +- Support automatically scaling LR according to GPU number and samples per GPU +- Support Class Aware Sampler that improves performance on OpenImages Dataset + +#### New Features + +- Support [Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation](https://arxiv.org/abs/2012.07177), see [example configs](configs/simple_copy_paste/mask_rcnn_r50_fpn_syncbn-all_rpn-2conv_ssj_scp_32x2_270k_coco.py) (#7501) + +- Support Class Aware Sampler, users can set + + ```python + data=dict(train_dataloader=dict(class_aware_sampler=dict(num_sample_class=1)))) + ``` + + in the config to use `ClassAwareSampler`. Examples can be found in [the configs of OpenImages Dataset](https://github.com/open-mmlab/mmdetection/tree/main/configs/openimages/faster_rcnn_r50_fpn_32x2_cas_1x_openimages.py). (#7436) + +- Support automatically scaling LR according to GPU number and samples per GPU. (#7482) + In each config, there is a corresponding config of auto-scaling LR as below, + + ```python + auto_scale_lr = dict(enable=True, base_batch_size=N) + ``` + + where `N` is the batch size used for the current learning rate in the config (also equals to `samples_per_gpu` * gpu number to train this config). + By default, we set `enable=False` so that the original usages will not be affected. Users can set `enable=True` in each config or add `--auto-scale-lr` after the command line to enable this feature and should check the correctness of `base_batch_size` in customized configs. + +- Support setting dataloader arguments in config and add functions to handle config compatibility. (#7668) + The comparison between the old and new usages is as below. + + + + + + + + + + + +
v2.23.0v2.24.0
+ + ```python + data = dict( + samples_per_gpu=64, workers_per_gpu=4, + train=dict(type='xxx', ...), + val=dict(type='xxx', samples_per_gpu=4, ...), + test=dict(type='xxx', ...), + ) + ``` + + + + ```python + # A recommended config that is clear + data = dict( + train=dict(type='xxx', ...), + val=dict(type='xxx', ...), + test=dict(type='xxx', ...), + # Use different batch size during inference. + train_dataloader=dict(samples_per_gpu=64, workers_per_gpu=4), + val_dataloader=dict(samples_per_gpu=8, workers_per_gpu=2), + test_dataloader=dict(samples_per_gpu=8, workers_per_gpu=2), + ) + + # Old style still works but allows to set more arguments about data loaders + data = dict( + samples_per_gpu=64, # only works for train_dataloader + workers_per_gpu=4, # only works for train_dataloader + train=dict(type='xxx', ...), + val=dict(type='xxx', ...), + test=dict(type='xxx', ...), + # Use different batch size during inference. + val_dataloader=dict(samples_per_gpu=8, workers_per_gpu=2), + test_dataloader=dict(samples_per_gpu=8, workers_per_gpu=2), + ) + ``` + +
+ +- Support memory profile hook. Users can use it to monitor the memory usages during training as below (#7560) + + ```python + custom_hooks = [ + dict(type='MemoryProfilerHook', interval=50) + ] + ``` + +- Support to run on PyTorch with MLU chip (#7578) + +- Support re-spliting data batch with tag (#7641) + +- Support the `DiceCost` used by [K-Net](https://arxiv.org/abs/2106.14855) in `MaskHungarianAssigner` (#7716) + +- Support splitting COCO data for Semi-supervised object detection (#7431) + +- Support Pathlib for Config.fromfile (#7685) + +- Support to use file client in OpenImages dataset (#7433) + +- Add a probability parameter to Mosaic transformation (#7371) + +- Support specifying interpolation mode in `Resize` pipeline (#7585) + +#### Bug Fixes + +- Avoid invalid bbox after deform_sampling (#7567) +- Fix the issue that argument color_theme does not take effect when exporting confusion matrix (#7701) +- Fix the `end_level` in Necks, which should be the index of the end input backbone level (#7502) +- Fix the bug that `mix_results` may be None in `MultiImageMixDataset` (#7530) +- Fix the bug in ResNet plugin when two plugins are used (#7797) + +#### Improvements + +- Enhance `load_json_logs` of analyze_logs.py for resumed training logs (#7732) +- Add argument `out_file` in image_demo.py (#7676) +- Allow mixed precision training with `SimOTAAssigner` (#7516) +- Updated INF to 100000.0 to be the same as that in the official YOLOX (#7778) +- Add documentations of: + - how to get channels of a new backbone (#7642) + - how to unfreeze the backbone network (#7570) + - how to train fast_rcnn model (#7549) + - proposals in Deformable DETR (#7690) + - from-scratch install script in get_started.md (#7575) +- Release pre-trained models of + - [Mask2Former](configs/mask2former) (#7595, #7709) + - RetinaNet with ResNet-18 and release models (#7387) + - RetinaNet with EfficientNet backbone (#7646) + +#### Contributors + +A total of 27 developers contributed to this release. +Thanks @jovialio, @zhangsanfeng2022, @HarryZJ, @jamiechoi1995, @nestiank, @PeterH0323, @RangeKing, @Y-M-Y, @mattcasey02, @weiji14, @Yulv-git, @xiefeifeihu, @FANG-MING, @meng976537406, @nijkah, @sudz123, @CCODING04, @SheffieldCao, @Czm369, @BIGWangYuDong, @zytx121, @jbwang1997, @chhluo, @jshilong, @RangiLyu, @hhaAndroid, @ZwwWayne + +### v2.23.0 (28/3/2022) + +#### Highlights + +- Support Mask2Former: [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) +- Support EfficientNet: [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) +- Support setting data root through environment variable `MMDET_DATASETS`, users don't have to modify the corresponding path in config files anymore. +- Find a good recipe for fine-tuning high precision ResNet backbone pre-trained by Torchvision. + +#### New Features + +- Support [Mask2Former](configs/mask2former)(#6938)(#7466)(#7471) +- Support [EfficientNet](configs/efficientnet) (#7514) +- Support setting data root through environment variable `MMDET_DATASETS`, users don't have to modify the corresponding path in config files anymore. (#7386) +- Support setting different seeds to different ranks (#7432) +- Update the `dist_train.sh` so that the script can be used to support launching multi-node training on machines without slurm (#7415) +- Find a good recipe for fine-tuning high precision ResNet backbone pre-trained by Torchvision (#7489) + +#### Bug Fixes + +- Fix bug in VOC unit test which removes the data directory (#7270) +- Adjust the order of `get_classes` and `FileClient` (#7276) +- Force the inputs of `get_bboxes` in yolox_head to float32 (#7324) +- Fix misplaced arguments in LoadPanopticAnnotations (#7388) +- Fix reduction=mean in CELoss. (#7449) +- Update unit test of CrossEntropyCost (#7537) +- Fix memory leaking in panpotic segmentation evaluation (#7538) +- Fix the bug of shape broadcast in YOLOv3 (#7551) + +#### Improvements + +- Add Chinese version of onnx2tensorrt.md (#7219) +- Update colab tutorials (#7310) +- Update information about Localization Distillation (#7350) +- Add Chinese version of `finetune.md` (#7178) +- Update YOLOX log for non square input (#7235) +- Add `nproc` in `coco_panoptic.py` for panoptic quality computing (#7315) +- Allow to set channel_order in LoadImageFromFile (#7258) +- Take point sample related functions out of mask_point_head (#7353) +- Add instance evaluation for coco_panoptic (#7313) +- Enhance the robustness of analyze_logs.py (#7407) +- Supplementary notes of sync_random_seed (#7440) +- Update docstring of cross entropy loss (#7472) +- Update pascal voc result (#7503) +- We create How-to documentation to record any questions about How to xxx. In this version, we added + - How to use Mosaic augmentation (#7507) + - How to use backbone in mmcls (#7438) + - How to produce and submit the prediction results of panoptic segmentation models on COCO test-dev set (#7430)) + +#### Contributors + +A total of 27 developers contributed to this release. +Thanks @ZwwWayne, @haofanwang, @shinya7y, @chhluo, @yangrisheng, @triple-Mu, @jbwang1997, @HikariTJU, @imflash217, @274869388, @zytx121, @matrixgame2018, @jamiechoi1995, @BIGWangYuDong, @JingweiZhang12, @Xiangxu-0103, @hhaAndroid, @jshilong, @osbm, @ceroytres, @bunge-bedstraw-herb, @Youth-Got, @daavoo, @jiangyitong, @RangiLyu, @CCODING04, @yarkable + +### v2.22.0 (24/2/2022) + +#### Highlights + +- Support MaskFormer: [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278) (#7212) +- Support DyHead: [Dynamic Head: Unifying Object Detection Heads with Attentions](https://arxiv.org/abs/2106.08322) (#6823) +- Release a good recipe of using ResNet in object detectors pre-trained by [ResNet Strikes Back](https://arxiv.org/abs/2110.00476), which consistently brings about 3~4 mAP improvements over RetinaNet, Faster/Mask/Cascade Mask R-CNN (#7001) +- Support [Open Images Dataset](https://storage.googleapis.com/openimages/web/index.html) (#6331) +- Support TIMM backbone: [PyTorch Image Models](https://github.com/rwightman/pytorch-image-models) (#7020) + +#### New Features + +- Support [MaskFormer](configs/maskformer) (#7212) +- Support [DyHead](configs/dyhead) (#6823) +- Support [ResNet Strikes Back](configs/resnet_strikes_back) (#7001) +- Support [OpenImages Dataset](configs/openimages) (#6331) +- Support [TIMM backbone](configs/timm_example) (#7020) +- Support visualization for Panoptic Segmentation (#7041) + +#### Breaking Changes + +In order to support the visualization for Panoptic Segmentation, the `num_classes` can not be `None` when using the `get_palette` function to determine whether to use the panoptic palette. + +#### Bug Fixes + +- Fix bug for the best checkpoints can not be saved when the `key_score` is None (#7101) +- Fix MixUp transform filter boxes failing case (#7080) +- Add missing properties in SABLHead (#7091) +- Fix bug when NaNs exist in confusion matrix (#7147) +- Fix PALETTE AttributeError in downstream task (#7230) + +#### Improvements + +- Speed up SimOTA matching (#7098) +- Add Chinese translation of `docs_zh-CN/tutorials/init_cfg.md` (#7188) + +#### Contributors + +A total of 20 developers contributed to this release. +Thanks @ZwwWayne, @hhaAndroid, @RangiLyu, @AronLin, @BIGWangYuDong, @jbwang1997, @zytx121, @chhluo, @shinya7y, @LuooChen, @dvansa, @siatwangmin, @del-zhenwu, @vikashranjan26, @haofanwang, @jamiechoi1995, @HJoonKwon, @yarkable, @zhijian-liu, @RangeKing + +### v2.21.0 (8/2/2022) + +### Breaking Changes + +To standardize the contents in config READMEs and meta files of OpenMMLab projects, the READMEs and meta files in each config directory have been significantly changed. The template will be released in the future, for now, you can refer to the examples of README for [algorithm](https://github.com/open-mmlab/mmdetection/blob/master/configs/faster_rcnn/README.md), [dataset](https://github.com/open-mmlab/mmdetection/blob/master/configs/deepfashion/README.md) and [backbone](https://github.com/open-mmlab/mmdetection/blob/master/configs/regnet/README.md). To align with the standard, the configs in dcn are put into to two directories named `dcn` and `dcnv2`. + +#### New Features + +- Allow to customize colors of different classes during visualization (#6716) +- Support CPU training (#7016) +- Add download script of COCO, LVIS, and VOC dataset (#7015) + +#### Bug Fixes + +- Fix weight conversion issue of RetinaNet with Swin-S (#6973) +- Update `__repr__` of `Compose` (#6951) +- Fix BadZipFile Error when build docker (#6966) +- Fix bug in non-distributed multi-gpu training/testing (#7019) +- Fix bbox clamp in PyTorch 1.10 (#7074) +- Relax the requirement of PALETTE in dataset wrappers (#7085) +- Keep the same weights before reassign in the PAA head (#7032) +- Update code demo in doc (#7092) + +#### Improvements + +- Speed-up training by allow to set variables of multi-processing (#6974, #7036) +- Add links of Chinese tutorials in readme (#6897) +- Disable cv2 multiprocessing by default for acceleration (#6867) +- Deprecate the support for "python setup.py test" (#6998) +- Re-organize metafiles and config readmes (#7051) +- Fix None grad problem during training TOOD by adding `SigmoidGeometricMean` (#7090) + +#### Contributors + +A total of 26 developers contributed to this release. +Thanks @del-zhenwu, @zimoqingfeng, @srishilesh, @imyhxy, @jenhaoyang, @jliu-ac, @kimnamu, @ShengliLiu, @garvan2021, @ciusji, @DIYer22, @kimnamu, @q3394101, @zhouzaida, @gaotongxiao, @topsy404, @AntoAndGar, @jbwang1997, @nijkah, @ZwwWayne, @Czm369, @jshilong, @RangiLyu, @BIGWangYuDong, @hhaAndroid, @AronLin + +### v2.20.0 (27/12/2021) + +#### New Features + +- Support [TOOD](configs/tood/README.md): Task-aligned One-stage Object Detection (ICCV 2021 Oral) (#6746) +- Support resuming from the latest checkpoint automatically (#6727) + +#### Bug Fixes + +- Fix wrong bbox `loss_weight` of the PAA head (#6744) +- Fix the padding value of `gt_semantic_seg` in batch collating (#6837) +- Fix test error of lvis when using `classwise` (#6845) +- Avoid BC-breaking of `get_local_path` (#6719) +- Fix bug in `sync_norm_hook` when the BN layer does not exist (#6852) +- Use pycocotools directly no matter what platform it is (#6838) + +#### Improvements + +- Add unit test for SimOTA with no valid bbox (#6770) +- Use precommit to check readme (#6802) +- Support selecting GPU-ids in non-distributed testing time (#6781) + +#### Contributors + +A total of 16 developers contributed to this release. +Thanks @ZwwWayne, @Czm369, @jshilong, @RangiLyu, @BIGWangYuDong, @hhaAndroid, @jamiechoi1995, @AronLin, @Keiku, @gkagkos, @fcakyon, @www516717402, @vansin, @zactodd, @kimnamu, @jenhaoyang + +### v2.19.1 (14/12/2021) + +#### New Features + +- Release [YOLOX](configs/yolox/README.md) COCO pretrained models (#6698) + +#### Bug Fixes + +- Fix DCN initialization in DenseHead (#6625) +- Fix initialization of ConvFCHead (#6624) +- Fix PseudoSampler in RCNN (#6622) +- Fix weight initialization in Swin and PVT (#6663) +- Fix dtype bug in BaseDenseHead (#6767) +- Fix SimOTA with no valid bbox (#6733) + +#### Improvements + +- Add an example of combining swin and one-stage models (#6621) +- Add `get_ann_info` to dataset_wrappers (#6526) +- Support keeping image ratio in the multi-scale training of YOLOX (#6732) +- Support `bbox_clip_border` for the augmentations of YOLOX (#6730) + +#### Documents + +- Update metafile (#6717) +- Add mmhuman3d in readme (#6699) +- Update FAQ docs (#6587) +- Add doc for `detect_anomalous_params` (#6697) + +#### Contributors + +A total of 11 developers contributed to this release. +Thanks @ZwwWayne, @LJoson, @Czm369, @jshilong, @ZCMax, @RangiLyu, @BIGWangYuDong, @hhaAndroid, @zhaoxin111, @GT9505, @shinya7y + +### v2.19.0 (29/11/2021) + +#### Highlights + +- Support [Label Assignment Distillation](https://arxiv.org/abs/2108.10520) +- Support `persistent_workers` for Pytorch >= 1.7 +- Align accuracy to the updated official YOLOX + +#### New Features + +- Support [Label Assignment Distillation](https://arxiv.org/abs/2108.10520) (#6342) +- Support `persistent_workers` for Pytorch >= 1.7 (#6435) + +#### Bug Fixes + +- Fix repeatedly output warning message (#6584) +- Avoid infinite GPU waiting in dist training (#6501) +- Fix SSD512 config error (#6574) +- Fix MMDetection model to ONNX command (#6558) + +#### Improvements + +- Refactor configs of FP16 models (#6592) +- Align accuracy to the updated official YOLOX (#6443) +- Speed up training and reduce memory cost when using PhotoMetricDistortion. (#6442) +- Make OHEM work with seesaw loss (#6514) + +#### Documents + +- Update README.md (#6567) + +#### Contributors + +A total of 11 developers contributed to this release. +Thanks @FloydHsiu, @RangiLyu, @ZwwWayne, @AndreaPi, @st9007a, @hachreak, @BIGWangYuDong, @hhaAndroid, @AronLin, @chhluo, @vealocia, @HarborYuan, @st9007a, @jshilong + +### v2.18.1 (15/11/2021) + +#### Highlights + +- Release [QueryInst](http://arxiv.org/abs/2105.01928) pre-trained weights (#6460) +- Support plot confusion matrix (#6344) + +#### New Features + +- Release [QueryInst](http://arxiv.org/abs/2105.01928) pre-trained weights (#6460) +- Support plot confusion matrix (#6344) + +#### Bug Fixes + +- Fix aug test error when the number of prediction bboxes is 0 (#6398) +- Fix SpatialReductionAttention in PVT (#6488) +- Fix wrong use of `trunc_normal_init` in PVT and Swin-Transformer (#6432) + +#### Improvements + +- Save the printed AP information of COCO API to logger (#6505) +- Always map location to cpu when load checkpoint (#6405) +- Set a random seed when the user does not set a seed (#6457) + +#### Documents + +- Chinese version of [Corruption Benchmarking](robustness_benchmarking.md) (#6375) +- Fix config path in docs (#6396) +- Update GRoIE readme (#6401) + +#### Contributors + +A total of 11 developers contributed to this release. +Thanks @st9007a, @hachreak, @HarborYuan, @vealocia, @chhluo, @AndreaPi, @AronLin, @BIGWangYuDong, @hhaAndroid, @RangiLyu, @ZwwWayne + +### v2.18.0 (27/10/2021) + +#### Highlights + +- Support [QueryInst](http://arxiv.org/abs/2105.01928) (#6050) +- Refactor dense heads to decouple onnx export logics from `get_bboxes` and speed up inference (#5317, #6003, #6369, #6268, #6315) + +#### New Features + +- Support [QueryInst](http://arxiv.org/abs/2105.01928) (#6050) +- Support infinite sampler (#5996) + +#### Bug Fixes + +- Fix init_weight in fcn_mask_head (#6378) +- Fix type error in imshow_bboxes of RPN (#6386) +- Fix broken colab link in MMDetection Tutorial (#6382) +- Make sure the device and dtype of scale_factor are the same as bboxes (#6374) +- Remove sampling hardcode (#6317) +- Fix RandomAffine bbox coordinate recorrection (#6293) +- Fix init bug of final cls/reg layer in convfc head (#6279) +- Fix img_shape broken in auto_augment (#6259) +- Fix kwargs parameter missing error in two_stage (#6256) + +#### Improvements + +- Unify the interface of stuff head and panoptic head (#6308) +- Polish readme (#6243) +- Add code-spell pre-commit hook and fix a typo (#6306) +- Fix typo (#6245, #6190) +- Fix sampler unit test (#6284) +- Fix `forward_dummy` of YOLACT to enable `get_flops` (#6079) +- Fix link error in the config documentation (#6252) +- Adjust the order to beautify the document (#6195) + +#### Refactors + +- Refactor one-stage get_bboxes logic (#5317) +- Refactor ONNX export of One-Stage models (#6003, #6369) +- Refactor dense_head and speedup (#6268) +- Migrate to use prior_generator in training of dense heads (#6315) + +#### Contributors + +A total of 18 developers contributed to this release. +Thanks @Boyden, @onnkeat, @st9007a, @vealocia, @yhcao6, @DapangpangX, @yellowdolphin, @cclauss, @kennymckormick, +@pingguokiller, @collinzrj, @AndreaPi, @AronLin, @BIGWangYuDong, @hhaAndroid, @jshilong, @RangiLyu, @ZwwWayne + +### v2.17.0 (28/9/2021) + +#### Highlights + +- Support [PVT](https://arxiv.org/abs/2102.12122) and [PVTv2](https://arxiv.org/abs/2106.13797) +- Support [SOLO](https://arxiv.org/abs/1912.04488) +- Support large scale jittering and New Mask R-CNN baselines +- Speed up `YOLOv3` inference + +#### New Features + +- Support [PVT](https://arxiv.org/abs/2102.12122) and [PVTv2](https://arxiv.org/abs/2106.13797) (#5780) +- Support [SOLO](https://arxiv.org/abs/1912.04488) (#5832) +- Support large scale jittering and New Mask R-CNN baselines (#6132) +- Add a general data structure for the results of models (#5508) +- Added a base class for one-stage instance segmentation (#5904) +- Speed up `YOLOv3` inference (#5991) +- Release Swin Transformer pre-trained models (#6100) +- Support mixed precision training in `YOLOX` (#5983) +- Support `val` workflow in `YOLACT` (#5986) +- Add script to test `torchserve` (#5936) +- Support `onnxsim` with dynamic input shape (#6117) + +#### Bug Fixes + +- Fix the function naming errors in `model_wrappers` (#5975) +- Fix regression loss bug when the input is an empty tensor (#5976) +- Fix scores not contiguous error in `centernet_head` (#6016) +- Fix missing parameters bug in `imshow_bboxes` (#6034) +- Fix bug in `aug_test` of `HTC` when the length of `det_bboxes` is 0 (#6088) +- Fix empty proposal errors in the training of some two-stage models (#5941) +- Fix `dynamic_axes` parameter error in `ONNX` dynamic shape export (#6104) +- Fix `dynamic_shape` bug of `SyncRandomSizeHook` (#6144) +- Fix the Swin Transformer config link error in the configuration (#6172) + +#### Improvements + +- Add filter rules in `Mosaic` transform (#5897) +- Add size divisor in get flops to avoid some potential bugs (#6076) +- Add Chinese translation of `docs_zh-CN/tutorials/customize_dataset.md` (#5915) +- Add Chinese translation of `conventions.md` (#5825) +- Add description of the output of data pipeline (#5886) +- Add dataset information in the README file for `PanopticFPN` (#5996) +- Add `extra_repr` for `DropBlock` layer to get details in the model printing (#6140) +- Fix CI out of memory and add PyTorch1.9 Python3.9 unit tests (#5862) +- Fix download links error of some model (#6069) +- Improve the generalization of XML dataset (#5943) +- Polish assertion error messages (#6017) +- Remove `opencv-python-headless` dependency by `albumentations` (#5868) +- Check dtype in transform unit tests (#5969) +- Replace the default theme of documentation with PyTorch Sphinx Theme (#6146) +- Update the paper and code fields in the metafile (#6043) +- Support to customize padding value of segmentation map (#6152) +- Support to resize multiple segmentation maps (#5747) + +#### Contributors + +A total of 24 developers contributed to this release. +Thanks @morkovka1337, @HarborYuan, @guillaumefrd, @guigarfr, @www516717402, @gaotongxiao, @ypwhs, @MartaYang, @shinya7y, @justiceeem, @zhaojinjian0000, @VVsssssk, @aravind-anantha, @wangbo-zhao, @czczup, @whai362, @czczup, @marijnl, @AronLin, @BIGWangYuDong, @hhaAndroid, @jshilong, @RangiLyu, @ZwwWayne + +### v2.16.0 (30/8/2021) + +#### Highlights + +- Support [Panoptic FPN](https://arxiv.org/abs/1901.02446) and [Swin Transformer](https://arxiv.org/abs/2103.14030) + +#### New Features + +- Support [Panoptic FPN](https://arxiv.org/abs/1901.02446) and release models (#5577, #5902) +- Support Swin Transformer backbone (#5748) +- Release RetinaNet models pre-trained with multi-scale 3x schedule (#5636) +- Add script to convert unlabeled image list to coco format (#5643) +- Add hook to check whether the loss value is valid (#5674) +- Add YOLO anchor optimizing tool (#5644) +- Support export onnx models without post process. (#5851) +- Support classwise evaluation in CocoPanopticDataset (#5896) +- Adapt browse_dataset for concatenated datasets. (#5935) +- Add `PatchEmbed` and `PatchMerging` with `AdaptivePadding` (#5952) + +#### Bug Fixes + +- Fix unit tests of YOLOX (#5859) +- Fix lose randomness in `imshow_det_bboxes` (#5845) +- Make output result of `ImageToTensor` contiguous (#5756) +- Fix inference bug when calling `regress_by_class` in RoIHead in some cases (#5884) +- Fix bug in CIoU loss where alpha should not have gradient. (#5835) +- Fix the bug that `multiscale_output` is defined but not used in HRNet (#5887) +- Set the priority of EvalHook to LOW. (#5882) +- Fix a YOLOX bug when applying bbox rescaling in test mode (#5899) +- Fix mosaic coordinate error (#5947) +- Fix dtype of bbox in RandomAffine. (#5930) + +#### Improvements + +- Add Chinese version of `data_pipeline` and (#5662) +- Support to remove state dicts of EMA when publishing models. (#5858) +- Refactor the loss function in HTC and SCNet (#5881) +- Use warnings instead of logger.warning (#5540) +- Use legacy coordinate in metric of VOC (#5627) +- Add Chinese version of customize_losses (#5826) +- Add Chinese version of model_zoo (#5827) + +#### Contributors + +A total of 19 developers contributed to this release. +Thanks @ypwhs, @zywvvd, @collinzrj, @OceanPang, @ddonatien, @@haotian-liu, @viibridges, @Muyun99, @guigarfr, @zhaojinjian0000, @jbwang1997,@wangbo-zhao, @xvjiarui, @RangiLyu, @jshilong, @AronLin, @BIGWangYuDong, @hhaAndroid, @ZwwWayne + +### v2.15.1 (11/8/2021) + +#### Highlights + +- Support [YOLOX](https://arxiv.org/abs/2107.08430) + +#### New Features + +- Support [YOLOX](https://arxiv.org/abs/2107.08430)(#5756, #5758, #5760, #5767, #5770, #5774, #5777, #5808, #5828, #5848) + +#### Bug Fixes + +- Update correct SSD models. (#5789) +- Fix casting error in mask structure (#5820) +- Fix MMCV deployment documentation links. (#5790) + +#### Improvements + +- Use dynamic MMCV download link in TorchServe dockerfile (#5779) +- Rename the function `upsample_like` to `interpolate_as` for more general usage (#5788) + +#### Contributors + +A total of 14 developers contributed to this release. +Thanks @HAOCHENYE, @xiaohu2015, @HsLOL, @zhiqwang, @Adamdad, @shinya7y, @Johnson-Wang, @RangiLyu, @jshilong, @mmeendez8, @AronLin, @BIGWangYuDong, @hhaAndroid, @ZwwWayne + +### v2.15.0 (02/8/2021) + +#### Highlights + +- Support adding [MIM](https://github.com/open-mmlab/mim) dependencies during pip installation +- Support MobileNetV2 for SSD-Lite and YOLOv3 +- Support Chinese Documentation + +#### New Features + +- Add function `upsample_like` (#5732) +- Support to output pdf and epub format documentation (#5738) +- Support and release Cascade Mask R-CNN 3x pre-trained models (#5645) +- Add `ignore_index` to CrossEntropyLoss (#5646) +- Support adding [MIM](https://github.com/open-mmlab/mim) dependencies during pip installation (#5676) +- Add MobileNetV2 config and models for YOLOv3 (#5510) +- Support COCO Panoptic Dataset (#5231) +- Support ONNX export of cascade models (#5486) +- Support DropBlock with RetinaNet (#5544) +- Support MobileNetV2 SSD-Lite (#5526) + +#### Bug Fixes + +- Fix the device of label in multiclass_nms (#5673) +- Fix error of backbone initialization from pre-trained checkpoint in config file (#5603, #5550) +- Fix download links of RegNet pretrained weights (#5655) +- Fix two-stage runtime error given empty proposal (#5559) +- Fix flops count error in DETR (#5654) +- Fix unittest for `NumClassCheckHook` when it is not used. (#5626) +- Fix description bug of using custom dataset (#5546) +- Fix bug of `multiclass_nms` that returns the global indices (#5592) +- Fix `valid_mask` logic error in RPNHead (#5562) +- Fix unit test error of pretrained configs (#5561) +- Fix typo error in anchor_head.py (#5555) +- Fix bug when using dataset wrappers (#5552) +- Fix a typo error in demo/MMDet_Tutorial.ipynb (#5511) +- Fixing crash in `get_root_logger` when `cfg.log_level` is not None (#5521) +- Fix docker version (#5502) +- Fix optimizer parameter error when using `IterBasedRunner` (#5490) + +#### Improvements + +- Add unit tests for MMTracking (#5620) +- Add Chinese translation of documentation (#5718, #5618, #5558, #5423, #5593, #5421, #5408. #5369, #5419, #5530, #5531) +- Update resource limit (#5697) +- Update docstring for InstaBoost (#5640) +- Support key `reduction_override` in all loss functions (#5515) +- Use repeatdataset to accelerate CenterNet training (#5509) +- Remove unnecessary code in autoassign (#5519) +- Add documentation about `init_cfg` (#5273) + +#### Contributors + +A total of 18 developers contributed to this release. +Thanks @OceanPang, @AronLin, @hellock, @Outsider565, @RangiLyu, @ElectronicElephant, @likyoo, @BIGWangYuDong, @hhaAndroid, @noobying, @yyz561, @likyoo, +@zeakey, @ZwwWayne, @ChenyangLiu, @johnson-magic, @qingswu, @BuxianChen + +### v2.14.0 (29/6/2021) + +#### Highlights + +- Add `simple_test` to dense heads to improve the consistency of single-stage and two-stage detectors +- Revert the `test_mixins` to single image test to improve efficiency and readability +- Add Faster R-CNN and Mask R-CNN config using multi-scale training with 3x schedule + +#### New Features + +- Support pretrained models from MoCo v2 and SwAV (#5286) +- Add Faster R-CNN and Mask R-CNN config using multi-scale training with 3x schedule (#5179, #5233) +- Add `reduction_override` in MSELoss (#5437) +- Stable support of exporting DETR to ONNX with dynamic shapes and batch inference (#5168) +- Stable support of exporting PointRend to ONNX with dynamic shapes and batch inference (#5440) + +#### Bug Fixes + +- Fix size mismatch bug in `multiclass_nms` (#4980) +- Fix the import path of `MultiScaleDeformableAttention` (#5338) +- Fix errors in config of GCNet ResNext101 models (#5360) +- Fix Grid-RCNN error when there is no bbox result (#5357) +- Fix errors in `onnx_export` of bbox_head when setting reg_class_agnostic (#5468) +- Fix type error of AutoAssign in the document (#5478) +- Fix web links ending with `.md` (#5315) + +#### Improvements + +- Add `simple_test` to dense heads to improve the consistency of single-stage and two-stage detectors (#5264) +- Add support for mask diagonal flip in TTA (#5403) +- Revert the `test_mixins` to single image test to improve efficiency and readability (#5249) +- Make YOLOv3 Neck more flexible (#5218) +- Refactor SSD to make it more general (#5291) +- Refactor `anchor_generator` and `point_generator` (#5349) +- Allow to configure out the `mask_head` of the HTC algorithm (#5389) +- Delete deprecated warning in FPN (#5311) +- Move `model.pretrained` to `model.backbone.init_cfg` (#5370) +- Make deployment tools more friendly to use (#5280) +- Clarify installation documentation (#5316) +- Add ImageNet Pretrained Models docs (#5268) +- Add FAQ about training loss=nan solution and COCO AP or AR =-1 (# 5312, #5313) +- Change all weight links of http to https (#5328) + +### v2.13.0 (01/6/2021) + +#### Highlights + +- Support new methods: [CenterNet](https://arxiv.org/abs/1904.07850), [Seesaw Loss](https://arxiv.org/abs/2008.10032), [MobileNetV2](https://arxiv.org/abs/1801.04381) + +#### New Features + +- Support paper [Objects as Points](https://arxiv.org/abs/1904.07850) (#4602) +- Support paper [Seesaw Loss for Long-Tailed Instance Segmentation (CVPR 2021)](https://arxiv.org/abs/2008.10032) (#5128) +- Support [MobileNetV2](https://arxiv.org/abs/1801.04381) backbone and inverted residual block (#5122) +- Support [MIM](https://github.com/open-mmlab/mim) (#5143) +- ONNX exportation with dynamic shapes of CornerNet (#5136) +- Add `mask_soft` config option to allow non-binary masks (#4615) +- Add PWC metafile (#5135) + +#### Bug Fixes + +- Fix YOLOv3 FP16 training error (#5172) +- Fix Cacscade R-CNN TTA test error when `det_bboxes` length is 0 (#5221) +- Fix `iou_thr` variable naming errors in VOC recall calculation function (#5195) +- Fix Faster R-CNN performance dropped in ONNX Runtime (#5197) +- Fix DETR dict changed error when using python 3.8 during iteration (#5226) + +#### Improvements + +- Refactor ONNX export of two stage detector (#5205) +- Replace MMDetection's EvalHook with MMCV's EvalHook for consistency (#4806) +- Update RoI extractor for ONNX (#5194) +- Use better parameter initialization in YOLOv3 head for higher performance (#5181) +- Release new DCN models of Mask R-CNN by mixed-precision training (#5201) +- Update YOLOv3 model weights (#5229) +- Add DetectoRS ResNet-101 model weights (#4960) +- Discard bboxes with sizes equals to `min_bbox_size` (#5011) +- Remove duplicated code in DETR head (#5129) +- Remove unnecessary object in class definition (#5180) +- Fix doc link (#5192) + +### v2.12.0 (01/5/2021) + +#### Highlights + +- Support new methods: [AutoAssign](https://arxiv.org/abs/2007.03496), [YOLOF](https://arxiv.org/abs/2103.09460), and [Deformable DETR](https://arxiv.org/abs/2010.04159) +- Stable support of exporting models to ONNX with batched images and dynamic shape (#5039) + +#### Backwards Incompatible Changes + +MMDetection is going through big refactoring for more general and convenient usages during the releases from v2.12.0 to v2.15.0 (maybe longer). +In v2.12.0 MMDetection inevitably brings some BC-breakings, including the MMCV dependency, model initialization, model registry, and mask AP evaluation. + +- MMCV version. MMDetection v2.12.0 relies on the newest features in MMCV 1.3.3, including `BaseModule` for unified parameter initialization, model registry, and the CUDA operator `MultiScaleDeformableAttn` for [Deformable DETR](https://arxiv.org/abs/2010.04159). Note that MMCV 1.3.2 already contains all the features used by MMDet but has known issues. Therefore, we recommend users skip MMCV v1.3.2 and use v1.3.3, though v1.3.2 might work for most cases. +- Unified model initialization (#4750). To unify the parameter initialization in OpenMMLab projects, MMCV supports `BaseModule` that accepts `init_cfg` to allow the modules' parameters initialized in a flexible and unified manner. Now the users need to explicitly call `model.init_weights()` in the training script to initialize the model (as in [here](https://github.com/open-mmlab/mmdetection/blob/master/tools/train.py#L162), previously this was handled by the detector. The models in MMDetection have been re-benchmarked to ensure accuracy based on PR #4750. __The downstream projects should update their code accordingly to use MMDetection v2.12.0__. +- Unified model registry (#5059). To easily use backbones implemented in other OpenMMLab projects, MMDetection migrates to inherit the model registry created in MMCV (#760). In this way, as long as the backbone is supported in an OpenMMLab project and that project also uses the registry in MMCV, users can use that backbone in MMDetection by simply modifying the config without copying the code of that backbone into MMDetection. +- Mask AP evaluation (#4898). Previous versions calculate the areas of masks through the bounding boxes when calculating the mask AP of small, medium, and large instances. To indeed use the areas of masks, we pop the key `bbox` during mask AP calculation. This change does not affect the overall mask AP evaluation and aligns the mask AP of similar models in other projects like Detectron2. + +#### New Features + +- Support paper [AutoAssign: Differentiable Label Assignment for Dense Object Detection](https://arxiv.org/abs/2007.03496) (#4295) +- Support paper [You Only Look One-level Feature](https://arxiv.org/abs/2103.09460) (#4295) +- Support paper [Deformable DETR: Deformable Transformers for End-to-End Object Detection](https://arxiv.org/abs/2010.04159) (#4778) +- Support calculating IoU with FP16 tensor in `bbox_overlaps` to save memory and keep speed (#4889) +- Add `__repr__` in custom dataset to count the number of instances (#4756) +- Add windows support by updating requirements.txt (#5052) +- Stable support of exporting models to ONNX with batched images and dynamic shape, including SSD, FSAF,FCOS, YOLOv3, RetinaNet, Faster R-CNN, and Mask R-CNN (#5039) + +#### Improvements + +- Use MMCV `MODEL_REGISTRY` (#5059) +- Unified parameter initialization for more flexible usage (#4750) +- Rename variable names and fix docstring in anchor head (#4883) +- Support training with empty GT in Cascade RPN (#4928) +- Add more details of usage of `test_robustness` in documentation (#4917) +- Changing to use `pycocotools` instead of `mmpycocotools` to fully support Detectron2 and MMDetection in one environment (#4939) +- Update torch serve dockerfile to support dockers of more versions (#4954) +- Add check for training with single class dataset (#4973) +- Refactor transformer and DETR Head (#4763) +- Update FPG model zoo (#5079) +- More accurate mask AP of small/medium/large instances (#4898) + +#### Bug Fixes + +- Fix bug in mean_ap.py when calculating mAP by 11 points (#4875) +- Fix error when key `meta` is not in old checkpoints (#4936) +- Fix hanging bug when training with empty GT in VFNet, GFL, and FCOS by changing the place of `reduce_mean` (#4923, #4978, #5058) +- Fix asyncronized inference error and provide related demo (#4941) +- Fix IoU losses dimensionality unmatch error (#4982) +- Fix torch.randperm whtn using PyTorch 1.8 (#5014) +- Fix empty bbox error in `mask_head` when using CARAFE (#5062) +- Fix `supplement_mask` bug when there are zero-size RoIs (#5065) +- Fix testing with empty rois in RoI Heads (#5081) + +### v2.11.0 (01/4/2021) + +__Highlights__ + +- Support new method: [Localization Distillation for Object Detection](https://arxiv.org/pdf/2102.12252.pdf) +- Support Pytorch2ONNX with batch inference and dynamic shape + +__New Features__ + +- Support [Localization Distillation for Object Detection](https://arxiv.org/pdf/2102.12252.pdf) (#4758) +- Support Pytorch2ONNX with batch inference and dynamic shape for Faster-RCNN and mainstream one-stage detectors (#4796) + +__Improvements__ + +- Support batch inference in head of RetinaNet (#4699) +- Add batch dimension in second stage of Faster-RCNN (#4785) +- Support batch inference in bbox coder (#4721) +- Add check for `ann_ids` in `COCODataset` to ensure it is unique (#4789) +- support for showing the FPN results (#4716) +- support dynamic shape for grid_anchor (#4684) +- Move pycocotools version check to when it is used (#4880) + +__Bug Fixes__ + +- Fix a bug of TridentNet when doing the batch inference (#4717) +- Fix a bug of Pytorch2ONNX in FASF (#4735) +- Fix a bug when show the image with float type (#4732) + +### v2.10.0 (01/03/2021) + +#### Highlights + +- Support new methods: [FPG](https://arxiv.org/abs/2004.03580) +- Support ONNX2TensorRT for SSD, FSAF, FCOS, YOLOv3, and Faster R-CNN. + +#### New Features + +- Support ONNX2TensorRT for SSD, FSAF, FCOS, YOLOv3, and Faster R-CNN (#4569) +- Support [Feature Pyramid Grids (FPG)](https://arxiv.org/abs/2004.03580) (#4645) +- Support video demo (#4420) +- Add seed option for sampler (#4665) +- Support to customize type of runner (#4570, #4669) +- Support synchronizing BN buffer in `EvalHook` (#4582) +- Add script for GIF demo (#4573) + +#### Bug Fixes + +- Fix ConfigDict AttributeError and add Colab link (#4643) +- Avoid crash in empty gt training of GFL head (#4631) +- Fix `iou_thrs` bug in RPN evaluation (#4581) +- Fix syntax error of config when upgrading model version (#4584) + +#### Improvements + +- Refactor unit test file structures (#4600) +- Refactor nms config (#4636) +- Get loading pipeline by checking the class directly rather than through config strings (#4619) +- Add doctests for mask target generation and mask structures (#4614) +- Use deep copy when copying pipeline arguments (#4621) +- Update documentations (#4642, #4650, #4620, #4630) +- Remove redundant code calling `import_modules_from_strings` (#4601) +- Clean deprecated FP16 API (#4571) +- Check whether `CLASSES` is correctly initialized in the initialization of `XMLDataset` (#4555) +- Support batch inference in the inference API (#4462, #4526) +- Clean deprecated warning and fix 'meta' error (#4695) + +### v2.9.0 (01/02/2021) + +#### Highlights + +- Support new methods: [SCNet](https://arxiv.org/abs/2012.10150), [Sparse R-CNN](https://arxiv.org/abs/2011.12450) +- Move `train_cfg` and `test_cfg` into model in configs +- Support to visualize results based on prediction quality + +#### New Features + +- Support [SCNet](https://arxiv.org/abs/2012.10150) (#4356) +- Support [Sparse R-CNN](https://arxiv.org/abs/2011.12450) (#4219) +- Support evaluate mAP by multiple IoUs (#4398) +- Support concatenate dataset for testing (#4452) +- Support to visualize results based on prediction quality (#4441) +- Add ONNX simplify option to Pytorch2ONNX script (#4468) +- Add hook for checking compatibility of class numbers in heads and datasets (#4508) + +#### Bug Fixes + +- Fix CPU inference bug of Cascade RPN (#4410) +- Fix NMS error of CornerNet when there is no prediction box (#4409) +- Fix TypeError in CornerNet inference (#4411) +- Fix bug of PAA when training with background images (#4391) +- Fix the error that the window data is not destroyed when `out_file is not None` and `show==False` (#4442) +- Fix order of NMS `score_factor` that will decrease the performance of YOLOv3 (#4473) +- Fix bug in HTC TTA when the number of detection boxes is 0 (#4516) +- Fix resize error in mask data structures (#4520) + +#### Improvements + +- Allow to customize classes in LVIS dataset (#4382) +- Add tutorials for building new models with existing datasets (#4396) +- Add CPU compatibility information in documentation (#4405) +- Add documentation of deprecated `ImageToTensor` for batch inference (#4408) +- Add more details in documentation for customizing dataset (#4430) +- Switch `imshow_det_bboxes` visualization backend from OpenCV to Matplotlib (#4389) +- Deprecate `ImageToTensor` in `image_demo.py` (#4400) +- Move train_cfg/test_cfg into model (#4347, #4489) +- Update docstring for `reg_decoded_bbox` option in bbox heads (#4467) +- Update dataset information in documentation (#4525) +- Release pre-trained R50 and R101 PAA detectors with multi-scale 3x training schedules (#4495) +- Add guidance for speed benchmark (#4537) + +### v2.8.0 (04/01/2021) + +#### Highlights + +- Support new methods: [Cascade RPN](https://arxiv.org/abs/1909.06720), [TridentNet](https://arxiv.org/abs/1901.01892) + +#### New Features + +- Support [Cascade RPN](https://arxiv.org/abs/1909.06720) (#1900) +- Support [TridentNet](https://arxiv.org/abs/1901.01892) (#3313) + +#### Bug Fixes + +- Fix bug of show result in async_benchmark (#4367) +- Fix scale factor in MaskTestMixin (#4366) +- Fix but when returning indices in `multiclass_nms` (#4362) +- Fix bug of empirical attention in resnext backbone error (#4300) +- Fix bug of `img_norm_cfg` in FCOS-HRNet models with updated performance and models (#4250) +- Fix invalid checkpoint and log in Mask R-CNN models on Cityscapes dataset (#4287) +- Fix bug in distributed sampler when dataset is too small (#4257) +- Fix bug of 'PAFPN has no attribute extra_convs_on_inputs' (#4235) + +#### Improvements + +- Update model url from aws to aliyun (#4349) +- Update ATSS for PyTorch 1.6+ (#4359) +- Update script to install ruby in pre-commit installation (#4360) +- Delete deprecated `mmdet.ops` (#4325) +- Refactor hungarian assigner for more general usage in Sparse R-CNN (#4259) +- Handle scipy import in DETR to reduce package dependencies (#4339) +- Update documentation of usages for config options after MMCV (1.2.3) supports overriding list in config (#4326) +- Update pre-train models of faster rcnn trained on COCO subsets (#4307) +- Avoid zero or too small value for beta in Dynamic R-CNN (#4303) +- Add doccumentation for Pytorch2ONNX (#4271) +- Add deprecated warning FPN arguments (#4264) +- Support returning indices of kept bboxes when using nms (#4251) +- Update type and device requirements when creating tensors `GFLHead` (#4210) +- Update device requirements when creating tensors in `CrossEntropyLoss` (#4224) + +### v2.7.0 (30/11/2020) + +- Support new method: [DETR](https://arxiv.org/abs/2005.12872), [ResNest](https://arxiv.org/abs/2004.08955), Faster R-CNN DC5. +- Support YOLO, Mask R-CNN, and Cascade R-CNN models exportable to ONNX. + +#### New Features + +- Support [DETR](https://arxiv.org/abs/2005.12872) (#4201, #4206) +- Support to link the best checkpoint in training (#3773) +- Support to override config through options in inference.py (#4175) +- Support YOLO, Mask R-CNN, and Cascade R-CNN models exportable to ONNX (#4087, #4083) +- Support [ResNeSt](https://arxiv.org/abs/2004.08955) backbone (#2959) +- Support unclip border bbox regression (#4076) +- Add tpfp func in evaluating AP (#4069) +- Support mixed precision training of SSD detector with other backbones (#4081) +- Add Faster R-CNN DC5 models (#4043) + +#### Bug Fixes + +- Fix bug of `gpu_id` in distributed training mode (#4163) +- Support Albumentations with version higher than 0.5 (#4032) +- Fix num_classes bug in faster rcnn config (#4088) +- Update code in docs/2_new_data_model.md (#4041) + +#### Improvements + +- Ensure DCN offset to have similar type as features in VFNet (#4198) +- Add config links in README files of models (#4190) +- Add tutorials for loss conventions (#3818) +- Add solution to installation issues in 30-series GPUs (#4176) +- Update docker version in get_started.md (#4145) +- Add model statistics and polish some titles in configs README (#4140) +- Clamp neg probability in FreeAnchor (#4082) +- Speed up expanding large images (#4089) +- Fix Pytorch 1.7 incompatibility issues (#4103) +- Update trouble shooting page to resolve segmentation fault (#4055) +- Update aLRP-Loss in project page (#4078) +- Clean duplicated `reduce_mean` function (#4056) +- Refactor Q&A (#4045) + +### v2.6.0 (1/11/2020) + +- Support new method: [VarifocalNet](https://arxiv.org/abs/2008.13367). +- Refactored documentation with more tutorials. + +#### New Features + +- Support GIoU calculation in `BboxOverlaps2D`, and re-implement `giou_loss` using `bbox_overlaps` (#3936) +- Support random sampling in CPU mode (#3948) +- Support VarifocalNet (#3666, #4024) + +#### Bug Fixes + +- Fix SABL validating bug in Cascade R-CNN (#3913) +- Avoid division by zero in PAA head when num_pos=0 (#3938) +- Fix temporary directory bug of multi-node testing error (#4034, #4017) +- Fix `--show-dir` option in test script (#4025) +- Fix GA-RetinaNet r50 model url (#3983) +- Update code in docs and fix broken urls (#3947) + +#### Improvements + +- Refactor pytorch2onnx API into `mmdet.core.export` and use `generate_inputs_and_wrap_model` for pytorch2onnx (#3857, #3912) +- Update RPN upgrade scripts for v2.5.0 compatibility (#3986) +- Use mmcv `tensor2imgs` (#4010) +- Update test robustness (#4000) +- Update trouble shooting page (#3994) +- Accelerate PAA training speed (#3985) +- Support batch_size > 1 in validation (#3966) +- Use RoIAlign implemented in MMCV for inference in CPU mode (#3930) +- Documentation refactoring (#4031) + +### v2.5.0 (5/10/2020) + +#### Highlights + +- Support new methods: [YOLACT](https://arxiv.org/abs/1904.02689), [CentripetalNet](https://arxiv.org/abs/2003.09119). +- Add more documentations for easier and more clear usage. + +#### Backwards Incompatible Changes + +__FP16 related methods are imported from mmcv instead of mmdet. (#3766, #3822)__ +Mixed precision training utils in `mmdet.core.fp16` are moved to `mmcv.runner`, including `force_fp32`, `auto_fp16`, `wrap_fp16_model`, and `Fp16OptimizerHook`. A deprecation warning will be raised if users attempt to import those methods from `mmdet.core.fp16`, and will be finally removed in V2.10.0. + +__\[0, N-1\] represents foreground classes and N indicates background classes for all models. (#3221)__ +Before v2.5.0, the background label for RPN is 0, and N for other heads. Now the behavior is consistent for all models. Thus `self.background_labels` in `dense_heads` is removed and all heads use `self.num_classes` to indicate the class index of background labels. +This change has no effect on the pre-trained models in the v2.x model zoo, but will affect the training of all models with RPN heads. Two-stage detectors whose RPN head uses softmax will be affected because the order of categories is changed. + +**Only call `get_subset_by_classes` when `test_mode=True` and `self.filter_empty_gt=True` (#3695)** +Function `get_subset_by_classes` in dataset is refactored and only filters out images when `test_mode=True` and `self.filter_empty_gt=True`. +In the original implementation, `get_subset_by_classes` is not related to the flag `self.filter_empty_gt` and will only be called when the classes is set during initialization no matter `test_mode` is `True` or `False`. This brings ambiguous behavior and potential bugs in many cases. After v2.5.0, if `filter_empty_gt=False`, no matter whether the classes are specified in a dataset, the dataset will use all the images in the annotations. If `filter_empty_gt=True` and `test_mode=True`, no matter whether the classes are specified, the dataset will call \`\`get_subset_by_classes\` to check the images and filter out images containing no GT boxes. Therefore, the users should be responsible for the data filtering/cleaning process for the test dataset. + +#### New Features + +- Test time augmentation for single stage detectors (#3844, #3638) +- Support to show the name of experiments during training (#3764) +- Add `Shear`, `Rotate`, `Translate` Augmentation (#3656, #3619, #3687) +- Add image-only transformations including `Constrast`, `Equalize`, `Color`, and `Brightness`. (#3643) +- Support [YOLACT](https://arxiv.org/abs/1904.02689) (#3456) +- Support [CentripetalNet](https://arxiv.org/abs/2003.09119) (#3390) +- Support PyTorch 1.6 in docker (#3905) + +#### Bug Fixes + +- Fix the bug of training ATSS when there is no ground truth boxes (#3702) +- Fix the bug of using Focal Loss when there is `num_pos` is 0 (#3702) +- Fix the label index mapping in dataset browser (#3708) +- Fix Mask R-CNN training stuck problem when their is no positive rois (#3713) +- Fix the bug of `self.rpn_head.test_cfg` in `RPNTestMixin` by using `self.rpn_head` in rpn head (#3808) +- Fix deprecated `Conv2d` from mmcv.ops (#3791) +- Fix device bug in RepPoints (#3836) +- Fix SABL validating bug (#3849) +- Use `https://download.openmmlab.com/mmcv/dist/index.html` for installing MMCV (#3840) +- Fix nonzero in NMS for PyTorch 1.6.0 (#3867) +- Fix the API change bug of PAA (#3883) +- Fix typo in bbox_flip (#3886) +- Fix cv2 import error of ligGL.so.1 in Dockerfile (#3891) + +#### Improvements + +- Change to use `mmcv.utils.collect_env` for collecting environment information to avoid duplicate codes (#3779) +- Update checkpoint file names to v2.0 models in documentation (#3795) +- Update tutorials for changing runtime settings (#3778), modifying loss (#3777) +- Improve the function of `simple_test_bboxes` in SABL (#3853) +- Convert mask to bool before using it as img's index for robustness and speedup (#3870) +- Improve documentation of modules and dataset customization (#3821) + +### v2.4.0 (5/9/2020) + +__Highlights__ + +- Fix lots of issues/bugs and reorganize the trouble shooting page +- Support new methods [SABL](https://arxiv.org/abs/1912.04260), [YOLOv3](https://arxiv.org/abs/1804.02767), and [PAA Assign](https://arxiv.org/abs/2007.08103) +- Support Batch Inference +- Start to publish `mmdet` package to PyPI since v2.3.0 +- Switch model zoo to download.openmmlab.com + +__Backwards Incompatible Changes__ + +- Support Batch Inference (#3564, #3686, #3705): Since v2.4.0, MMDetection could inference model with multiple images in a single GPU. + This change influences all the test APIs in MMDetection and downstream codebases. To help the users migrate their code, we use `replace_ImageToTensor` (#3686) to convert legacy test data pipelines during dataset initialization. +- Support RandomFlip with horizontal/vertical/diagonal direction (#3608): Since v2.4.0, MMDetection supports horizontal/vertical/diagonal flip in the data augmentation. This influences bounding box, mask, and image transformations in data augmentation process and the process that will map those data back to the original format. +- Migrate to use `mmlvis` and `mmpycocotools` for COCO and LVIS dataset (#3727). The APIs are fully compatible with the original `lvis` and `pycocotools`. Users need to uninstall the existing pycocotools and lvis packages in their environment first and install `mmlvis` & `mmpycocotools`. + +__Bug Fixes__ + +- Fix default mean/std for onnx (#3491) +- Fix coco evaluation and add metric items (#3497) +- Fix typo for install.md (#3516) +- Fix atss when sampler per gpu is 1 (#3528) +- Fix import of fuse_conv_bn (#3529) +- Fix bug of gaussian_target, update unittest of heatmap (#3543) +- Fixed VOC2012 evaluate (#3553) +- Fix scale factor bug of rescale (#3566) +- Fix with_xxx_attributes in base detector (#3567) +- Fix boxes scaling when number is 0 (#3575) +- Fix rfp check when neck config is a list (#3591) +- Fix import of fuse conv bn in benchmark.py (#3606) +- Fix webcam demo (#3634) +- Fix typo and itemize issues in tutorial (#3658) +- Fix error in distributed training when some levels of FPN are not assigned with bounding boxes (#3670) +- Fix the width and height orders of stride in valid flag generation (#3685) +- Fix weight initialization bug in Res2Net DCN (#3714) +- Fix bug in OHEMSampler (#3677) + +__New Features__ + +- Support Cutout augmentation (#3521) +- Support evaluation on multiple datasets through ConcatDataset (#3522) +- Support [PAA assign](https://arxiv.org/abs/2007.08103) #(3547) +- Support eval metric with pickle results (#3607) +- Support [YOLOv3](https://arxiv.org/abs/1804.02767) (#3083) +- Support [SABL](https://arxiv.org/abs/1912.04260) (#3603) +- Support to publish to Pypi in github-action (#3510) +- Support custom imports (#3641) + +__Improvements__ + +- Refactor common issues in documentation (#3530) +- Add pytorch 1.6 to CI config (#3532) +- Add config to runner meta (#3534) +- Add eval-option flag for testing (#3537) +- Add init_eval to evaluation hook (#3550) +- Add include_bkg in ClassBalancedDataset (#3577) +- Using config's loading in inference_detector (#3611) +- Add ATSS ResNet-101 models in model zoo (#3639) +- Update urls to download.openmmlab.com (#3665) +- Support non-mask training for CocoDataset (#3711) + +### v2.3.0 (5/8/2020) + +__Highlights__ + +- The CUDA/C++ operators have been moved to `mmcv.ops`. For backward compatibility `mmdet.ops` is kept as warppers of `mmcv.ops`. +- Support new methods [CornerNet](https://arxiv.org/abs/1808.01244), [DIOU](https://arxiv.org/abs/1911.08287)/[CIOU](https://arxiv.org/abs/2005.03572) loss, and new dataset: [LVIS V1](https://arxiv.org/abs/1908.03195) +- Provide more detailed colab training tutorials and more complete documentation. +- Support to convert RetinaNet from Pytorch to ONNX. + +__Bug Fixes__ + +- Fix the model initialization bug of DetectoRS (#3187) +- Fix the bug of module names in NASFCOSHead (#3205) +- Fix the filename bug in publish_model.py (#3237) +- Fix the dimensionality bug when `inside_flags.any()` is `False` in dense heads (#3242) +- Fix the bug of forgetting to pass flip directions in `MultiScaleFlipAug` (#3262) +- Fixed the bug caused by default value of `stem_channels` (#3333) +- Fix the bug of model checkpoint loading for CPU inference (#3318, #3316) +- Fix topk bug when box number is smaller than the expected topk number in ATSSAssigner (#3361) +- Fix the gt priority bug in center_region_assigner.py (#3208) +- Fix NaN issue of iou calculation in iou_loss.py (#3394) +- Fix the bug that `iou_thrs` is not actually used during evaluation in coco.py (#3407) +- Fix test-time augmentation of RepPoints (#3435) +- Fix runtimeError caused by incontiguous tensor in Res2Net+DCN (#3412) + +__New Features__ + +- Support [CornerNet](https://arxiv.org/abs/1808.01244) (#3036) +- Support [DIOU](https://arxiv.org/abs/1911.08287)/[CIOU](https://arxiv.org/abs/2005.03572) loss (#3151) +- Support [LVIS V1](https://arxiv.org/abs/1908.03195) dataset (#) +- Support customized hooks in training (#3395) +- Support fp16 training of generalized focal loss (#3410) +- Support to convert RetinaNet from Pytorch to ONNX (#3075) + +__Improvements__ + +- Support to process ignore boxes in ATSS assigner (#3082) +- Allow to crop images without ground truth in `RandomCrop` (#3153) +- Enable the the `Accuracy` module to set threshold (#3155) +- Refactoring unit tests (#3206) +- Unify the training settings of `to_float32` and `norm_cfg` in RegNets configs (#3210) +- Add colab training tutorials for beginners (#3213, #3273) +- Move CUDA/C++ operators into `mmcv.ops` and keep `mmdet.ops` as warppers for backward compatibility (#3232)(#3457) +- Update installation scripts in documentation (#3290) and dockerfile (#3320) +- Support to set image resize backend (#3392) +- Remove git hash in version file (#3466) +- Check mmcv version to force version compatibility (#3460) + +### v2.2.0 (1/7/2020) + +__Highlights__ + +- Support new methods: [DetectoRS](https://arxiv.org/abs/2006.02334), [PointRend](https://arxiv.org/abs/1912.08193), [Generalized Focal Loss](https://arxiv.org/abs/2006.04388), [Dynamic R-CNN](https://arxiv.org/abs/2004.06002) + +__Bug Fixes__ + +- Fix FreeAnchor when no gt in image (#3176) +- Clean up deprecated usage of `register_module()` (#3092, #3161) +- Fix pretrain bug in NAS FCOS (#3145) +- Fix `num_classes` in SSD (#3142) +- Fix FCOS warmup (#3119) +- Fix `rstrip` in `tools/publish_model.py` +- Fix `flip_ratio` default value in RandomFLip pipeline (#3106) +- Fix cityscapes eval with ms_rcnn (#3112) +- Fix RPN softmax (#3056) +- Fix filename of LVIS@v0.5 (#2998) +- Fix nan loss by filtering out-of-frame gt_bboxes in COCO (#2999) +- Fix bug in FSAF (#3018) +- Add FocalLoss `num_classes` check (#2964) +- Fix PISA Loss when there are no gts (#2992) +- Avoid nan in `iou_calculator` (#2975) +- Prevent possible bugs in loading and transforms caused by shallow copy (#2967) + +__New Features__ + +- Add DetectoRS (#3064) +- Support Generalize Focal Loss (#3097) +- Support PointRend (#2752) +- Support Dynamic R-CNN (#3040) +- Add DeepFashion dataset (#2968) +- Implement FCOS training tricks (#2935) +- Use BaseDenseHead as base class for anchor-base heads (#2963) +- Add `with_cp` for BasicBlock (#2891) +- Add `stem_channels` argument for ResNet (#2954) + +__Improvements__ + +- Add anchor free base head (#2867) +- Migrate to github action (#3137) +- Add docstring for datasets, pipelines, core modules and methods (#3130, #3125, #3120) +- Add VOC benchmark (#3060) +- Add `concat` mode in GRoI (#3098) +- Remove cmd arg `autorescale-lr` (#3080) +- Use `len(data['img_metas'])` to indicate `num_samples` (#3073, #3053) +- Switch to EpochBasedRunner (#2976) + +### v2.1.0 (8/6/2020) + +__Highlights__ + +- Support new backbones: [RegNetX](https://arxiv.org/abs/2003.13678), [Res2Net](https://arxiv.org/abs/1904.01169) +- Support new methods: [NASFCOS](https://arxiv.org/abs/1906.04423), [PISA](https://arxiv.org/abs/1904.04821), [GRoIE](https://arxiv.org/abs/2004.13665) +- Support new dataset: [LVIS](https://arxiv.org/abs/1908.03195) + +__Bug Fixes__ + +- Change the CLI argument `--validate` to `--no-validate` to enable validation after training epochs by default. (#2651) +- Add missing cython to docker file (#2713) +- Fix bug in nms cpu implementation (#2754) +- Fix bug when showing mask results (#2763) +- Fix gcc requirement (#2806) +- Fix bug in async test (#2820) +- Fix mask encoding-decoding bugs in test API (#2824) +- Fix bug in test time augmentation (#2858, #2921, #2944) +- Fix a typo in comment of apis/train (#2877) +- Fix the bug of returning None when no gt bboxes are in the original image in `RandomCrop`. Fix the bug that misses to handle `gt_bboxes_ignore`, `gt_label_ignore`, and `gt_masks_ignore` in `RandomCrop`, `MinIoURandomCrop` and `Expand` modules. (#2810) +- Fix bug of `base_channels` of regnet (#2917) +- Fix the bug of logger when loading pre-trained weights in base detector (#2936) + +__New Features__ + +- Add IoU models (#2666) +- Add colab demo for inference +- Support class agnostic nms (#2553) +- Add benchmark gathering scripts for development only (#2676) +- Add mmdet-based project links (#2736, #2767, #2895) +- Add config dump in training (#2779) +- Add ClassBalancedDataset (#2721) +- Add res2net backbone (#2237) +- Support RegNetX models (#2710) +- Use `mmcv.FileClient` to support different storage backends (#2712) +- Add ClassBalancedDataset (#2721) +- Code Release: Prime Sample Attention in Object Detection (CVPR 2020) (#2626) +- Implement NASFCOS (#2682) +- Add class weight in CrossEntropyLoss (#2797) +- Support LVIS dataset (#2088) +- Support GRoIE (#2584) + +__Improvements__ + +- Allow different x and y strides in anchor heads. (#2629) +- Make FSAF loss more robust to no gt (#2680) +- Compute pure inference time instead (#2657) and update inference speed (#2730) +- Avoided the possibility that a patch with 0 area is cropped. (#2704) +- Add warnings when deprecated `imgs_per_gpu` is used. (#2700) +- Add a mask rcnn example for config (#2645) +- Update model zoo (#2762, #2866, #2876, #2879, #2831) +- Add `ori_filename` to img_metas and use it in test show-dir (#2612) +- Use `img_fields` to handle multiple images during image transform (#2800) +- Add upsample_cfg support in FPN (#2787) +- Add `['img']` as default `img_fields` for back compatibility (#2809) +- Rename the pretrained model from `open-mmlab://resnet50_caffe` and `open-mmlab://resnet50_caffe_bgr` to `open-mmlab://detectron/resnet50_caffe` and `open-mmlab://detectron2/resnet50_caffe`. (#2832) +- Added sleep(2) in test.py to reduce hanging problem (#2847) +- Support `c10::half` in CARAFE (#2890) +- Improve documentations (#2918, #2714) +- Use optimizer constructor in mmcv and clean the original implementation in `mmdet.core.optimizer` (#2947) + +### v2.0.0 (6/5/2020) + +In this release, we made lots of major refactoring and modifications. + +1. __Faster speed__. We optimize the training and inference speed for common models, achieving up to 30% speedup for training and 25% for inference. Please refer to [model zoo](model_zoo.md#comparison-with-detectron2) for details. + +2. __Higher performance__. We change some default hyperparameters with no additional cost, which leads to a gain of performance for most models. Please refer to [compatibility](compatibility.md#training-hyperparameters) for details. + +3. __More documentation and tutorials__. We add a bunch of documentation and tutorials to help users get started more smoothly. Read it [here](https://mmdetection.readthedocs.io/en/latest/). + +4. __Support PyTorch 1.5__. The support for 1.1 and 1.2 is dropped, and we switch to some new APIs. + +5. __Better configuration system__. Inheritance is supported to reduce the redundancy of configs. + +6. __Better modular design__. Towards the goal of simplicity and flexibility, we simplify some encapsulation while add more other configurable modules like BBoxCoder, IoUCalculator, OptimizerConstructor, RoIHead. Target computation is also included in heads and the call hierarchy is simpler. + +7. Support new methods: [FSAF](https://arxiv.org/abs/1903.00621) and PAFPN (part of [PAFPN](https://arxiv.org/abs/1803.01534)). + +__Breaking Changes__ +Models training with MMDetection 1.x are not fully compatible with 2.0, please refer to the [compatibility doc](compatibility.md) for the details and how to migrate to the new version. + +__Improvements__ + +- Unify cuda and cpp API for custom ops. (#2277) +- New config files with inheritance. (#2216) +- Encapsulate the second stage into RoI heads. (#1999) +- Refactor GCNet/EmpericalAttention into plugins. (#2345) +- Set low quality match as an option in IoU-based bbox assigners. (#2375) +- Change the codebase's coordinate system. (#2380) +- Refactor the category order in heads. 0 means the first positive class instead of background now. (#2374) +- Add bbox sampler and assigner registry. (#2419) +- Speed up the inference of RPN. (#2420) +- Add `train_cfg` and `test_cfg` as class members in all anchor heads. (#2422) +- Merge target computation methods into heads. (#2429) +- Add bbox coder to support different bbox encoding and losses. (#2480) +- Unify the API for regression loss. (#2156) +- Refactor Anchor Generator. (#2474) +- Make `lr` an optional argument for optimizers. (#2509) +- Migrate to modules and methods in MMCV. (#2502, #2511, #2569, #2572) +- Support PyTorch 1.5. (#2524) +- Drop the support for Python 3.5 and use F-string in the codebase. (#2531) + +__Bug Fixes__ + +- Fix the scale factors for resized images without keep the aspect ratio. (#2039) +- Check if max_num > 0 before slicing in NMS. (#2486) +- Fix Deformable RoIPool when there is no instance. (#2490) +- Fix the default value of assigned labels. (#2536) +- Fix the evaluation of Cityscapes. (#2578) + +__New Features__ + +- Add deep_stem and avg_down option to ResNet, i.e., support ResNetV1d. (#2252) +- Add L1 loss. (#2376) +- Support both polygon and bitmap for instance masks. (#2353, #2540) +- Support CPU mode for inference. (#2385) +- Add optimizer constructor for complicated configuration of optimizers. (#2397, #2488) +- Implement PAFPN. (#2392) +- Support empty tensor input for some modules. (#2280) +- Support for custom dataset classes without overriding it. (#2408, #2443) +- Support to train subsets of coco dataset. (#2340) +- Add iou_calculator to potentially support more IoU calculation methods. (2405) +- Support class wise mean AP (was removed in the last version). (#2459) +- Add option to save the testing result images. (#2414) +- Support MomentumUpdaterHook. (#2571) +- Add a demo to inference a single image. (#2605) + +### v1.1.0 (24/2/2020) + +__Highlights__ + +- Dataset evaluation is rewritten with a unified api, which is used by both evaluation hooks and test scripts. +- Support new methods: [CARAFE](https://arxiv.org/abs/1905.02188). + +__Breaking Changes__ + +- The new MMDDP inherits from the official DDP, thus the `__init__` api is changed to be the same as official DDP. +- The `mask_head` field in HTC config files is modified. +- The evaluation and testing script is updated. +- In all transforms, instance masks are stored as a numpy array shaped (n, h, w) instead of a list of (h, w) arrays, where n is the number of instances. + +__Bug Fixes__ + +- Fix IOU assigners when ignore_iof_thr > 0 and there is no pred boxes. (#2135) +- Fix mAP evaluation when there are no ignored boxes. (#2116) +- Fix the empty RoI input for Deformable RoI Pooling. (#2099) +- Fix the dataset settings for multiple workflows. (#2103) +- Fix the warning related to `torch.uint8` in PyTorch 1.4. (#2105) +- Fix the inference demo on devices other than gpu:0. (#2098) +- Fix Dockerfile. (#2097) +- Fix the bug that `pad_val` is unused in Pad transform. (#2093) +- Fix the albumentation transform when there is no ground truth bbox. (#2032) + +__Improvements__ + +- Use torch instead of numpy for random sampling. (#2094) +- Migrate to the new MMDDP implementation in MMCV v0.3. (#2090) +- Add meta information in logs. (#2086) +- Rewrite Soft NMS with pytorch extension and remove cython as a dependency. (#2056) +- Rewrite dataset evaluation. (#2042, #2087, #2114, #2128) +- Use numpy array for masks in transforms. (#2030) + +__New Features__ + +- Implement "CARAFE: Content-Aware ReAssembly of FEatures". (#1583) +- Add `worker_init_fn()` in data_loader when seed is set. (#2066, #2111) +- Add logging utils. (#2035) + +### v1.0.0 (30/1/2020) + +This release mainly improves the code quality and add more docstrings. + +__Highlights__ + +- Documentation is online now: . +- Support new models: [ATSS](https://arxiv.org/abs/1912.02424). +- DCN is now available with the api `build_conv_layer` and `ConvModule` like the normal conv layer. +- A tool to collect environment information is available for trouble shooting. + +__Bug Fixes__ + +- Fix the incompatibility of the latest numpy and pycocotools. (#2024) +- Fix the case when distributed package is unavailable, e.g., on Windows. (#1985) +- Fix the dimension issue for `refine_bboxes()`. (#1962) +- Fix the typo when `seg_prefix` is a list. (#1906) +- Add segmentation map cropping to RandomCrop. (#1880) +- Fix the return value of `ga_shape_target_single()`. (#1853) +- Fix the loaded shape of empty proposals. (#1819) +- Fix the mask data type when using albumentation. (#1818) + +__Improvements__ + +- Enhance AssignResult and SamplingResult. (#1995) +- Add ability to overwrite existing module in Registry. (#1982) +- Reorganize requirements and make albumentations and imagecorruptions optional. (#1969) +- Check NaN in `SSDHead`. (#1935) +- Encapsulate the DCN in ResNe(X)t into a ConvModule & Conv_layers. (#1894) +- Refactoring for mAP evaluation and support multiprocessing and logging. (#1889) +- Init the root logger before constructing Runner to log more information. (#1865) +- Split `SegResizeFlipPadRescale` into different existing transforms. (#1852) +- Move `init_dist()` to MMCV. (#1851) +- Documentation and docstring improvements. (#1971, #1938, #1869, #1838) +- Fix the color of the same class for mask visualization. (#1834) +- Remove the option `keep_all_stages` in HTC and Cascade R-CNN. (#1806) + +__New Features__ + +- Add two test-time options `crop_mask` and `rle_mask_encode` for mask heads. (#2013) +- Support loading grayscale images as single channel. (#1975) +- Implement "Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection". (#1872) +- Add sphinx generated docs. (#1859, #1864) +- Add GN support for flops computation. (#1850) +- Collect env info for trouble shooting. (#1812) + +### v1.0rc1 (13/12/2019) + +The RC1 release mainly focuses on improving the user experience, and fixing bugs. + +__Highlights__ + +- Support new models: [FoveaBox](https://arxiv.org/abs/1904.03797), [RepPoints](https://arxiv.org/abs/1904.11490) and [FreeAnchor](https://arxiv.org/abs/1909.02466). +- Add a Dockerfile. +- Add a jupyter notebook demo and a webcam demo. +- Setup the code style and CI. +- Add lots of docstrings and unit tests. +- Fix lots of bugs. + +__Breaking Changes__ + +- There was a bug for computing COCO-style mAP w.r.t different scales (AP_s, AP_m, AP_l), introduced by #621. (#1679) + +__Bug Fixes__ + +- Fix a sampling interval bug in Libra R-CNN. (#1800) +- Fix the learning rate in SSD300 WIDER FACE. (#1781) +- Fix the scaling issue when `keep_ratio=False`. (#1730) +- Fix typos. (#1721, #1492, #1242, #1108, #1107) +- Fix the shuffle argument in `build_dataloader`. (#1693) +- Clip the proposal when computing mask targets. (#1688) +- Fix the "index out of range" bug for samplers in some corner cases. (#1610, #1404) +- Fix the NMS issue on devices other than GPU:0. (#1603) +- Fix SSD Head and GHM Loss on CPU. (#1578) +- Fix the OOM error when there are too many gt bboxes. (#1575) +- Fix the wrong keyword argument `nms_cfg` in HTC. (#1573) +- Process masks and semantic segmentation in Expand and MinIoUCrop transforms. (#1550, #1361) +- Fix a scale bug in the Non Local op. (#1528) +- Fix a bug in transforms when `gt_bboxes_ignore` is None. (#1498) +- Fix a bug when `img_prefix` is None. (#1497) +- Pass the device argument to `grid_anchors` and `valid_flags`. (#1478) +- Fix the data pipeline for test_robustness. (#1476) +- Fix the argument type of deformable pooling. (#1390) +- Fix the coco_eval when there are only two classes. (#1376) +- Fix a bug in Modulated DeformableConv when deformable_group>1. (#1359) +- Fix the mask cropping in RandomCrop. (#1333) +- Fix zero outputs in DeformConv when not running on cuda:0. (#1326) +- Fix the type issue in Expand. (#1288) +- Fix the inference API. (#1255) +- Fix the inplace operation in Expand. (#1249) +- Fix the from-scratch training config. (#1196) +- Fix inplace add in RoIExtractor which cause an error in PyTorch 1.2. (#1160) +- Fix FCOS when input images has no positive sample. (#1136) +- Fix recursive imports. (#1099) + +__Improvements__ + +- Print the config file and mmdet version in the log. (#1721) +- Lint the code before compiling in travis CI. (#1715) +- Add a probability argument for the `Expand` transform. (#1651) +- Update the PyTorch and CUDA version in the docker file. (#1615) +- Raise a warning when specifying `--validate` in non-distributed training. (#1624, #1651) +- Beautify the mAP printing. (#1614) +- Add pre-commit hook. (#1536) +- Add the argument `in_channels` to backbones. (#1475) +- Add lots of docstrings and unit tests, thanks to [@Erotemic](https://github.com/Erotemic). (#1603, #1517, #1506, #1505, #1491, #1479, #1477, #1475, #1474) +- Add support for multi-node distributed test when there is no shared storage. (#1399) +- Optimize Dockerfile to reduce the image size. (#1306) +- Update new results of HRNet. (#1284, #1182) +- Add an argument `no_norm_on_lateral` in FPN. (#1240) +- Test the compiling in CI. (#1235) +- Move docs to a separate folder. (#1233) +- Add a jupyter notebook demo. (#1158) +- Support different type of dataset for training. (#1133) +- Use int64_t instead of long in cuda kernels. (#1131) +- Support unsquare RoIs for bbox and mask heads. (#1128) +- Manually add type promotion to make compatible to PyTorch 1.2. (#1114) +- Allowing validation dataset for computing validation loss. (#1093) +- Use `.scalar_type()` instead of `.type()` to suppress some warnings. (#1070) + +__New Features__ + +- Add an option `--with_ap` to compute the AP for each class. (#1549) +- Implement "FreeAnchor: Learning to Match Anchors for Visual Object Detection". (#1391) +- Support [Albumentations](https://github.com/albumentations-team/albumentations) for augmentations in the data pipeline. (#1354) +- Implement "FoveaBox: Beyond Anchor-based Object Detector". (#1339) +- Support horizontal and vertical flipping. (#1273, #1115) +- Implement "RepPoints: Point Set Representation for Object Detection". (#1265) +- Add test-time augmentation to HTC and Cascade R-CNN. (#1251) +- Add a COCO result analysis tool. (#1228) +- Add Dockerfile. (#1168) +- Add a webcam demo. (#1155, #1150) +- Add FLOPs counter. (#1127) +- Allow arbitrary layer order for ConvModule. (#1078) + +### v1.0rc0 (27/07/2019) + +- Implement lots of new methods and components (Mixed Precision Training, HTC, Libra R-CNN, Guided Anchoring, Empirical Attention, Mask Scoring R-CNN, Grid R-CNN (Plus), GHM, GCNet, FCOS, HRNet, Weight Standardization, etc.). Thank all collaborators! +- Support two additional datasets: WIDER FACE and Cityscapes. +- Refactoring for loss APIs and make it more flexible to adopt different losses and related hyper-parameters. +- Speed up multi-gpu testing. +- Integrate all compiling and installing in a single script. + +### v0.6.0 (14/04/2019) + +- Up to 30% speedup compared to the model zoo. +- Support both PyTorch stable and nightly version. +- Replace NMS and SigmoidFocalLoss with Pytorch CUDA extensions. + +### v0.6rc0(06/02/2019) + +- Migrate to PyTorch 1.0. + +### v0.5.7 (06/02/2019) + +- Add support for Deformable ConvNet v2. (Many thanks to the authors and [@chengdazhi](https://github.com/chengdazhi)) +- This is the last release based on PyTorch 0.4.1. + +### v0.5.6 (17/01/2019) + +- Add support for Group Normalization. +- Unify RPNHead and single stage heads (RetinaHead, SSDHead) with AnchorHead. + +### v0.5.5 (22/12/2018) + +- Add SSD for COCO and PASCAL VOC. +- Add ResNeXt backbones and detection models. +- Refactoring for Samplers/Assigners and add OHEM. +- Add VOC dataset and evaluation scripts. + +### v0.5.4 (27/11/2018) + +- Add SingleStageDetector and RetinaNet. + +### v0.5.3 (26/11/2018) + +- Add Cascade R-CNN and Cascade Mask R-CNN. +- Add support for Soft-NMS in config files. + +### v0.5.2 (21/10/2018) + +- Add support for custom datasets. +- Add a script to convert PASCAL VOC annotations to the expected format. + +### v0.5.1 (20/10/2018) + +- Add BBoxAssigner and BBoxSampler, the `train_cfg` field in config files are restructured. +- `ConvFCRoIHead` / `SharedFCRoIHead` are renamed to `ConvFCBBoxHead` / `SharedFCBBoxHead` for consistency. diff --git a/mmdet_code/SR-TOD/docs/en/notes/compatibility.md b/mmdet_code/SR-TOD/docs/en/notes/compatibility.md new file mode 100644 index 0000000000000000000000000000000000000000..26325e249dc6f867925c10390b0c52cc6c52e6e0 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/notes/compatibility.md @@ -0,0 +1,178 @@ +# Compatibility of MMDetection 2.x + +## MMDetection 2.25.0 + +In order to support Mask2Former for instance segmentation, the original config files of Mask2Former for panpotic segmentation need to be renamed [PR #7571](https://github.com/open-mmlab/mmdetection/pull/7571). + + + + + + + + + + + +
before v2.25.0after v2.25.0
+ +``` +'mask2former_xxx_coco.py' represents config files for **panoptic segmentation**. +``` + + + +``` +'mask2former_xxx_coco.py' represents config files for **instance segmentation**. +'mask2former_xxx_coco-panoptic.py' represents config files for **panoptic segmentation**. +``` + +
+ +## MMDetection 2.21.0 + +In order to support CPU training, the logic of scatter in batch collating has been changed. We recommend to use +MMCV v1.4.4 or higher. For more details, please refer to [MMCV PR #1621](https://github.com/open-mmlab/mmcv/pull/1621). + +## MMDetection 2.18.1 + +### MMCV compatibility + +In order to fix the wrong weight reference bug in BaseTransformerLayer, the logic in batch first mode of MultiheadAttention has been changed. +We recommend to use MMCV v1.3.17 or higher. For more details, please refer to [MMCV PR #1418](https://github.com/open-mmlab/mmcv/pull/1418). + +## MMDetection 2.18.0 + +### DIIHead compatibility + +In order to support QueryInst, attn_feats is added into the returned tuple of DIIHead. + +## MMDetection 2.14.0 + +### MMCV Version + +In order to fix the problem that the priority of EvalHook is too low, all hook priorities have been re-adjusted in 1.3.8, so MMDetection 2.14.0 needs to rely on the latest MMCV 1.3.8 version. For related information, please refer to [#1120](https://github.com/open-mmlab/mmcv/pull/1120), for related issues, please refer to [#5343](https://github.com/open-mmlab/mmdetection/issues/5343). + +### SSD compatibility + +In v2.14.0, to make SSD more flexible to use, [PR5291](https://github.com/open-mmlab/mmdetection/pull/5291) refactored its backbone, neck and head. The users can use the script `tools/model_converters/upgrade_ssd_version.py` to convert their models. + +```bash +python tools/model_converters/upgrade_ssd_version.py ${OLD_MODEL_PATH} ${NEW_MODEL_PATH} +``` + +- OLD_MODEL_PATH: the path to load the old version SSD model. +- NEW_MODEL_PATH: the path to save the converted model weights. + +## MMDetection 2.12.0 + +MMDetection is going through big refactoring for more general and convenient usages during the releases from v2.12.0 to v2.18.0 (maybe longer). +In v2.12.0 MMDetection inevitably brings some BC-breakings, including the MMCV dependency, model initialization, model registry, and mask AP evaluation. + +### MMCV Version + +MMDetection v2.12.0 relies on the newest features in MMCV 1.3.3, including `BaseModule` for unified parameter initialization, model registry, and the CUDA operator `MultiScaleDeformableAttn` for [Deformable DETR](https://arxiv.org/abs/2010.04159). Note that MMCV 1.3.2 already contains all the features used by MMDet but has known issues. Therefore, we recommend users to skip MMCV v1.3.2 and use v1.3.2, though v1.3.2 might work for most of the cases. + +### Unified model initialization + +To unify the parameter initialization in OpenMMLab projects, MMCV supports `BaseModule` that accepts `init_cfg` to allow the modules' parameters initialized in a flexible and unified manner. Now the users need to explicitly call `model.init_weights()` in the training script to initialize the model (as in [here](https://github.com/open-mmlab/mmdetection/blob/main/tools/train.py#L162), previously this was handled by the detector. **The downstream projects must update their model initialization accordingly to use MMDetection v2.12.0**. Please refer to PR #4750 for details. + +### Unified model registry + +To easily use backbones implemented in other OpenMMLab projects, MMDetection v2.12.0 inherits the model registry created in MMCV (#760). In this way, as long as the backbone is supported in an OpenMMLab project and that project also uses the registry in MMCV, users can use that backbone in MMDetection by simply modifying the config without copying the code of that backbone into MMDetection. Please refer to PR #5059 for more details. + +### Mask AP evaluation + +Before [PR 4898](https://github.com/open-mmlab/mmdetection/pull/4898) and V2.12.0, the mask AP of small, medium, and large instances is calculated based on the bounding box area rather than the real mask area. This leads to higher `APs` and `APm` but lower `APl` but will not affect the overall mask AP. [PR 4898](https://github.com/open-mmlab/mmdetection/pull/4898) change it to use mask areas by deleting `bbox` in mask AP calculation. +The new calculation does not affect the overall mask AP evaluation and is consistent with [Detectron2](https://github.com/facebookresearch/detectron2/). + +## Compatibility with MMDetection 1.x + +MMDetection 2.0 goes through a big refactoring and addresses many legacy issues. It is not compatible with the 1.x version, i.e., running inference with the same model weights in these two versions will produce different results. Thus, MMDetection 2.0 re-benchmarks all the models and provides their links and logs in the model zoo. + +The major differences are in four folds: coordinate system, codebase conventions, training hyperparameters, and modular design. + +### Coordinate System + +The new coordinate system is consistent with [Detectron2](https://github.com/facebookresearch/detectron2/) and treats the center of the most left-top pixel as (0, 0) rather than the left-top corner of that pixel. +Accordingly, the system interprets the coordinates in COCO bounding box and segmentation annotations as coordinates in range `[0, width]` or `[0, height]`. +This modification affects all the computation related to the bbox and pixel selection, +which is more natural and accurate. + +- The height and width of a box with corners (x1, y1) and (x2, y2) in the new coordinate system is computed as `width = x2 - x1` and `height = y2 - y1`. + In MMDetection 1.x and previous version, a "+ 1" was added both height and width. + This modification are in three folds: + + 1. Box transformation and encoding/decoding in regression. + 2. IoU calculation. This affects the matching process between ground truth and bounding box and the NMS process. The effect to compatibility is very negligible, though. + 3. The corners of bounding box is in float type and no longer quantized. This should provide more accurate bounding box results. This also makes the bounding box and RoIs not required to have minimum size of 1, whose effect is small, though. + +- The anchors are center-aligned to feature grid points and in float type. + In MMDetection 1.x and previous version, the anchors are in `int` type and not center-aligned. + This affects the anchor generation in RPN and all the anchor-based methods. + +- ROIAlign is better aligned with the image coordinate system. The new implementation is adopted from [Detectron2](https://github.com/facebookresearch/detectron2/tree/master/detectron2/layers/csrc/ROIAlign). + The RoIs are shifted by half a pixel by default when they are used to cropping RoI features, compared to MMDetection 1.x. + The old behavior is still available by setting `aligned=False` instead of `aligned=True`. + +- Mask cropping and pasting are more accurate. + + 1. We use the new RoIAlign to crop mask targets. In MMDetection 1.x, the bounding box is quantized before it is used to crop mask target, and the crop process is implemented by numpy. In new implementation, the bounding box for crop is not quantized and sent to RoIAlign. This implementation accelerates the training speed by a large margin (~0.1s per iter, ~2 hour when training Mask R50 for 1x schedule) and should be more accurate. + + 2. In MMDetection 2.0, the "`paste_mask()`" function is different and should be more accurate than those in previous versions. This change follows the modification in [Detectron2](https://github.com/facebookresearch/detectron2/blob/master/detectron2/structures/masks.py) and can improve mask AP on COCO by ~0.5% absolute. + +### Codebase Conventions + +- MMDetection 2.0 changes the order of class labels to reduce unused parameters in regression and mask branch more naturally (without +1 and -1). + This effect all the classification layers of the model to have a different ordering of class labels. The final layers of regression branch and mask head no longer keep K+1 channels for K categories, and their class orders are consistent with the classification branch. + + - In MMDetection 2.0, label "K" means background, and labels \[0, K-1\] correspond to the K = num_categories object categories. + + - In MMDetection 1.x and previous version, label "0" means background, and labels \[1, K\] correspond to the K categories. + + - **Note**: The class order of softmax RPN is still the same as that in 1.x in versions\<=2.4.0 while sigmoid RPN is not affected. The class orders in all heads are unified since MMDetection v2.5.0. + +- Low quality matching in R-CNN is not used. In MMDetection 1.x and previous versions, the `max_iou_assigner` will match low quality boxes for each ground truth box in both RPN and R-CNN training. We observe this sometimes does not assign the most perfect GT box to some bounding boxes, + thus MMDetection 2.0 do not allow low quality matching by default in R-CNN training in the new system. This sometimes may slightly improve the box AP (~0.1% absolute). + +- Separate scale factors for width and height. In MMDetection 1.x and previous versions, the scale factor is a single float in mode `keep_ratio=True`. This is slightly inaccurate because the scale factors for width and height have slight difference. MMDetection 2.0 adopts separate scale factors for width and height, the improvement on AP ~0.1% absolute. + +- Configs name conventions are changed. MMDetection V2.0 adopts the new name convention to maintain the gradually growing model zoo as the following: + + ```shell + [model]_(model setting)_[backbone]_[neck]_(norm setting)_(misc)_(gpu x batch)_[schedule]_[dataset].py, + ``` + + where the (`misc`) includes DCN and GCBlock, etc. More details are illustrated in the [documentation for config](tutorials/config) + +- MMDetection V2.0 uses new ResNet Caffe backbones to reduce warnings when loading pre-trained models. Most of the new backbones' weights are the same as the former ones but do not have `conv.bias`, except that they use a different `img_norm_cfg`. Thus, the new backbone will not cause warning of unexpected keys. + +### Training Hyperparameters + +The change in training hyperparameters does not affect +model-level compatibility but slightly improves the performance. The major ones are: + +- The number of proposals after nms is changed from 2000 to 1000 by setting `nms_post=1000` and `max_num=1000`. + This slightly improves both mask AP and bbox AP by ~0.2% absolute. + +- The default box regression losses for Mask R-CNN, Faster R-CNN and RetinaNet are changed from smooth L1 Loss to L1 loss. This leads to an overall improvement in box AP (~0.6% absolute). However, using L1-loss for other methods such as Cascade R-CNN and HTC does not improve the performance, so we keep the original settings for these methods. + +- The sample num of RoIAlign layer is set to be 0 for simplicity. This leads to slightly improvement on mask AP (~0.2% absolute). + +- The default setting does not use gradient clipping anymore during training for faster training speed. This does not degrade performance of the most of models. For some models such as RepPoints we keep using gradient clipping to stabilize the training process and to obtain better performance. + +- The default warmup ratio is changed from 1/3 to 0.001 for a more smooth warming up process since the gradient clipping is usually not used. The effect is found negligible during our re-benchmarking, though. + +### Upgrade Models from 1.x to 2.0 + +To convert the models trained by MMDetection V1.x to MMDetection V2.0, the users can use the script `tools/model_converters/upgrade_model_version.py` to convert +their models. The converted models can be run in MMDetection V2.0 with slightly dropped performance (less than 1% AP absolute). +Details can be found in `configs/legacy`. + +## pycocotools compatibility + +`mmpycocotools` is the OpenMMlab's fork of official `pycocotools`, which works for both MMDetection and Detectron2. +Before [PR 4939](https://github.com/open-mmlab/mmdetection/pull/4939), since `pycocotools` and `mmpycocotool` have the same package name, if users already installed `pycocotools` (installed Detectron2 first under the same environment), then the setup of MMDetection will skip installing `mmpycocotool`. Thus MMDetection fails due to the missing `mmpycocotools`. +If MMDetection is installed before Detectron2, they could work under the same environment. +[PR 4939](https://github.com/open-mmlab/mmdetection/pull/4939) deprecates mmpycocotools in favor of official pycocotools. +Users may install MMDetection and Detectron2 under the same environment after [PR 4939](https://github.com/open-mmlab/mmdetection/pull/4939), no matter what the installation order is. diff --git a/mmdet_code/SR-TOD/docs/en/notes/contribution_guide.md b/mmdet_code/SR-TOD/docs/en/notes/contribution_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d622c0abed31f206faef9be121f57050f2a9447c --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/notes/contribution_guide.md @@ -0,0 +1 @@ +# Contribution diff --git a/mmdet_code/SR-TOD/docs/en/notes/faq.md b/mmdet_code/SR-TOD/docs/en/notes/faq.md new file mode 100644 index 0000000000000000000000000000000000000000..d8205cf555e402e42e993cbf21e55356a7ab3ce6 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/notes/faq.md @@ -0,0 +1,239 @@ +# Frequently Asked Questions + +We list some common troubles faced by many users and their corresponding solutions here. Feel free to enrich the list if you find any frequent issues and have ways to help others to solve them. If the contents here do not cover your issue, please create an issue using the [provided templates](https://github.com/open-mmlab/mmdetection/blob/main/.github/ISSUE_TEMPLATE/error-report.md/) and make sure you fill in all required information in the template. + +## PyTorch 2.0 Support + +The vast majority of algorithms in MMDetection now support PyTorch 2.0 and its `torch.compile` function. Users only need to install MMDetection 3.0.0rc7 or later versions to enjoy this feature. If any unsupported algorithms are found during use, please feel free to give us feedback. We also welcome contributions from the community to benchmark the speed improvement brought by using the `torch.compile` function. + +To enable the `torch.compile` function, simply add `--cfg-options compile=True` after `train.py` or `test.py`. For example, to enable `torch.compile` for RTMDet, you can use the following command: + +```shell +# Single GPU +python tools/train.py configs/rtmdet/rtmdet_s_8xb32-300e_coco.py --cfg-options compile=True + +# Single node multiple GPUs +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True + +# Single node multiple GPUs + AMP +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True --amp +``` + +It is important to note that PyTorch 2.0's support for dynamic shapes is not yet fully developed. In most object detection algorithms, not only are the input shapes dynamic, but the loss calculation and post-processing parts are also dynamic. This can lead to slower training speeds when using the `torch.compile` function. Therefore, if you wish to enable the `torch.compile` function, you should follow these principles: + +1. Input images to the network are fixed shape, not multi-scale +2. set `torch._dynamo.config.cache_size_limit` parameter. TorchDynamo will convert and cache the Python bytecode, and the compiled functions will be stored in the cache. When the next check finds that the function needs to be recompiled, the function will be recompiled and cached. However, if the number of recompilations exceeds the maximum value set (64), the function will no longer be cached or recompiled. As mentioned above, the loss calculation and post-processing parts of the object detection algorithm are also dynamically calculated, and these functions need to be recompiled every time. Therefore, setting the `torch._dynamo.config.cache_size_limit` parameter to a smaller value can effectively reduce the compilation time + +In MMDetection, you can set the `torch._dynamo.config.cache_size_limit` parameter through the environment variable `DYNAMO_CACHE_SIZE_LIMIT`. For example, the command is as follows: + +```shell +# Single GPU +export DYNAMO_CACHE_SIZE_LIMIT = 4 +python tools/train.py configs/rtmdet/rtmdet_s_8xb32-300e_coco.py --cfg-options compile=True + +# Single node multiple GPUs +export DYNAMO_CACHE_SIZE_LIMIT = 4 +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True +``` + +About the common questions about PyTorch 2.0's dynamo, you can refer to [here](https://pytorch.org/docs/stable/dynamo/faq.html) + +## Installation + +Compatibility issue between MMCV and MMDetection; "ConvWS is already registered in conv layer"; "AssertionError: MMCV==xxx is used but incompatible. Please install mmcv>=xxx, \<=xxx." + +Compatible MMDetection, MMEngine, and MMCV versions are shown as below. Please choose the correct version of MMCV to avoid installation issues. + +| MMDetection version | MMCV version | MMEngine version | +| :-----------------: | :---------------------: | :----------------------: | +| main | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | +| 3.1.0 | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | +| 3.0.0 | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | +| 3.0.0rc6 | mmcv>=2.0.0rc4, \<2.1.0 | mmengine>=0.6.0, \<1.0.0 | +| 3.0.0rc5 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | +| 3.0.0rc4 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | +| 3.0.0rc3 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | +| 3.0.0rc2 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | +| 3.0.0rc1 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | +| 3.0.0rc0 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | + +**Note:** + +1. If you want to install mmdet-v2.x, the compatible MMDetection and MMCV versions table can be found at [here](https://mmdetection.readthedocs.io/en/stable/faq.html#installation). Please choose the correct version of MMCV to avoid installation issues. +2. In MMCV-v2.x, `mmcv-full` is rename to `mmcv`, if you want to install `mmcv` without CUDA ops, you can install `mmcv-lite`. + +- "No module named 'mmcv.ops'"; "No module named 'mmcv.\_ext'". + + 1. Uninstall existing `mmcv-lite` in the environment using `pip uninstall mmcv-lite`. + 2. Install `mmcv` following the [installation instruction](https://mmcv.readthedocs.io/en/2.x/get_started/installation.html). + +- "Microsoft Visual C++ 14.0 or graeter is required" during installation on Windows. + + This error happens when building the 'pycocotools.\_mask' extension of pycocotools and the environment lacks corresponding C++ compilation dependencies. You need to download it at Microsoft officials [visual-cpp-build-tools](https://visualstudio.microsoft.com/zh-hans/visual-cpp-build-tools/), select the "Use C ++ Desktop Development" option to install the minimum dependencies, and then reinstall pycocotools. + +- Using Albumentations + + If you would like to use `albumentations`, we suggest using `pip install -r requirements/albu.txt` or + `pip install -U albumentations --no-binary qudida,albumentations`. + If you simply use `pip install albumentations>=0.3.2`, it will install `opencv-python-headless` simultaneously (even though you have already installed `opencv-python`). + Please refer to the [official documentation](https://albumentations.ai/docs/getting_started/installation/#note-on-opencv-dependencies) for details. + +- ModuleNotFoundError is raised when using some algorithms + + Some extra dependencies are required for Instaboost, Panoptic Segmentation, LVIS dataset, etc. Please note the error message and install corresponding packages, e.g., + + ```shell + # for instaboost + pip install instaboostfast + # for panoptic segmentation + pip install git+https://github.com/cocodataset/panopticapi.git + # for LVIS dataset + pip install git+https://github.com/lvis-dataset/lvis-api.git + ``` + +## Coding + +- Do I need to reinstall mmdet after some code modifications + + If you follow the best practice and install mmdet with `pip install -e .`, any local modifications made to the code will take effect without reinstallation. + +- How to develop with multiple MMDetection versions + + You can have multiple folders like mmdet-3.0, mmdet-3.1. + When you run the train or test script, it will adopt the mmdet package in the current folder. + + To use the default MMDetection installed in the environment rather than the one you are working with, you can remove the following line in those scripts: + + ```shell + PYTHONPATH="$(dirname $0)/..":$PYTHONPATH + ``` + +## PyTorch/CUDA Environment + +- "RTX 30 series card fails when building MMCV or MMDet" + + 1. Temporary work-around: do `MMCV_WITH_OPS=1 MMCV_CUDA_ARGS='-gencode=arch=compute_80,code=sm_80' pip install -e .`. + The common issue is `nvcc fatal : Unsupported gpu architecture 'compute_86'`. This means that the compiler should optimize for sm_86, i.e., nvidia 30 series card, but such optimizations have not been supported by CUDA toolkit 11.0. + This work-around modifies the compile flag by adding `MMCV_CUDA_ARGS='-gencode=arch=compute_80,code=sm_80'`, which tells `nvcc` to optimize for **sm_80**, i.e., Nvidia A100. Although A100 is different from the 30 series card, they use similar ampere architecture. This may hurt the performance but it works. + 2. PyTorch developers have updated that the default compiler flags should be fixed by [pytorch/pytorch#47585](https://github.com/pytorch/pytorch/pull/47585). So using PyTorch-nightly may also be able to solve the problem, though we have not tested it yet. + +- "invalid device function" or "no kernel image is available for execution". + + 1. Check if your cuda runtime version (under `/usr/local/`), `nvcc --version` and `conda list cudatoolkit` version match. + 2. Run `python mmdet/utils/collect_env.py` to check whether PyTorch, torchvision, and MMCV are built for the correct GPU architecture. + You may need to set `TORCH_CUDA_ARCH_LIST` to reinstall MMCV. + The GPU arch table could be found [here](https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#gpu-feature-list), + i.e. run `TORCH_CUDA_ARCH_LIST=7.0 pip install mmcv` to build MMCV for Volta GPUs. + The compatibility issue could happen when using old GPUS, e.g., Tesla K80 (3.7) on colab. + 3. Check whether the running environment is the same as that when mmcv/mmdet has compiled. + For example, you may compile mmcv using CUDA 10.0 but run it on CUDA 9.0 environments. + +- "undefined symbol" or "cannot open xxx.so". + + 1. If those symbols are CUDA/C++ symbols (e.g., libcudart.so or GLIBCXX), check whether the CUDA/GCC runtimes are the same as those used for compiling mmcv, + i.e. run `python mmdet/utils/collect_env.py` to see if `"MMCV Compiler"`/`"MMCV CUDA Compiler"` is the same as `"GCC"`/`"CUDA_HOME"`. + 2. If those symbols are PyTorch symbols (e.g., symbols containing caffe, aten, and TH), check whether the PyTorch version is the same as that used for compiling mmcv. + 3. Run `python mmdet/utils/collect_env.py` to check whether PyTorch, torchvision, and MMCV are built by and running on the same environment. + +- setuptools.sandbox.UnpickleableException: DistutilsSetupError("each element of 'ext_modules' option must be an Extension instance or 2-tuple") + + 1. If you are using miniconda rather than anaconda, check whether Cython is installed as indicated in [#3379](https://github.com/open-mmlab/mmdetection/issues/3379). + You need to manually install Cython first and then run command `pip install -r requirements.txt`. + 2. You may also need to check the compatibility between the `setuptools`, `Cython`, and `PyTorch` in your environment. + +- "Segmentation fault". + + 1. Check you GCC version and use GCC 5.4. This usually caused by the incompatibility between PyTorch and the environment (e.g., GCC \< 4.9 for PyTorch). We also recommend the users to avoid using GCC 5.5 because many feedbacks report that GCC 5.5 will cause "segmentation fault" and simply changing it to GCC 5.4 could solve the problem. + + 2. Check whether PyTorch is correctly installed and could use CUDA op, e.g. type the following command in your terminal. + + ```shell + python -c 'import torch; print(torch.cuda.is_available())' + ``` + + And see whether they could correctly output results. + + 3. If Pytorch is correctly installed, check whether MMCV is correctly installed. + + ```shell + python -c 'import mmcv; import mmcv.ops' + ``` + + If MMCV is correctly installed, then there will be no issue of the above two commands. + + 4. If MMCV and Pytorch is correctly installed, you man use `ipdb`, `pdb` to set breakpoints or directly add 'print' in mmdetection code and see which part leads the segmentation fault. + +## Training + +- "Loss goes Nan" + + 1. Check if the dataset annotations are valid: zero-size bounding boxes will cause the regression loss to be Nan due to the commonly used transformation for box regression. Some small size (width or height are smaller than 1) boxes will also cause this problem after data augmentation (e.g., instaboost). So check the data and try to filter out those zero-size boxes and skip some risky augmentations on the small-size boxes when you face the problem. + 2. Reduce the learning rate: the learning rate might be too large due to some reasons, e.g., change of batch size. You can rescale them to the value that could stably train the model. + 3. Extend the warmup iterations: some models are sensitive to the learning rate at the start of the training. You can extend the warmup iterations, e.g., change the `warmup_iters` from 500 to 1000 or 2000. + 4. Add gradient clipping: some models requires gradient clipping to stabilize the training process. The default of `grad_clip` is `None`, you can add gradient clippint to avoid gradients that are too large, i.e., set `optim_wrapper=dict(clip_grad=dict(max_norm=35, norm_type=2))` in your config file. + +- "GPU out of memory" + + 1. There are some scenarios when there are large amount of ground truth boxes, which may cause OOM during target assignment. You can set `gpu_assign_thr=N` in the config of assigner thus the assigner will calculate box overlaps through CPU when there are more than N GT boxes. + + 2. Set `with_cp=True` in the backbone. This uses the sublinear strategy in PyTorch to reduce GPU memory cost in the backbone. + + 3. Try mixed precision training using following the examples in `config/fp16`. The `loss_scale` might need further tuning for different models. + + 4. Try to use `AvoidCUDAOOM` to avoid GPU out of memory. It will first retry after calling `torch.cuda.empty_cache()`. If it still fails, it will then retry by converting the type of inputs to FP16 format. If it still fails, it will try to copy inputs from GPUs to CPUs to continue computing. Try AvoidOOM in you code to make the code continue to run when GPU memory runs out: + + ```python + from mmdet.utils import AvoidCUDAOOM + + output = AvoidCUDAOOM.retry_if_cuda_oom(some_function)(input1, input2) + ``` + + You can also try `AvoidCUDAOOM` as a decorator to make the code continue to run when GPU memory runs out: + + ```python + from mmdet.utils import AvoidCUDAOOM + + @AvoidCUDAOOM.retry_if_cuda_oom + def function(*args, **kwargs): + ... + return xxx + ``` + +- "RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one" + + 1. This error indicates that your module has parameters that were not used in producing loss. This phenomenon may be caused by running different branches in your code in DDP mode. + 2. You can set `find_unused_parameters = True` in the config to solve the above problems, but this will slow down the training speed. + 3. You can set `detect_anomalous_params = True` in the config or `model_wrapper_cfg = dict(type='MMDistributedDataParallel', detect_anomalous_params=True)` (More details please refer to [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/mmengine/model/wrappers/distributed.py#L91)) to get the name of those unused parameters. Note `detect_anomalous_params = True` will slow down the training speed, so it is recommended for debugging only. + +- Save the best model + + It can be turned on by configuring `default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=1, save_best='auto'),`. In the case of the `auto` parameter, the first key in the returned evaluation result will be used as the basis for selecting the best model. You can also directly set the key in the evaluation result to manually set it, for example, `save_best='coco/bbox_mAP'`. + +## Evaluation + +- COCO Dataset, AP or AR = -1 + 1. According to the definition of COCO dataset, the small and medium areas in an image are less than 1024 (32\*32), 9216 (96\*96), respectively. + 2. If the corresponding area has no object, the result of AP and AR will set to -1. + +## Model + +- `style` in ResNet + + The `style` parameter in ResNet allows either `pytorch` or `caffe` style. It indicates the difference in the Bottleneck module. Bottleneck is a stacking structure of `1x1-3x3-1x1` convolutional layers. In the case of `caffe` mode, the convolution layer with `stride=2` is the first `1x1` convolution, while in `pyorch` mode, it is the second `3x3` convolution has `stride=2`. A sample code is as below: + + ```python + if self.style == 'pytorch': + self.conv1_stride = 1 + self.conv2_stride = stride + else: + self.conv1_stride = stride + self.conv2_stride = 1 + ``` + +- ResNeXt parameter description + + ResNeXt comes from the paper [`Aggregated Residual Transformations for Deep Neural Networks`](https://arxiv.org/abs/1611.05431). It introduces group and uses “cardinality” to control the number of groups to achieve a balance between accuracy and complexity. It controls the basic width and grouping parameters of the internal Bottleneck module through two hyperparameters `baseWidth` and `cardinality`. An example configuration name in MMDetection is `mask_rcnn_x101_64x4d_fpn_mstrain-poly_3x_coco.py`, where `mask_rcnn` represents the algorithm using Mask R-CNN, `x101` represents the backbone network using ResNeXt-101, and `64x4d` represents that the bottleneck block has 64 group and each group has basic width of 4. + +- `norm_eval` in backbone + + Since the detection model is usually large and the input image resolution is high, this will result in a small batch of the detection model, which will make the variance of the statistics calculated by BatchNorm during the training process very large and not as stable as the statistics obtained during the pre-training of the backbone network . Therefore, the `norm_eval=True` mode is generally used in training, and the BatchNorm statistics in the pre-trained backbone network are directly used. The few algorithms that use large batches are the `norm_eval=False` mode, such as NASFPN. For the backbone network without ImageNet pre-training and the batch is relatively small, you can consider using `SyncBN`. diff --git a/mmdet_code/SR-TOD/docs/en/notes/projects.md b/mmdet_code/SR-TOD/docs/en/notes/projects.md new file mode 100644 index 0000000000000000000000000000000000000000..3123e2b020e912683190ef44389b2a14d0ee6c4a --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/notes/projects.md @@ -0,0 +1,57 @@ +# Projects based on MMDetection + +There are many projects built upon MMDetection. +We list some of them as examples of how to extend MMDetection for your own projects. +As the page might not be completed, please feel free to create a PR to update this page. + +## Projects as an extension + +Some projects extend the boundary of MMDetection for deployment or other research fields. +They reveal the potential of what MMDetection can do. We list several of them as below. + +- [OTEDetection](https://github.com/opencv/mmdetection): OpenVINO training extensions for object detection. +- [MMDetection3d](https://github.com/open-mmlab/mmdetection3d): OpenMMLab's next-generation platform for general 3D object detection. + +## Projects of papers + +There are also projects released with papers. +Some of the papers are published in top-tier conferences (CVPR, ICCV, and ECCV), the others are also highly influential. +To make this list also a reference for the community to develop and compare new object detection algorithms, we list them following the time order of top-tier conferences. +Methods already supported and maintained by MMDetection are not listed. + +- Involution: Inverting the Inherence of Convolution for Visual Recognition, CVPR21. [\[paper\]](https://arxiv.org/abs/2103.06255)[\[github\]](https://github.com/d-li14/involution) +- Multiple Instance Active Learning for Object Detection, CVPR 2021. [\[paper\]](https://openaccess.thecvf.com/content/CVPR2021/papers/Yuan_Multiple_Instance_Active_Learning_for_Object_Detection_CVPR_2021_paper.pdf)[\[github\]](https://github.com/yuantn/MI-AOD) +- Adaptive Class Suppression Loss for Long-Tail Object Detection, CVPR 2021. [\[paper\]](https://arxiv.org/abs/2104.00885)[\[github\]](https://github.com/CASIA-IVA-Lab/ACSL) +- Generalizable Pedestrian Detection: The Elephant In The Room, CVPR2021. [\[paper\]](https://arxiv.org/abs/2003.08799)[\[github\]](https://github.com/hasanirtiza/Pedestron) +- Group Fisher Pruning for Practical Network Compression, ICML2021. [\[paper\]](https://github.com/jshilong/FisherPruning/blob/main/resources/paper.pdf)[\[github\]](https://github.com/jshilong/FisherPruning) +- Overcoming Classifier Imbalance for Long-tail Object Detection with Balanced Group Softmax, CVPR2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/papers/Li_Overcoming_Classifier_Imbalance_for_Long-Tail_Object_Detection_With_Balanced_Group_CVPR_2020_paper.pdf)[\[github\]](https://github.com/FishYuLi/BalancedGroupSoftmax) +- Coherent Reconstruction of Multiple Humans from a Single Image, CVPR2020. [\[paper\]](https://jiangwenpl.github.io/multiperson/)[\[github\]](https://github.com/JiangWenPL/multiperson) +- Look-into-Object: Self-supervised Structure Modeling for Object Recognition, CVPR 2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/papers/Zhou_Look-Into-Object_Self-Supervised_Structure_Modeling_for_Object_Recognition_CVPR_2020_paper.pdf)[\[github\]](https://github.com/JDAI-CV/LIO) +- Video Panoptic Segmentation, CVPR2020. [\[paper\]](https://arxiv.org/abs/2006.11339)[\[github\]](https://github.com/mcahny/vps) +- D2Det: Towards High Quality Object Detection and Instance Segmentation, CVPR2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/html/Cao_D2Det_Towards_High_Quality_Object_Detection_and_Instance_Segmentation_CVPR_2020_paper.html)[\[github\]](https://github.com/JialeCao001/D2Det) +- CentripetalNet: Pursuing High-quality Keypoint Pairs for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.09119)[\[github\]](https://github.com/KiveeDong/CentripetalNet) +- Learning a Unified Sample Weighting Network for Object Detection, CVPR 2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/html/Cai_Learning_a_Unified_Sample_Weighting_Network_for_Object_Detection_CVPR_2020_paper.html)[\[github\]](https://github.com/caiqi/sample-weighting-network) +- Scale-equalizing Pyramid Convolution for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2005.03101) [\[github\]](https://github.com/jshilong/SEPC) +- Revisiting the Sibling Head in Object Detector, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.07540)[\[github\]](https://github.com/Sense-X/TSD) +- PolarMask: Single Shot Instance Segmentation with Polar Representation, CVPR2020. [\[paper\]](https://arxiv.org/abs/1909.13226)[\[github\]](https://github.com/xieenze/PolarMask) +- Hit-Detector: Hierarchical Trinity Architecture Search for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.11818)[\[github\]](https://github.com/ggjy/HitDet.pytorch) +- ZeroQ: A Novel Zero Shot Quantization Framework, CVPR2020. [\[paper\]](https://arxiv.org/abs/2001.00281)[\[github\]](https://github.com/amirgholami/ZeroQ) +- CBNet: A Novel Composite Backbone Network Architecture for Object Detection, AAAI2020. [\[paper\]](https://aaai.org/Papers/AAAI/2020GB/AAAI-LiuY.1833.pdf)[\[github\]](https://github.com/VDIGPKU/CBNet) +- RDSNet: A New Deep Architecture for Reciprocal Object Detection and Instance Segmentation, AAAI2020. [\[paper\]](https://arxiv.org/abs/1912.05070)[\[github\]](https://github.com/wangsr126/RDSNet) +- Training-Time-Friendly Network for Real-Time Object Detection, AAAI2020. [\[paper\]](https://arxiv.org/abs/1909.00700)[\[github\]](https://github.com/ZJULearning/ttfnet) +- Cascade RPN: Delving into High-Quality Region Proposal Network with Adaptive Convolution, NeurIPS 2019. [\[paper\]](https://arxiv.org/abs/1909.06720)[\[github\]](https://github.com/thangvubk/Cascade-RPN) +- Reasoning R-CNN: Unifying Adaptive Global Reasoning into Large-scale Object Detection, CVPR2019. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2019/papers/Xu_Reasoning-RCNN_Unifying_Adaptive_Global_Reasoning_Into_Large-Scale_Object_Detection_CVPR_2019_paper.pdf)[\[github\]](https://github.com/chanyn/Reasoning-RCNN) +- Learning RoI Transformer for Oriented Object Detection in Aerial Images, CVPR2019. [\[paper\]](https://arxiv.org/abs/1812.00155)[\[github\]](https://github.com/dingjiansw101/AerialDetection) +- SOLO: Segmenting Objects by Locations. [\[paper\]](https://arxiv.org/abs/1912.04488)[\[github\]](https://github.com/WXinlong/SOLO) +- SOLOv2: Dynamic, Faster and Stronger. [\[paper\]](https://arxiv.org/abs/2003.10152)[\[github\]](https://github.com/WXinlong/SOLO) +- Dense Peppoints: Representing Visual Objects with Dense Point Sets. [\[paper\]](https://arxiv.org/abs/1912.11473)[\[github\]](https://github.com/justimyhxu/Dense-RepPoints) +- IterDet: Iterative Scheme for Object Detection in Crowded Environments. [\[paper\]](https://arxiv.org/abs/2005.05708)[\[github\]](https://github.com/saic-vul/iterdet) +- Cross-Iteration Batch Normalization. [\[paper\]](https://arxiv.org/abs/2002.05712)[\[github\]](https://github.com/Howal/Cross-iterationBatchNorm) +- A Ranking-based, Balanced Loss Function Unifying Classification and Localisation in Object Detection, NeurIPS2020 [\[paper\]](https://arxiv.org/abs/2009.13592)[\[github\]](https://github.com/kemaloksuz/aLRPLoss) +- RelationNet++: Bridging Visual Representations for Object Detection via Transformer Decoder, NeurIPS2020 [\[paper\]](https://arxiv.org/abs/2010.15831)[\[github\]](https://github.com/microsoft/RelationNet2) +- Generalized Focal Loss V2: Learning Reliable Localization Quality Estimation for Dense Object Detection, CVPR2021[\[paper\]](https://arxiv.org/abs/2011.12885)[\[github\]](https://github.com/implus/GFocalV2) +- Swin Transformer: Hierarchical Vision Transformer using Shifted Windows, ICCV2021[\[paper\]](https://arxiv.org/abs/2103.14030)[\[github\]](https://github.com/SwinTransformer/) +- Focal Transformer: Focal Self-attention for Local-Global Interactions in Vision Transformers, NeurIPS2021[\[paper\]](https://arxiv.org/abs/2107.00641)[\[github\]](https://github.com/microsoft/Focal-Transformer) +- End-to-End Semi-Supervised Object Detection with Soft Teacher, ICCV2021[\[paper\]](https://arxiv.org/abs/2106.09018)[\[github\]](https://github.com/microsoft/SoftTeacher) +- CBNetV2: A Novel Composite Backbone Network Architecture for Object Detection [\[paper\]](http://arxiv.org/abs/2107.00420)[\[github\]](https://github.com/VDIGPKU/CBNetV2) +- Instances as Queries, ICCV2021 [\[paper\]](https://openaccess.thecvf.com/content/ICCV2021/papers/Fang_Instances_As_Queries_ICCV_2021_paper.pdf)[\[github\]](https://github.com/hustvl/QueryInst) diff --git a/mmdet_code/SR-TOD/docs/en/overview.md b/mmdet_code/SR-TOD/docs/en/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..7c7d96b70872bc5590f6b5c2dbc6ce4fb7afa938 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/overview.md @@ -0,0 +1,54 @@ +# OVERVIEW + +This chapter introduces you to the framework of MMDetection, and provides links to detailed tutorials about MMDetection. + +## What is MMDetection + +![image](https://user-images.githubusercontent.com/12907710/137271636-56ba1cd2-b110-4812-8221-b4c120320aa9.png) + +MMDetection is an object detection toolbox that contains a rich set of object detection, instance segmentation, and panoptic segmentation methods as well as related components and modules, and below is its whole framework: + +MMDetection consists of 7 main parts, apis, structures, datasets, models, engine, evaluation and visualization. + +- **apis** provides high-level APIs for model inference. +- **structures** provides data structures like bbox, mask, and DetDataSample. +- **datasets** supports various dataset for object detection, instance segmentation, and panoptic segmentation. + - **transforms** contains a lot of useful data augmentation transforms. + - **samplers** defines different data loader sampling strategy. +- **models** is the most vital part for detectors and contains different components of a detector. + - **detectors** defines all of the detection model classes. + - **data_preprocessors** is for preprocessing the input data of the model. + - **backbones** contains various backbone networks. + - **necks** contains various neck components. + - **dense_heads** contains various detection heads that perform dense predictions. + - **roi_heads** contains various detection heads that predict from RoIs. + - **seg_heads** contains various segmentation heads. + - **losses** contains various loss functions. + - **task_modules** provides modules for detection tasks. E.g. assigners, samplers, box coders, and prior generators. + - **layers** provides some basic neural network layers. +- **engine** is a part for runtime components. + - **runner** provides extensions for [MMEngine's runner](https://mmengine.readthedocs.io/en/latest/tutorials/runner.html). + - **schedulers** provides schedulers for adjusting optimization hyperparameters. + - **optimizers** provides optimizers and optimizer wrappers. + - **hooks** provides various hooks of the runner. +- **evaluation** provides different metrics for evaluating model performance. +- **visualization** is for visualizing detection results. + +## How to Use this Guide + +Here is a detailed step-by-step guide to learn more about MMDetection: + +1. For installation instructions, please see [get_started](get_started.md). + +2. Refer to the below tutorials for the basic usage of MMDetection. + + - [Train and Test](https://mmdetection.readthedocs.io/en/latest/user_guides/index.html#train-test) + + - [Useful Tools](https://mmdetection.readthedocs.io/en/latest/user_guides/index.html#useful-tools) + +3. Refer to the below tutorials to dive deeper: + + - [Basic Concepts](https://mmdetection.readthedocs.io/en/latest/advanced_guides/index.html#basic-concepts) + - [Component Customization](https://mmdetection.readthedocs.io/en/latest/advanced_guides/index.html#component-customization) + +4. For users of MMDetection 2.x version, we provide a guide to help you adapt to the new version. You can find it in the [migration guide](./migration/migration.md). diff --git a/mmdet_code/SR-TOD/docs/en/stat.py b/mmdet_code/SR-TOD/docs/en/stat.py new file mode 100644 index 0000000000000000000000000000000000000000..f0589e337e0da6e3dbac0e2827433c77709064ea --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/stat.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +import functools as func +import glob +import os.path as osp +import re + +import numpy as np + +url_prefix = 'https://github.com/open-mmlab/mmdetection/blob/main/configs' + +files = sorted(glob.glob('../../configs/*/README.md')) + +stats = [] +titles = [] +num_ckpts = 0 + +for f in files: + url = osp.dirname(f.replace('../../configs', url_prefix)) + + with open(f, 'r') as content_file: + content = content_file.read() + + title = content.split('\n')[0].replace('# ', '').strip() + ckpts = set(x.lower().strip() + for x in re.findall(r'\[model\]\((https?.*)\)', content)) + + if len(ckpts) == 0: + continue + + _papertype = [x for x in re.findall(r'\[([A-Z]+)\]', content)] + assert len(_papertype) > 0 + papertype = _papertype[0] + + paper = set([(papertype, title)]) + + titles.append(title) + num_ckpts += len(ckpts) + + statsmsg = f""" +\t* [{papertype}] [{title}]({url}) ({len(ckpts)} ckpts) +""" + stats.append((paper, ckpts, statsmsg)) + +allpapers = func.reduce(lambda a, b: a.union(b), [p for p, _, _ in stats]) +msglist = '\n'.join(x for _, _, x in stats) + +papertypes, papercounts = np.unique([t for t, _ in allpapers], + return_counts=True) +countstr = '\n'.join( + [f' - {t}: {c}' for t, c in zip(papertypes, papercounts)]) + +modelzoo = f""" +# Model Zoo Statistics + +* Number of papers: {len(set(titles))} +{countstr} + +* Number of checkpoints: {num_ckpts} + +{msglist} +""" + +with open('modelzoo_statistics.md', 'w') as f: + f.write(modelzoo) diff --git a/mmdet_code/SR-TOD/docs/en/switch_language.md b/mmdet_code/SR-TOD/docs/en/switch_language.md new file mode 100644 index 0000000000000000000000000000000000000000..b2c4ad9db394a147483388b245ffb3c72f81642e --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/switch_language.md @@ -0,0 +1,3 @@ +## English + +## 简体中文 diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/config.md b/mmdet_code/SR-TOD/docs/en/user_guides/config.md new file mode 100644 index 0000000000000000000000000000000000000000..69bd91194e0da67a40733a72a715374192767d50 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/config.md @@ -0,0 +1,612 @@ +# Learn about Configs + +MMDetection and other OpenMMLab repositories use [MMEngine's config system](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html). It has a modular and inheritance design, which is convenient to conduct various experiments. + +## Config file content + +MMDetection uses a modular design, all modules with different functions can be configured through the config. Taking Mask R-CNN as an example, we will introduce each field in the config according to different function modules: + +### Model config + +In MMDetection's config, we use `model` to set up detection algorithm components. In addition to neural network components such as `backbone`, `neck`, etc, it also requires `data_preprocessor`, `train_cfg`, and `test_cfg`. `data_preprocessor` is responsible for processing a batch of data output by dataloader. `train_cfg`, and `test_cfg` in the model config are for training and testing hyperparameters of the components. + +```python +model = dict( + type='MaskRCNN', # The name of detector + data_preprocessor=dict( # The config of data preprocessor, usually includes image normalization and padding + type='DetDataPreprocessor', # The type of the data preprocessor, refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.data_preprocessors.DetDataPreprocessor + mean=[123.675, 116.28, 103.53], # Mean values used to pre-training the pre-trained backbone models, ordered in R, G, B + std=[58.395, 57.12, 57.375], # Standard variance used to pre-training the pre-trained backbone models, ordered in R, G, B + bgr_to_rgb=True, # whether to convert image from BGR to RGB + pad_mask=True, # whether to pad instance masks + pad_size_divisor=32), # The size of padded image should be divisible by ``pad_size_divisor`` + backbone=dict( # The config of backbone + type='ResNet', # The type of backbone network. Refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.backbones.ResNet + depth=50, # The depth of backbone, usually it is 50 or 101 for ResNet and ResNext backbones. + num_stages=4, # Number of stages of the backbone. + out_indices=(0, 1, 2, 3), # The index of output feature maps produced in each stage + frozen_stages=1, # The weights in the first stage are frozen + norm_cfg=dict( # The config of normalization layers. + type='BN', # Type of norm layer, usually it is BN or GN + requires_grad=True), # Whether to train the gamma and beta in BN + norm_eval=True, # Whether to freeze the statistics in BN + style='pytorch', # The style of backbone, 'pytorch' means that stride 2 layers are in 3x3 Conv, 'caffe' means stride 2 layers are in 1x1 Convs. + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), # The ImageNet pretrained backbone to be loaded + neck=dict( + type='FPN', # The neck of detector is FPN. We also support 'NASFPN', 'PAFPN', etc. Refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.necks.FPN for more details. + in_channels=[256, 512, 1024, 2048], # The input channels, this is consistent with the output channels of backbone + out_channels=256, # The output channels of each level of the pyramid feature map + num_outs=5), # The number of output scales + rpn_head=dict( + type='RPNHead', # The type of RPN head is 'RPNHead', we also support 'GARPNHead', etc. Refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.dense_heads.RPNHead for more details. + in_channels=256, # The input channels of each input feature map, this is consistent with the output channels of neck + feat_channels=256, # Feature channels of convolutional layers in the head. + anchor_generator=dict( # The config of anchor generator + type='AnchorGenerator', # Most of methods use AnchorGenerator, SSD Detectors uses `SSDAnchorGenerator`. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/prior_generators/anchor_generator.py#L18 for more details + scales=[8], # Basic scale of the anchor, the area of the anchor in one position of a feature map will be scale * base_sizes + ratios=[0.5, 1.0, 2.0], # The ratio between height and width. + strides=[4, 8, 16, 32, 64]), # The strides of the anchor generator. This is consistent with the FPN feature strides. The strides will be taken as base_sizes if base_sizes is not set. + bbox_coder=dict( # Config of box coder to encode and decode the boxes during training and testing + type='DeltaXYWHBBoxCoder', # Type of box coder. 'DeltaXYWHBBoxCoder' is applied for most of the methods. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/coders/delta_xywh_bbox_coder.py#L13 for more details. + target_means=[0.0, 0.0, 0.0, 0.0], # The target means used to encode and decode boxes + target_stds=[1.0, 1.0, 1.0, 1.0]), # The standard variance used to encode and decode boxes + loss_cls=dict( # Config of loss function for the classification branch + type='CrossEntropyLoss', # Type of loss for classification branch, we also support FocalLoss etc. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/cross_entropy_loss.py#L201 for more details + use_sigmoid=True, # RPN usually performs two-class classification, so it usually uses the sigmoid function. + loss_weight=1.0), # Loss weight of the classification branch. + loss_bbox=dict( # Config of loss function for the regression branch. + type='L1Loss', # Type of loss, we also support many IoU Losses and smooth L1-loss, etc. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/smooth_l1_loss.py#L56 for implementation. + loss_weight=1.0)), # Loss weight of the regression branch. + roi_head=dict( # RoIHead encapsulates the second stage of two-stage/cascade detectors. + type='StandardRoIHead', + bbox_roi_extractor=dict( # RoI feature extractor for bbox regression. + type='SingleRoIExtractor', # Type of the RoI feature extractor, most of methods uses SingleRoIExtractor. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/roi_extractors/single_level_roi_extractor.py#L13 for details. + roi_layer=dict( # Config of RoI Layer + type='RoIAlign', # Type of RoI Layer, DeformRoIPoolingPack and ModulatedDeformRoIPoolingPack are also supported. Refer to https://mmcv.readthedocs.io/en/latest/api.html#mmcv.ops.RoIAlign for details. + output_size=7, # The output size of feature maps. + sampling_ratio=0), # Sampling ratio when extracting the RoI features. 0 means adaptive ratio. + out_channels=256, # output channels of the extracted feature. + featmap_strides=[4, 8, 16, 32]), # Strides of multi-scale feature maps. It should be consistent with the architecture of the backbone. + bbox_head=dict( # Config of box head in the RoIHead. + type='Shared2FCBBoxHead', # Type of the bbox head, Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py#L220 for implementation details. + in_channels=256, # Input channels for bbox head. This is consistent with the out_channels in roi_extractor + fc_out_channels=1024, # Output feature channels of FC layers. + roi_feat_size=7, # Size of RoI features + num_classes=80, # Number of classes for classification + bbox_coder=dict( # Box coder used in the second stage. + type='DeltaXYWHBBoxCoder', # Type of box coder. 'DeltaXYWHBBoxCoder' is applied for most of the methods. + target_means=[0.0, 0.0, 0.0, 0.0], # Means used to encode and decode box + target_stds=[0.1, 0.1, 0.2, 0.2]), # Standard variance for encoding and decoding. It is smaller since the boxes are more accurate. [0.1, 0.1, 0.2, 0.2] is a conventional setting. + reg_class_agnostic=False, # Whether the regression is class agnostic. + loss_cls=dict( # Config of loss function for the classification branch + type='CrossEntropyLoss', # Type of loss for classification branch, we also support FocalLoss etc. + use_sigmoid=False, # Whether to use sigmoid. + loss_weight=1.0), # Loss weight of the classification branch. + loss_bbox=dict( # Config of loss function for the regression branch. + type='L1Loss', # Type of loss, we also support many IoU Losses and smooth L1-loss, etc. + loss_weight=1.0)), # Loss weight of the regression branch. + mask_roi_extractor=dict( # RoI feature extractor for mask generation. + type='SingleRoIExtractor', # Type of the RoI feature extractor, most of methods uses SingleRoIExtractor. + roi_layer=dict( # Config of RoI Layer that extracts features for instance segmentation + type='RoIAlign', # Type of RoI Layer, DeformRoIPoolingPack and ModulatedDeformRoIPoolingPack are also supported + output_size=14, # The output size of feature maps. + sampling_ratio=0), # Sampling ratio when extracting the RoI features. + out_channels=256, # Output channels of the extracted feature. + featmap_strides=[4, 8, 16, 32]), # Strides of multi-scale feature maps. + mask_head=dict( # Mask prediction head + type='FCNMaskHead', # Type of mask head, refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.roi_heads.FCNMaskHead for implementation details. + num_convs=4, # Number of convolutional layers in mask head. + in_channels=256, # Input channels, should be consistent with the output channels of mask roi extractor. + conv_out_channels=256, # Output channels of the convolutional layer. + num_classes=80, # Number of class to be segmented. + loss_mask=dict( # Config of loss function for the mask branch. + type='CrossEntropyLoss', # Type of loss used for segmentation + use_mask=True, # Whether to only train the mask in the correct class. + loss_weight=1.0))), # Loss weight of mask branch. + train_cfg = dict( # Config of training hyperparameters for rpn and rcnn + rpn=dict( # Training config of rpn + assigner=dict( # Config of assigner + type='MaxIoUAssigner', # Type of assigner, MaxIoUAssigner is used for many common detectors. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/assigners/max_iou_assigner.py#L14 for more details. + pos_iou_thr=0.7, # IoU >= threshold 0.7 will be taken as positive samples + neg_iou_thr=0.3, # IoU < threshold 0.3 will be taken as negative samples + min_pos_iou=0.3, # The minimal IoU threshold to take boxes as positive samples + match_low_quality=True, # Whether to match the boxes under low quality (see API doc for more details). + ignore_iof_thr=-1), # IoF threshold for ignoring bboxes + sampler=dict( # Config of positive/negative sampler + type='RandomSampler', # Type of sampler, PseudoSampler and other samplers are also supported. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/samplers/random_sampler.py#L14 for implementation details. + num=256, # Number of samples + pos_fraction=0.5, # The ratio of positive samples in the total samples. + neg_pos_ub=-1, # The upper bound of negative samples based on the number of positive samples. + add_gt_as_proposals=False), # Whether add GT as proposals after sampling. + allowed_border=-1, # The border allowed after padding for valid anchors. + pos_weight=-1, # The weight of positive samples during training. + debug=False), # Whether to set the debug mode + rpn_proposal=dict( # The config to generate proposals during training + nms_across_levels=False, # Whether to do NMS for boxes across levels. Only work in `GARPNHead`, naive rpn does not support do nms cross levels. + nms_pre=2000, # The number of boxes before NMS + nms_post=1000, # The number of boxes to be kept by NMS. Only work in `GARPNHead`. + max_per_img=1000, # The number of boxes to be kept after NMS. + nms=dict( # Config of NMS + type='nms', # Type of NMS + iou_threshold=0.7 # NMS threshold + ), + min_bbox_size=0), # The allowed minimal box size + rcnn=dict( # The config for the roi heads. + assigner=dict( # Config of assigner for second stage, this is different for that in rpn + type='MaxIoUAssigner', # Type of assigner, MaxIoUAssigner is used for all roi_heads for now. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/assigners/max_iou_assigner.py#L14 for more details. + pos_iou_thr=0.5, # IoU >= threshold 0.5 will be taken as positive samples + neg_iou_thr=0.5, # IoU < threshold 0.5 will be taken as negative samples + min_pos_iou=0.5, # The minimal IoU threshold to take boxes as positive samples + match_low_quality=False, # Whether to match the boxes under low quality (see API doc for more details). + ignore_iof_thr=-1), # IoF threshold for ignoring bboxes + sampler=dict( + type='RandomSampler', # Type of sampler, PseudoSampler and other samplers are also supported. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/samplers/random_sampler.py#L14 for implementation details. + num=512, # Number of samples + pos_fraction=0.25, # The ratio of positive samples in the total samples. + neg_pos_ub=-1, # The upper bound of negative samples based on the number of positive samples. + add_gt_as_proposals=True + ), # Whether add GT as proposals after sampling. + mask_size=28, # Size of mask + pos_weight=-1, # The weight of positive samples during training. + debug=False)), # Whether to set the debug mode + test_cfg = dict( # Config for testing hyperparameters for rpn and rcnn + rpn=dict( # The config to generate proposals during testing + nms_across_levels=False, # Whether to do NMS for boxes across levels. Only work in `GARPNHead`, naive rpn does not support do nms cross levels. + nms_pre=1000, # The number of boxes before NMS + nms_post=1000, # The number of boxes to be kept by NMS. Only work in `GARPNHead`. + max_per_img=1000, # The number of boxes to be kept after NMS. + nms=dict( # Config of NMS + type='nms', #Type of NMS + iou_threshold=0.7 # NMS threshold + ), + min_bbox_size=0), # The allowed minimal box size + rcnn=dict( # The config for the roi heads. + score_thr=0.05, # Threshold to filter out boxes + nms=dict( # Config of NMS in the second stage + type='nms', # Type of NMS + iou_thr=0.5), # NMS threshold + max_per_img=100, # Max number of detections of each image + mask_thr_binary=0.5))) # Threshold of mask prediction +``` + +### Dataset and evaluator config + +[Dataloaders](https://mmengine.readthedocs.io/en/latest/tutorials/dataset.html) are required for the training, validation, and testing of the [runner](https://mmengine.readthedocs.io/en/latest/tutorials/runner.html). Dataset and data pipeline need to be set to build the dataloader. Due to the complexity of this part, we use intermediate variables to simplify the writing of dataloader configs. + +```python +dataset_type = 'CocoDataset' # Dataset type, this will be used to define the dataset +data_root = 'data/coco/' # Root path of data +backend_args = None # Arguments to instantiate the corresponding file backend + +train_pipeline = [ # Training data processing pipeline + dict(type='LoadImageFromFile', backend_args=backend_args), # First pipeline to load images from file path + dict( + type='LoadAnnotations', # Second pipeline to load annotations for current image + with_bbox=True, # Whether to use bounding box, True for detection + with_mask=True, # Whether to use instance mask, True for instance segmentation + poly2mask=True), # Whether to convert the polygon mask to instance mask, set False for acceleration and to save memory + dict( + type='Resize', # Pipeline that resizes the images and their annotations + scale=(1333, 800), # The largest scale of the images + keep_ratio=True # Whether to keep the ratio between height and width + ), + dict( + type='RandomFlip', # Augmentation pipeline that flips the images and their annotations + prob=0.5), # The probability to flip + dict(type='PackDetInputs') # Pipeline that formats the annotation data and decides which keys in the data should be packed into data_samples +] +test_pipeline = [ # Testing data processing pipeline + dict(type='LoadImageFromFile', backend_args=backend_args), # First pipeline to load images from file path + dict(type='Resize', scale=(1333, 800), keep_ratio=True), # Pipeline that resizes the images + dict( + type='PackDetInputs', # Pipeline that formats the annotation data and decides which keys in the data should be packed into data_samples + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( # Train dataloader config + batch_size=2, # Batch size of a single GPU + num_workers=2, # Worker to pre-fetch data for each single GPU + persistent_workers=True, # If ``True``, the dataloader will not shut down the worker processes after an epoch end, which can accelerate training speed. + sampler=dict( # training data sampler + type='DefaultSampler', # DefaultSampler which supports both distributed and non-distributed training. Refer to https://mmengine.readthedocs.io/en/latest/api/generated/mmengine.dataset.DefaultSampler.html#mmengine.dataset.DefaultSampler + shuffle=True), # randomly shuffle the training data in each epoch + batch_sampler=dict(type='AspectRatioBatchSampler'), # Batch sampler for grouping images with similar aspect ratio into a same batch. It can reduce GPU memory cost. + dataset=dict( # Train dataset config + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', # Path of annotation file + data_prefix=dict(img='train2017/'), # Prefix of image path + filter_cfg=dict(filter_empty_gt=True, min_size=32), # Config of filtering images and annotations + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( # Validation dataloader config + batch_size=1, # Batch size of a single GPU. If batch-size > 1, the extra padding area may influence the performance. + num_workers=2, # Worker to pre-fetch data for each single GPU + persistent_workers=True, # If ``True``, the dataloader will not shut down the worker processes after an epoch end, which can accelerate training speed. + drop_last=False, # Whether to drop the last incomplete batch, if the dataset size is not divisible by the batch size + sampler=dict( + type='DefaultSampler', + shuffle=False), # not shuffle during validation and testing + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, # Turn on the test mode of the dataset to avoid filtering annotations or images + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader # Testing dataloader config +``` + +[Evaluators](https://mmengine.readthedocs.io/en/latest/tutorials/evaluation.html) are used to compute the metrics of the trained model on the validation and testing datasets. The config of evaluators consists of one or a list of metric configs: + +```python +val_evaluator = dict( # Validation evaluator config + type='CocoMetric', # The coco metric used to evaluate AR, AP, and mAP for detection and instance segmentation + ann_file=data_root + 'annotations/instances_val2017.json', # Annotation file path + metric=['bbox', 'segm'], # Metrics to be evaluated, `bbox` for detection and `segm` for instance segmentation + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator # Testing evaluator config +``` + +Since the test dataset has no annotation files, the test_dataloader and test_evaluator config in MMDetection are generally equal to the val's. If you want to save the detection results on the test dataset, you can write the config like this: + +```python +# inference on test dataset and +# format the output results for submission. +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'annotations/image_info_test-dev2017.json', + data_prefix=dict(img='test2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/image_info_test-dev2017.json', + metric=['bbox', 'segm'], # Metrics to be evaluated + format_only=True, # Only format and save the results to coco json file + outfile_prefix='./work_dirs/coco_detection/test') # The prefix of output json files +``` + +### Training and testing config + +MMEngine's runner uses Loop to control the training, validation, and testing processes. +Users can set the maximum training epochs and validation intervals with these fields. + +```python +train_cfg = dict( + type='EpochBasedTrainLoop', # The training loop type. Refer to https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py + max_epochs=12, # Maximum training epochs + val_interval=1) # Validation intervals. Run validation every epoch. +val_cfg = dict(type='ValLoop') # The validation loop type +test_cfg = dict(type='TestLoop') # The testing loop type +``` + +### Optimization config + +`optim_wrapper` is the field to configure optimization-related settings. The optimizer wrapper not only provides the functions of the optimizer, but also supports functions such as gradient clipping, mixed precision training, etc. Find more in [optimizer wrapper tutorial](https://mmengine.readthedocs.io/en/latest/tutorials/optim_wrapper.html). + +```python +optim_wrapper = dict( # Optimizer wrapper config + type='OptimWrapper', # Optimizer wrapper type, switch to AmpOptimWrapper to enable mixed precision training. + optimizer=dict( # Optimizer config. Support all kinds of optimizers in PyTorch. Refer to https://pytorch.org/docs/stable/optim.html#algorithms + type='SGD', # Stochastic gradient descent optimizer + lr=0.02, # The base learning rate + momentum=0.9, # Stochastic gradient descent with momentum + weight_decay=0.0001), # Weight decay of SGD + clip_grad=None, # Gradient clip option. Set None to disable gradient clip. Find usage in https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html + ) +``` + +`param_scheduler` is a field that configures methods of adjusting optimization hyperparameters such as learning rate and momentum. Users can combine multiple schedulers to create a desired parameter adjustment strategy. Find more in [parameter scheduler tutorial](https://mmengine.readthedocs.io/en/latest/tutorials/param_scheduler.html) and [parameter scheduler API documents](https://mmengine.readthedocs.io/en/latest/api/generated/mmengine.optim._ParamScheduler.html#mmengine.optim._ParamScheduler) + +```python +param_scheduler = [ + # Linear learning rate warm-up scheduler + dict( + type='LinearLR', # Use linear policy to warmup learning rate + start_factor=0.001, # The ratio of the starting learning rate used for warmup + by_epoch=False, # The warmup learning rate is updated by iteration + begin=0, # Start from the first iteration + end=500), # End the warmup at the 500th iteration + # The main LRScheduler + dict( + type='MultiStepLR', # Use multi-step learning rate policy during training + by_epoch=True, # The learning rate is updated by epoch + begin=0, # Start from the first epoch + end=12, # End at the 12th epoch + milestones=[8, 11], # Epochs to decay the learning rate + gamma=0.1) # The learning rate decay ratio +] +``` + +### Hook config + +Users can attach Hooks to training, validation, and testing loops to insert some operations during running. There are two different hook fields, one is `default_hooks` and the other is `custom_hooks`. + +`default_hooks` is a dict of hook configs, and they are the hooks must be required at the runtime. They have default priority which should not be modified. If not set, runner will use the default values. To disable a default hook, users can set its config to `None`. Find more in [HOOK](https://mmengine.readthedocs.io/en/latest/tutorials/hook.html). + +```python +default_hooks = dict( + timer=dict(type='IterTimerHook'), # Update the time spent during iteration into message hub + logger=dict(type='LoggerHook', interval=50), # Collect logs from different components of Runner and write them to terminal, JSON file, tensorboard and wandb .etc + param_scheduler=dict(type='ParamSchedulerHook'), # update some hyper-parameters of optimizer + checkpoint=dict(type='CheckpointHook', interval=1), # Save checkpoints periodically + sampler_seed=dict(type='DistSamplerSeedHook'), # Ensure distributed Sampler shuffle is active + visualization=dict(type='DetVisualizationHook')) # Detection Visualization Hook. Used to visualize validation and testing process prediction results +``` + +`custom_hooks` is a list of all other hook configs. Users can develop their own hooks and insert them in this field. + +```python +custom_hooks = [] +``` + +### Runtime config + +```python +default_scope = 'mmdet' # The default registry scope to find modules. Refer to https://mmengine.readthedocs.io/en/latest/advanced_tutorials/registry.html + +env_cfg = dict( + cudnn_benchmark=False, # Whether to enable cudnn benchmark + mp_cfg=dict( # Multi-processing config + mp_start_method='fork', # Use fork to start multi-processing threads. 'fork' usually faster than 'spawn' but maybe unsafe. See discussion in https://github.com/pytorch/pytorch/issues/1355 + opencv_num_threads=0), # Disable opencv multi-threads to avoid system being overloaded + dist_cfg=dict(backend='nccl'), # Distribution configs +) + +vis_backends = [dict(type='LocalVisBackend')] # Visualization backends. Refer to https://mmengine.readthedocs.io/en/latest/advanced_tutorials/visualization.html +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +log_processor = dict( + type='LogProcessor', # Log processor to process runtime logs + window_size=50, # Smooth interval of log values + by_epoch=True) # Whether to format logs with epoch type. Should be consistent with the train loop's type. + +log_level = 'INFO' # The level of logging. +load_from = None # Load model checkpoint as a pre-trained model from a given path. This will not resume training. +resume = False # Whether to resume from the checkpoint defined in `load_from`. If `load_from` is None, it will resume the latest checkpoint in the `work_dir`. +``` + +## Iter-based config + +MMEngine's Runner also provides an iter-based training loop except for epoch-based. +To use iter-based training, users should modify the `train_cfg`, `param_scheduler`, `train_dataloader`, `default_hooks`, and `log_processor`. +Here is an example of changing an epoch-based RetinaNet config to iter-based: `configs/retinanet/retinanet_r50_fpn_90k_coco.py` + +```python +# Iter-based training config +train_cfg = dict( + _delete_=True, # Ignore the base config setting (optional) + type='IterBasedTrainLoop', # Use iter-based training loop + max_iters=90000, # Maximum iterations + val_interval=10000) # Validation interval + + +# Change the scheduler to iter-based +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=90000, + by_epoch=False, + milestones=[60000, 80000], + gamma=0.1) +] + +# Switch to InfiniteSampler to avoid dataloader restart +train_dataloader = dict(sampler=dict(type='InfiniteSampler')) + +# Change the checkpoint saving interval to iter-based +default_hooks = dict(checkpoint=dict(by_epoch=False, interval=10000)) + +# Change the log format to iter-based +log_processor = dict(by_epoch=False) +``` + +## Config file inheritance + +There are 4 basic component types under `config/_base_`, dataset, model, schedule, default_runtime. +Many methods could be easily constructed with one of these models like Faster R-CNN, Mask R-CNN, Cascade R-CNN, RPN, SSD. +The configs that are composed by components from `_base_` are called the _primitive_. + +For all configs under the same folder, it is recommended to have only **one** _primitive_ config. All other configs should inherit from the _primitive_ config. In this way, the maximum of inheritance level is 3. + +For easy understanding, we recommend contributors to inherit from existing methods. +For example, if some modification is made based on Faster R-CNN, users may first inherit the basic Faster R-CNN structure by specifying `_base_ = ../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py`, then modify the necessary fields in the config files. + +If you are building an entirely new method that does not share the structure with any of the existing methods, you may create a folder `xxx_rcnn` under `configs`, + +Please refer to [mmengine config tutorial](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html) for detailed documentation. + +By setting the `_base_` field, we can set which files the current configuration file inherits from. + +When `_base_` is a string of a file path, it means inheriting the contents from one config file. + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' +``` + +When `_base_` is a list of multiple file paths, it means inheriting from multiple files. + +```python +_base_ = [ + '../_base_/models/mask-rcnn_r50_fpn.py', + '../_base_/datasets/coco_instance.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +``` + +If you wish to inspect the config file, you may run `python tools/misc/print_config.py /PATH/TO/CONFIG` to see the complete config. + +### Ignore some fields in the base configs + +Sometimes, you may set `_delete_=True` to ignore some of the fields in base configs. +You may refer to [mmengine config tutorial](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html) for a simple illustration. + +In MMDetection, for example, to change the backbone of Mask R-CNN with the following config. + +```python +model = dict( + type='MaskRCNN', + 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', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict(...), + rpn_head=dict(...), + roi_head=dict(...)) +``` + +`ResNet` and `HRNet` use different keywords to construct. + +```python +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + _delete_=True, + type='HRNet', + extra=dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128)), + stage4=dict( + num_modules=3, + num_branches=4, + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256))), + init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://msra/hrnetv2_w32')), + neck=dict(...)) +``` + +The `_delete_=True` would replace all old keys in `backbone` field with new keys. + +### Use intermediate variables in configs + +Some intermediate variables are used in the configs files, like `train_pipeline`/`test_pipeline` in datasets. +It's worth noting that when modifying intermediate variables in the children configs, users need to pass the intermediate variables into corresponding fields again. +For example, we would like to use a multi-scale strategy to train a Mask R-CNN. `train_pipeline`/`test_pipeline` are intermediate variables we would like to modify. + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', scale=[(1333, 640), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) +val_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +test_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +``` + +We first define the new `train_pipeline`/`test_pipeline` and pass them into dataloader fields. + +Similarly, if we would like to switch from `SyncBN` to `BN` or `MMSyncBN`, we need to substitute every `norm_cfg` in the config. + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' +norm_cfg = dict(type='BN', requires_grad=True) +model = dict( + backbone=dict(norm_cfg=norm_cfg), + neck=dict(norm_cfg=norm_cfg), + ...) +``` + +### Reuse variables in \_base\_ file + +If the users want to reuse the variables in the base file, they can get a copy of the corresponding variable by using `{{_base_.xxx}}`. E.g: + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' + +a = {{_base_.model}} # Variable `a` is equal to the `model` defined in `_base_` +``` + +## Modify config through script arguments + +When submitting jobs using `tools/train.py` or `tools/test.py`, you may specify `--cfg-options` to in-place modify the config. + +- Update config keys of dict chains. + + The config options can be specified following the order of the dict keys in the original config. + For example, `--cfg-options model.backbone.norm_eval=False` changes the all BN modules in model backbones to `train` mode. + +- Update keys inside a list of configs. + + Some config dicts are composed as a list in your config. For example, the training pipeline `train_dataloader.dataset.pipeline` is normally a list + e.g. `[dict(type='LoadImageFromFile'), ...]`. If you want to change `'LoadImageFromFile'` to `'LoadImageFromNDArray'` in the pipeline, + you may specify `--cfg-options data.train.pipeline.0.type=LoadImageFromNDArray`. + +- Update values of list/tuples. + + If the value to be updated is a list or a tuple. For example, the config file normally sets `model.data_preprocessor.mean=[123.675, 116.28, 103.53]`. If you want to + change the mean values, you may specify `--cfg-options model.data_preprocessor.mean="[127,127,127]"`. Note that the quotation mark `"` is necessary to + support list/tuple data types, and **NO** white space is allowed inside the quotation marks in the specified value. + +## Config name style + +We follow the below style to name config files. Contributors are advised to follow the same style. + +``` +{algorithm name}_{model component names [component1]_[component2]_[...]}_{training settings}_{training dataset information}_{testing dataset information}.py +``` + +The file name is divided into five parts. All parts and components are connected with `_` and words of each part or component should be connected with `-`. + +- `{algorithm name}`: The name of the algorithm. It can be a detector name such as `faster-rcnn`, `mask-rcnn`, etc. Or can be a semi-supervised or knowledge-distillation algorithm such as `soft-teacher`, `lad`. etc. +- `{model component names}`: Names of the components used in the algorithm such as backbone, neck, etc. For example, `r50-caffe_fpn_gn-head` means using caffe-style ResNet50, FPN and detection head with Group Norm in the algorithm. +- `{training settings}`: Information of training settings such as batch size, augmentations, loss trick, scheduler, and epochs/iterations. For example: `4xb4-mixup-giou-coslr-100e` means using 8-gpus x 4-images-per-gpu, mixup augmentation, GIoU loss, cosine annealing learning rate, and train 100 epochs. + Some abbreviations: + - `{gpu x batch_per_gpu}`: GPUs and samples per GPU. `bN` indicates N batch size per GPU. E.g. `4xb4` is the short term of 4-GPUs x 4-images-per-GPU. And `8xb2` is used by default if not mentioned. + - `{schedule}`: training schedule, options are `1x`, `2x`, `20e`, etc. + `1x` and `2x` means 12 epochs and 24 epochs respectively. + `20e` is adopted in cascade models, which denotes 20 epochs. + For `1x`/`2x`, the initial learning rate decays by a factor of 10 at the 8/16th and 11/22th epochs. + For `20e`, the initial learning rate decays by a factor of 10 at the 16th and 19th epochs. +- `{training dataset information}`: Training dataset names like `coco`, `coco-panoptic`, `cityscapes`, `voc-0712`, `wider-face`. +- `{testing dataset information}` (optional): Testing dataset name for models trained on one dataset but tested on another. If not mentioned, it means the model was trained and tested on the same dataset type. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/dataset_prepare.md b/mmdet_code/SR-TOD/docs/en/user_guides/dataset_prepare.md new file mode 100644 index 0000000000000000000000000000000000000000..f03f4c57e9ee38bb74ba4351ce98f93f3348c1e4 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/dataset_prepare.md @@ -0,0 +1,310 @@ +# Dataset Prepare + +### Basic Detection Dataset Preparation + +MMDetection supports multiple public datasets including COCO, Pascal VOC, CityScapes, and [more](../../../configs/_base_/datasets). + +Public datasets like [Pascal VOC](http://host.robots.ox.ac.uk/pascal/VOC/index.html) or mirror and [COCO](https://cocodataset.org/#download) are available from official websites or mirrors. Note: In the detection task, Pascal VOC 2012 is an extension of Pascal VOC 2007 without overlap, and we usually use them together. +It is recommended to download and extract the dataset somewhere outside the project directory and symlink the dataset root to `$MMDETECTION/data` as below. +If your folder structure is different, you may need to change the corresponding paths in config files. + +We provide a script to download datasets such as COCO, you can run `python tools/misc/download_dataset.py --dataset-name coco2017` to download COCO dataset. +For users in China, more datasets can be downloaded from the opensource dataset platform: [OpenDataLab](https://opendatalab.com/?source=OpenMMLab%20GitHub). + +For more usage please refer to [dataset-download](./useful_tools.md#dataset-download) + +```text +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ ├── cityscapes +│ │ ├── annotations +│ │ ├── leftImg8bit +│ │ │ ├── train +│ │ │ ├── val +│ │ ├── gtFine +│ │ │ ├── train +│ │ │ ├── val +│ ├── VOCdevkit +│ │ ├── VOC2007 +│ │ ├── VOC2012 +``` + +Some models require additional [COCO-stuff](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip) datasets, such as HTC, DetectoRS and SCNet, you can download, unzip, and then move them to the coco folder. The directory should be like this. + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +``` + +Panoptic segmentation models like PanopticFPN require additional [COCO Panoptic](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip) datasets, you can download, unzip, and then move them to the coco annotation folder. The directory should be like this. + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── panoptic_train2017.json +│ │ │ ├── panoptic_train2017 +│ │ │ ├── panoptic_val2017.json +│ │ │ ├── panoptic_val2017 +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +``` + +The [cityscapes](https://www.cityscapes-dataset.com/) annotations need to be converted into the coco format using `tools/dataset_converters/cityscapes.py`: + +```shell +pip install cityscapesscripts + +python tools/dataset_converters/cityscapes.py \ + ./data/cityscapes \ + --nproc 8 \ + --out-dir ./data/cityscapes/annotations +``` + +### COCO Caption Dataset Preparation + +COCO Caption uses the COCO2014 dataset image and uses the annotation of karpathy. + +At first, you need to download the COCO2014 dataset. + +```shell +python tools/misc/download_dataset.py --dataset-name coco2014 --unzip +``` + +The dataset will be downloaded to `data/coco` under the current path. Then download the annotation of karpathy. + +```shell +cd data/coco/annotations +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_train.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val_gt.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test_gt.json +``` + +The final directory structure of the dataset folder that can be directly used for training and testing is as follows: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── coco_karpathy_train.json +│ │ │ ├── coco_karpathy_test.json +│ │ │ ├── coco_karpathy_val.json +│ │ │ ├── coco_karpathy_val_gt.json +│ │ │ ├── coco_karpathy_test_gt.json +│ │ ├── train2014 +│ │ ├── val2014 +│ │ ├── test2014 +``` + +### COCO Semantic Dataset Preparation + +There are two types of annotations for COCO semantic segmentation, which differ mainly in the definition of category names, so there are two ways to handle them. The first is to directly use the stuffthingmaps dataset, and the second is to use the panoptic dataset. + +**(1) Use stuffthingmaps dataset** + +The download link for this dataset is [stuffthingmaps_trainval2017](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip). Please download and extract it to the `data/coco` folder. + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +``` + +This dataset is different from the standard COCO category annotation in that it includes 172 classes: 80 "thing" classes, 91 "stuff" classes, and 1 "unlabeled" class. The description of each class can be found at https://github.com/nightrome/cocostuff/blob/master/labels.md. + +Although only 172 categories are annotated, the maximum label ID in `stuffthingmaps` is 182, and some categories in the middle are not annotated. In addition, the "unlabeled" category of class 0 is removed. Therefore, the relationship between the value at each position in the final `stuffthingmaps` image can be found at https://github.com/kazuto1011/deeplab-pytorch/blob/master/data/datasets/cocostuff/labels.txt. + +To train efficiently and conveniently for users, we need to remove 12 unannotated classes before starting training or evaluation. The names of these 12 classes are: `street sign, hat, shoe, eye glasses, plate, mirror, window, desk, door, blender, hair brush`. The category information that can be used for training and evaluation can be found in `mmdet/datasets/coco_semantic.py`. + +You can use `tools/dataset_converters/coco_stuff164k.py` to convert the downloaded `stuffthingmaps` to a dataset that can be directly used for training and evaluation. The directory structure of the converted dataset is as follows: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +│ │ ├── stuffthingmaps_semseg +``` + +`stuffthingmaps_semseg` is the newly generated COCO semantic segmentation dataset that can be directly used for training and testing. + +**(2) use panoptic dataset** + +The number of categories in the semantic segmentation dataset generated through panoptic annotation will be less than that generated using the `stuffthingmaps` dataset. First, you need to prepare the panoptic segmentation annotations, and then use the following script to complete the conversion. + +```shell +python tools/dataset_converters/prepare_coco_semantic_annos_from_panoptic_annos.py data/coco +``` + +The directory structure of the converted dataset is as follows: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── panoptic_train2017.json +│ │ │ ├── panoptic_train2017 +│ │ │ ├── panoptic_val2017.json +│ │ │ ├── panoptic_val2017 +│ │ │ ├── panoptic_semseg_train2017 +│ │ │ ├── panoptic_semseg_val2017 +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +``` + +`panoptic_semseg_train2017` and `panoptic_semseg_val2017` are the newly generated COCO semantic segmentation datasets that can be directly used for training and testing. Note that their category information is the same as that of COCO panoptic segmentation, including both "thing" and "stuff" categories. + +### RefCOCO Dataset Preparation + +The images and annotations of [RefCOCO](https://github.com/lichengunc/refer) series datasets can be download by running `tools/misc/download_dataset.py`: + +```shell +python tools/misc/download_dataset.py --dataset-name refcoco --save-dir data/coco --unzip +``` + +Then the directory should be like this: + +```text +data +├── coco +│ ├── refcoco +│   │   ├── instances.json +│   │   ├── refs(google).p +│   │   └── refs(unc).p +│   ├── refcoco+ +│   │   ├── instances.json +│   │   └── refs(unc).p +│   ├── refcocog +│   │   ├── instances.json +│   │   ├── refs(google).p +│   │   └── refs(umd).p +| |── train2014 +``` + +### ADE20K 2016 Dataset Preparation + +The images and annotations of [ADE20K](https://groups.csail.mit.edu/vision/datasets/ADE20K/) dataset can be download by running `tools/misc/download_dataset.py`: + +```shell +python tools/misc/download_dataset.py --dataset-name ade20k_2016 --save-dir data --unzip +``` + +Then move the annotations to the `data/ADEChallengeData2016` directory and run the preprocess script to produce the coco format annotations: + +```shell +mv data/annotations_instance data/ADEChallengeData2016/ +mv data/categoryMapping.txt data/ADEChallengeData2016/ +mv data/imgCatIds.json data/ADEChallengeData2016/ +python tools/dataset_converters/ade20k2coco.py data/ADEChallengeData2016 --task panoptic +python tools/dataset_converters/ade20k2coco.py data/ADEChallengeData2016 --task instance +``` + +The directory should be like this. + +```text +data +├── ADEChallengeData2016 +│   ├── ade20k_instance_train.json +│   ├── ade20k_instance_val.json +│   ├── ade20k_panoptic_train +| | ├── ADE_train_00000001.png +| | ├── ADE_train_00000002.png +| | ├── ... +│   ├── ade20k_panoptic_train.json +│   ├── ade20k_panoptic_val +| | ├── ADE_val_00000001.png +| | ├── ADE_val_00000002.png +| | ├── ... +│   ├── ade20k_panoptic_val.json +│   ├── annotations +| | ├── training +| | | ├── ADE_train_00000001.png +| | | ├── ADE_train_00000002.png +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.png +| | | ├── ADE_val_00000002.png +| | | ├── ... +│   ├── annotations_instance +| | ├── training +| | | ├── ADE_train_00000001.png +| | | ├── ADE_train_00000002.png +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.png +| | | ├── ADE_val_00000002.png +| | | ├── ... +│   ├── categoryMapping.txt +│   ├── images +│   | ├── training +| | | ├── ADE_train_00000001.jpg +| | | ├── ADE_train_00000002.jpg +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.jpg +| | | ├── ADE_val_00000002.jpg +| | | ├── ... +│   ├── imgCatIds.json +│   ├── objectInfo150.txt +| |── sceneCategories.txt +``` + +The above folders include all data of ADE20K's semantic segmentation, instance segmentation, and panoptic segmentation. + +### Download from OpenDataLab + +By using [OpenDataLab](https://opendatalab.com/), researchers can obtain free formatted datasets in various fields. Through the search function of the platform, researchers may address the dataset they look for quickly and easily. Using the formatted datasets from the platform, researchers can efficiently conduct tasks across datasets. + +Currently, MIM supports downloading VOC and COCO datasets from OpenDataLab with one command line. More datasets will be supported in the future. You can also directly download the datasets you need from the OpenDataLab platform and then convert them to the format required by MMDetection. + +If you use MIM to download, make sure that the version is greater than v0.3.8. You can use the following command to update: + +```Bash +pip install -U openmim +``` + +```Bash +# install OpenDataLab CLI tools +pip install -U opendatalab +# log in OpenDataLab, registry +odl login + +# download voc2007 and preprocess by MIM +mim download mmdet --dataset voc2007 + +# download voc2012 and preprocess by MIM +mim download mmdet --dataset voc2012 + +# download coco2017 and preprocess by MIM +mim download mmdet --dataset coco2017 +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/deploy.md b/mmdet_code/SR-TOD/docs/en/user_guides/deploy.md new file mode 100644 index 0000000000000000000000000000000000000000..db320d1409eb984f2eb79af2ee1bec455476f60f --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/deploy.md @@ -0,0 +1,173 @@ +# Model Deployment + +The deployment of OpenMMLab codebases, including MMDetection, MMPretrain and so on are supported by [MMDeploy](https://github.com/open-mmlab/mmdeploy). +The latest deployment guide for MMDetection can be found from [here](https://mmdeploy.readthedocs.io/en/dev-1.x/04-supported-codebases/mmdet.html). + +This tutorial is organized as follows: + +- [Installation](#installation) +- [Convert model](#convert-model) +- [Model specification](#model-specification) +- [Model inference](#model-inference) + - [Backend model inference](#backend-model-inference) + - [SDK model inference](#sdk-model-inference) +- [Supported models](#supported-models) + +## Installation + +Please follow the [guide](https://mmdetection.readthedocs.io/en/latest/get_started.html) to install mmdet. And then install mmdeploy from source by following [this](https://mmdeploy.readthedocs.io/en/1.x/get_started.html#installation) guide. + +```{note} +If you install mmdeploy prebuilt package, please also clone its repository by 'git clone https://github.com/open-mmlab/mmdeploy.git --depth=1' to get the deployment config files. +``` + +## Convert model + +Suppose mmdetection and mmdeploy repositories are in the same directory, and the working directory is the root path of mmdetection. + +Take [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py) model as an example. You can download its checkpoint from [here](https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth), and then convert it to onnx model as follows: + +```python +from mmdeploy.apis import torch2onnx +from mmdeploy.backend.sdk.export_info import export2SDK + +img = 'demo/demo.jpg' +work_dir = 'mmdeploy_models/mmdet/onnx' +save_file = 'end2end.onnx' +deploy_cfg = '../mmdeploy/configs/mmdet/detection/detection_onnxruntime_dynamic.py' +model_cfg = 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model_checkpoint = 'faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' +device = 'cpu' + +# 1. convert model to onnx +torch2onnx(img, work_dir, save_file, deploy_cfg, model_cfg, + model_checkpoint, device) + +# 2. extract pipeline info for inference by MMDeploy SDK +export2SDK(deploy_cfg, model_cfg, work_dir, pth=model_checkpoint, + device=device) +``` + +It is crucial to specify the correct deployment config during model conversion. MMDeploy has already provided builtin deployment config [files](https://github.com/open-mmlab/mmdeploy/tree/1.x/configs/mmdet) of all supported backends for mmdetection, under which the config file path follows the pattern: + +``` +{task}/{task}_{backend}-{precision}_{static | dynamic}_{shape}.py +``` + +- **{task}:** task in mmdetection. + + There are two of them. One is `detection` and the other is `instance-seg`, indicating instance segmentation. + + mmdet models like `RetinaNet`, `Faster R-CNN` and `DETR` and so on belongs to `detection` task. While `Mask R-CNN` is one of `instance-seg` models. + + **DO REMEMBER TO USE** `detection/detection_*.py` deployment config file when trying to convert detection models and use `instance-seg/instance-seg_*.py` to deploy instance segmentation models. + +- **{backend}:** inference backend, such as onnxruntime, tensorrt, pplnn, ncnn, openvino, coreml etc. + +- **{precision}:** fp16, int8. When it's empty, it means fp32 + +- **{static | dynamic}:** static shape or dynamic shape + +- **{shape}:** input shape or shape range of a model + +Therefore, in the above example, you can also convert `Faster R-CNN` to tensorrt-fp16 model by `detection_tensorrt-fp16_dynamic-320x320-1344x1344.py`. + +```{tip} +When converting mmdet models to tensorrt models, --device should be set to "cuda" +``` + +## Model specification + +Before moving on to model inference chapter, let's know more about the converted model structure which is very important for model inference. + +The converted model locates in the working directory like `mmdeploy_models/mmdet/onnx` in the previous example. It includes: + +``` +mmdeploy_models/mmdet/onnx +├── deploy.json +├── detail.json +├── end2end.onnx +└── pipeline.json +``` + +in which, + +- **end2end.onnx**: backend model which can be inferred by ONNX Runtime +- ***xxx*.json**: the necessary information for mmdeploy SDK + +The whole package **mmdeploy_models/mmdet/onnx** is defined as **mmdeploy SDK model**, i.e., **mmdeploy SDK model** includes both backend model and inference meta information. + +## Model inference + +### Backend model inference + +Take the previous converted `end2end.onnx` model as an example, you can use the following code to inference the model and visualize the results. + +```python +from mmdeploy.apis.utils import build_task_processor +from mmdeploy.utils import get_input_shape, load_config +import torch + +deploy_cfg = '../mmdeploy/configs/mmdet/detection/detection_onnxruntime_dynamic.py' +model_cfg = 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +device = 'cpu' +backend_model = ['mmdeploy_models/mmdet/onnx/end2end.onnx'] +image = 'demo/demo.jpg' + +# read deploy_cfg and model_cfg +deploy_cfg, model_cfg = load_config(deploy_cfg, model_cfg) + +# build task and backend model +task_processor = build_task_processor(model_cfg, deploy_cfg, device) +model = task_processor.build_backend_model(backend_model) + +# process input image +input_shape = get_input_shape(deploy_cfg) +model_inputs, _ = task_processor.create_input(image, input_shape) + +# do model inference +with torch.no_grad(): + result = model.test_step(model_inputs) + +# visualize results +task_processor.visualize( + image=image, + model=model, + result=result[0], + window_name='visualize', + output_file='output_detection.png') +``` + +### SDK model inference + +You can also perform SDK model inference like following, + +```python +from mmdeploy_python import Detector +import cv2 + +img = cv2.imread('demo/demo.jpg') + +# create a detector +detector = Detector(model_path='mmdeploy_models/mmdet/onnx', + device_name='cpu', device_id=0) +# perform inference +bboxes, labels, masks = detector(img) + +# visualize inference result +indices = [i for i in range(len(bboxes))] +for index, bbox, label_id in zip(indices, bboxes, labels): + [left, top, right, bottom], score = bbox[0:4].astype(int), bbox[4] + if score < 0.3: + continue + + cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0)) + +cv2.imwrite('output_detection.png', img) +``` + +Besides python API, mmdeploy SDK also provides other FFI (Foreign Function Interface), such as C, C++, C#, Java and so on. You can learn their usage from [demos](https://github.com/open-mmlab/mmdeploy/tree/1.x/demo). + +## Supported models + +Please refer to [here](https://mmdeploy.readthedocs.io/en/1.x/04-supported-codebases/mmdet.html#supported-models) for the supported model list. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/finetune.md b/mmdet_code/SR-TOD/docs/en/user_guides/finetune.md new file mode 100644 index 0000000000000000000000000000000000000000..e181ebaece237a7b62cce4aaa8065b0839dc52ae --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/finetune.md @@ -0,0 +1,96 @@ +# Finetuning Models + +Detectors pre-trained on the COCO dataset can serve as a good pre-trained model for other datasets, e.g., CityScapes and KITTI Dataset. +This tutorial provides instructions for users to use the models provided in the [Model Zoo](../model_zoo.md) for other datasets to obtain better performance. + +There are two steps to finetune a model on a new dataset. + +- Add support for the new dataset following [Customize Datasets](../advanced_guides/customize_dataset.md). +- Modify the configs as will be discussed in this tutorial. + +Take the finetuning process on Cityscapes Dataset as an example, the users need to modify five parts in the config. + +## Inherit base configs + +To release the burden and reduce bugs in writing the whole configs, MMDetection V3.0 support inheriting configs from multiple existing configs. To finetune a Mask RCNN model, the new config needs to inherit +`_base_/models/mask-rcnn_r50_fpn.py` to build the basic structure of the model. To use the Cityscapes Dataset, the new config can also simply inherit `_base_/datasets/cityscapes_instance.py`. For runtime settings such as logger settings, the new config needs to inherit `_base_/default_runtime.py`. For training schedules, the new config can to inherit `_base_/schedules/schedule_1x.py`. These configs are in the `configs` directory and the users can also choose to write the whole contents rather than use inheritance. + +```python +_base_ = [ + '../_base_/models/mask-rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py', + '../_base_/schedules/schedule_1x.py' +] +``` + +## Modify head + +Then the new config needs to modify the head according to the class numbers of the new datasets. By only changing `num_classes` in the roi_head, the weights of the pre-trained models are mostly reused except for the final prediction head. + +```python +model = dict( + roi_head=dict( + bbox_head=dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[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='SmoothL1Loss', beta=1.0, loss_weight=1.0)), + mask_head=dict( + type='FCNMaskHead', + num_convs=4, + in_channels=256, + conv_out_channels=256, + num_classes=8, + loss_mask=dict( + type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) +``` + +## Modify dataset + +The users may also need to prepare the dataset and write the configs about dataset, refer to [Customize Datasets](../advanced_guides/customize_dataset.md) for more detail. MMDetection V3.0 already supports VOC, WIDERFACE, COCO, LIVS, OpenImages, DeepFashion, Objects365, and Cityscapes Dataset. + +## Modify training schedule + +The finetuning hyperparameters vary from the default schedule. It usually requires a smaller learning rate and fewer training epochs + +```python +# optimizer +# lr is set for a batch size of 8 +optim_wrapper = dict(optimizer=dict(lr=0.01)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=8, + by_epoch=True, + milestones=[7], + gamma=0.1) +] + +# max_epochs +train_cfg = dict(max_epochs=8) + +# log config +default_hooks = dict(logger=dict(interval=100)), +``` + +## Use pre-trained model + +To use the pre-trained model, the new config adds the link of pre-trained models in the `load_from`. The users might need to download the model weights before training to avoid the download time during training. + +```python +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth' # noqa +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/index.rst b/mmdet_code/SR-TOD/docs/en/user_guides/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..e74fc5fb555312abad6077f2a51c9901d792bd11 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/index.rst @@ -0,0 +1,41 @@ +Train & Test +************** + +MMDetection provides hundreds of pretrained detection models in `Model Zoo `_, +and supports multiple standard datasets, including Pascal VOC, COCO, CityScapes, LVIS, etc. This note will show how to perform common tasks on these existing models and standard datasets: + + +.. toctree:: + :maxdepth: 1 + + config.md + inference.md + dataset_prepare.md + test.md + train.md + new_model.md + finetune.md + test_results_submission.md + init_cfg.md + single_stage_as_rpn.md + semi_det.md + + +Useful Tools +************ + +.. toctree:: + :maxdepth: 1 + + useful_tools.md + useful_hooks.md + visualization.md + robustness_benchmarking.md + deploy.md + label_studio.md + tracking_analysis_tools.md + tracking_config.md + tracking_dataset_prepare.md + tracking_inference.md + tracking_train_test.md + tracking_visualization.md diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/inference.md b/mmdet_code/SR-TOD/docs/en/user_guides/inference.md new file mode 100644 index 0000000000000000000000000000000000000000..8eeed39af4407b39daa974d6bab332f6feb74b42 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/inference.md @@ -0,0 +1,286 @@ +# Inference with existing models + +MMDetection provides hundreds of pre-trained detection models in [Model Zoo](https://mmdetection.readthedocs.io/en/latest/model_zoo.html). +This note will show how to inference, which means using trained models to detect objects on images. + +In MMDetection, a model is defined by a [configuration file](https://mmdetection.readthedocs.io/en/latest/user_guides/config.html) and existing model parameters are saved in a checkpoint file. + +To start with, we recommend [RTMDet](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet) with this [configuration file](https://github.com/open-mmlab/mmdetection/blob/main/configs/rtmdet/rtmdet_l_8xb32-300e_coco.py) and this [checkpoint file](https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_l_8xb32-300e_coco/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth). It is recommended to download the checkpoint file to `checkpoints` directory. + +## High-level APIs for inference + +MMDetection provides high-level Python APIs for inference on images. Here is an example of building the model and inference on given images or videos. + +```python +import cv2 +import mmcv +from mmcv.transforms import Compose +from mmengine.utils import track_iter_progress +from mmdet.registry import VISUALIZERS +from mmdet.apis import init_detector, inference_detector + + +# Specify the path to model config and checkpoint file +config_file = 'configs/rtmdet/rtmdet_l_8xb32-300e_coco.py' +checkpoint_file = 'checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth' + +# Build the model from a config file and a checkpoint file +model = init_detector(config_file, checkpoint_file, device='cuda:0') + +# Init visualizer +visualizer = VISUALIZERS.build(model.cfg.visualizer) +# The dataset_meta is loaded from the checkpoint and +# then pass to the model in init_detector +visualizer.dataset_meta = model.dataset_meta + +# Test a single image and show the results +img = 'test.jpg' # or img = mmcv.imread(img), which will only load it once +result = inference_detector(model, img) + +# Show the results +img = mmcv.imread(img) +img = mmcv.imconvert(img, 'bgr', 'rgb') + + +visualizer.add_datasample( + 'result', + img, + data_sample=result, + draw_gt=False, + show=True) + +# Test a video and show the results +# Build test pipeline +model.cfg.test_dataloader.dataset.pipeline[0].type = 'LoadImageFromNDArray' +test_pipeline = Compose(model.cfg.test_dataloader.dataset.pipeline) + +# visualizer has been created in line 31 and 34, if you run this demo in one notebook, +# you need not build the visualizer again. + +# Init visualizer +visualizer = VISUALIZERS.build(model.cfg.visualizer) +# The dataset_meta is loaded from the checkpoint and +# then pass to the model in init_detector +visualizer.dataset_meta = model.dataset_meta + +# The interval of show (ms), 0 is block +wait_time = 1 + +video_reader = mmcv.VideoReader('video.mp4') + +cv2.namedWindow('video', 0) + +for frame in track_iter_progress(video_reader): + result = inference_detector(model, frame, test_pipeline=test_pipeline) + visualizer.add_datasample( + name='video', + image=frame, + data_sample=result, + draw_gt=False, + show=False) + frame = visualizer.get_image() + mmcv.imshow(frame, 'video', wait_time) + +cv2.destroyAllWindows() +``` + +A notebook demo can be found in [demo/inference_demo.ipynb](https://github.com/open-mmlab/mmdetection/blob/main/demo/inference_demo.ipynb). + +Note: `inference_detector` only supports single-image inference for now. + +## Demos + +We also provide three demo scripts, implemented with high-level APIs and supporting functionality codes. +Source codes are available [here](https://github.com/open-mmlab/mmdetection/blob/main/demo). + +### Image demo + +This script performs inference on a single image. + +```shell +python demo/image_demo.py \ + ${IMAGE_FILE} \ + ${CONFIG_FILE} \ + [--weights ${WEIGHTS}] \ + [--device ${GPU_ID}] \ + [--pred-score-thr ${SCORE_THR}] +``` + +Examples: + +```shell +python demo/image_demo.py demo/demo.jpg \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + --weights checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --device cpu +``` + +#### Webcam demo + +This is a live demo from a webcam. + +```shell +python demo/webcam_demo.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--camera-id ${CAMERA-ID}] \ + [--score-thr ${SCORE_THR}] +``` + +Examples: + +```shell +python demo/webcam_demo.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth +``` + +### Video demo + +This script performs inference on a video. + +```shell +python demo/video_demo.py \ + ${VIDEO_FILE} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--score-thr ${SCORE_THR}] \ + [--out ${OUT_FILE}] \ + [--show] \ + [--wait-time ${WAIT_TIME}] +``` + +Examples: + +```shell +python demo/video_demo.py demo/demo.mp4 \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --out result.mp4 +``` + +#### Video demo with GPU acceleration + +This script performs inference on a video with GPU acceleration. + +```shell +python demo/video_gpuaccel_demo.py \ + ${VIDEO_FILE} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--score-thr ${SCORE_THR}] \ + [--nvdecode] \ + [--out ${OUT_FILE}] \ + [--show] \ + [--wait-time ${WAIT_TIME}] +``` + +Examples: + +```shell +python demo/video_gpuaccel_demo.py demo/demo.mp4 \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --nvdecode --out result.mp4 +``` + +## Multi-modal algorithm inference demo and evaluation + +As multimodal vision algorithms continue to evolve, MMDetection has also supported such algorithms. This section demonstrates how to use the demo and eval scripts corresponding to multimodal algorithms using the GLIP algorithm and model as the example. Moreover, MMDetection integrated a [gradio_demo project](../../../projects/gradio_demo/), which allows developers to quickly play with all image input tasks in MMDetection on their local devices. Check the [document](../../../projects/gradio_demo/README.md) for more details. + +### Preparation + +Please first make sure that you have the correct dependencies installed: + +```shell +# if source +pip install -r requirements/multimodal.txt + +# if wheel +mim install mmdet[multimodal] +``` + +MMDetection has already implemented GLIP algorithms and provided the weights, you can download directly from urls: + +```shell +cd mmdetection +wget https://download.openmmlab.com/mmdetection/v3.0/glip/glip_tiny_a_mmdet-b3654169.pth +``` + +### Inference + +Once the model is successfully downloaded, you can use the `demo/image_demo.py` script to run the inference. + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts bench +``` + +Demo result will be similar to this: + +
+ +
+ +If users would like to detect multiple targets, please declare them in the format of `xx . xx .` after the `--texts`. + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts 'bench . car .' +``` + +And the result will be like this one: + +
+ +
+ +You can also use a sentence as the input prompt for the `--texts` field, for example: + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts 'There are a lot of cars here.' +``` + +The result will be similar to this: + +
+ +
+ +### Evaluation + +The GLIP implementation in MMDetection does not have any performance degradation, our benchmark is as follows: + +| Model | official mAP | mmdet mAP | +| ----------------------- | :----------: | :-------: | +| glip_A_Swin_T_O365.yaml | 42.9 | 43.0 | +| glip_Swin_T_O365.yaml | 44.9 | 44.9 | +| glip_Swin_L.yaml | 51.4 | 51.3 | + +Users can use the test script we provided to run evaluation as well. Here is a basic example: + +```shell +# 1 gpu +python tools/test.py configs/glip/glip_atss_swin-t_fpn_dyhead_pretrain_obj365.py glip_tiny_a_mmdet-b3654169.pth + +# 8 GPU +./tools/dist_test.sh configs/glip/glip_atss_swin-t_fpn_dyhead_pretrain_obj365.py glip_tiny_a_mmdet-b3654169.pth 8 +``` + +The result will be similar to this: + +```shell +Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.428 +Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1000 ] = 0.594 +Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=1000 ] = 0.466 +Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.300 +Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.477 +Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.534 +Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.634 +Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=300 ] = 0.634 +Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=1000 ] = 0.634 +Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.473 +Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.690 +Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.789 +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/init_cfg.md b/mmdet_code/SR-TOD/docs/en/user_guides/init_cfg.md new file mode 100644 index 0000000000000000000000000000000000000000..2af6da6e722c83675c947694265700bfed12e8ba --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/init_cfg.md @@ -0,0 +1,161 @@ +# Weight initialization + +During training, a proper initialization strategy is beneficial to speeding up the training or obtaining a higher performance. [MMCV](https://github.com/open-mmlab/mmcv/blob/master/mmcv/cnn/utils/weight_init.py) provide some commonly used methods for initializing modules like `nn.Conv2d`. Model initialization in MMdetection mainly uses `init_cfg`. Users can initialize models with following two steps: + +1. Define `init_cfg` for a model or its components in `model_cfg`, but `init_cfg` of children components have higher priority and will override `init_cfg` of parents modules. +2. Build model as usual, but call `model.init_weights()` method explicitly, and model parameters will be initialized as configuration. + +The high-level workflow of initialization in MMdetection is : + +model_cfg(init_cfg) -> build_from_cfg -> model -> init_weight() -> initialize(self, self.init_cfg) -> children's init_weight() + +### Description + +It is dict or list\[dict\], and contains the following keys and values: + +- `type` (str), containing the initializer name in `INTIALIZERS`, and followed by arguments of the initializer. +- `layer` (str or list\[str\]), containing the names of basic layers in Pytorch or MMCV with learnable parameters that will be initialized, e.g. `'Conv2d'`,`'DeformConv2d'`. +- `override` (dict or list\[dict\]), containing the sub-modules that not inherit from BaseModule and whose initialization configuration is different from other layers' which are in `'layer'` key. Initializer defined in `type` will work for all layers defined in `layer`, so if sub-modules are not derived Classes of `BaseModule` but can be initialized as same ways of layers in `layer`, it does not need to use `override`. `override` contains: + - `type` followed by arguments of initializer; + - `name` to indicate sub-module which will be initialized. + +### Initialize parameters + +Inherit a new model from `mmcv.runner.BaseModule` or `mmdet.models` Here we show an example of FooModel. + +```python +import torch.nn as nn +from mmcv.runner import BaseModule + +class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=None): + super(FooModel, self).__init__(init_cfg) + ... +``` + +- Initialize model by using `init_cfg` directly in code + + ```python + import torch.nn as nn + from mmcv.runner import BaseModule + # or directly inherit mmdet models + + class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=XXX): + super(FooModel, self).__init__(init_cfg) + ... + ``` + +- Initialize model by using `init_cfg` directly in `mmcv.Sequential` or `mmcv.ModuleList` code + + ```python + from mmcv.runner import BaseModule, ModuleList + + class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=None): + super(FooModel, self).__init__(init_cfg) + ... + self.conv1 = ModuleList(init_cfg=XXX) + ``` + +- Initialize model by using `init_cfg` in config file + + ```python + model = dict( + ... + model = dict( + type='FooModel', + arg1=XXX, + arg2=XXX, + init_cfg=XXX), + ... + ``` + +### Usage of init_cfg + +1. Initialize model by `layer` key + + If we only define `layer`, it just initialize the layer in `layer` key. + + NOTE: Value of `layer` key is the class name with attributes weights and bias of Pytorch, (so such as `MultiheadAttention layer` is not supported). + +- Define `layer` key for initializing module with same configuration. + + ```python + init_cfg = dict(type='Constant', layer=['Conv1d', 'Conv2d', 'Linear'], val=1) + # initialize whole module with same configuration + ``` + +- Define `layer` key for initializing layer with different configurations. + +```python +init_cfg = [dict(type='Constant', layer='Conv1d', val=1), + dict(type='Constant', layer='Conv2d', val=2), + dict(type='Constant', layer='Linear', val=3)] +# nn.Conv1d will be initialized with dict(type='Constant', val=1) +# nn.Conv2d will be initialized with dict(type='Constant', val=2) +# nn.Linear will be initialized with dict(type='Constant', val=3) +``` + +2. Initialize model by `override` key + +- When initializing some specific part with its attribute name, we can use `override` key, and the value in `override` will ignore the value in init_cfg. + + ```python + # layers: + # self.feat = nn.Conv1d(3, 1, 3) + # self.reg = nn.Conv2d(3, 3, 3) + # self.cls = nn.Linear(1,2) + + init_cfg = dict(type='Constant', + layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(type='Constant', name='reg', val=3, bias=4)) + # self.feat and self.cls will be initialized with dict(type='Constant', val=1, bias=2) + # The module called 'reg' will be initialized with dict(type='Constant', val=3, bias=4) + ``` + +- If `layer` is None in init_cfg, only sub-module with the name in override will be initialized, and type and other args in override can be omitted. + + ```python + # layers: + # self.feat = nn.Conv1d(3, 1, 3) + # self.reg = nn.Conv2d(3, 3, 3) + # self.cls = nn.Linear(1,2) + + init_cfg = dict(type='Constant', val=1, bias=2, override=dict(name='reg')) + + # self.feat and self.cls will be initialized by Pytorch + # The module called 'reg' will be initialized with dict(type='Constant', val=1, bias=2) + ``` + +- If we don't define `layer` key or `override` key, it will not initialize anything. + +- Invalid usage + + ```python + # It is invalid that override don't have name key + init_cfg = dict(type='Constant', layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(type='Constant', val=3, bias=4)) + + # It is also invalid that override has name and other args except type + init_cfg = dict(type='Constant', layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(name='reg', val=3, bias=4)) + ``` + +3. Initialize model with the pretrained model + + ```python + init_cfg = dict(type='Pretrained', + checkpoint='torchvision://resnet50') + ``` + +More details can refer to the documentation in [MMEngine](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/initialize.html) diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/label_studio.md b/mmdet_code/SR-TOD/docs/en/user_guides/label_studio.md new file mode 100644 index 0000000000000000000000000000000000000000..d4b3744734984aaf91d95183248785394ba53959 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/label_studio.md @@ -0,0 +1,256 @@ +# Semi-automatic Object Detection Annotation with MMDetection and Label-Studio + +Annotation data is a time-consuming and laborious task. This article introduces how to perform semi-automatic annotation using the RTMDet algorithm in MMDetection in conjunction with Label-Studio software. Specifically, using RTMDet to predict image annotations and then refining the annotations with Label-Studio. Community users can refer to this process and methodology and apply it to other fields. + +- RTMDet: RTMDet is a high-precision single-stage object detection algorithm developed by OpenMMLab, open-sourced in the MMDetection object detection toolbox. Its open-source license is Apache 2.0, and it can be used freely without restrictions by industrial users. + +- [Label Studio](https://github.com/heartexlabs/label-studio) is an excellent annotation software covering the functionality of dataset annotation in areas such as image classification, object detection, and segmentation. + +In this article, we will use [cat](https://download.openmmlab.com/mmyolo/data/cat_dataset.zip) images for semi-automatic annotation. + +## Environment Configuration + +To begin with, you need to create a virtual environment and then install PyTorch and MMCV. In this article, we will specify the versions of PyTorch and MMCV. Next, you can install MMDetection, Label-Studio, and label-studio-ml-backend using the following steps: + +Create a virtual environment: + +```shell +conda create -n rtmdet python=3.9 -y +conda activate rtmdet +``` + +Install PyTorch: + +```shell +# Linux and Windows CPU only +pip install torch==1.10.1+cpu torchvision==0.11.2+cpu torchaudio==0.10.1 -f https://download.pytorch.org/whl/cpu/torch_stable.html +# Linux and Windows CUDA 11.3 +pip install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio==0.10.1 -f https://download.pytorch.org/whl/cu113/torch_stable.html +# OSX +pip install torch==1.10.1 torchvision==0.11.2 torchaudio==0.10.1 +``` + +Install MMCV: + +```shell +pip install -U openmim +mim install "mmcv>=2.0.0" +# Installing mmcv will automatically install mmengine +``` + +Install MMDetection: + +```shell +git clone https://github.com/open-mmlab/mmdetection +cd mmdetection +pip install -v -e . +``` + +Install Label-Studio and label-studio-ml-backend: + +```shell +# Installing Label-Studio may take some time, if the version is not found, please use the official source +pip install label-studio==1.7.2 +pip install label-studio-ml==1.0.9 +``` + +Download the rtmdet weights: + +```shell +cd path/to/mmetection +mkdir work_dirs +cd work_dirs +wget https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_m_8xb32-300e_coco/rtmdet_m_8xb32-300e_coco_20220719_112220-229f527c.pth +``` + +## Start the Service + +Start the RTMDet backend inference service: + +```shell +cd path/to/mmetection + +label-studio-ml start projects/LabelStudio/backend_template --with \ +config_file=configs/rtmdet/rtmdet_m_8xb32-300e_coco.py \ +checkpoint_file=./work_dirs/rtmdet_m_8xb32-300e_coco_20220719_112220-229f527c.pth \ +device=cpu \ +--port 8003 +# Set device=cpu to use CPU inference, and replace cpu with cuda:0 to use GPU inference. +``` + +![](https://cdn.vansin.top/picgo20230330131601.png) + +The RTMDet backend inference service has now been started. To configure it in the Label-Studio web system, use http://localhost:8003 as the backend inference service. + +Now, start the Label-Studio web service: + +```shell +label-studio start +``` + +![](https://cdn.vansin.top/picgo20230330132913.png) + +Open your web browser and go to http://localhost:8080/ to see the Label-Studio interface. + +![](https://cdn.vansin.top/picgo20230330133118.png) + +Register a user and then create an RTMDet-Semiautomatic-Label project. + +![](https://cdn.vansin.top/picgo20230330133333.png) + +Download the example cat images by running the following command and import them using the Data Import button: + +```shell +cd path/to/mmetection +mkdir data && cd data + +wget https://download.openmmlab.com/mmyolo/data/cat_dataset.zip && unzip cat_dataset.zip +``` + +![](https://cdn.vansin.top/picgo20230330133628.png) + +![](https://cdn.vansin.top/picgo20230330133715.png) + +Then, select the Object Detection With Bounding Boxes template. + +![](https://cdn.vansin.top/picgo20230330133807.png) + +```shell +airplane +apple +backpack +banana +baseball_bat +baseball_glove +bear +bed +bench +bicycle +bird +boat +book +bottle +bowl +broccoli +bus +cake +car +carrot +cat +cell_phone +chair +clock +couch +cow +cup +dining_table +dog +donut +elephant +fire_hydrant +fork +frisbee +giraffe +hair_drier +handbag +horse +hot_dog +keyboard +kite +knife +laptop +microwave +motorcycle +mouse +orange +oven +parking_meter +person +pizza +potted_plant +refrigerator +remote +sandwich +scissors +sheep +sink +skateboard +skis +snowboard +spoon +sports_ball +stop_sign +suitcase +surfboard +teddy_bear +tennis_racket +tie +toaster +toilet +toothbrush +traffic_light +train +truck +tv +umbrella +vase +wine_glass +zebra +``` + +Then, copy and add the above categories to Label-Studio and click Save. + +![](https://cdn.vansin.top/picgo20230330134027.png) + +In the Settings, click Add Model to add the RTMDet backend inference service. + +![](https://cdn.vansin.top/picgo20230330134320.png) + +Click Validate and Save, and then click Start Labeling. + +![](https://cdn.vansin.top/picgo20230330134424.png) + +If you see Connected as shown below, the backend inference service has been successfully added. + +![](https://cdn.vansin.top/picgo20230330134554.png) + +## Start Semi-Automatic Labeling + +Click on Label to start labeling. + +![](https://cdn.vansin.top/picgo20230330134804.png) + +We can see that the RTMDet backend inference service has successfully returned the predicted results and displayed them on the image. However, we noticed that the predicted bounding boxes for the cats are a bit too large and not very accurate. + +![](https://cdn.vansin.top/picgo20230403104419.png) + +We manually adjust the position of the cat bounding box, and then click Submit to complete the annotation of this image. + +![](https://cdn.vansin.top/picgo/20230403105923.png) + +After submitting all images, click export to export the labeled dataset in COCO format. + +![](https://cdn.vansin.top/picgo20230330135921.png) + +Use VS Code to open the unzipped folder to see the labeled dataset, which includes the images and the annotation files in JSON format. + +![](https://cdn.vansin.top/picgo20230330140321.png) + +At this point, the semi-automatic labeling is complete. We can use this dataset to train a more accurate model in MMDetection and then continue semi-automatic labeling on newly collected images with this model. This way, we can iteratively expand the high-quality dataset and improve the accuracy of the model. + +## Use MMYOLO as the Backend Inference Service + +If you want to use Label-Studio in MMYOLO, you can refer to replacing the config_file and checkpoint_file with the configuration file and weight file of MMYOLO when starting the backend inference service. + +```shell +cd path/to/mmetection + +label-studio-ml start projects/LabelStudio/backend_template --with \ +config_file= path/to/mmyolo_config.py \ +checkpoint_file= path/to/mmyolo_weights.pth \ +device=cpu \ +--port 8003 +# device=cpu is for using CPU inference. If using GPU inference, replace cpu with cuda:0. +``` + +Rotation object detection and instance segmentation are still under development, please stay tuned. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/new_model.md b/mmdet_code/SR-TOD/docs/en/user_guides/new_model.md new file mode 100644 index 0000000000000000000000000000000000000000..c7af855ae3165fcc96d30f65887b620323d85c68 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/new_model.md @@ -0,0 +1,290 @@ +# Train with customized models and standard datasets + +In this note, you will know how to train, test and inference your own customized models under standard datasets. We use the cityscapes dataset to train a customized Cascade Mask R-CNN R50 model as an example to demonstrate the whole process, which using [`AugFPN`](https://github.com/Gus-Guo/AugFPN) to replace the default `FPN` as neck, and add `Rotate` or `TranslateX` as training-time auto augmentation. + +The basic steps are as below: + +1. Prepare the standard dataset +2. Prepare your own customized model +3. Prepare a config +4. Train, test, and inference models on the standard dataset. + +## Prepare the standard dataset + +In this note, as we use the standard cityscapes dataset as an example. + +It is recommended to symlink the dataset root to `$MMDETECTION/data`. +If your folder structure is different, you may need to change the corresponding paths in config files. + +```none +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ ├── cityscapes +│ │ ├── annotations +│ │ ├── leftImg8bit +│ │ │ ├── train +│ │ │ ├── val +│ │ ├── gtFine +│ │ │ ├── train +│ │ │ ├── val +│ ├── VOCdevkit +│ │ ├── VOC2007 +│ │ ├── VOC2012 + +``` + +Or you can set your dataset root through + +```bash +export MMDET_DATASETS=$data_root +``` + +We will replace dataset root with `$MMDET_DATASETS`, so you don't have to modify the corresponding path in config files. + +The cityscapes annotations have to be converted into the coco format using `tools/dataset_converters/cityscapes.py`: + +```shell +pip install cityscapesscripts +python tools/dataset_converters/cityscapes.py ./data/cityscapes --nproc 8 --out-dir ./data/cityscapes/annotations +``` + +Currently, the config files in `cityscapes` use COCO pre-trained weights to initialize. +You could download the pre-trained models in advance if the network is unavailable or slow, otherwise, it would cause errors at the beginning of training. + +## Prepare your own customized model + +The second step is to use your own module or training setting. Assume that we want to implement a new neck called `AugFPN` to replace with the default `FPN` under the existing detector Cascade Mask R-CNN R50. The following implements `AugFPN` under MMDetection. + +### 1. Define a new neck (e.g. AugFPN) + +Firstly create a new file `mmdet/models/necks/augfpn.py`. + +```python +import torch.nn as nn +from mmdet.registry import MODELS + + +@MODELS.register_module() +class AugFPN(nn.Module): + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False): + pass + + def forward(self, inputs): + # implementation is ignored + pass +``` + +### 2. Import the module + +You can either add the following line to `mmdet/models/necks/__init__.py`, + +```python +from .augfpn import AugFPN +``` + +or alternatively add + +```python +custom_imports = dict( + imports=['mmdet.models.necks.augfpn'], + allow_failed_imports=False) +``` + +to the config file and avoid modifying the original code. + +### 3. Modify the config file + +```python +neck=dict( + type='AugFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5) +``` + +For more detailed usages about customizing your own models (e.g. implement a new backbone, head, loss, etc) and runtime training settings (e.g. define a new optimizer, use gradient clip, customize training schedules and hooks, etc), please refer to the guideline [Customize Models](../advanced_guides/customize_models.md) and [Customize Runtime Settings](../advanced_guides/customize_runtime.md) respectively. + +## Prepare a config + +The third step is to prepare a config for your own training setting. Assume that we want to add `AugFPN` and `Rotate` or `Translate` augmentation to existing Cascade Mask R-CNN R50 to train the cityscapes dataset, and assume the config is under directory `configs/cityscapes/` and named as `cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py`, the config is as below. + +```python +# The new config inherits the base configs to highlight the necessary modification +_base_ = [ + '../_base_/models/cascade-mask-rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py' +] + +model = dict( + # set None to avoid loading ImageNet pre-trained backbone, + # instead here we set `load_from` to load from COCO pre-trained detectors. + backbone=dict(init_cfg=None), + # replace neck from defaultly `FPN` to our new implemented module `AugFPN` + neck=dict( + type='AugFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5), + # We also need to change the num_classes in head from 80 to 8, to match the + # cityscapes dataset's annotation. This modification involves `bbox_head` and `mask_head`. + roi_head=dict( + bbox_head=[ + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # change the number of classes from defaultly COCO to cityscapes + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.1, 0.1, 0.2, 0.2]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, + loss_weight=1.0)), + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # change the number of classes from defaultly COCO to cityscapes + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.05, 0.05, 0.1, 0.1]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, + loss_weight=1.0)), + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # change the number of classes from defaultly COCO to cityscapes + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.033, 0.033, 0.067, 0.067]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) + ], + mask_head=dict( + type='FCNMaskHead', + num_convs=4, + in_channels=256, + conv_out_channels=256, + # change the number of classes from default COCO to cityscapes + num_classes=8, + loss_mask=dict( + type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) + +# over-write `train_pipeline` for new added `AutoAugment` training setting +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='AutoAugment', + policies=[ + [dict( + type='Rotate', + level=5, + img_border_value=(124, 116, 104), + prob=0.5) + ], + [dict(type='Rotate', level=7, img_border_value=(124, 116, 104)), + dict( + type='TranslateX', + level=5, + prob=0.5, + img_border_value=(124, 116, 104)) + ], + ]), + dict( + type='RandomResize', + scale=[(2048, 800), (2048, 1024)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs'), +] + +# set batch_size per gpu, and set new training pipeline +train_dataloader = dict( + batch_size=1, + num_workers=3, + # over-write `pipeline` with new training pipeline setting + dataset=dict(pipeline=train_pipeline)) + +# Set optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)) + +# Set customized learning policy +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=10, + by_epoch=True, + milestones=[8], + gamma=0.1) +] + +# train, val, test loop config +train_cfg = dict(max_epochs=10, val_interval=1) + +# We can use the COCO pre-trained Cascade Mask R-CNN R50 model for a more stable performance initialization +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco/cascade_mask_rcnn_r50_fpn_1x_coco_20200203-9d4dcb24.pth' +``` + +## Train a new model + +To train a model with the new config, you can simply run + +```shell +python tools/train.py configs/cityscapes/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py +``` + +For more detailed usages, please refer to the [training guide](train.md). + +## Test and inference + +To test the trained model, you can simply run + +```shell +python tools/test.py configs/cityscapes/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py work_dirs/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes/epoch_10.pth +``` + +For more detailed usages, please refer to the [testing guide](test.md). diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/robustness_benchmarking.md b/mmdet_code/SR-TOD/docs/en/user_guides/robustness_benchmarking.md new file mode 100644 index 0000000000000000000000000000000000000000..f6579564293379b6cf05705311368a7aa750b3fe --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/robustness_benchmarking.md @@ -0,0 +1,110 @@ +# Corruption Benchmarking + +## Introduction + +We provide tools to test object detection and instance segmentation models on the image corruption benchmark defined in [Benchmarking Robustness in Object Detection: Autonomous Driving when Winter is Coming](https://arxiv.org/abs/1907.07484). +This page provides basic tutorials how to use the benchmark. + +```latex +@article{michaelis2019winter, + title={Benchmarking Robustness in Object Detection: + Autonomous Driving when Winter is Coming}, + author={Michaelis, Claudio and Mitzkus, Benjamin and + Geirhos, Robert and Rusak, Evgenia and + Bringmann, Oliver and Ecker, Alexander S. and + Bethge, Matthias and Brendel, Wieland}, + journal={arXiv:1907.07484}, + year={2019} +} +``` + +![image corruption example](../../../resources/corruptions_sev_3.png) + +## About the benchmark + +To submit results to the benchmark please visit the [benchmark homepage](https://github.com/bethgelab/robust-detection-benchmark) + +The benchmark is modelled after the [imagenet-c benchmark](https://github.com/hendrycks/robustness) which was originally +published in [Benchmarking Neural Network Robustness to Common Corruptions and Perturbations](https://arxiv.org/abs/1903.12261) (ICLR 2019) by Dan Hendrycks and Thomas Dietterich. + +The image corruption functions are included in this library but can be installed separately using: + +```shell +pip install imagecorruptions +``` + +Compared to imagenet-c a few changes had to be made to handle images of arbitrary size and greyscale images. +We also modified the 'motion blur' and 'snow' corruptions to remove dependency from a linux specific library, +which would have to be installed separately otherwise. For details please refer to the [imagecorruptions repository](https://github.com/bethgelab/imagecorruptions). + +## Inference with pretrained models + +We provide a testing script to evaluate a models performance on any combination of the corruptions provided in the benchmark. + +### Test a dataset + +- [x] single GPU testing +- [ ] multiple GPU testing +- [ ] visualize detection results + +You can use the following commands to test a models performance under the 15 corruptions used in the benchmark. + +```shell +# single-gpu testing +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] +``` + +Alternatively different group of corruptions can be selected. + +```shell +# noise +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] --corruptions noise + +# blur +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] --corruptions blur + +# wetaher +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] --corruptions weather + +# digital +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] --corruptions digital +``` + +Or a costom set of corruptions e.g.: + +```shell +# gaussian noise, zoom blur and snow +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions gaussian_noise zoom_blur snow +``` + +Finally the corruption severities to evaluate can be chosen. +Severity 0 corresponds to clean data and the effect increases from 1 to 5. + +```shell +# severity 1 +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --severities 1 + +# severities 0,2,4 +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --severities 0 2 4 +``` + +## Results for modelzoo models + +The results on COCO 2017val are shown in the below table. + +| Model | Backbone | Style | Lr schd | box AP clean | box AP corr. | box % | mask AP clean | mask AP corr. | mask % | +| :-----------------: | :-----------------: | :-----: | :-----: | :----------: | :----------: | :---: | :-----------: | :-----------: | :----: | +| Faster R-CNN | R-50-FPN | pytorch | 1x | 36.3 | 18.2 | 50.2 | - | - | - | +| Faster R-CNN | R-101-FPN | pytorch | 1x | 38.5 | 20.9 | 54.2 | - | - | - | +| Faster R-CNN | X-101-32x4d-FPN | pytorch | 1x | 40.1 | 22.3 | 55.5 | - | - | - | +| Faster R-CNN | X-101-64x4d-FPN | pytorch | 1x | 41.3 | 23.4 | 56.6 | - | - | - | +| Faster R-CNN | R-50-FPN-DCN | pytorch | 1x | 40.0 | 22.4 | 56.1 | - | - | - | +| Faster R-CNN | X-101-32x4d-FPN-DCN | pytorch | 1x | 43.4 | 26.7 | 61.6 | - | - | - | +| Mask R-CNN | R-50-FPN | pytorch | 1x | 37.3 | 18.7 | 50.1 | 34.2 | 16.8 | 49.1 | +| Mask R-CNN | R-50-FPN-DCN | pytorch | 1x | 41.1 | 23.3 | 56.7 | 37.2 | 20.7 | 55.7 | +| Cascade R-CNN | R-50-FPN | pytorch | 1x | 40.4 | 20.1 | 49.7 | - | - | - | +| Cascade Mask R-CNN | R-50-FPN | pytorch | 1x | 41.2 | 20.7 | 50.2 | 35.7 | 17.6 | 49.3 | +| RetinaNet | R-50-FPN | pytorch | 1x | 35.6 | 17.8 | 50.1 | - | - | - | +| Hybrid Task Cascade | X-101-64x4d-FPN-DCN | pytorch | 1x | 50.6 | 32.7 | 64.7 | 43.8 | 28.1 | 64.0 | + +Results may vary slightly due to the stochastic application of the corruptions. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/semi_det.md b/mmdet_code/SR-TOD/docs/en/user_guides/semi_det.md new file mode 100644 index 0000000000000000000000000000000000000000..94ec3d670c86ca1e6843f182d00a0c5bf811f238 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/semi_det.md @@ -0,0 +1,324 @@ +# Semi-supervised Object Detection + +Semi-supervised object detection uses both labeled data and unlabeled data for training. It not only reduces the annotation burden for training high-performance object detectors but also further improves the object detector by using a large number of unlabeled data. + +A typical procedure to train a semi-supervised object detector is as below: + +- [Prepare and split dataset](#Prepare-and-split-dataset) +- [Configure multi-branch pipeline](#Configure-multi-branch-pipeline) +- [Configure semi-supervised dataloader](#Configure-semi-supervised-dataloader) +- [Configure semi-supervised model](#Configure-semi-supervised-model) +- [Configure MeanTeacherHook](#Configure-MeanTeacherHook) +- [Configure TeacherStudentValLoop](#Configure-TeacherStudentValLoop) + +## Prepare and split dataset + +We provide a dataset download script, which downloads the coco2017 dataset by default and decompresses it automatically. + +```shell +python tools/misc/download_dataset.py +``` + +The decompressed dataset directory structure is as below: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +There are two common experimental settings for semi-supervised object detection on the coco2017 dataset: + +(1) Split `train2017` according to a fixed percentage (1%, 2%, 5% and 10%) as a labeled dataset, and the rest of `train2017` as an unlabeled dataset. Because the different splits of `train2017` as labeled datasets will cause significant fluctuation on the accuracy of the semi-supervised detectors, five-fold cross-validation is used in practice to evaluate the algorithm. We provide the dataset split script: + +```shell +python tools/misc/split_coco.py +``` + +By default, the script will split `train2017` according to the labeled data ratio 1%, 2%, 5% and 10%, and each split will be randomly repeated 5 times for cross-validation. The generated semi-supervised annotation file name format is as below: + +- the name format of labeled dataset: `instances_train2017.{fold}@{percent}.json` +- the name format of unlabeled dataset: `instances_train2017.{fold}@{percent}-unlabeled.json` + +Here, `fold` is used for cross-validation, and `percent` represents the ratio of labeled data. The directory structure of the divided dataset is as below: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── semi_anns +│ │ │ ├── instances_train2017.1@1.json +│ │ │ ├── instances_train2017.1@1-unlabeled.json +│ │ │ ├── instances_train2017.1@2.json +│ │ │ ├── instances_train2017.1@2-unlabeled.json +│ │ │ ├── instances_train2017.1@5.json +│ │ │ ├── instances_train2017.1@5-unlabeled.json +│ │ │ ├── instances_train2017.1@10.json +│ │ │ ├── instances_train2017.1@10-unlabeled.json +│ │ │ ├── instances_train2017.2@1.json +│ │ │ ├── instances_train2017.2@1-unlabeled.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +(2) Use `train2017` as the labeled dataset and `unlabeled2017` as the unlabeled dataset. Since `image_info_unlabeled2017.json` does not contain `categories` information, the `CocoDataset` cannot be initialized, so you need to write the `categories` of `instances_train2017.json` into `image_info_unlabeled2017.json` and save it as `instances_unlabeled2017.json`, the relevant script is as below: + +```python +from mmengine.fileio import load, dump + +anns_train = load('instances_train2017.json') +anns_unlabeled = load('image_info_unlabeled2017.json') +anns_unlabeled['categories'] = anns_train['categories'] +dump(anns_unlabeled, 'instances_unlabeled2017.json') +``` + +The processed dataset directory is as below: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_unlabeled2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +## Configure multi-branch pipeline + +There are two main approaches to semi-supervised learning, +[consistency regularization](https://research.nvidia.com/sites/default/files/publications/laine2017iclr_paper.pdf) +and [pseudo label](https://www.researchgate.net/profile/Dong-Hyun-Lee/publication/280581078_Pseudo-Label_The_Simple_and_Efficient_Semi-Supervised_Learning_Method_for_Deep_Neural_Networks/links/55bc4ada08ae092e9660b776/Pseudo-Label-The-Simple-and-Efficient-Semi-Supervised-Learning-Method-for-Deep-Neural-Networks.pdf). +Consistency regularization often requires some careful design, while pseudo label have a simpler form and are easier to extend to downstream tasks. +We adopt a teacher-student joint training semi-supervised object detection framework based on pseudo label, so labeled data and unlabeled data need to configure different data pipeline: + +(1) Pipeline for labeled data: + +```python +# pipeline used to augment labeled data, +# which will be sent to student model for supervised training. +sup_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict(type='MultiBranch', sup=dict(type='PackDetInputs')) +] +``` + +(2) Pipeline for unlabeled data: + +```python +# pipeline used to augment unlabeled data weakly, +# which will be sent to teacher model for predicting pseudo instances. +weak_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data strongly, +# which will be sent to student model for unsupervised training. +strong_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomOrder', + transforms=[ + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='RandAugment', aug_space=geometric, aug_num=1), + ]), + dict(type='RandomErasing', n_patches=(1, 5), ratio=(0, 0.2)), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data into different views +unsup_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadEmptyAnnotations'), + dict( + type='MultiBranch', + unsup_teacher=weak_pipeline, + unsup_student=strong_pipeline, + ) +] +``` + +## Configure semi-supervised dataloader + +(1) Build a semi-supervised dataset. Use `ConcatDataset` to concatenate labeled and unlabeled datasets. + +```python +labeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=sup_pipeline) + +unlabeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_unlabeled2017.json', + data_prefix=dict(img='unlabeled2017/'), + filter_cfg=dict(filter_empty_gt=False), + pipeline=unsup_pipeline) + +train_dataloader = dict( + batch_size=batch_size, + num_workers=num_workers, + persistent_workers=True, + sampler=dict( + type='GroupMultiSourceSampler', + batch_size=batch_size, + source_ratio=[1, 4]), + dataset=dict( + type='ConcatDataset', datasets=[labeled_dataset, unlabeled_dataset])) +``` + +(2) Use multi-source dataset sampler. Use `GroupMultiSourceSampler` to sample data form batches from `labeled_dataset` and `labeled_dataset`, `source_ratio` controls the proportion of labeled data and unlabeled data in the batch. `GroupMultiSourceSampler` also ensures that the images in the same batch have similar aspect ratios. If you don't need to guarantee the aspect ratio of the images in the batch, you can use `MultiSourceSampler`. The sampling diagram of `GroupMultiSourceSampler` is as below: + +
+ +
+ +`sup=1000` indicates that the scale of the labeled dataset is 1000, `sup_h=200` indicates that the scale of the images with an aspect ratio greater than or equal to 1 in the labeled dataset is 200, and `sup_w=800` indicates that the scale of the images with an aspect ratio less than 1 in the labeled dataset is 800, +`unsup=9000` indicates that the scale of the unlabeled dataset is 9000, `unsup_h=1800` indicates that the scale of the images with an aspect ratio greater than or equal to 1 in the unlabeled dataset is 1800, and `unsup_w=7200` indicates the scale of the images with an aspect ratio less than 1 in the unlabeled dataset is 7200. +`GroupMultiSourceSampler` randomly selects a group according to the overall aspect ratio distribution of the images in the labeled dataset and the unlabeled dataset, and then sample data to form batches from the two datasets according to `source_ratio`, so labeled datasets and unlabeled datasets have different repetitions. + +## Configure semi-supervised model + +We choose `Faster R-CNN` as `detector` for semi-supervised training. Take the semi-supervised object detection algorithm `SoftTeacher` as an example, +the model configuration can be inherited from `_base_/models/faster-rcnn_r50_fpn.py`, replacing the backbone network of the detector with `caffe` style. +Note that unlike the supervised training configs, `Faster R-CNN` as `detector` is an attribute of `model`, not `model` . +In addition, `data_preprocessor` needs to be set to `MultiBranchDataPreprocessor`, which is used to pad and normalize images from different pipelines. +Finally, parameters required for semi-supervised training and testing can be configured via `semi_train_cfg` and `semi_test_cfg`. + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', '../_base_/default_runtime.py', + '../_base_/datasets/semi_coco_detection.py' +] + +detector = _base_.model +detector.data_preprocessor = dict( + type='DetDataPreprocessor', + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False, + pad_size_divisor=32) +detector.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=False), + norm_eval=True, + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe')) + +model = dict( + _delete_=True, + type='SoftTeacher', + detector=detector, + data_preprocessor=dict( + type='MultiBranchDataPreprocessor', + data_preprocessor=detector.data_preprocessor), + semi_train_cfg=dict( + freeze_teacher=True, + sup_weight=1.0, + unsup_weight=4.0, + pseudo_label_initial_score_thr=0.5, + rpn_pseudo_thr=0.9, + cls_pseudo_thr=0.9, + reg_pseudo_thr=0.02, + jitter_times=10, + jitter_scale=0.06, + min_pseudo_bbox_wh=(1e-2, 1e-2)), + semi_test_cfg=dict(predict_on='teacher')) +``` + +In addition, we also support semi-supervised training for other detection models, such as `RetinaNet` and `Cascade R-CNN`. Since `SoftTeacher` only supports `Faster R-CNN`, it needs to be replaced with `SemiBaseDetector`, example is as below: + +```python +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', '../_base_/default_runtime.py', + '../_base_/datasets/semi_coco_detection.py' +] + +detector = _base_.model + +model = dict( + _delete_=True, + type='SemiBaseDetector', + detector=detector, + data_preprocessor=dict( + type='MultiBranchDataPreprocessor', + data_preprocessor=detector.data_preprocessor), + semi_train_cfg=dict( + freeze_teacher=True, + sup_weight=1.0, + unsup_weight=1.0, + cls_pseudo_thr=0.9, + min_pseudo_bbox_wh=(1e-2, 1e-2)), + semi_test_cfg=dict(predict_on='teacher')) +``` + +Following the semi-supervised training configuration of `SoftTeacher`, change `batch_size` to 2 and `source_ratio` to `[1, 1]`, the experimental results of supervised and semi-supervised training of `RetinaNet`, `Faster R-CNN`, `Cascade R-CNN` and `SoftTeacher` on the 10% coco `train2017` are as below: + +| Model | Detector | BackBone | Style | sup-0.1-coco mAP | semi-0.1-coco mAP | +| :--------------: | :-----------: | :------: | :---: | :--------------: | :---------------: | +| SemiBaseDetector | RetinaNet | R-50-FPN | caffe | 23.5 | 27.7 | +| SemiBaseDetector | Faster R-CNN | R-50-FPN | caffe | 26.7 | 28.4 | +| SemiBaseDetector | Cascade R-CNN | R-50-FPN | caffe | 28.0 | 29.7 | +| SoftTeacher | Faster R-CNN | R-50-FPN | caffe | 26.7 | 31.1 | + +## Configure MeanTeacherHook + +Usually, the teacher model is updated by Exponential Moving Average (EMA) the student model, and then the teacher model is optimized with the optimization of the student model, which can be achieved by configuring `custom_hooks`: + +```python +custom_hooks = [dict(type='MeanTeacherHook')] +``` + +## Configure TeacherStudentValLoop + +Since there are two models in the teacher-student joint training framework, we can replace `ValLoop` with `TeacherStudentValLoop` to test the accuracy of both models during the training process. + +```python +val_cfg = dict(type='TeacherStudentValLoop') +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/single_stage_as_rpn.md b/mmdet_code/SR-TOD/docs/en/user_guides/single_stage_as_rpn.md new file mode 100644 index 0000000000000000000000000000000000000000..93a48dd7c5c26ebebac417370737e80032bc63ee --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/single_stage_as_rpn.md @@ -0,0 +1,176 @@ +# Use a single stage detector as RPN + +Region proposal network (RPN) is a submodule in [Faster R-CNN](https://arxiv.org/abs/1506.01497), which generates proposals for the second stage of Faster R-CNN. Most two-stage detectors in MMDetection use [`RPNHead`](../../../mmdet/models/dense_heads/rpn_head.py) to generate proposals as RPN. However, any single-stage detector can serve as an RPN since their bounding box predictions can also be regarded as region proposals and thus be refined in the R-CNN. Therefore, MMDetection v3.0 supports that. + +To illustrate the whole process, here we give an example of how to use an anchor-free single-stage model [FCOS](../../../configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py) as an RPN in [Faster R-CNN](../../../configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py). + +The outline of this tutorial is as below: + +1. Use `FCOSHead` as an `RPNHead` in Faster R-CNN +2. Evaluate proposals +3. Train the customized Faster R-CNN with pre-trained FCOS + +## Use `FCOSHead` as an `RPNHead` in Faster R-CNN + +To set `FCOSHead` as an `RPNHead` in Faster R-CNN, we should create a new config file named `configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py`, and replace with the setting of `rpn_head` with the setting of `bbox_head` in `configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py`. Besides, we still use the neck setting of FCOS with strides of `[8, 16, 32, 64, 128]`, and update `featmap_strides` of `bbox_roi_extractor` to `[8, 16, 32, 64, 128]`. To avoid loss goes NAN, we apply warmup during the first 1000 iterations instead of the first 500 iterations, which means that the lr increases more slowly. The config is as follows: + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +model = dict( + # copied from configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py + neck=dict( + start_level=1, + add_extra_convs='on_output', # use P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # ignore the unused old settings + type='FCOSHead', + num_classes=1, # num_classes = 1 for rpn, if num_classes > 1, it will be set to 1 in TwoStageDetector automatically + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + roi_head=dict( # update featmap_strides due to the strides in neck + bbox_roi_extractor=dict(featmap_strides=[8, 16, 32, 64, 128]))) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), # Slowly increase lr, otherwise loss becomes NAN + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[8, 11], + gamma=0.1) +] +``` + +Then, we could use the following command to train our customized model. For more training commands, please refer to [here](train.md). + +```python +# training with 8 GPUS +bash tools/dist_train.sh configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py \ + 8 \ + --work-dir ./work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco +``` + +## Evaluate proposals + +The quality of proposals is of great importance to the performance of detector, therefore, we also provide a way to evaluate proposals. Same as above, create a new config file named `configs/rpn/fcos-rpn_r50_fpn_1x_coco.py`, and replace with setting of `rpn_head` with the setting of `bbox_head` in `configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py`. + +```python +_base_ = [ + '../_base_/models/rpn_r50_fpn.py', '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +val_evaluator = dict(metric='proposal_fast') +test_evaluator = val_evaluator + +model = dict( + # copied from configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py + neck=dict( + start_level=1, + add_extra_convs='on_output', # use P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # ignore the unused old settings + type='FCOSHead', + num_classes=1, # num_classes = 1 for rpn, if num_classes > 1, it will be set to 1 in RPN automatically + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) +``` + +Suppose we have the checkpoint `./work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco/epoch_12.pth` after training, then we can evaluate the quality of proposals with the following command. + +```python +# testing with 8 GPUs +bash tools/dist_test.sh \ + configs/rpn/fcos-rpn_r50_fpn_1x_coco.py \ + ./work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco/epoch_12.pth \ + 8 +``` + +## Train the customized Faster R-CNN with pre-trained FCOS + +Pre-training not only speeds up convergence of training, but also improves the performance of the detector. Therefore, here we give an example to illustrate how to do use a pre-trained FCOS as an RPN to accelerate training and improve the accuracy. Suppose we want to use `FCOSHead` as an rpn head in Faster R-CNN and train with the pre-trained [`fcos_r50-caffe_fpn_gn-head_1x_coco`](https://download.openmmlab.com/mmdetection/v2.0/fcos/fcos_r50_caffe_fpn_gn-head_1x_coco/fcos_r50_caffe_fpn_gn-head_1x_coco-821213aa.pth). The content of config file named `configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco.py` is as the following. Note that `fcos_r50-caffe_fpn_gn-head_1x_coco` uses a caffe version of ResNet50, the pixel mean and std in `data_preprocessor` thus need to be updated. + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +model = dict( + data_preprocessor=dict( + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False), + backbone=dict( + norm_cfg=dict(type='BN', requires_grad=False), + style='caffe', + init_cfg=None), # the checkpoint in ``load_from`` contains the weights of backbone + neck=dict( + start_level=1, + add_extra_convs='on_output', # use P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # ignore the unused old settings + type='FCOSHead', + num_classes=1, # num_classes = 1 for rpn, if num_classes > 1, it will be set to 1 in TwoStageDetector automatically + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + roi_head=dict( # update featmap_strides due to the strides in neck + bbox_roi_extractor=dict(featmap_strides=[8, 16, 32, 64, 128]))) + +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/fcos/fcos_r50_caffe_fpn_gn-head_1x_coco/fcos_r50_caffe_fpn_gn-head_1x_coco-821213aa.pth' +``` + +The command for training is as below. + +```python +bash tools/dist_train.sh \ + configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco.py \ + 8 \ + --work-dir ./work_dirs/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/test.md b/mmdet_code/SR-TOD/docs/en/user_guides/test.md new file mode 100644 index 0000000000000000000000000000000000000000..a7855e10ec73126c0e48012e7f77d4f8355899fd --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/test.md @@ -0,0 +1,303 @@ +# Test existing models on standard datasets + +To evaluate a model's accuracy, one usually tests the model on some standard datasets, please refer to [dataset prepare guide](dataset_prepare.md) to prepare the dataset. + +This section will show how to test existing models on supported datasets. + +## Test existing models + +We provide testing scripts for evaluating an existing model on the whole dataset (COCO, PASCAL VOC, Cityscapes, etc.). +The following testing environments are supported: + +- single GPU +- CPU +- single node multiple GPUs +- multiple nodes + +Choose the proper script to perform testing depending on the testing environment. + +```shell +# Single-gpu testing +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# CPU: disable GPUs and run single-gpu testing script +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# Multi-gpu testing +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--out ${RESULT_FILE}] +``` + +`tools/dist_test.sh` also supports multi-node testing, but relies on PyTorch's [launch utility](https://pytorch.org/docs/stable/distributed.html#launch-utility). + +Optional arguments: + +- `RESULT_FILE`: Filename of the output results in pickle format. If not specified, the results will not be saved to a file. +- `--show`: If specified, detection results will be plotted on the images and shown in a new window. It is only applicable to single GPU testing and used for debugging and visualization. Please make sure that GUI is available in your environment. Otherwise, you may encounter an error like `cannot connect to X server`. +- `--show-dir`: If specified, detection results will be plotted on the images and saved to the specified directory. It is only applicable to single GPU testing and used for debugging and visualization. You do NOT need a GUI available in your environment for using this option. +- `--work-dir`: If specified, detection results containing evaluation metrics will be saved to the specified directory. +- `--cfg-options`: If specified, the key-value pair optional cfg will be merged into config file + +## Examples + +Assuming that you have already downloaded the checkpoints to the directory `checkpoints/`. + +1. Test RTMDet and visualize the results. Press any key for the next image. + Config and checkpoint files are available [here](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet). + + ```shell + python tools/test.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --show + ``` + +2. Test RTMDet and save the painted images for future visualization. + Config and checkpoint files are available [here](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet). + + ```shell + python tools/test.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --show-dir faster_rcnn_r50_fpn_1x_results + ``` + +3. Test Faster R-CNN on PASCAL VOC (without saving the test results). + Config and checkpoint files are available [here](../../../configs/pascal_voc). + + ```shell + python tools/test.py \ + configs/pascal_voc/faster-rcnn_r50_fpn_1x_voc0712.py \ + checkpoints/faster_rcnn_r50_fpn_1x_voc0712_20200624-c9895d40.pth + ``` + +4. Test Mask R-CNN with 8 GPUs, and evaluate. + Config and checkpoint files are available [here](../../../configs/mask_rcnn). + + ```shell + ./tools/dist_test.sh \ + configs/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 \ + --out results.pkl + ``` + +5. Test Mask R-CNN with 8 GPUs, and evaluate the metric **class-wise**. + Config and checkpoint files are available [here](../../../configs/mask_rcnn). + + ```shell + ./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 \ + --out results.pkl \ + --cfg-options test_evaluator.classwise=True + ``` + +6. Test Mask R-CNN on COCO test-dev with 8 GPUs, and generate JSON files for submitting to the official evaluation server. + Config and checkpoint files are available [here](../../../configs/mask_rcnn). + + Replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in [config](../../../configs/_base_/datasets/coco_instance.py) and run: + + ```shell + ./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 + ``` + + This command generates two JSON files `./work_dirs/coco_instance/test.bbox.json` and `./work_dirs/coco_instance/test.segm.json`. + +7. Test Mask R-CNN on Cityscapes test with 8 GPUs, and generate txt and png files for submitting to the official evaluation server. + Config and checkpoint files are available [here](../../../configs/cityscapes). + + Replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in [config](../../../configs/_base_/datasets/cityscapes_instance.py) and run: + + ```shell + ./tools/dist_test.sh \ + configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py \ + checkpoints/mask_rcnn_r50_fpn_1x_cityscapes_20200227-afe51d5a.pth \ + 8 + ``` + + The generated png and txt would be under `./work_dirs/cityscapes_metric/` directory. + +## Test without Ground Truth Annotations + +MMDetection supports to test models without ground-truth annotations using `CocoDataset`. If your dataset format is not in COCO format, please convert them to COCO format. For example, if your dataset format is VOC, you can directly convert it to COCO format by the [script in tools.](../../../tools/dataset_converters/pascal_voc.py) If your dataset format is Cityscapes, you can directly convert it to COCO format by the [script in tools.](../../../tools/dataset_converters/cityscapes.py) The rest of the formats can be converted using [this script](../../../tools/dataset_converters/images2coco.py). + +```shel +python tools/dataset_converters/images2coco.py \ + ${IMG_PATH} \ + ${CLASSES} \ + ${OUT} \ + [--exclude-extensions] +``` + +arguments: + +- `IMG_PATH`: The root path of images. +- `CLASSES`: The text file with a list of categories. +- `OUT`: The output annotation json file name. The save dir is in the same directory as `IMG_PATH`. +- `exclude-extensions`: The suffix of images to be excluded, such as 'png' and 'bmp'. + +After the conversion is complete, you need to replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in [config](../../../configs/_base_/datasets/coco_detection.py)(find which dataset in 'configs/_base_/datasets' the current config corresponds to) and run: + +```shell +# Single-gpu testing +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--show] + +# CPU: disable GPUs and run single-gpu testing script +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# Multi-gpu testing +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--show] +``` + +Assuming that the checkpoints in the [model zoo](https://mmdetection.readthedocs.io/en/latest/modelzoo_statistics.html) have been downloaded to the directory `checkpoints/`, we can test Mask R-CNN on COCO test-dev with 8 GPUs, and generate JSON files using the following command. + +```sh +./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 +``` + +This command generates two JSON files `./work_dirs/coco_instance/test.bbox.json` and `./work_dirs/coco_instance/test.segm.json`. + +## Batch Inference + +MMDetection supports inference with a single image or batched images in test mode. By default, we use single-image inference and you can use batch inference by modifying `samples_per_gpu` in the config of test data. You can do that either by modifying the config as below. + +```shell +data = dict(train_dataloader=dict(...), val_dataloader=dict(...), test_dataloader=dict(batch_size=2, ...)) +``` + +Or you can set it through `--cfg-options` as `--cfg-options test_dataloader.batch_size=2` + +## Test Time Augmentation (TTA) + +Test time augmentation (TTA) is a data augmentation strategy used during the test phase. It applies different augmentations, such as flipping and scaling, to the same image for model inference, and then merges the predictions of each augmented image to obtain more accurate predictions. To make it easier for users to use TTA, MMEngine provides [BaseTTAModel](https://mmengine.readthedocs.io/en/latest/api/generated/mmengine.model.BaseTTAModel.html#mmengine.model.BaseTTAModel) class, which allows users to implement different TTA strategies by simply extending the BaseTTAModel class according to their needs. + +In MMDetection, we provides [DetTTAModel](../../../mmdet/models/test_time_augs/det_tta.py) class, which inherits from BaseTTAModel. + +### Use case + +Using TTA requires two steps. First, you need to add `tta_model` and `tta_pipeline` in the configuration file: + +```shell +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict( + type='nms', + iou_threshold=0.5), + max_per_img=100)) + +tta_pipeline = [ + dict(type='LoadImageFromFile', + backend_args=None), + dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=(1333, 800), keep_ratio=True) + ], [ # It uses 2 flipping transformations (flipping and not flipping). + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ]])] +``` + +Second, set `--tta` when running the test scripts as examples below: + +```shell +# Single-gpu testing +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--tta] + +# CPU: disable GPUs and run single-gpu testing script +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--tta] + +# Multi-gpu testing +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--tta] +``` + +You can also modify the TTA config by yourself, such as adding scaling enhancement: + +```shell +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict( + type='nms', + iou_threshold=0.5), + max_per_img=100)) + +img_scales = [(1333, 800), (666, 400), (2000, 1200)] +tta_pipeline = [ + dict(type='LoadImageFromFile', + backend_args=None), + dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=s, keep_ratio=True) for s in img_scales + ], [ + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ]])] +``` + +The above data augmentation pipeline will first perform 3 multi-scaling transformations on the image, followed by 2 flipping transformations (flipping and not flipping). Finally, the image is packaged into the final result using PackDetInputs. + +Here are more TTA use cases for your reference: + +- [RetinaNet](../../../configs/retinanet/retinanet_tta.py) +- [CenterNet](../../../configs/centernet/centernet_tta.py) +- [YOLOX](../../../configs/rtmdet/rtmdet_tta.py) +- [RTMDet](../../../configs/yolox/yolox_tta.py) + +For more advanced usage and data flow of TTA, please refer to [MMEngine](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/test_time_augmentation.html#data-flow). We will support instance segmentation TTA latter. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/test_results_submission.md b/mmdet_code/SR-TOD/docs/en/user_guides/test_results_submission.md new file mode 100644 index 0000000000000000000000000000000000000000..721347ea1e9b7d3d50dc3b64d9adec7eda19d2ae --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/test_results_submission.md @@ -0,0 +1,182 @@ +# Test Results Submission + +## Panoptic segmentation test results submission + +The following sections introduce how to produce the prediction results of panoptic segmentation models on the COCO test-dev set and submit the predictions to [COCO evaluation server](https://competitions.codalab.org/competitions/19507). + +### Prerequisites + +- Download [COCO test dataset images](http://images.cocodataset.org/zips/test2017.zip), [testing image info](http://images.cocodataset.org/annotations/image_info_test2017.zip), and [panoptic train/val annotations](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip), then unzip them, put 'test2017' to `data/coco/`, put json files and annotation files to `data/coco/annotations/`. + +```shell +# suppose data/coco/ does not exist +mkdir -pv data/coco/ + +# download test2017 +wget -P data/coco/ http://images.cocodataset.org/zips/test2017.zip +wget -P data/coco/ http://images.cocodataset.org/annotations/image_info_test2017.zip +wget -P data/coco/ http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip + +# unzip them +unzip data/coco/test2017.zip -d data/coco/ +unzip data/coco/image_info_test2017.zip -d data/coco/ +unzip data/coco/panoptic_annotations_trainval2017.zip -d data/coco/ + +# remove zip files (optional) +rm -rf data/coco/test2017.zip data/coco/image_info_test2017.zip data/coco/panoptic_annotations_trainval2017.zip +``` + +- Run the following code to update category information in testing image info. Since the attribute `isthing` is missing in category information of 'image_info_test-dev2017.json', we need to update it with the category information in 'panoptic_val2017.json'. + +```shell +python tools/misc/gen_coco_panoptic_test_info.py data/coco/annotations +``` + +After completing the above preparations, your directory structure of `data` should be like this: + +```text +data +`-- coco + |-- annotations + | |-- image_info_test-dev2017.json + | |-- image_info_test2017.json + | |-- panoptic_image_info_test-dev2017.json + | |-- panoptic_train2017.json + | |-- panoptic_train2017.zip + | |-- panoptic_val2017.json + | `-- panoptic_val2017.zip + `-- test2017 +``` + +### Inference on coco test-dev + +To do inference on coco test-dev, we should update the setting of `test_dataloder` and `test_evaluator` first. There two ways to do this: 1. update them in config file; 2. update them in command line. + +#### Update them in config file + +The relevant settings are provided at the end of `configs/_base_/datasets/coco_panoptic.py`, as below. + +```python +test_dataloader = dict( + batch_size=1, + num_workers=1, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/panoptic_image_info_test-dev2017.json', + data_prefix=dict(img='test2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_evaluator = dict( + type='CocoPanopticMetric', + format_only=True, + ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', + outfile_prefix='./work_dirs/coco_panoptic/test') +``` + +Any of the following way can be used to update the setting for inference on coco test-dev set. + +Case 1: Directly uncomment the setting in `configs/_base_/datasets/coco_panoptic.py`. + +Case 2: Copy the following setting to the config file you used now. + +```python +test_dataloader = dict( + dataset=dict( + ann_file='annotations/panoptic_image_info_test-dev2017.json', + data_prefix=dict(img='test2017/', _delete_=True))) +test_evaluator = dict( + format_only=True, + ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', + outfile_prefix='./work_dirs/coco_panoptic/test') +``` + +Then infer on coco test-dev et by the following command. + +```shell +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} +``` + +#### Update them in command line + +The command for update of the related settings and inference on coco test-dev are as below. + +```shell +# test with single gpu +CUDA_VISIBLE_DEVICES=0 python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results + +# test with four gpus +CUDA_VISIBLE_DEVICES=0,1,3,4 bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + 8 \ # eights gpus + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results + +# test with slurm +GPUS=8 tools/slurm_test.sh \ + ${Partition} \ + ${JOB_NAME} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results +``` + +Example + +Suppose we perform inference on `test2017` using pretrained MaskFormer with ResNet-50 backbone. + +```shell +# test with single gpu +CUDA_VISIBLE_DEVICES=0 python tools/test.py \ + configs/maskformer/maskformer_r50_mstrain_16x1_75e_coco.py \ + checkpoints/maskformer_r50_mstrain_16x1_75e_coco_20220221_141956-bc2699cb.pth \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=work_dirs/maskformer/results +``` + +### Rename files and zip results + +After inference, the panoptic segmentation results (a json file and a directory where the masks are stored) will be in `WORK_DIR`. We should rename them according to the naming convention described on [COCO's Website](https://cocodataset.org/#upload). Finally, we need to compress the json and the directory where the masks are stored into a zip file, and rename the zip file according to the naming convention. Note that the zip file should **directly** contains the above two files. + +The commands to rename files and zip results: + +```shell +# In WORK_DIR, we have panoptic segmentation results: 'panoptic' and 'results.panoptic.json'. +cd ${WORK_DIR} + +# replace '[algorithm_name]' with the name of algorithm you used. +mv ./panoptic ./panoptic_test-dev2017_[algorithm_name]_results +mv ./results.panoptic.json ./panoptic_test-dev2017_[algorithm_name]_results.json +zip panoptic_test-dev2017_[algorithm_name]_results.zip -ur panoptic_test-dev2017_[algorithm_name]_results panoptic_test-dev2017_[algorithm_name]_results.json +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/tracking_analysis_tools.md b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_analysis_tools.md new file mode 100644 index 0000000000000000000000000000000000000000..acced58d47baa6d73227ab7b5b267c2ae84623eb --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_analysis_tools.md @@ -0,0 +1,86 @@ +**We provide lots of useful tools under the `tools/` directory.** + +## MOT Test-time Parameter Search + +`tools/analysis_tools/mot/mot_param_search.py` can search the parameters of the `tracker` in MOT models. +It is used as the same manner with `tools/test.py` but **different** in the configs. + +Here is an example that shows how to modify the configs: + +1. Define the desirable evaluation metrics to record. + + For example, you can define the `evaluator` as + + ```python + test_evaluator=dict(type='MOTChallengeMetrics', metric=['HOTA', 'CLEAR', 'Identity']) + ``` + + Of course, you can also customize the content of `metric` in `test_evaluator`. You are free to choose one or more of `['HOTA', 'CLEAR', 'Identity']`. + +2. Define the parameters and the values to search. + + Assume you have a tracker like + + ```python + model=dict( + tracker=dict( + type='BaseTracker', + obj_score_thr=0.5, + match_iou_thr=0.5 + ) + ) + ``` + + If you want to search the parameters of the tracker, just change the value to a list as follow + + ```python + model=dict( + tracker=dict( + type='BaseTracker', + obj_score_thr=[0.4, 0.5, 0.6], + match_iou_thr=[0.4, 0.5, 0.6, 0.7] + ) + ) + ``` + + Then the script will test the totally 12 cases and log the results. + +## MOT Error Visualize + +`tools/analysis_tools/mot/mot_error_visualize.py` can visualize errors for multiple object tracking. +This script needs the result of inference. By Default, the **red** bounding box denotes false positive, the **yellow** bounding box denotes the false negative and the **blue** bounding box denotes ID switch. + +``` +python tools/analysis_tools/mot/mot_error_visualize.py \ + ${CONFIG_FILE}\ + --input ${INPUT} \ + --result-dir ${RESULT_DIR} \ + [--output-dir ${OUTPUT}] \ + [--fps ${FPS}] \ + [--show] \ + [--backend ${BACKEND}] +``` + +The `RESULT_DIR` contains the inference results of all videos and the inference result is a `txt` file. + +Optional arguments: + +- `OUTPUT`: Output of the visualized demo. If not specified, the `--show` is obligate to show the video on the fly. +- `FPS`: FPS of the output video. +- `--show`: Whether show the video on the fly. +- `BACKEND`: The backend to visualize the boxes. Options are `cv2` and `plt`. + +## Browse dataset + +`tools/analysis_tools/mot/browse_dataset.py` can visualize the training dataset to check whether the dataset configuration is correct. + +**Examples:** + +```shell +python tools/analysis_tools/browse_dataset.py ${CONFIG_FILE} [--show-interval ${SHOW_INTERVAL}] +``` + +Optional arguments: + +- `SHOW_INTERVAL`: The interval of show (s). +- `--show`: Whether show the images on the fly. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/tracking_config.md b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_config.md new file mode 100644 index 0000000000000000000000000000000000000000..fa8aeea04f8ad1337b67ae50bbdd92b6dfbb1cdc --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_config.md @@ -0,0 +1,112 @@ +# Learn about Configs + +We use python files as our config system. You can find all the provided configs under $MMDetection/configs. + +We incorporate modular and inheritance design into our config system, +which is convenient to conduct various experiments. +If you wish to inspect the config file, +you may run `python tools/misc/print_config.py /PATH/TO/CONFIG` to see the complete config. + +## A brief description of a complete config + +A complete config usually contains the following primary fields: + +- `model`: the basic config of model, which may contain `data_preprocessor`, modules (e.g., `detector`, `motion`),`train_cfg`, `test_cfg`, etc. +- `train_dataloader`: the config of training dataloader, which usually contains `batch_size`, `num_workers`, `sampler`, `dataset`, etc. +- `val_dataloader`: the config of validation dataloader, which is similar with `train_dataloader`. +- `test_dataloader`: the config of testing dataloader, which is similar with `train_dataloader`. +- `val_evaluator`: the config of validation evaluator. For example,`type='MOTChallengeMetrics'` for MOT task on the MOTChallenge benchmarks. +- `test_evaluator`: the config of testing evaluator, which is similar with `val_evaluator`. +- `train_cfg`: the config of training loop. For example, `type='EpochBasedTrainLoop'`. +- `val_cfg`: the config of validation loop. For example, `type='VideoValLoop'`. +- `test_cfg`: the config of testing loop. For example, `type='VideoTestLoop'`. +- `default_hooks`: the config of default hooks, which may include hooks for timer, logger, param_scheduler, checkpoint, sampler_seed, visualization, etc. +- `vis_backends`: the config of visualization backends, which uses `type='LocalVisBackend'` as default. +- `visualizer`: the config of visualizer. `type='TrackLocalVisualizer'` for MOT tasks. +- `param_scheduler`: the config of parameter scheduler, which usually sets the learning rate scheduler. +- `optim_wrapper`: the config of optimizer wrapper, which contains optimization-related information, for example optimizer, gradient clipping, etc. +- `load_from`: load models as a pre-trained model from a given path. +- `resume`: If `True`, resume checkpoints from `load_from`, and the training will be resumed from the epoch when the checkpoint is saved. + +## Modify config through script arguments + +When submitting jobs using `tools/train.py` or `tools/test_tracking.py`, +you may specify `--cfg-options` to in-place modify the config. +We present several examples as follows. +For more details, please refer to [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/config.md). + +- **Update config keys of dict chains.** + + The config options can be specified following the order of the dict keys in the original config. + For example, `--cfg-options model.detector.backbone.norm_eval=False` changes the all BN modules in model backbones to train mode. + +- **Update keys inside a list of configs.** + + Some config dicts are composed as a list in your config. + For example, the testing pipeline `test_dataloader.dataset.pipeline` is normally a list e.g. `[dict(type='LoadImageFromFile'), ...]`. + If you want to change `LoadImageFromFile` to `LoadImageFromWebcam` in the pipeline, + you may specify `--cfg-options test_dataloader.dataset.pipeline.0.type=LoadImageFromWebcam`. + +- **Update values of list/tuples.** + + Maybe the value to be updated is a list or a tuple. + For example, you can change the key `mean` of `data_preprocessor` by specifying `--cfg-options model.data_preprocessor.mean=[0,0,0]`. + Note that **NO** white space is allowed inside the specified value. + +## Config File Structure + +There are 3 basic component types under `config/_base_`, i.e., dataset, model and default_runtime. +Many methods could be easily constructed with one of each like SORT, DeepSORT. +The configs that are composed by components from `_base_` are called *primitive*. + +For all configs under the same folder, it is recommended to have only **one** *primitive* config. +All other configs should inherit from the *primitive* config. +In this way, the maximum of inheritance level is 3. + +For easy understanding, we recommend contributors to inherit from exiting methods. +For example, if some modification is made base on Faster R-CNN, +user may first inherit the basic Faster R-CNN structure +by specifying `_base_ = ../_base_/models/faster-rcnn_r50-dc5.py`, +then modify the necessary fields in the config files. + +If you are building an entirely new method that does not share the structure with any of the existing methods, +you may create a folder `method_name` under `configs`. + +Please refer to [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/config.md) for detailed documentation. + +## Config Name Style + +We follow the below style to name config files. Contributors are advised to follow the same style. + +```shell +{method}_{module}_{train_cfg}_{train_data}_{test_data} +``` + +- `{method}`: method name, like `sort`. +- `{module}`: basic modules of the method, like `faster-rcnn_r50_fpn`. +- `{train_cfg}`: training config which usually contains batch size, epochs, etc, like `8xb4-80e`. +- `{train_data}`: training data, like `mot17halftrain`. +- `{test_data}`: testing data, like `test-mot17halfval`. + +## FAQ + +**Ignore some fields in the base configs** + +Sometimes, you may set `_delete_=True` to ignore some of fields in base configs. +You may refer to [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/config.md) for simple illustration. + +## Tracking Data Structure Introduction + +### Advantages and new features + +In mmdetection tracking task, we employ videos to organize the dataset and use +TrackDataSample to descirbe dataset info. + +- Based on video organization, we provide transform `UniformRefFrameSample` to sample key frames and ref frames and use `TransformBroadcaster` for for clip training. +- TrackDataSample can be viewd as a wrapper of multiple DetDataSample to some extent. It contains a property `video_data_samples` which is a list of DetDataSample, each of which corresponds to a single frame. In addition, it's metainfo includes key_frames_inds and ref_frames_inds to apply clip training way. +- Thanks to video-based data organization, the entire video can be directly tested. This way is more concise and intuitive. We also provide image_based test method, if your GPU mmemory cannot fit the entire video. + +### TODO + +- Some algorithms like StrongSORT, Mask2Former can not support video_based testing. These algorithms pose a challenge to GPU memory. we will optimize this problem in the future. +- Now we do not support joint training of video_based dataset like MOT Challenge Dataset and image_based dataset like Crowdhuman for the algorithm QDTrack. we will optimize this problem in the future. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/tracking_dataset_prepare.md b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_dataset_prepare.md new file mode 100644 index 0000000000000000000000000000000000000000..2c38569c9a13d367d6472a21c48b88b52bff1a82 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_dataset_prepare.md @@ -0,0 +1,247 @@ +## Dataset Preparation + +This page provides the instructions for dataset preparation on existing benchmarks, include + +- Multiple Object Tracking + + - [MOT Challenge](https://motchallenge.net/) + - [CrowdHuman](https://www.crowdhuman.org/) + +- Video Instance Segmentation + + - [YouTube-VIS](https://youtube-vos.org/dataset/vis/) + +### 1. Download Datasets + +Please download the datasets from the official websites. It is recommended to symlink the root of the datasets to `$MMDETECTION/data`. + +#### 1.1 Multiple Object Tracking + +- For the training and testing of multi object tracking task, one of the MOT Challenge datasets (e.g. MOT17, MOT20) are needed, CrowdHuman can be served as comlementary dataset. + +- For users in China, the following datasets can be downloaded from [OpenDataLab](https://opendatalab.com/) with high speed: + + - [MOT17](https://opendatalab.com/MOT17/download) + - [MOT20](https://opendatalab.com/MOT20/download) + - [CrowdHuman](https://opendatalab.com/CrowdHuman/download) + +#### 1.2 Video Instance Segmentation + +- For the training and testing of video instance segmetatioon task, only one of YouTube-VIS datasets (e.g. YouTube-VIS 2019, YouTube-VIS 2021) is needed. + +- YouTube-VIS 2019 dataset can be download from [YouTubeVOS](https://codalab.lisn.upsaclay.fr/competitions/6064) + +- YouTube-VIS 2021 dataset can be download from [YouTubeVOS](https://codalab.lisn.upsaclay.fr/competitions/7680) + +#### 1.3 Data Structure + +If your folder structure is different from the following, you may need to change the corresponding paths in config files. + +``` +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── annotations +│ │ +| ├── MOT15/MOT16/MOT17/MOT20 +| | ├── train +| | | ├── MOT17-02-DPM +| | | | ├── det +| │ │ │ ├── gt +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── test +| | | ├── MOT17-01-DPM +| | | | ├── det +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +│ │ +│ ├── crowdhuman +│ │ ├── annotation_train.odgt +│ │ ├── annotation_val.odgt +│ │ ├── train +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_train01.zip +│ │ │ ├── CrowdHuman_train02.zip +│ │ │ ├── CrowdHuman_train03.zip +│ │ ├── val +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_val.zip +│ │ +``` + +### 2. Convert Annotations + +In this case, you need to convert the official annotations to coco style. We provide scripts and the usages are as following: + +```shell +# MOT17 +# The processing of other MOT Challenge dataset is the same as MOT17 +python ./tools/dataset_converters/mot2coco.py -i ./data/MOT17/ -o ./data/MOT17/annotations --split-train --convert-det +python ./tools/dataset_converters/mot2reid.py -i ./data/MOT17/ -o ./data/MOT17/reid --val-split 0.2 --vis-threshold 0.3 + +# CrowdHuman +python ./tools/dataset_converters/crowdhuman2coco.py -i ./data/crowdhuman -o ./data/crowdhuman/annotations + +# YouTube-VIS 2019 +python ./tools/dataset_converters/youtubevis/youtubevis2coco.py -i ./data/youtube_vis_2019 -o ./data/youtube_vis_2019/annotations --version 2019 + +# YouTube-VIS 2021 +python ./tools/dataset_converters/youtubevis/youtubevis2coco.py -i ./data/youtube_vis_2021 -o ./data/youtube_vis_2021/annotations --version 2021 + +``` + +The folder structure will be as following after your run these scripts: + +``` +mmdetection +├── mmtrack +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── annotations +│ │ +| ├── MOT15/MOT16/MOT17/MOT20 +| | ├── train +| | | ├── MOT17-02-DPM +| | | | ├── det +| │ │ │ ├── gt +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── test +| | | ├── MOT17-01-DPM +| | | | ├── det +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── annotations +| | ├── reid +│ │ │ ├── imgs +│ │ │ ├── meta +│ │ +│ ├── crowdhuman +│ │ ├── annotation_train.odgt +│ │ ├── annotation_val.odgt +│ │ ├── train +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_train01.zip +│ │ │ ├── CrowdHuman_train02.zip +│ │ │ ├── CrowdHuman_train03.zip +│ │ ├── val +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_val.zip +│ │ ├── annotations +│ │ │ ├── crowdhuman_train.json +│ │ │ ├── crowdhuman_val.json +│ │ +│ ├── youtube_vis_2019 +│ │ │── train +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── valid +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── test +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── train.json (the official annotation files) +│ │ │── valid.json (the official annotation files) +│ │ │── test.json (the official annotation files) +│ │ │── annotations (the converted annotation file) +│ │ +│ ├── youtube_vis_2021 +│ │ │── train +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── valid +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── test +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── annotations (the converted annotation file) +``` + +#### The folder of annotations and reid in MOT15/MOT16/MOT17/MOT20 + +We take MOT17 dataset as examples, the other datasets share similar structure. + +There are 8 JSON files in `data/MOT17/annotations`: + +`train_cocoformat.json`: JSON file containing the annotations information of the training set in MOT17 dataset. + +`train_detections.pkl`: Pickle file containing the public detections of the training set in MOT17 dataset. + +`test_cocoformat.json`: JSON file containing the annotations information of the testing set in MOT17 dataset. + +`test_detections.pkl`: Pickle file containing the public detections of the testing set in MOT17 dataset. + +`half-train_cocoformat.json`, `half-train_detections.pkl`, `half-val_cocoformat.json`and `half-val_detections.pkl` share similar meaning with `train_cocoformat.json` and `train_detections.pkl`. The `half` means we split each video in the training set into half. The first half videos are denoted as `half-train` set, and the second half videos are denoted as`half-val` set. + +The structure of `data/MOT17/reid` is as follows: + +``` +reid +├── imgs +│ ├── MOT17-02-FRCNN_000002 +│ │ ├── 000000.jpg +│ │ ├── 000001.jpg +│ │ ├── ... +│ ├── MOT17-02-FRCNN_000003 +│ │ ├── 000000.jpg +│ │ ├── 000001.jpg +│ │ ├── ... +├── meta +│ ├── train_80.txt +│ ├── val_20.txt +``` + +The `80` in `train_80.txt` means the proportion of the training dataset to the whole ReID dataset is 80%. While the proportion of the validation dataset is 20%. + +For training, we provide a annotation list `train_80.txt`. Each line of the list contains a filename and its corresponding ground-truth labels. The format is as follows: + +``` +MOT17-05-FRCNN_000110/000018.jpg 0 +MOT17-13-FRCNN_000146/000014.jpg 1 +MOT17-05-FRCNN_000088/000004.jpg 2 +MOT17-02-FRCNN_000009/000081.jpg 3 +``` + +`MOT17-05-FRCNN_000110` denotes the 110-th person in `MOT17-05-FRCNN` video. + +For validation, The annotation list `val_20.txt` remains the same as format above. + +Images in `reid/imgs` are cropped from raw images in `MOT17/train` by the corresponding `gt.txt`. The value of ground-truth labels should fall in range `[0, num_classes - 1]`. + +#### The folder of annotations in crowdhuman + +There are 2 JSON files in `data/crowdhuman/annotations`: + +`crowdhuman_train.json`: JSON file containing the annotations information of the training set in CrowdHuman dataset. +`crowdhuman_val.json`: JSON file containing the annotations information of the validation set in CrowdHuman dataset. + +#### The folder of annotations in youtube_vis_2019/youtube_vis2021 + +There are 3 JSON files in `data/youtube_vis_2019/annotations` or `data/youtube_vis_2021/annotations`: + +`youtube_vis_2019_train.json`/`youtube_vis_2021_train.json`: JSON file containing the annotations information of the training set in youtube_vis_2019/youtube_vis2021 dataset. + +`youtube_vis_2019_valid.json`/`youtube_vis_2021_valid.json`: JSON file containing the annotations information of the validation set in youtube_vis_2019/youtube_vis2021 dataset. + +`youtube_vis_2019_test.json`/`youtube_vis_2021_test.json`: JSON file containing the annotations information of the testing set in youtube_vis_2019/youtube_vis2021 dataset. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/tracking_inference.md b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_inference.md new file mode 100644 index 0000000000000000000000000000000000000000..06a6912acf649ea9c02db25901260233cf99b697 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_inference.md @@ -0,0 +1,55 @@ +# Inference + +We provide demo scripts to inference a given video or a folder that contains continuous images. The source codes are available [here](https://github.com/open-mmlab/mmdetection/tree/tracking/demo). + +Note that if you use a folder as the input, the image names there must be **sortable** , which means we can re-order the images according to the numbers contained in the filenames. We now only support reading the images whose filenames end with `.jpg`, `.jpeg` and `.png`. + +## Inference MOT models + +This script can inference an input video / images with a multiple object tracking or video instance segmentation model. + +```shell +python demo/mot_demo.py \ + ${INPUTS} + ${CONFIG_FILE} \ + [--checkpoint ${CHECKPOINT_FILE}] \ + [--detector ${DETECTOR_FILE}] \ + [--reid ${REID_FILE}] \ + [--score-thr ${SCORE_THR}] \ + [--device ${DEVICE}] \ + [--out ${OUTPUT}] \ + [--show] +``` + +The `INPUT` and `OUTPUT` support both _mp4 video_ format and the _folder_ format. + +**Important:** For `DeepSORT`, `SORT`, `StrongSORT`, they need load the weight of the `reid` and the weight of the `detector` separately. Therefore, we use `--detector` and `--reid` to load weights. Other algorithms such as `ByteTrack`, `OCSORT` `QDTrack` `MaskTrackRCNN` and `Mask2Former` use `--checkpoint` to load weights. + +Optional arguments: + +- `CHECKPOINT_FILE`: The checkpoint is optional. +- `DETECTOR_FILE`: The detector is optional. +- `REID_FILE`: The reid is optional. +- `SCORE_THR`: The threshold of score to filter bboxes. +- `DEVICE`: The device for inference. Options are `cpu` or `cuda:0`, etc. +- `OUTPUT`: Output of the visualized demo. If not specified, the `--show` is obligate to show the video on the fly. +- `--show`: Whether show the video on the fly. + +**Examples of running mot model:** + +```shell +# Example 1: do not specify --checkpoint to use --detector +python demo/mot_demo.py \ + demo/demo_mot.mp4 \ + configs/sort/sort_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py \ + --detector \ + https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-half-64ee2ed4.pth \ + --out mot.mp4 + +# Example 2: use --checkpoint +python demo/mot_demo.py \ + demo/demo_mot.mp4 \ + configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py \ + --checkpoint https://download.openmmlab.com/mmtracking/mot/qdtrack/mot_dataset/qdtrack_faster-rcnn_r50_fpn_4e_mot17_20220315_145635-76f295ef.pth \ + --out mot.mp4 +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/tracking_train_test.md b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_train_test.md new file mode 100644 index 0000000000000000000000000000000000000000..1a6871d717d4740355788dd95047a80703184da9 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_train_test.md @@ -0,0 +1,229 @@ +# Learn to train and test + +## Train + +This section will show how to train existing models on supported datasets. +The following training environments are supported: + +- CPU +- single GPU +- single node multiple GPUs +- multiple nodes + +You can also manage jobs with Slurm. + +Important: + +- You can change the evaluation interval during training by modifying the `train_cfg` as + `train_cfg = dict(val_interval=10)`. That means evaluating the model every 10 epochs. +- The default learning rate in all config files is for 8 GPUs. + According to the [Linear Scaling Rule](https://arxiv.org/abs/1706.02677), + you need to set the learning rate proportional to the batch size if you use different GPUs or images per GPU, + e.g., `lr=0.01` for 8 GPUs * 1 img/gpu and lr=0.04 for 16 GPUs * 2 imgs/gpu. +- During training, log files and checkpoints will be saved to the working directory, + which is specified by CLI argument `--work-dir`. It uses `./work_dirs/CONFIG_NAME` as default. +- If you want the mixed precision training, simply specify CLI argument `--amp`. + +#### 1. Train on CPU + +The model is default put on cuda device. +Only if there are no cuda devices, the model will be put on cpu. +So if you want to train the model on CPU, you need to `export CUDA_VISIBLE_DEVICES=-1` to disable GPU visibility first. +More details in [MMEngine](https://github.com/open-mmlab/mmengine/blob/ca282aee9e402104b644494ca491f73d93a9544f/mmengine/runner/runner.py#L849-L850). + +```shell script +CUDA_VISIBLE_DEVICES=-1 python tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +An example of training the MOT model QDTrack on CPU: + +```shell script +CUDA_VISIBLE_DEVICES=-1 python tools/train.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +``` + +#### 2. Train on single GPU + +If you want to train the model on single GPU, you can directly use the `tools/train.py` as follows. + +```shell script +python tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +You can use `export CUDA_VISIBLE_DEVICES=$GPU_ID` to select the GPU. + +An example of training the MOT model QDTrack on single GPU: + +```shell script +CUDA_VISIBLE_DEVICES=2 python tools/train.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +``` + +#### 3. Train on single node multiple GPUs + +We provide `tools/dist_train.sh` to launch training on multiple GPUs. +The basic usage is as follows. + +```shell script +bash ./tools/dist_train.sh ${CONFIG_FILE} ${GPU_NUM} [optional arguments] +``` + +If you would like to launch multiple jobs on a single machine, +e.g., 2 jobs of 4-GPU training on a machine with 8 GPUs, +you need to specify different ports (29500 by default) for each job to avoid communication conflict. + +For example, you can set the port in commands as follows. + +```shell script +CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4 +CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4 +``` + +An example of training the MOT model QDTrack on single node multiple GPUs: + +```shell script +bash ./tools/dist_train.sh configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py 8 +``` + +#### 4. Train on multiple nodes + +If you launch with multiple machines simply connected with ethernet, you can simply run following commands: + +On the first machine: + +```shell script +NNODES=2 NODE_RANK=0 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR bash tools/dist_train.sh $CONFIG $GPUS +``` + +On the second machine: + +```shell script +NNODES=2 NODE_RANK=1 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR bash tools/dist_train.sh $CONFIG $GPUS +``` + +Usually it is slow if you do not have high speed networking like InfiniBand. + +#### 5. Train with Slurm + +[Slurm](https://slurm.schedmd.com/) is a good job scheduling system for computing clusters. +On a cluster managed by Slurm, you can use `slurm_train.sh` to spawn training jobs. +It supports both single-node and multi-node training. + +The basic usage is as follows. + +```shell script +bash ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR} ${GPUS} +``` + +An example of training the MOT model QDTrack with Slurm: + +```shell script +PORT=29501 \ +GPUS_PER_NODE=8 \ +SRUN_ARGS="--quotatype=reserved" \ +bash ./tools/slurm_train.sh \ +mypartition \ +mottrack +configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +./work_dirs/QDTrack \ +8 +``` + +## Test + +This section will show how to test existing models on supported datasets. +The following testing environments are supported: + +- CPU +- single GPU +- single node multiple GPUs +- multiple nodes + +You can also manage jobs with Slurm. + +Important: + +- In MOT, some algorithms like `DeepSORT`, `SORT`, `StrongSORT` need load the weight of the `reid` and the weight of the `detector` separately. + Other algorithms such as `ByteTrack`, `OCSORT` and `QDTrack` don't need. So we provide `--checkpoint`, `--detector` and `--reid` to load weights. +- We provide two ways to evaluate and test models, video_basede test and image_based test. some algorithms like `StrongSORT`, `Mask2former` only support + video_based test. if your GPU memory can't fit the entire video, you can switch test way by set sampler type. + For example: + video_based test: `sampler=dict(type='DefaultSampler', shuffle=False, round_up=False)` + image_based test: `sampler=dict(type='TrackImgSampler')` +- You can set the results saving path by modifying the key `outfile_prefix` in evaluator. + For example, `val_evaluator = dict(outfile_prefix='results/sort_mot17')`. + Otherwise, a temporal file will be created and will be removed after evaluation. +- If you just want the formatted results without evaluation, you can set `format_only=True`. + For example, `test_evaluator = dict(type='MOTChallengeMetric', metric=['HOTA', 'CLEAR', 'Identity'], outfile_prefix='sort_mot17_results', format_only=True)` + +#### 1. Test on CPU + +The model is default put on cuda device. +Only if there are no cuda devices, the model will be put on cpu. +So if you want to test the model on CPU, you need to `export CUDA_VISIBLE_DEVICES=-1` to disable GPU visibility first. +More details in [MMEngine](https://github.com/open-mmlab/mmengine/blob/ca282aee9e402104b644494ca491f73d93a9544f/mmengine/runner/runner.py#L849-L850). + +```shell script +CUDA_VISIBLE_DEVICES=-1 python tools/test_tracking.py ${CONFIG_FILE} [optional arguments] +``` + +An example of testing the MOT model SORT on CPU: + +```shell script +CUDA_VISIBLE_DEVICES=-1 python tools/test_tracking.py configs/sort/sort_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py --detector ${CHECKPOINT_FILE} +``` + +#### 2. Test on single GPU + +If you want to test the model on single GPU, you can directly use the `tools/test_tracking.py` as follows. + +```shell script +python tools/test_tracking.py ${CONFIG_FILE} [optional arguments] +``` + +You can use `export CUDA_VISIBLE_DEVICES=$GPU_ID` to select the GPU. + +An example of testing the MOT model QDTrack on single GPU: + +```shell script +CUDA_VISIBLE_DEVICES=2 python tools/test_tracking.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py --detector ${CHECKPOINT_FILE} +``` + +#### 3. Test on single node multiple GPUs + +We provide `tools/dist_test_tracking.sh` to launch testing on multiple GPUs. +The basic usage is as follows. + +```shell script +bash ./tools/dist_test_tracking.sh ${CONFIG_FILE} ${GPU_NUM} [optional arguments] +``` + +An example of testing the MOT model DeepSort on single node multiple GPUs: + +```shell script +bash ./tools/dist_test_tracking.sh configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py 8 --detector ${CHECKPOINT_FILE} --reid ${CHECKPOINT_FILE} +``` + +#### 4. Test on multiple nodes + +You can test on multiple nodes, which is similar with "Train on multiple nodes". + +#### 5. Test with Slurm + +On a cluster managed by Slurm, you can use `slurm_test_tracking.sh` to spawn testing jobs. +It supports both single-node and multi-node testing. + +The basic usage is as follows. + +```shell script +[GPUS=${GPUS}] bash tools/slurm_test_tracking.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} [optional arguments] +``` + +An example of testing the VIS model Mask2former with Slurm: + +```shell script +GPUS=8 +bash tools/slurm_test_tracking.sh \ +mypartition \ +vis \ +configs/mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py \ +--checkpoint ${CHECKPOINT_FILE} +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/tracking_visualization.md b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..28953256200a3a6c76254de46f74875f070be172 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/tracking_visualization.md @@ -0,0 +1,47 @@ +# Learn about Visualization + +## Local Visualization + +This section will present how to visualize the detection/tracking results with local visualizer. + +If you want to draw prediction results, you can turn this feature on by setting `draw=True` in `TrackVisualizationHook` as follows. + +```shell script +default_hooks = dict(visualization=dict(type='TrackVisualizationHook', draw=True)) +``` + +Specifically, the `TrackVisualizationHook` has the following arguments: + +- `draw`: whether to draw prediction results. If it is False, it means that no drawing will be done. Defaults to False. +- `interval`: The interval of visualization. Defaults to 30. +- `score_thr`: The threshold to visualize the bboxes and masks. Defaults to 0.3. +- `show`: Whether to display the drawn image. Default to False. +- `wait_time`: The interval of show (s). Defaults to 0. +- `test_out_dir`: directory where painted images will be saved in testing process. +- `backend_args`: Arguments to instantiate a file client. Defaults to `None`. + +In the `TrackVisualizationHook`, `TrackLocalVisualizer` will be called to implement visualization for MOT and VIS tasks. +We will present the details below. +You can refer to MMEngine for more details about [Visualization](https://github.com/open-mmlab/mmengine/blob/main/docs/en/advanced_tutorials/visualization.md) and [Hook](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/hook.md). + +#### Tracking Visualization + +We realize the tracking visualization with class `TrackLocalVisualizer`. +You can call it as follows. + +```python +visualizer = dict(type='TrackLocalVisualizer') +``` + +It has the following arguments: + +- `name`: Name of the instance. Defaults to 'visualizer'. +- `image`: The origin image to draw. The format should be RGB. Defaults to None. +- `vis_backends`: Visual backend config list. Defaults to None. +- `save_dir`: Save file dir for all storage backends. If it is None, the backend storage will not save any data. +- `line_width`: The linewidth of lines. Defaults to 3. +- `alpha`: The transparency of bboxes or mask. Defaults to 0.8. + +Here is a visualization example of DeepSORT: + +![test_img_89](https://user-images.githubusercontent.com/99722489/186062929-6d0e4663-0d8e-4045-9ec8-67e0e41da876.png) diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/train.md b/mmdet_code/SR-TOD/docs/en/user_guides/train.md new file mode 100644 index 0000000000000000000000000000000000000000..b67555fd822ffafee79475528301f40be1fe05ac --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/train.md @@ -0,0 +1,456 @@ +# Train predefined models on standard datasets + +MMDetection also provides out-of-the-box tools for training detection models. +This section will show how to train _predefined_ models (under [configs](../../../configs)) on standard datasets i.e. COCO. + +## Prepare datasets + +Preparing datasets is also necessary for training. See section [Prepare datasets](#prepare-datasets) above for details. + +**Note**: +Currently, the config files under `configs/cityscapes` use COCO pre-trained weights to initialize. +If your network connection is slow or unavailable, it's advisable to download existing models before beginning training to avoid errors. + +## Learning rate auto scaling + +**Important**: The default learning rate in config files is for 8 GPUs and 2 sample per GPU (batch size = 8 * 2 = 16). And it had been set to `auto_scale_lr.base_batch_size` in `config/_base_/schedules/schedule_1x.py`. The learning rate will be automatically scaled based on the value at a batch size of 16. Meanwhile, to avoid affecting other codebases that use mmdet, the default setting for the `auto_scale_lr.enable` flag is `False`. + +If you want to enable this feature, you need to add argument `--auto-scale-lr`. And you need to check the config name which you want to use before you process the command, because the config name indicates the default batch size. +By default, it is `8 x 2 = 16 batch size`, like `faster_rcnn_r50_caffe_fpn_90k_coco.py` or `pisa_faster_rcnn_x101_32x4d_fpn_1x_coco.py`. In other cases, you will see the config file name have `_NxM_` in dictating, like `cornernet_hourglass104_mstest_32x3_210e_coco.py` which batch size is `32 x 3 = 96`, or `scnet_x101_64x4d_fpn_8x1_20e_coco.py` which batch size is `8 x 1 = 8`. + +**Please remember to check the bottom of the specific config file you want to use, it will have `auto_scale_lr.base_batch_size` if the batch size is not `16`. If you can't find those values, check the config file which in `_base_=[xxx]` and you will find it. Please do not modify its values if you want to automatically scale the LR.** + +The basic usage of learning rate auto scaling is as follows. + +```shell +python tools/train.py \ + ${CONFIG_FILE} \ + --auto-scale-lr \ + [optional arguments] +``` + +If you enabled this feature, the learning rate will be automatically scaled according to the number of GPUs on the machine and the batch size of training. See [linear scaling rule](https://arxiv.org/abs/1706.02677) for details. For example, If there are 4 GPUs and 2 pictures on each GPU, `lr = 0.01`, then if there are 16 GPUs and 4 pictures on each GPU, it will automatically scale to `lr = 0.08`. + +If you don't want to use it, you need to calculate the learning rate according to the [linear scaling rule](https://arxiv.org/abs/1706.02677) manually then change `optimizer.lr` in specific config file. + +## Training on a single GPU + +We provide `tools/train.py` to launch training jobs on a single GPU. +The basic usage is as follows. + +```shell +python tools/train.py \ + ${CONFIG_FILE} \ + [optional arguments] +``` + +During training, log files and checkpoints will be saved to the working directory, which is specified by `work_dir` in the config file or via CLI argument `--work-dir`. + +By default, the model is evaluated on the validation set every epoch, the evaluation interval can be specified in the config file as shown below. + +```python +# evaluate the model every 12 epochs. +train_cfg = dict(val_interval=12) +``` + +This tool accepts several optional arguments, including: + +- `--work-dir ${WORK_DIR}`: Override the working directory. +- `--resume`: resume from the latest checkpoint in the work_dir automatically. +- `--resume ${CHECKPOINT_FILE}`: resume from the specific checkpoint. +- `--cfg-options 'Key=value'`: Overrides other settings in the used config. + +**Note:** + +There is a difference between `resume` and `load-from`: + +`resume` loads both the weights of the model and the state of the optimizer, and it inherits the iteration number from the specified checkpoint, so training does not start again from scratch. `load-from`, on the other hand, only loads the weights of the model, and its training starts from scratch. It is often used for fine-tuning a model. `load-from` needs to be written in the config file, while `resume` is passed as a command line argument. + +## Training on CPU + +The process of training on the CPU is consistent with single GPU training. We just need to disable GPUs before the training process. + +```shell +export CUDA_VISIBLE_DEVICES=-1 +``` + +And then run the script [above](#training-on-a-single-GPU). + +**Note**: + +We do not recommend users to use the CPU for training because it is too slow. We support this feature to allow users to debug on machines without GPU for convenience. + +## Training on multiple GPUs + +We provide `tools/dist_train.sh` to launch training on multiple GPUs. +The basic usage is as follows. + +```shell +bash ./tools/dist_train.sh \ + ${CONFIG_FILE} \ + ${GPU_NUM} \ + [optional arguments] +``` + +Optional arguments remain the same as stated [above](#training-on-a-single-GPU). + +### Launch multiple jobs simultaneously + +If you would like to launch multiple jobs on a single machine, e.g., 2 jobs of 4-GPU training on a machine with 8 GPUs, +you need to specify different ports (29500 by default) for each job to avoid communication conflict. + +If you use `dist_train.sh` to launch training jobs, you can set the port in the commands. + +```shell +CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4 +CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4 +``` + +## Train with multiple machines + +If you launch with multiple machines simply connected with ethernet, you can simply run the following commands: + +On the first machine: + +```shell +NNODES=2 NODE_RANK=0 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS +``` + +On the second machine: + +```shell +NNODES=2 NODE_RANK=1 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS +``` + +Usually, it is slow if you do not have high-speed networking like InfiniBand. + +## Manage jobs with Slurm + +[Slurm](https://slurm.schedmd.com/) is a good job scheduling system for computing clusters. +On a cluster managed by Slurm, you can use `slurm_train.sh` to spawn training jobs. It supports both single-node and multi-node training. + +The basic usage is as follows. + +```shell +[GPUS=${GPUS}] ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR} +``` + +Below is an example of using 16 GPUs to train Mask R-CNN on a Slurm partition named _dev_, and set the work-dir to some shared file systems. + +```shell +GPUS=16 ./tools/slurm_train.sh dev mask_r50_1x configs/mask-rcnn_r50_fpn_1x_coco.py /nfs/xxxx/mask_rcnn_r50_fpn_1x +``` + +You can check [the source code](../../../tools/slurm_train.sh) to review full arguments and environment variables. + +When using Slurm, the port option needs to be set in one of the following ways: + +1. Set the port through `--options`. This is more recommended since it does not change the original configs. + + ```shell + CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} --cfg-options 'dist_params.port=29500' + CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} --cfg-options 'dist_params.port=29501' + ``` + +2. Modify the config files to set different communication ports. + + In `config1.py`, set + + ```python + dist_params = dict(backend='nccl', port=29500) + ``` + + In `config2.py`, set + + ```python + dist_params = dict(backend='nccl', port=29501) + ``` + + Then you can launch two jobs with `config1.py` and `config2.py`. + + ```shell + CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} + CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} + ``` + +# Train with customized datasets + +In this part, you will know how to train predefined models with customized datasets and then test it. We use the [balloon dataset](https://github.com/matterport/Mask_RCNN/tree/master/samples/balloon) as an example to describe the whole process. + +The basic steps are as below: + +1. Prepare the customized dataset +2. Prepare a config +3. Train, test, and infer models on the customized dataset. + +## Prepare the customized dataset + +There are three ways to support a new dataset in MMDetection: + +1. Reorganize the dataset into COCO format. +2. Reorganize the dataset into a middle format. +3. Implement a new dataset. + +Usually, we recommend using the first two methods which are usually easier than the third. + +In this note, we give an example of converting the data into COCO format. + +**Note**: Datasets and metrics have been decoupled except CityScapes since MMDetection 3.0. Therefore, users can use any kind of evaluation metrics for any format of datasets during validation. For example: evaluate on COCO dataset with VOC metric, or evaluate on OpenImages dataset with both VOC and COCO metrics. + +### COCO annotation format + +The necessary keys of COCO format for instance segmentation are as below, for the complete details, please refer [here](https://cocodataset.org/#format-data). + +```json +{ + "images": [image], + "annotations": [annotation], + "categories": [category] +} + +image = { + "id": int, + "width": int, + "height": int, + "file_name": str, +} + +annotation = { + "id": int, + "image_id": int, + "category_id": int, + "segmentation": RLE or [polygon], + "area": float, + "bbox": [x,y,width,height], # (x, y) are the coordinates of the upper left corner of the bbox + "iscrowd": 0 or 1, +} + +categories = [{ + "id": int, + "name": str, + "supercategory": str, +}] +``` + +Assume we use the balloon dataset. +After downloading the data, we need to implement a function to convert the annotation format into the COCO format. Then we can use implemented `CocoDataset` to load the data and perform training and evaluation. + +If you take a look at the dataset, you will find the dataset format is as below: + +```json +{'base64_img_data': '', + 'file_attributes': {}, + 'filename': '34020010494_e5cb88e1c4_k.jpg', + 'fileref': '', + 'regions': {'0': {'region_attributes': {}, + 'shape_attributes': {'all_points_x': [1020, + 1000, + 994, + 1003, + 1023, + 1050, + 1089, + 1134, + 1190, + 1265, + 1321, + 1361, + 1403, + 1428, + 1442, + 1445, + 1441, + 1427, + 1400, + 1361, + 1316, + 1269, + 1228, + 1198, + 1207, + 1210, + 1190, + 1177, + 1172, + 1174, + 1170, + 1153, + 1127, + 1104, + 1061, + 1032, + 1020], + 'all_points_y': [963, + 899, + 841, + 787, + 738, + 700, + 663, + 638, + 621, + 619, + 643, + 672, + 720, + 765, + 800, + 860, + 896, + 942, + 990, + 1035, + 1079, + 1112, + 1129, + 1134, + 1144, + 1153, + 1166, + 1166, + 1150, + 1136, + 1129, + 1122, + 1112, + 1084, + 1037, + 989, + 963], + 'name': 'polygon'}}}, + 'size': 1115004} +``` + +The annotation is a JSON file where each key indicates an image's all annotations. +The code to convert the balloon dataset into coco format is as below. + +```python +import os.path as osp + +import mmcv + +from mmengine.fileio import dump, load +from mmengine.utils import track_iter_progress + + +def convert_balloon_to_coco(ann_file, out_file, image_prefix): + data_infos = load(ann_file) + + annotations = [] + images = [] + obj_count = 0 + for idx, v in enumerate(track_iter_progress(data_infos.values())): + filename = v['filename'] + img_path = osp.join(image_prefix, filename) + height, width = mmcv.imread(img_path).shape[:2] + + images.append( + dict(id=idx, file_name=filename, height=height, width=width)) + + for _, obj in v['regions'].items(): + assert not obj['region_attributes'] + obj = obj['shape_attributes'] + px = obj['all_points_x'] + py = obj['all_points_y'] + poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)] + poly = [p for x in poly for p in x] + + x_min, y_min, x_max, y_max = (min(px), min(py), max(px), max(py)) + + data_anno = dict( + image_id=idx, + id=obj_count, + category_id=0, + bbox=[x_min, y_min, x_max - x_min, y_max - y_min], + area=(x_max - x_min) * (y_max - y_min), + segmentation=[poly], + iscrowd=0) + annotations.append(data_anno) + obj_count += 1 + + coco_format_json = dict( + images=images, + annotations=annotations, + categories=[{ + 'id': 0, + 'name': 'balloon' + }]) + dump(coco_format_json, out_file) + + +if __name__ == '__main__': + convert_balloon_to_coco(ann_file='data/balloon/train/via_region_data.json', + out_file='data/balloon/train/annotation_coco.json', + image_prefix='data/balloon/train') + convert_balloon_to_coco(ann_file='data/balloon/val/via_region_data.json', + out_file='data/balloon/val/annotation_coco.json', + image_prefix='data/balloon/val') + +``` + +Using the function above, users can successfully convert the annotation file into json format, then we can use `CocoDataset` to train and evaluate the model with `CocoMetric`. + +## Prepare a config + +The second step is to prepare a config thus the dataset could be successfully loaded. Assume that we want to use Mask R-CNN with FPN, the config to train the detector on balloon dataset is as below. Assume the config is under directory `configs/balloon/` and named as `mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py`, the config is as below. Please refer [Learn about Configs — MMDetection 3.0.0 documentation](https://mmdetection.readthedocs.io/en/latest/user_guides/config.html) to get detailed information about config files. + +```python +# The new config inherits a base config to highlight the necessary modification +_base_ = '../mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_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 +data_root = 'data/balloon/' +metainfo = { + 'classes': ('balloon', ), + 'palette': [ + (220, 20, 60), + ] +} +train_dataloader = dict( + batch_size=1, + dataset=dict( + data_root=data_root, + metainfo=metainfo, + ann_file='train/annotation_coco.json', + data_prefix=dict(img='train/'))) +val_dataloader = dict( + dataset=dict( + data_root=data_root, + metainfo=metainfo, + ann_file='val/annotation_coco.json', + data_prefix=dict(img='val/'))) +test_dataloader = val_dataloader + +# Modify metric related settings +val_evaluator = dict(ann_file=data_root + 'val/annotation_coco.json') +test_evaluator = val_evaluator + +# We can use the pre-trained Mask RCNN model to obtain higher performance +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth' + +``` + +## Train a new model + +To train a model with the new config, you can simply run + +```shell +python tools/train.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py +``` + +For more detailed usages, please refer to the [training guide](https://mmdetection.readthedocs.io/en/latest/user_guides/train.html#train-predefined-models-on-standard-datasets). + +## Test and inference + +To test the trained model, you can simply run + +```shell +python tools/test.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py work_dirs/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon/epoch_12.pth +``` + +For more detailed usages, please refer to the [testing guide](https://mmdetection.readthedocs.io/en/latest/user_guides/test.html). diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/useful_hooks.md b/mmdet_code/SR-TOD/docs/en/user_guides/useful_hooks.md new file mode 100644 index 0000000000000000000000000000000000000000..4c30686d68ac555707fa3af0432b914ee0672f76 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/useful_hooks.md @@ -0,0 +1,105 @@ +# Useful Hooks + +MMDetection and MMEngine provide users with various useful hooks including log hooks, `NumClassCheckHook`, etc. This tutorial introduces the functionalities and usages of hooks implemented in MMDetection. For using hooks in MMEngine, please read the [API documentation in MMEngine](https://github.com/open-mmlab/mmengine/tree/main/docs/en/tutorials/hook.md). + +## CheckInvalidLossHook + +## NumClassCheckHook + +## MemoryProfilerHook + +[Memory profiler hook](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/engine/hooks/memory_profiler_hook.py) records memory information including virtual memory, swap memory, and the memory of the current process. This hook helps grasp the memory usage of the system and discover potential memory leak bugs. To use this hook, users should install `memory_profiler` and `psutil` by `pip install memory_profiler psutil` first. + +### Usage + +To use this hook, users should add the following code to the config file. + +```python +custom_hooks = [ + dict(type='MemoryProfilerHook', interval=50) +] +``` + +### Result + +During training, you can see the messages in the log recorded by `MemoryProfilerHook` as below. + +```text +The system has 250 GB (246360 MB + 9407 MB) of memory and 8 GB (5740 MB + 2452 MB) of swap memory in total. Currently 9407 MB (4.4%) of memory and 5740 MB (29.9%) of swap memory were consumed. And the current training process consumed 5434 MB of memory. +``` + +```text +2022-04-21 08:49:56,881 - mmengine - INFO - Memory information available_memory: 246360 MB, used_memory: 9407 MB, memory_utilization: 4.4 %, available_swap_memory: 5740 MB, used_swap_memory: 2452 MB, swap_memory_utilization: 29.9 %, current_process_memory: 5434 MB +``` + +## SetEpochInfoHook + +## SyncNormHook + +## SyncRandomSizeHook + +## YOLOXLrUpdaterHook + +## YOLOXModeSwitchHook + +## How to implement a custom hook + +In general, there are 20 points where hooks can be inserted from the beginning to the end of model training. The users can implement custom hooks and insert them at different points in the process of training to do what they want. + +- global points: `before_run`, `after_run` +- points in training: `before_train`, `before_train_epoch`, `before_train_iter`, `after_train_iter`, `after_train_epoch`, `after_train` +- points in validation: `before_val`, `before_val_epoch`, `before_val_iter`, `after_val_iter`, `after_val_epoch`, `after_val` +- points at testing: `before_test`, `before_test_epoch`, `before_test_iter`, `after_test_iter`, `after_test_epoch`, `after_test` +- other points: `before_save_checkpoint`, `after_save_checkpoint` + +For example, users can implement a hook to check loss and terminate training when loss goes NaN. To achieve that, there are three steps to go: + +1. Implement a new hook that inherits the `Hook` class in MMEngine, and implement `after_train_iter` method which checks whether loss goes NaN after every `n` training iterations. +2. The implemented hook should be registered in `HOOKS` by `@HOOKS.register_module()` as shown in the code below. +3. Add `custom_hooks = [dict(type='MemoryProfilerHook', interval=50)]` in the config file. + +```python +from typing import Optional + +import torch +from mmengine.hooks import Hook +from mmengine.runner import Runner + +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class CheckInvalidLossHook(Hook): + """Check invalid loss hook. + + This hook will regularly check whether the loss is valid + during training. + + Args: + interval (int): Checking interval (every k iterations). + Default: 50. + """ + + def __init__(self, interval: int = 50) -> None: + self.interval = interval + + def after_train_iter(self, + runner: Runner, + batch_idx: int, + data_batch: Optional[dict] = None, + outputs: Optional[dict] = None) -> None: + """Regularly check whether the loss is valid every n iterations. + + Args: + runner (:obj:`Runner`): The runner of the training process. + batch_idx (int): The index of the current batch in the train loop. + data_batch (dict, Optional): Data from dataloader. + Defaults to None. + outputs (dict, Optional): Outputs from model. Defaults to None. + """ + if self.every_n_train_iters(runner, self.interval): + assert torch.isfinite(outputs['loss']), \ + runner.logger.info('loss become infinite or NaN!') +``` + +Please read [customize_runtime](../advanced_guides/customize_runtime.md) for more about implementing a custom hook. diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/useful_tools.md b/mmdet_code/SR-TOD/docs/en/user_guides/useful_tools.md new file mode 100644 index 0000000000000000000000000000000000000000..007d367ec8c931c2b68a6a53233fd0af33c82d2e --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/useful_tools.md @@ -0,0 +1,586 @@ +Apart from training/testing scripts, We provide lots of useful tools under the +`tools/` directory. + +## Log Analysis + +`tools/analysis_tools/analyze_logs.py` plots loss/mAP curves given a training +log file. Run `pip install seaborn` first to install the dependency. + +```shell +python tools/analysis_tools/analyze_logs.py plot_curve [--keys ${KEYS}] [--eval-interval ${EVALUATION_INTERVAL}] [--title ${TITLE}] [--legend ${LEGEND}] [--backend ${BACKEND}] [--style ${STYLE}] [--out ${OUT_FILE}] +``` + +![loss curve image](../../../resources/loss_curve.png) + +Examples: + +- Plot the classification loss of some run. + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log.json --keys loss_cls --legend loss_cls + ``` + +- Plot the classification and regression loss of some run, and save the figure to a pdf. + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log.json --keys loss_cls loss_bbox --out losses.pdf + ``` + +- Compare the bbox mAP of two runs in the same figure. + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log1.json log2.json --keys bbox_mAP --legend run1 run2 + ``` + +- Compute the average training speed. + + ```shell + python tools/analysis_tools/analyze_logs.py cal_train_time log.json [--include-outliers] + ``` + + The output is expected to be like the following. + + ```text + -----Analyze train time of work_dirs/some_exp/20190611_192040.log.json----- + slowest epoch 11, average time is 1.2024 + fastest epoch 1, average time is 1.1909 + time std over epochs is 0.0028 + average iter time: 1.1959 s/iter + ``` + +## Result Analysis + +`tools/analysis_tools/analyze_results.py` calculates single image mAP and saves or shows the topk images with the highest and lowest scores based on prediction results. + +**Usage** + +```shell +python tools/analysis_tools/analyze_results.py \ + ${CONFIG} \ + ${PREDICTION_PATH} \ + ${SHOW_DIR} \ + [--show] \ + [--wait-time ${WAIT_TIME}] \ + [--topk ${TOPK}] \ + [--show-score-thr ${SHOW_SCORE_THR}] \ + [--cfg-options ${CFG_OPTIONS}] +``` + +Description of all arguments: + +- `config` : The path of a model config file. +- `prediction_path`: Output result file in pickle format from `tools/test.py` +- `show_dir`: Directory where painted GT and detection images will be saved +- `--show`:Determines whether to show painted images, If not specified, it will be set to `False` +- `--wait-time`: The interval of show (s), 0 is block +- `--topk`: The number of saved images that have the highest and lowest `topk` scores after sorting. If not specified, it will be set to `20`. +- `--show-score-thr`: Show score threshold. If not specified, it will be set to `0`. +- `--cfg-options`: If specified, the key-value pair optional cfg will be merged into config file + +**Examples**: + +Assume that you have got result file in pickle format from `tools/test.py` in the path './result.pkl'. + +1. Test Faster R-CNN and visualize the results, save images to the directory `results/` + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --show +``` + +2. Test Faster R-CNN and specified topk to 50, save images to the directory `results/` + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --topk 50 +``` + +3. If you want to filter the low score prediction results, you can specify the `show-score-thr` parameter + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --show-score-thr 0.3 +``` + +## Visualization + +### Visualize Datasets + +`tools/analysis_tools/browse_dataset.py` helps the user to browse a detection dataset (both +images and bounding box annotations) visually, or save the image to a +designated directory. + +```shell +python tools/misc/browse_dataset.py ${CONFIG} [-h] [--skip-type ${SKIP_TYPE[SKIP_TYPE...]}] [--output-dir ${OUTPUT_DIR}] [--not-show] [--show-interval ${SHOW_INTERVAL}] +``` + +### Visualize Models + +First, convert the model to ONNX as described +[here](#convert-mmdetection-model-to-onnx-experimental). +Note that currently only RetinaNet is supported, support for other models +will be coming in later versions. +The converted model could be visualized by tools like [Netron](https://github.com/lutzroeder/netron). + +### Visualize Predictions + +If you need a lightweight GUI for visualizing the detection results, you can refer [DetVisGUI project](https://github.com/Chien-Hung/DetVisGUI/tree/mmdetection). + +## Error Analysis + +`tools/analysis_tools/coco_error_analysis.py` analyzes COCO results per category and by +different criterion. It can also make a plot to provide useful information. + +```shell +python tools/analysis_tools/coco_error_analysis.py ${RESULT} ${OUT_DIR} [-h] [--ann ${ANN}] [--types ${TYPES[TYPES...]}] +``` + +Example: + +Assume that you have got [Mask R-CNN checkpoint file](https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_fpn_1x_coco/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth) in the path 'checkpoint'. For other checkpoints, please refer to our [model zoo](./model_zoo.md). + +You can modify the test_evaluator to save the results bbox by: + +1. Find which dataset in 'configs/base/datasets' the current config corresponds to. +2. Replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in dataset config. +3. Use the following command to get the results bbox and segmentation json file. + +```shell +python tools/test.py \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoint/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ +``` + +1. Get COCO bbox error results per category , save analyze result images to the directory(In [config](../../../configs/_base_/datasets/coco_instance.py) the default directory is './work_dirs/coco_instance/test') + +```shell +python tools/analysis_tools/coco_error_analysis.py \ + results.bbox.json \ + results \ + --ann=data/coco/annotations/instances_val2017.json \ +``` + +2. Get COCO segmentation error results per category , save analyze result images to the directory + +```shell +python tools/analysis_tools/coco_error_analysis.py \ + results.segm.json \ + results \ + --ann=data/coco/annotations/instances_val2017.json \ + --types='segm' +``` + +## Model Serving + +In order to serve an `MMDetection` model with [`TorchServe`](https://pytorch.org/serve/), you can follow the steps: + +### 1. Install TorchServe + +Suppose you have a `Python` environment with `PyTorch` and `MMDetection` successfully installed, +then you could run the following command to install `TorchServe` and its dependencies. +For more other installation options, please refer to the [quick start](https://github.com/pytorch/serve/blob/master/README.md#serve-a-model). + +```shell +python -m pip install torchserve torch-model-archiver torch-workflow-archiver nvgpu +``` + +**Note**: Please refer to [torchserve docker](https://github.com/pytorch/serve/blob/master/docker/README.md) if you want to use `TorchServe` in docker. + +### 2. Convert model from MMDetection to TorchServe + +```shell +python tools/deployment/mmdet2torchserve.py ${CONFIG_FILE} ${CHECKPOINT_FILE} \ +--output-folder ${MODEL_STORE} \ +--model-name ${MODEL_NAME} +``` + +### 3. Start `TorchServe` + +```shell +torchserve --start --ncs \ + --model-store ${MODEL_STORE} \ + --models ${MODEL_NAME}.mar +``` + +### 4. Test deployment + +```shell +curl -O curl -O https://raw.githubusercontent.com/pytorch/serve/master/docs/images/3dogs.jpg +curl http://127.0.0.1:8080/predictions/${MODEL_NAME} -T 3dogs.jpg +``` + +You should obtain a response similar to: + +```json +[ + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 294.63409423828125, + 203.99111938476562, + 417.048583984375, + 281.62744140625 + ], + "score": 0.9987992644309998 + }, + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 404.26019287109375, + 126.0080795288086, + 574.5091552734375, + 293.6662292480469 + ], + "score": 0.9979367256164551 + }, + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 197.2144775390625, + 93.3067855834961, + 307.8505554199219, + 276.7560119628906 + ], + "score": 0.993338406085968 + } +] +``` + +#### Compare results + +And you can use `test_torchserver.py` to compare result of `TorchServe` and `PyTorch`, and visualize them. + +```shell +python tools/deployment/test_torchserver.py ${IMAGE_FILE} ${CONFIG_FILE} ${CHECKPOINT_FILE} ${MODEL_NAME} +[--inference-addr ${INFERENCE_ADDR}] [--device ${DEVICE}] [--score-thr ${SCORE_THR}] [--work-dir ${WORK_DIR}] +``` + +Example: + +```shell +python tools/deployment/test_torchserver.py \ +demo/demo.jpg \ +configs/yolo/yolov3_d53_8xb8-320-273e_coco.py \ +checkpoint/yolov3_d53_320_273e_coco-421362b6.pth \ +yolov3 \ +--work-dir ./work-dir +``` + +### 5. Stop `TorchServe` + +```shell +torchserve --stop +``` + +## Model Complexity + +`tools/analysis_tools/get_flops.py` is a script adapted from [flops-counter.pytorch](https://github.com/sovrasov/flops-counter.pytorch) to compute the FLOPs and params of a given model. + +```shell +python tools/analysis_tools/get_flops.py ${CONFIG_FILE} [--shape ${INPUT_SHAPE}] +``` + +You will get the results like this. + +```text +============================== +Input shape: (3, 1280, 800) +Flops: 239.32 GFLOPs +Params: 37.74 M +============================== +``` + +**Note**: This tool is still experimental and we do not guarantee that the +number is absolutely correct. You may well use the result for simple +comparisons, but double check it before you adopt it in technical reports or papers. + +1. FLOPs are related to the input shape while parameters are not. The default + input shape is (1, 3, 1280, 800). +2. Some operators are not counted into FLOPs like GN and custom operators. Refer to [`mmcv.cnn.get_model_complexity_info()`](https://github.com/open-mmlab/mmcv/blob/2.x/mmcv/cnn/utils/flops_counter.py) for details. +3. The FLOPs of two-stage detectors is dependent on the number of proposals. + +## Model conversion + +### MMDetection model to ONNX + +We provide a script to convert model to [ONNX](https://github.com/onnx/onnx) format. We also support comparing the output results between Pytorch and ONNX model for verification. More details can refer to [mmdeploy](https://github.com/open-mmlab/mmdeploy) + +### MMDetection 1.x model to MMDetection 2.x + +`tools/model_converters/upgrade_model_version.py` upgrades a previous MMDetection checkpoint +to the new version. Note that this script is not guaranteed to work as some +breaking changes are introduced in the new version. It is recommended to +directly use the new checkpoints. + +```shell +python tools/model_converters/upgrade_model_version.py ${IN_FILE} ${OUT_FILE} [-h] [--num-classes NUM_CLASSES] +``` + +### RegNet model to MMDetection + +`tools/model_converters/regnet2mmdet.py` convert keys in pycls pretrained RegNet models to +MMDetection style. + +```shell +python tools/model_converters/regnet2mmdet.py ${SRC} ${DST} [-h] +``` + +### Detectron ResNet to Pytorch + +`tools/model_converters/detectron2pytorch.py` converts keys in the original detectron pretrained +ResNet models to PyTorch style. + +```shell +python tools/model_converters/detectron2pytorch.py ${SRC} ${DST} ${DEPTH} [-h] +``` + +### Prepare a model for publishing + +`tools/model_converters/publish_model.py` helps users to prepare their model for publishing. + +Before you upload a model to AWS, you may want to + +1. convert model weights to CPU tensors +2. delete the optimizer states and +3. compute the hash of the checkpoint file and append the hash id to the + filename. + +```shell +python tools/model_converters/publish_model.py ${INPUT_FILENAME} ${OUTPUT_FILENAME} +``` + +E.g., + +```shell +python tools/model_converters/publish_model.py work_dirs/faster_rcnn/latest.pth faster_rcnn_r50_fpn_1x_20190801.pth +``` + +The final output filename will be `faster_rcnn_r50_fpn_1x_20190801-{hash id}.pth`. + +## Dataset Conversion + +`tools/data_converters/` contains tools to convert the Cityscapes dataset +and Pascal VOC dataset to the COCO format. + +```shell +python tools/dataset_converters/cityscapes.py ${CITYSCAPES_PATH} [-h] [--img-dir ${IMG_DIR}] [--gt-dir ${GT_DIR}] [-o ${OUT_DIR}] [--nproc ${NPROC}] +python tools/dataset_converters/pascal_voc.py ${DEVKIT_PATH} [-h] [-o ${OUT_DIR}] +``` + +## Dataset Download + +`tools/misc/download_dataset.py` supports downloading datasets such as COCO, VOC, and LVIS. + +```shell +python tools/misc/download_dataset.py --dataset-name coco2017 +python tools/misc/download_dataset.py --dataset-name voc2007 +python tools/misc/download_dataset.py --dataset-name lvis +``` + +For users in China, these datasets can also be downloaded from [OpenDataLab](https://opendatalab.com/?source=OpenMMLab%20GitHub) with high speed: + +- [COCO2017](https://opendatalab.com/COCO_2017/download?source=OpenMMLab%20GitHub) +- [VOC2007](https://opendatalab.com/PASCAL_VOC2007/download?source=OpenMMLab%20GitHub) +- [VOC2012](https://opendatalab.com/PASCAL_VOC2012/download?source=OpenMMLab%20GitHub) +- [LVIS](https://opendatalab.com/LVIS/download?source=OpenMMLab%20GitHub) + +## Benchmark + +### Robust Detection Benchmark + +`tools/analysis_tools/test_robustness.py` and`tools/analysis_tools/robustness_eval.py` helps users to evaluate model robustness. The core idea comes from [Benchmarking Robustness in Object Detection: Autonomous Driving when Winter is Coming](https://arxiv.org/abs/1907.07484). For more information how to evaluate models on corrupted images and results for a set of standard models please refer to [robustness_benchmarking.md](robustness_benchmarking.md). + +### FPS Benchmark + +`tools/analysis_tools/benchmark.py` helps users to calculate FPS. The FPS value includes model forward and post-processing. In order to get a more accurate value, currently only supports single GPU distributed startup mode. + +```shell +python -m torch.distributed.launch --nproc_per_node=1 --master_port=${PORT} tools/analysis_tools/benchmark.py \ + ${CONFIG} \ + [--checkpoint ${CHECKPOINT}] \ + [--repeat-num ${REPEAT_NUM}] \ + [--max-iter ${MAX_ITER}] \ + [--log-interval ${LOG_INTERVAL}] \ + --launcher pytorch +``` + +Examples: Assuming that you have already downloaded the `Faster R-CNN` model checkpoint to the directory `checkpoints/`. + +```shell +python -m torch.distributed.launch --nproc_per_node=1 --master_port=29500 tools/analysis_tools/benchmark.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \ + --launcher pytorch +``` + +## Miscellaneous + +### Evaluating a metric + +`tools/analysis_tools/eval_metric.py` evaluates certain metrics of a pkl result file +according to a config file. + +```shell +python tools/analysis_tools/eval_metric.py ${CONFIG} ${PKL_RESULTS} [-h] [--format-only] [--eval ${EVAL[EVAL ...]}] + [--cfg-options ${CFG_OPTIONS [CFG_OPTIONS ...]}] + [--eval-options ${EVAL_OPTIONS [EVAL_OPTIONS ...]}] +``` + +### Print the entire config + +`tools/misc/print_config.py` prints the whole config verbatim, expanding all its +imports. + +```shell +python tools/misc/print_config.py ${CONFIG} [-h] [--options ${OPTIONS [OPTIONS...]}] +``` + +## Hyper-parameter Optimization + +### YOLO Anchor Optimization + +`tools/analysis_tools/optimize_anchors.py` provides two method to optimize YOLO anchors. + +One is k-means anchor cluster which refers from [darknet](https://github.com/AlexeyAB/darknet/blob/master/src/detector.c#L1421). + +```shell +python tools/analysis_tools/optimize_anchors.py ${CONFIG} --algorithm k-means --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} --output-dir ${OUTPUT_DIR} +``` + +Another is using differential evolution to optimize anchors. + +```shell +python tools/analysis_tools/optimize_anchors.py ${CONFIG} --algorithm differential_evolution --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} --output-dir ${OUTPUT_DIR} +``` + +E.g., + +```shell +python tools/analysis_tools/optimize_anchors.py configs/yolo/yolov3_d53_8xb8-320-273e_coco.py --algorithm differential_evolution --input-shape 608 608 --device cuda --output-dir work_dirs +``` + +You will get: + +``` +loading annotations into memory... +Done (t=9.70s) +creating index... +index created! +2021-07-19 19:37:20,951 - mmdet - INFO - Collecting bboxes from annotation... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 117266/117266, 15874.5 task/s, elapsed: 7s, ETA: 0s + +2021-07-19 19:37:28,753 - mmdet - INFO - Collected 849902 bboxes. +differential_evolution step 1: f(x)= 0.506055 +differential_evolution step 2: f(x)= 0.506055 +...... + +differential_evolution step 489: f(x)= 0.386625 +2021-07-19 19:46:40,775 - mmdet - INFO Anchor evolution finish. Average IOU: 0.6133754253387451 +2021-07-19 19:46:40,776 - mmdet - INFO Anchor differential evolution result:[[10, 12], [15, 30], [32, 22], [29, 59], [61, 46], [57, 116], [112, 89], [154, 198], [349, 336]] +2021-07-19 19:46:40,798 - mmdet - INFO Result saved in work_dirs/anchor_optimize_result.json +``` + +## Confusion Matrix + +A confusion matrix is a summary of prediction results. + +`tools/analysis_tools/confusion_matrix.py` can analyze the prediction results and plot a confusion matrix table. + +First, run `tools/test.py` to save the `.pkl` detection results. + +Then, run + +``` +python tools/analysis_tools/confusion_matrix.py ${CONFIG} ${DETECTION_RESULTS} ${SAVE_DIR} --show +``` + +And you will get a confusion matrix like this: + +![confusion_matrix_example](https://user-images.githubusercontent.com/12907710/140513068-994cdbf4-3a4a-48f0-8fd8-2830d93fd963.png) + +## COCO Separated & Occluded Mask Metric + +Detecting occluded objects still remains a challenge for state-of-the-art object detectors. +We implemented the metric presented in paper [A Tri-Layer Plugin to Improve Occluded Detection](https://arxiv.org/abs/2210.10046) to calculate the recall of separated and occluded masks. + +There are two ways to use this metric: + +### Offline evaluation + +We provide a script to calculate the metric with a dumped prediction file. + +First, use the `tools/test.py` script to dump the detection results: + +```shell +python tools/test.py ${CONFIG} ${MODEL_PATH} --out results.pkl +``` + +Then, run the `tools/analysis_tools/coco_occluded_separated_recall.py` script to get the recall of separated and occluded masks: + +```shell +python tools/analysis_tools/coco_occluded_separated_recall.py results.pkl --out occluded_separated_recall.json +``` + +The output should be like this: + +``` +loading annotations into memory... +Done (t=0.51s) +creating index... +index created! +processing detection results... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5000/5000, 109.3 task/s, elapsed: 46s, ETA: 0s +computing occluded mask recall... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5550/5550, 780.5 task/s, elapsed: 7s, ETA: 0s +COCO occluded mask recall: 58.79% +COCO occluded mask success num: 3263 +computing separated mask recall... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 3522/3522, 778.3 task/s, elapsed: 5s, ETA: 0s +COCO separated mask recall: 31.94% +COCO separated mask success num: 1125 + ++-----------+--------+-------------+ +| mask type | recall | num correct | ++-----------+--------+-------------+ +| occluded | 58.79% | 3263 | +| separated | 31.94% | 1125 | ++-----------+--------+-------------+ +Evaluation results have been saved to occluded_separated_recall.json. +``` + +### Online evaluation + +We implement `CocoOccludedSeparatedMetric` which inherits from the `CocoMetic`. +To evaluate the recall of separated and occluded masks during training, just replace the evaluator metric type with `'CocoOccludedSeparatedMetric'` in your config: + +```python +val_evaluator = dict( + type='CocoOccludedSeparatedMetric', # modify this + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False) +test_evaluator = val_evaluator +``` + +Please cite the paper if you use this metric: + +```latex +@article{zhan2022triocc, + title={A Tri-Layer Plugin to Improve Occluded Detection}, + author={Zhan, Guanqi and Xie, Weidi and Zisserman, Andrew}, + journal={British Machine Vision Conference}, + year={2022} +} +``` diff --git a/mmdet_code/SR-TOD/docs/en/user_guides/visualization.md b/mmdet_code/SR-TOD/docs/en/user_guides/visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..dade26ed6883fde2e299039008946d29a879f2b2 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/en/user_guides/visualization.md @@ -0,0 +1,91 @@ +# Visualization + +Before reading this tutorial, it is recommended to read MMEngine's [Visualization](https://github.com/open-mmlab/mmengine/blob/main/docs/en/advanced_tutorials/visualization.md) documentation to get a first glimpse of the `Visualizer` definition and usage. + +In brief, the [`Visualizer`](mmengine.visualization.Visualizer) is implemented in MMEngine to meet the daily visualization needs, and contains three main functions: + +- Implement common drawing APIs, such as [`draw_bboxes`](mmengine.visualization.Visualizer.draw_bboxes) which implements bounding box drawing functions, [`draw_lines`](mmengine.visualization.Visualizer.draw_lines) implements the line drawing function. +- Support writing visualization results, learning rate curves, loss function curves, and verification accuracy curves to various backends, including local disks and common deep learning training logging tools such as [TensorBoard](https://www.tensorflow.org/tensorboard) and [Wandb](https://wandb.ai/site). +- Support calling anywhere in the code to visualize or record intermediate states of the model during training or testing, such as feature maps and validation results. + +Based on MMEngine's Visualizer, MMDet comes with a variety of pre-built visualization tools that can be used by the user by simply modifying the following configuration files. + +- The `tools/analysis_tools/browse_dataset.py` script provides a dataset visualization function that draws images and corresponding annotations after Data Transforms, as described in [`browse_dataset.py`](useful_tools.md#Visualization). +- MMEngine implements `LoggerHook`, which uses `Visualizer` to write the learning rate, loss and evaluation results to the backend set by `Visualizer`. Therefore, by modifying the `Visualizer` backend in the configuration file, for example to ` TensorBoardVISBackend` or `WandbVISBackend`, you can implement logging to common training logging tools such as `TensorBoard` or `WandB`, thus making it easy for users to use these visualization tools to analyze and monitor the training process. +- The `VisualizerHook` is implemented in MMDet, which uses the `Visualizer` to visualize or store the prediction results of the validation or prediction phase into the backend set by the `Visualizer`, so by modifying the `Visualizer` backend in the configuration file, for example, to ` TensorBoardVISBackend` or `WandbVISBackend`, you can implement storing the predicted images to `TensorBoard` or `Wandb`. + +## Configuration + +Thanks to the use of the registration mechanism, in MMDet we can set the behavior of the `Visualizer` by modifying the configuration file. Usually, we define the default configuration for the visualizer in `configs/_base_/default_runtime.py`, see [configuration tutorial](config.md) for details. + +```Python +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', + vis_backends=vis_backends, + name='visualizer') +``` + +Based on the above example, we can see that the configuration of `Visualizer` consists of two main parts, namely, the type of `Visualizer` and the visualization backend `vis_backends` it uses. + +- Users can directly use `DetLocalVisualizer` to visualize labels or predictions for support tasks. +- MMDet sets the visualization backend `vis_backend` to the local visualization backend `LocalVisBackend` by default, saving all visualization results and other training information in a local folder. + +## Storage + +MMDet uses the local visualization backend [`LocalVisBackend`](mmengine.visualization.LocalVisBackend) by default, and the model loss, learning rate, model evaluation accuracy and visualization The information stored in `VisualizerHook` and `LoggerHook`, including loss, learning rate, evaluation accuracy will be saved to the `{work_dir}/{config_name}/{time}/{vis_data}` folder by default. In addition, MMDet also supports other common visualization backends, such as `TensorboardVisBackend` and `WandbVisBackend`, and you only need to change the `vis_backends` type in the configuration file to the corresponding visualization backend. For example, you can store data to `TensorBoard` and `Wandb` by simply inserting the following code block into the configuration file. + +```Python +# https://mmengine.readthedocs.io/en/latest/api/visualization.html +_base_.visualizer.vis_backends = [ + dict(type='LocalVisBackend'), # + dict(type='TensorboardVisBackend'), + dict(type='WandbVisBackend'),] +``` + +## Plot + +### Plot the prediction results + +MMDet mainly uses [`DetVisualizationHook`](mmdet.engine.hooks.DetVisualizationHook) to plot the prediction results of validation and test, by default `DetVisualizationHook` is off, and the default configuration is as follows. + +```Python +visualization=dict( # user visualization of validation and test results + type='DetVisualizationHook', + draw=False, + interval=1, + show=False) +``` + +The following table shows the parameters supported by `DetVisualizationHook`. + +| Parameters | Description | +| :--------: | :-----------------------------------------------------------------------------------------------------------: | +| draw | The DetVisualizationHook is turned on and off by the enable parameter, which is the default state. | +| interval | Controls how much iteration to store or display the results of a val or test if VisualizationHook is enabled. | +| show | Controls whether to visualize the results of val or test. | + +If you want to enable `DetVisualizationHook` related functions and configurations during training or testing, you only need to modify the configuration, take `configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py` as an example, draw annotations and predictions at the same time, and display the images, the configuration can be modified as follows + +```Python +visualization = _base_.default_hooks.visualization +visualization.update(dict(draw=True, show=True)) +``` + +
+ +
+ +The `test.py` procedure is further simplified by providing the `--show` and `--show-dir` parameters to visualize the annotation and prediction results during the test without modifying the configuration. + +```Shell +# Show test results +python tools/test.py configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_tiny_8xb32-300e_coco/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --show + +# Specify where to store the prediction results +python tools/test.py configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_tiny_8xb32-300e_coco/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --show-dir imgs/ +``` + +
+ +
diff --git a/mmdet_code/SR-TOD/docs/zh_cn/Makefile b/mmdet_code/SR-TOD/docs/zh_cn/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d4bb2cbb9eddb1bb1b4f366623044af8e4830919 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/_static/css/readthedocs.css b/mmdet_code/SR-TOD/docs/zh_cn/_static/css/readthedocs.css new file mode 100644 index 0000000000000000000000000000000000000000..57ed0ad084827ae75f5c58d3799ff5cfa6e40600 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/_static/css/readthedocs.css @@ -0,0 +1,6 @@ +.header-logo { + background-image: url("../image/mmdet-logo.png"); + background-size: 156px 40px; + height: 40px; + width: 156px; +} diff --git a/mmdet_code/SR-TOD/docs/zh_cn/_static/image/mmdet-logo.png b/mmdet_code/SR-TOD/docs/zh_cn/_static/image/mmdet-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..da0b5a3f01ba8ba79c63189e09b4689f3fe25472 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/_static/image/mmdet-logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3cbc8783587b4c1edd6300c8026007514b8fee8298d2a7cfa48a53936f47610 +size 32181 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/conventions.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/conventions.md new file mode 100644 index 0000000000000000000000000000000000000000..9fb1f14c89840f24a068a07469db92c5c5022324 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/conventions.md @@ -0,0 +1,109 @@ +# 默认约定 + +如果你想把 MMDetection 修改为自己的项目,请遵循下面的约定。 + +## 关于图片 shape 顺序的说明 + +在OpenMMLab 2.0中, 为了与 OpenCV 的输入参数相一致,图片处理 pipeline 中关于图像 shape 的输入参数总是以 `(width, height)` 的顺序排列。 +相反,为了计算方便,经过 pipeline 和 model 的字段的顺序是 `(height, width)`。具体来说在每个数据 pipeline 处理的结果中,字段和它们的值含义如下: + +- img_shape: (height, width) +- ori_shape: (height, width) +- pad_shape: (height, width) +- batch_input_shape: (height, width) + +以 `Mosaic` 为例,其初始化参数如下所示: + +```python +@TRANSFORMS.register_module() +class Mosaic(BaseTransform): + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + center_ratio_range: Tuple[float, float] = (0.5, 1.5), + bbox_clip_border: bool = True, + pad_val: float = 114.0, + prob: float = 1.0) -> None: + ... + + # img_scale 顺序应该是 (width, height) + self.img_scale = img_scale + + def transform(self, results: dict) -> dict: + ... + + results['img'] = mosaic_img + # (height, width) + results['img_shape'] = mosaic_img.shape[:2] +``` + +## 损失 + +在 MMDetection 中,`model(**data)` 的返回值是一个字典,包含着所有的损失和评价指标,他们将会由 `model(**data)` 返回。 + +例如,在 bbox head 中, + +```python +class BBoxHead(nn.Module): + ... + def loss(self, ...): + losses = dict() + # 分类损失 + losses['loss_cls'] = self.loss_cls(...) + # 分类准确率 + losses['acc'] = accuracy(...) + # 边界框损失 + losses['loss_bbox'] = self.loss_bbox(...) + return losses +``` + +`'bbox_head.loss()'` 在模型 forward 阶段会被调用。返回的字典中包含了 `'loss_bbox'`,`'loss_cls'`,`'acc'`。只有 `'loss_bbox'`, `'loss_cls'` 会被用于反向传播,`'acc'` 只会被作为评价指标来监控训练过程。 + +我们默认,只有那些键的名称中包含 `'loss'` 的值会被用于反向传播。这个行为可以通过修改 `BaseDetector.train_step()` 来改变。 + +## 空 proposals + +在 MMDetection 中,我们为两阶段方法中空 proposals 的情况增加了特殊处理和单元测试。我们同时需要处理整个 batch 和单一图片中空 proposals 的情况。例如,在 CascadeRoIHead 中, + +```python +# 简单的测试 +... + +# 在整个 batch中 都没有 proposals +if rois.shape[0] == 0: + bbox_results = [[ + np.zeros((0, 5), dtype=np.float32) + for _ in range(self.bbox_head[-1].num_classes) + ]] * num_imgs + if self.with_mask: + mask_classes = self.mask_head[-1].num_classes + segm_results = [[[] for _ in range(mask_classes)] + for _ in range(num_imgs)] + results = list(zip(bbox_results, segm_results)) + else: + results = bbox_results + return results +... + +# 在单张图片中没有 proposals +for i in range(self.num_stages): + ... + if i < self.num_stages - 1: + for j in range(num_imgs): + # 处理空 proposals + if rois[j].shape[0] > 0: + bbox_label = cls_score[j][:, :-1].argmax(dim=1) + refine_roi = self.bbox_head[i].regress_by_class( + rois[j], bbox_label[j], bbox_pred[j], img_metas[j]) + refine_roi_list.append(refine_roi) +``` + +如果你有自定义的 `RoIHead`, 你可以参考上面的方法来处理空 proposals 的情况。 + +## 全景分割数据集 + +在 MMDetection 中,我们支持了 COCO 全景分割数据集 `CocoPanopticDataset`。对于它的实现,我们在这里声明一些默认约定。 + +1. 在 mmdet\<=2.16.0 时,语义分割标注中的前景和背景标签范围与 MMDetection 中的默认规定有所不同。标签 `0` 代表 `VOID` 标签。 + 从 mmdet=2.17.0 开始,为了和框的类别标注保持一致,语义分割标注的类别标签也改为从 `0` 开始,标签 `255` 代表 `VOID` 类。 + 为了达成这一目标,我们在流程 `Pad` 里支持了设置 `seg` 的填充值的功能。 +2. 在评估中,全景分割结果必须是一个与原图大小相同的图。结果图中每个像素的值有如此形式:`instance_id * INSTANCE_OFFSET + category_id`。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_dataset.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_dataset.md new file mode 100644 index 0000000000000000000000000000000000000000..e845f37f2db4b92f1fb600baf4d8d0a8dab1a7c0 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_dataset.md @@ -0,0 +1,425 @@ +# 自定义数据集 + +## 支持新的数据格式 + +为了支持新的数据格式,可以选择将数据转换成现成的格式(COCO 或者 PASCAL)或将其转换成中间格式。当然也可以选择以离线的形式(在训练之前使用脚本转换)或者在线的形式(实现一个新的 dataset 在训练中进行转换)来转换数据。 + +在 MMDetection 中,建议将数据转换成 COCO 格式并以离线的方式进行,因此在完成数据转换后只需修改配置文件中的标注数据的路径和类别即可。 + +### 将新的数据格式转换为现有的数据格式 + +最简单的方法就是将你的数据集转换成现有的数据格式(COCO 或者 PASCAL VOC) + +COCO 格式的 JSON 标注文件有如下必要的字段: + +```python +'images': [ + { + 'file_name': 'COCO_val2014_000000001268.jpg', + 'height': 427, + 'width': 640, + 'id': 1268 + }, + ... +], + +'annotations': [ + { + 'segmentation': [[192.81, + 247.09, + ... + 219.03, + 249.06]], # 如果有 mask 标签且为多边形 XY 点坐标格式,则需要保证至少包括 3 个点坐标,否则为无效多边形 + 'area': 1035.749, + 'iscrowd': 0, + 'image_id': 1268, + 'bbox': [192.81, 224.8, 74.73, 33.43], + 'category_id': 16, + 'id': 42986 + }, + ... +], + +'categories': [ + {'id': 0, 'name': 'car'}, + ] +``` + +在 JSON 文件中有三个必要的键: + +- `images`: 包含多个图片以及它们的信息的数组,例如 `file_name`、`height`、`width` 和 `id`。 +- `annotations`: 包含多个实例标注信息的数组。 +- `categories`: 包含多个类别名字和 ID 的数组。 + +在数据预处理之后,使用现有的数据格式来训练自定义的新数据集有如下两步(以 COCO 为例): + +1. 为自定义数据集修改配置文件。 +2. 检查自定义数据集的标注。 + +这里我们举一个例子来展示上面的两个步骤,这个例子使用包括 5 个类别的 COCO 格式的数据集来训练一个现有的 Cascade Mask R-CNN R50-FPN 检测器 + +#### 1. 为自定义数据集修改配置文件 + +配置文件的修改涉及两个方面: + +1. `dataloaer` 部分。需要在 `train_dataloader.dataset`、`val_dataloader.dataset` 和 `test_dataloader.dataset` 中添加 `metainfo=dict(classes=classes)`, 其中 classes 必须是 tuple 类型。 +2. `model` 部分中的 `num_classes`。需要将默认值(COCO 数据集中为 80)修改为自定义数据集中的类别数。 + +`configs/my_custom_config.py` 内容如下: + +```python + +# 新的配置来自基础的配置以更好地说明需要修改的地方 +_base_ = './cascade_mask_rcnn_r50_fpn_1x_coco.py' + +# 1. 数据集设定 +dataset_type = 'CocoDataset' +classes = ('a', 'b', 'c', 'd', 'e') +data_root='path/to/your/' + +train_dataloader = dict( + batch_size=2, + num_workers=2, + dataset=dict( + type=dataset_type, + # 将类别名字添加至 `metainfo` 字段中 + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='train/annotation_data', + data_prefix=dict(img='train/image_data') + ) + ) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + dataset=dict( + type=dataset_type, + test_mode=True, + # 将类别名字添加至 `metainfo` 字段中 + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='val/annotation_data', + data_prefix=dict(img='val/image_data') + ) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + dataset=dict( + type=dataset_type, + test_mode=True, + # 将类别名字添加至 `metainfo` 字段中 + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='test/annotation_data', + data_prefix=dict(img='test/image_data') + ) + ) + +# 2. 模型设置 + +# 将所有的 `num_classes` 默认值修改为 5(原来为80) +model = dict( + roi_head=dict( + bbox_head=[ + dict( + type='Shared2FCBBoxHead', + # 将所有的 `num_classes` 默认值修改为 5(原来为 80) + num_classes=5), + dict( + type='Shared2FCBBoxHead', + # 将所有的 `num_classes` 默认值修改为 5(原来为 80) + num_classes=5), + dict( + type='Shared2FCBBoxHead', + # 将所有的 `num_classes` 默认值修改为 5(原来为 80) + num_classes=5)], + # 将所有的 `num_classes` 默认值修改为 5(原来为 80) + mask_head=dict(num_classes=5))) +``` + +#### 2. 检查自定义数据集的标注 + +假设你自己的数据集是 COCO 格式,那么需要保证数据的标注没有问题: + +1. 标注文件中 `categories` 的长度要与配置中的 `classes` 元组长度相匹配,它们都表示有几类。(如例子中有 5 个类别) +2. 配置文件中 `classes` 字段应与标注文件里 `categories` 下的 `name` 有相同的元素且顺序一致。MMDetection 会自动将 `categories` 中不连续的 `id` 映射成连续的索引,因此 `categories` 下的 `name`的字符串顺序会影响标签的索引。同时,配置文件中的 `classes` 的字符串顺序也会影响到预测框可视化时的标签。 +3. `annotations` 中的 `category_id` 必须是有效的值。比如所有 `category_id` 的值都应该属于 `categories` 中的 `id`。 + +下面是一个有效标注的例子: + +```python + +'annotations': [ + { + 'segmentation': [[192.81, + 247.09, + ... + 219.03, + 249.06]], # 如果有 mask 标签。 + 'area': 1035.749, + 'iscrowd': 0, + 'image_id': 1268, + 'bbox': [192.81, 224.8, 74.73, 33.43], + 'category_id': 16, + 'id': 42986 + }, + ... +], + +# MMDetection 会自动将 `categories` 中不连续的 `id` 映射成连续的索引。 +'categories': [ + {'id': 1, 'name': 'a'}, {'id': 3, 'name': 'b'}, {'id': 4, 'name': 'c'}, {'id': 16, 'name': 'd'}, {'id': 17, 'name': 'e'}, + ] +``` + +我们使用这种方式来支持 CityScapes 数据集。脚本在 [cityscapes.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/dataset_converters/cityscapes.py) 并且我们提供了微调的 [configs](https://github.com/open-mmlab/mmdetection/blob/main/configs/cityscapes). + +**注意** + +1. 对于实例分割数据集, **MMDetection 目前只支持评估 COCO 格式的 mask AP**. +2. 推荐训练之前进行离线转换,这样就可以继续使用 `CocoDataset` 且只需修改标注文件的路径以及训练的种类。 + +### 调整新的数据格式为中间格式 + +如果不想将标注格式转换为 COCO 或者 PASCAL 格式也是可行的。实际上,我们在 MMEngine 的 [BaseDataset](https://github.com/open-mmlab/mmengine/blob/main/mmengine/dataset/base_dataset.py#L116) 中定义了一种简单的标注格式并且与所有现有的数据格式兼容,也能进行离线或者在线转换。 + +数据集的标注必须为 `json` 或 `yaml`,`yml` 或 `pickle`,`pkl` 格式;标注文件中存储的字典必须包含 `metainfo` 和 `data_list` 两个字段。其中 `metainfo` 是一个字典,里面包含数据集的元信息,例如类别信息;`data_list` 是一个列表,列表中每个元素是一个字典,该字典定义了一个原始数据(raw data),每个原始数据包含一个或若干个训练/测试样本。 + +以下是一个 JSON 标注文件的例子: + +```json +{ + 'metainfo': + { + 'classes': ('person', 'bicycle', 'car', 'motorcycle'), + ... + }, + 'data_list': + [ + { + "img_path": "xxx/xxx_1.jpg", + "height": 604, + "width": 640, + "instances": + [ + { + "bbox": [0, 0, 10, 20], + "bbox_label": 1, + "ignore_flag": 0 + }, + { + "bbox": [10, 10, 110, 120], + "bbox_label": 2, + "ignore_flag": 0 + } + ] + }, + { + "img_path": "xxx/xxx_2.jpg", + "height": 320, + "width": 460, + "instances": + [ + { + "bbox": [10, 0, 20, 20], + "bbox_label": 3, + "ignore_flag": 1 + } + ] + }, + ... + ] +} +``` + +有些数据集可能会提供如:crowd/difficult/ignored bboxes 标注,那么我们使用 `ignore_flag`来包含它们。 + +在得到上述标准的数据标注格式后,可以直接在配置中使用 MMDetection 的 [BaseDetDataset](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/datasets/base_det_dataset.py#L13) ,而无需进行转换。 + +### 自定义数据集例子 + +假设文本文件中表示的是一种全新的标注格式。边界框的标注信息保存在 `annotation.txt` 中,内容如下: + +``` +# +000001.jpg +1280 720 +2 +10 20 40 60 1 +20 40 50 60 2 +# +000002.jpg +1280 720 +3 +50 20 40 60 2 +20 40 30 45 2 +30 40 50 60 3 +``` + +我们可以在 `mmdet/datasets/my_dataset.py` 中创建一个新的 dataset 用以加载数据。 + +```python +import mmengine +from mmdet.base_det_dataset import BaseDetDataset +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class MyDataset(BaseDetDataset): + + METAINFO = { + 'classes': ('person', 'bicycle', 'car', 'motorcycle'), + 'palette': [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230)] + } + + def load_data_list(self, ann_file): + ann_list = mmengine.list_from_file(ann_file) + + data_infos = [] + for i, ann_line in enumerate(ann_list): + if ann_line != '#': + continue + + img_shape = ann_list[i + 2].split(' ') + width = int(img_shape[0]) + height = int(img_shape[1]) + bbox_number = int(ann_list[i + 3]) + + instances = [] + for anns in ann_list[i + 4:i + 4 + bbox_number]: + instance = {} + instance['bbox'] = [float(ann) for ann in anns.split(' ')[:4]] + instance['bbox_label']=int(anns[4]) + instances.append(instance) + + data_infos.append( + dict( + img_path=ann_list[i + 1], + img_id=i, + width=width, + height=height, + instances=instances + )) + + return data_infos +``` + +配置文件中,可以使用 `MyDataset` 进行如下修改 + +```python +dataset_A_train = dict( + type='MyDataset', + ann_file = 'image_list.txt', + pipeline=train_pipeline +) +``` + +## 使用 dataset 包装器自定义数据集 + +MMEngine 也支持非常多的数据集包装器(wrapper)来混合数据集或在训练时修改数据集的分布,其支持如下三种数据集包装: + +- `RepeatDataset`:将整个数据集简单地重复。 +- `ClassBalancedDataset`:以类别均衡的方式重复数据集。 +- `ConcatDataset`:合并数据集。 + +具体使用方式见 [MMEngine 数据集包装器](#TODO)。 + +## 修改数据集的类别 + +根据现有数据集的类型,我们可以修改它们的类别名称来训练其标注的子集。 +例如,如果只想训练当前数据集中的三个类别,那么就可以修改数据集的 `metainfo` 字典,数据集就会自动屏蔽掉其他类别的真实框。 + +```python +classes = ('person', 'bicycle', 'car') +train_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +val_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +test_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +``` + +**注意** + +- 在 MMDetection v2.5.0 之前,如果类别为集合时数据集将自动过滤掉不包含 GT 的图片,且没办法通过修改配置将其关闭。这是一种不可取的行为而且会引起混淆,因为当类别不是集合时数据集时,只有在 `filter_empty_gt=True` 以及 `test_mode=False` 的情况下才会过滤掉不包含 GT 的图片。在 MMDetection v2.5.0 之后,我们将图片的过滤以及类别的修改进行解耦,数据集只有在 `filter_cfg=dict(filter_empty_gt=True)` 和 `test_mode=False` 的情况下才会过滤掉不包含 GT 的图片,无论类别是否为集合。设置类别只会影响用于训练的标注类别,用户可以自行决定是否过滤不包含 GT 的图片。 +- 直接使用 MMEngine 中的 `BaseDataset` 或者 MMDetection 中的 `BaseDetDataset` 时用户不能通过修改配置来过滤不含 GT 的图片,但是可以通过离线的方式来解决。 +- 当设置数据集中的 `classes` 时,记得修改 `num_classes`。从 v2.9.0 (PR#4508) 之后,我们实现了 [NumClassCheckHook](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/engine/hooks/num_class_check_hook.py) 来检查类别数是否一致。 + +## COCO 全景分割数据集 + +现在我们也支持 COCO Panoptic Dataset,全景注释的格式与 COCO 格式不同,其前景和背景都将存在于注释文件中。COCO Panoptic 格式的注释 JSON 文件具有以下必要的键: + +```python +'images': [ + { + 'file_name': '000000001268.jpg', + 'height': 427, + 'width': 640, + 'id': 1268 + }, + ... +] + +'annotations': [ + { + 'filename': '000000001268.jpg', + 'image_id': 1268, + 'segments_info': [ + { + 'id':8345037, # One-to-one correspondence with the id in the annotation map. + 'category_id': 51, + 'iscrowd': 0, + 'bbox': (x1, y1, w, h), # The bbox of the background is the outer rectangle of its mask. + 'area': 24315 + }, + ... + ] + }, + ... +] + +'categories': [ # including both foreground categories and background categories + {'id': 0, 'name': 'person'}, + ... + ] +``` + +此外,`seg` 必须设置为全景注释图像的路径。 + +```python +dataset_type = 'CocoPanopticDataset' +data_root='path/to/your/' + +train_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='train/image_data/', seg='train/panoptic/image_annotation_data/') + ) +) +val_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='val/image_data/', seg='val/panoptic/image_annotation_data/') + ) +) +test_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='test/image_data/', seg='test/panoptic/image_annotation_data/') + ) +) +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_losses.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_losses.md new file mode 100644 index 0000000000000000000000000000000000000000..07ccccda128f7604b6bc80bf30b2251498eede5e --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_losses.md @@ -0,0 +1,125 @@ +# 自定义损失函数 + +MMDetection 为用户提供了不同的损失函数。但是默认的配置可能无法适应不同的数据和模型,所以用户可能会希望修改某一个损失函数来适应新的情况。 + +本教程首先详细的解释计算损失的过程然后给出一些关于如何修改每一个步骤的指导。对损失的修改可以被分为微调和加权。 + +## 一个损失的计算过程 + +给定输入(包括预测和目标,以及权重),损失函数会把输入的张量映射到最后的损失标量。映射过程可以分为下面五个步骤: + +1. 设置采样方法为对正负样本进行采样。 + +2. 通过损失核函数获取**元素**或者**样本**损失。 + +3. 通过权重张量来给损失**逐元素**权重。 + +4. 把损失张量归纳为一个**标量**。 + +5. 用一个**张量**给当前损失一个权重。 + +## 设置采样方法(步骤 1) + +对于一些损失函数,需要采样策略来避免正负样本之间的不平衡。 + +例如,在RPN head中使用`CrossEntropyLoss`时,我们需要在`train_cfg`中设置`RandomSampler` + +```python +train_cfg=dict( + rpn=dict( + sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False)) +``` + +对于其他一些具有正负样本平衡机制的损失,例如 Focal Loss、GHMC 和 QualityFocalLoss,不再需要进行采样。 + +## 微调损失 + +微调一个损失主要与步骤 2,4,5 有关,大部分的修改可以在配置文件中指定。这里我们用 [Focal Loss (FL)](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/focal_loss.py) 作为例子。 +下面的代码分别是构建 FL 的方法和它的配置文件,他们是一一对应的。 + +```python +@LOSSES.register_module() +class FocalLoss(nn.Module): + + def __init__(self, + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + reduction='mean', + loss_weight=1.0): +``` + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0) +``` + +### 微调超参数(步骤2) + +`gamma` 和 `beta` 是 Focal Loss 中的两个超参数。如果我们想把 `gamma` 的值设为 1.5,把 `alpha` 的值设为 0.5,我们可以在配置文件中按照如下指定: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=1.5, + alpha=0.5, + loss_weight=1.0) +``` + +### 微调归纳方式(步骤4) + +Focal Loss 默认的归纳方式是 `mean`。如果我们想把归纳方式从 `mean` 改成 `sum`,我们可以在配置文件中按照如下指定: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0, + reduction='sum') +``` + +### 微调损失权重(步骤5) + +这里的损失权重是一个标量,他用来控制多任务学习中不同损失的重要程度,例如,分类损失和回归损失。如果我们想把分类损失的权重设为 0.5,我们可以在配置文件中如下指定: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=0.5) +``` + +## 加权损失(步骤3) + +加权损失就是我们逐元素修改损失权重。更具体来说,我们给损失张量乘以一个与他有相同形状的权重张量。所以,损失中不同的元素可以被赋予不同的比例,所以这里叫做逐元素。损失的权重在不同模型中变化很大,而且与上下文相关,但是总的来说主要有两种损失权重:分类损失的 `label_weights` 和边界框的 `bbox_weights`。你可以在相应的头中的 `get_target` 方法中找到他们。这里我们使用 [ATSSHead](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/dense_heads/atss_head.py#L322) 作为一个例子。它继承了 [AnchorHead](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/dense_heads/anchor_head.py) ,但是我们重写它的 +`get_targets` 方法来产生不同的 `label_weights` 和 `bbox_weights`。 + +``` +class ATSSHead(AnchorHead): + + ... + + def get_targets(self, + anchor_list, + valid_flag_list, + gt_bboxes_list, + img_metas, + gt_bboxes_ignore_list=None, + gt_labels_list=None, + label_channels=1, + unmap_outputs=True): +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_models.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_models.md new file mode 100644 index 0000000000000000000000000000000000000000..5fa77e4195ba3f50dd113b1a25cb2307cdc3218f --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_models.md @@ -0,0 +1,412 @@ +# 自定义模型 + +我们简单地把模型的各个组件分为五类: + +- 主干网络 (backbone):通常是一个用来提取特征图 (feature map) 的全卷积网络 (FCN network),例如:ResNet, MobileNet。 +- Neck:主干网络和 Head 之间的连接部分,例如:FPN, PAFPN。 +- Head:用于具体任务的组件,例如:边界框预测和掩码预测。 +- 区域提取器 (roi extractor):从特征图中提取 RoI 特征,例如:RoI Align。 +- 损失 (loss):在 Head 组件中用于计算损失的部分,例如:FocalLoss, L1Loss, GHMLoss. + +## 开发新的组件 + +### 添加一个新的主干网络 + +这里,我们以 MobileNet 为例来展示如何开发新组件。 + +#### 1. 定义一个新的主干网络(以 MobileNet 为例) + +新建一个文件 `mmdet/models/backbones/mobilenet.py` + +```python +import torch.nn as nn + +from mmdet.registry import MODELS + + +@MODELS.register_module() +class MobileNet(nn.Module): + + def __init__(self, arg1, arg2): + pass + + def forward(self, x): # should return a tuple + pass +``` + +#### 2. 导入该模块 + +你可以添加下述代码到 `mmdet/models/backbones/__init__.py` + +```python +from .mobilenet import MobileNet +``` + +或添加: + +```python +custom_imports = dict( + imports=['mmdet.models.backbones.mobilenet'], + allow_failed_imports=False) +``` + +到配置文件以避免原始代码被修改。 + +#### 3. 在你的配置文件中使用该主干网络 + +```python +model = dict( + ... + backbone=dict( + type='MobileNet', + arg1=xxx, + arg2=xxx), + ... +``` + +### 添加新的 Neck + +#### 1. 定义一个 Neck(以 PAFPN 为例) + +新建一个文件 `mmdet/models/necks/pafpn.py` + +```python +import torch.nn as nn + +from mmdet.registry import MODELS + + +@MODELS.register_module() +class PAFPN(nn.Module): + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False): + pass + + def forward(self, inputs): + # implementation is ignored + pass +``` + +#### 2. 导入该模块 + +你可以添加下述代码到 `mmdet/models/necks/__init__.py` + +```python +from .pafpn import PAFPN +``` + +或添加: + +```python +custom_imports = dict( + imports=['mmdet.models.necks.pafpn'], + allow_failed_imports=False) +``` + +到配置文件以避免原始代码被修改。 + +#### 3. 修改配置文件 + +```python +neck=dict( + type='PAFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5) +``` + +### 添加新的 Head + +我们以 [Double Head R-CNN](https://arxiv.org/abs/1904.06493) 为例来展示如何添加一个新的 Head。 + +首先,添加一个新的 bbox head 到 `mmdet/models/roi_heads/bbox_heads/double_bbox_head.py`。 +Double Head R-CNN 在目标检测上实现了一个新的 bbox head。为了实现 bbox head,我们需要使用如下的新模块中三个函数。 + +```python +from typing import Tuple + +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule, ModuleList +from torch import Tensor + +from mmdet.models.backbones.resnet import Bottleneck +from mmdet.registry import MODELS +from mmdet.utils import ConfigType, MultiConfig, OptConfigType, OptMultiConfig +from .bbox_head import BBoxHead + + +@MODELS.register_module() +class DoubleConvFCBBoxHead(BBoxHead): + r"""Bbox head used in Double-Head R-CNN + + .. code-block:: none + + /-> cls + /-> shared convs -> + \-> reg + roi features + /-> cls + \-> shared fc -> + \-> reg + """ # noqa: W605 + + def __init__(self, + num_convs: int = 0, + num_fcs: int = 0, + conv_out_channels: int = 1024, + fc_out_channels: int = 1024, + conv_cfg: OptConfigType = None, + norm_cfg: ConfigType = dict(type='BN'), + init_cfg: MultiConfig = dict( + type='Normal', + override=[ + dict(type='Normal', name='fc_cls', std=0.01), + dict(type='Normal', name='fc_reg', std=0.001), + dict( + type='Xavier', + name='fc_branch', + distribution='uniform') + ]), + **kwargs) -> None: + kwargs.setdefault('with_avg_pool', True) + super().__init__(init_cfg=init_cfg, **kwargs) + + def forward(self, x_cls: Tensor, x_reg: Tensor) -> Tuple[Tensor]: + +``` + +然后,如有必要,实现一个新的 bbox head。我们打算从 `StandardRoIHead` 来继承新的 `DoubleHeadRoIHead`。我们可以发现 `StandardRoIHead` 已经实现了下述函数。 + +```python +from typing import List, Optional, Tuple + +import torch +from torch import Tensor + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.structures import DetDataSample +from mmdet.structures.bbox import bbox2roi +from mmdet.utils import ConfigType, InstanceList +from ..task_modules.samplers import SamplingResult +from ..utils import empty_instances, unpack_gt_instances +from .base_roi_head import BaseRoIHead + + +@MODELS.register_module() +class StandardRoIHead(BaseRoIHead): + """Simplest base roi head including one bbox head and one mask head.""" + + def init_assigner_sampler(self) -> None: + + def init_bbox_head(self, bbox_roi_extractor: ConfigType, + bbox_head: ConfigType) -> None: + + def init_mask_head(self, mask_roi_extractor: ConfigType, + mask_head: ConfigType) -> None: + + def forward(self, x: Tuple[Tensor], + rpn_results_list: InstanceList) -> tuple: + + def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, + batch_data_samples: List[DetDataSample]) -> dict: + + def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict: + + def bbox_loss(self, x: Tuple[Tensor], + sampling_results: List[SamplingResult]) -> dict: + + def mask_loss(self, x: Tuple[Tensor], + sampling_results: List[SamplingResult], bbox_feats: Tensor, + batch_gt_instances: InstanceList) -> dict: + + def _mask_forward(self, + x: Tuple[Tensor], + rois: Tensor = None, + pos_inds: Optional[Tensor] = None, + bbox_feats: Optional[Tensor] = None) -> dict: + + def predict_bbox(self, + x: Tuple[Tensor], + batch_img_metas: List[dict], + rpn_results_list: InstanceList, + rcnn_test_cfg: ConfigType, + rescale: bool = False) -> InstanceList: + + def predict_mask(self, + x: Tuple[Tensor], + batch_img_metas: List[dict], + results_list: InstanceList, + rescale: bool = False) -> InstanceList: + +``` + +Double Head 的修改主要在 bbox_forward 的逻辑中,且它从 `StandardRoIHead` 中继承了其他逻辑。在 `mmdet/models/roi_heads/double_roi_head.py` 中,我们用下述代码实现新的 bbox head: + +```python +from typing import Tuple + +from torch import Tensor + +from mmdet.registry import MODELS +from .standard_roi_head import StandardRoIHead + + +@MODELS.register_module() +class DoubleHeadRoIHead(StandardRoIHead): + """RoI head for `Double Head RCNN `_. + + Args: + reg_roi_scale_factor (float): The scale factor to extend the rois + used to extract the regression features. + """ + + def __init__(self, reg_roi_scale_factor: float, **kwargs): + super().__init__(**kwargs) + self.reg_roi_scale_factor = reg_roi_scale_factor + + def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict: + """Box head forward function used in both training and testing. + + Args: + x (tuple[Tensor]): List of multi-level img features. + rois (Tensor): RoIs with the shape (n, 5) where the first + column indicates batch id of each RoI. + + Returns: + dict[str, Tensor]: Usually returns a dictionary with keys: + + - `cls_score` (Tensor): Classification scores. + - `bbox_pred` (Tensor): Box energies / deltas. + - `bbox_feats` (Tensor): Extract bbox RoI features. + """ + bbox_cls_feats = self.bbox_roi_extractor( + x[:self.bbox_roi_extractor.num_inputs], rois) + bbox_reg_feats = self.bbox_roi_extractor( + x[:self.bbox_roi_extractor.num_inputs], + rois, + roi_scale_factor=self.reg_roi_scale_factor) + if self.with_shared_head: + bbox_cls_feats = self.shared_head(bbox_cls_feats) + bbox_reg_feats = self.shared_head(bbox_reg_feats) + cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats) + + bbox_results = dict( + cls_score=cls_score, + bbox_pred=bbox_pred, + bbox_feats=bbox_cls_feats) + return bbox_results +``` + +最终,用户需要把该模块添加到 `mmdet/models/bbox_heads/__init__.py` 和 `mmdet/models/roi_heads/__init__.py` 以使相关的注册表可以找到并加载他们。 + +或者,用户可以添加: + +```python +custom_imports=dict( + imports=['mmdet.models.roi_heads.double_roi_head', 'mmdet.models.roi_heads.bbox_heads.double_bbox_head']) +``` + +到配置文件并实现相同的目的。 + +Double Head R-CNN 的配置文件如下: + +```python +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + roi_head=dict( + type='DoubleHeadRoIHead', + reg_roi_scale_factor=1.3, + bbox_head=dict( + _delete_=True, + type='DoubleConvFCBBoxHead', + num_convs=4, + num_fcs=2, + in_channels=256, + conv_out_channels=1024, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=80, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[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=2.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=2.0)))) + +``` + +从 MMDetection 2.0 版本起,配置系统支持继承配置以使用户可以专注于修改。 +Double Head R-CNN 主要使用了一个新的 `DoubleHeadRoIHead` 和一个新的 `DoubleConvFCBBoxHead`,参数需要根据每个模块的 `__init__` 函数来设置。 + +### 添加新的损失 + +假设你想添加一个新的损失 `MyLoss` 用于边界框回归。 +为了添加一个新的损失函数,用户需要在 `mmdet/models/losses/my_loss.py` 中实现。 +装饰器 `weighted_loss` 可以使损失每个部分加权。 + +```python +import torch +import torch.nn as nn + +from mmdet.registry import LOSSES +from .utils import weighted_loss + + +@weighted_loss +def my_loss(pred, target): + assert pred.size() == target.size() and target.numel() > 0 + loss = torch.abs(pred - target) + return loss + +@LOSSES.register_module() +class MyLoss(nn.Module): + + def __init__(self, reduction='mean', loss_weight=1.0): + super(MyLoss, self).__init__() + self.reduction = reduction + self.loss_weight = loss_weight + + def forward(self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None): + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + loss_bbox = self.loss_weight * my_loss( + pred, target, weight, reduction=reduction, avg_factor=avg_factor) + return loss_bbox +``` + +然后,用户需要把它加到 `mmdet/models/losses/__init__.py`。 + +```python +from .my_loss import MyLoss, my_loss +``` + +或者,你可以添加: + +```python +custom_imports=dict( + imports=['mmdet.models.losses.my_loss']) +``` + +到配置文件来实现相同的目的。 + +如使用,请修改 `loss_xxx` 字段。 +因为 MyLoss 是用于回归的,你需要在 Head 中修改 `loss_xxx` 字段。 + +```python +loss_bbox=dict(type='MyLoss', loss_weight=1.0)) +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_runtime.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_runtime.md new file mode 100644 index 0000000000000000000000000000000000000000..d4a190987899ccefb044e6402b2b67ec998a3136 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_runtime.md @@ -0,0 +1,387 @@ +# 自定义训练配置 + +## 自定义优化相关的配置 + +优化相关的配置现在已全部集成到 `optim_wrapper` 中,通常包含三个域:`optimizer`, `paramwise_cfg`,`clip_grad`,具体细节见 [OptimWrapper](https://mmengine.readthedocs.io/en/latest/tutorials/optim_wrapper.md)。下面这个例子中,使用了 `AdamW` 作为优化器,主干部分的学习率缩小到原来的十分之一,以及添加了梯度裁剪。 + +```python +optim_wrapper = dict( + type='OptimWrapper', + # 优化器 + optimizer=dict( + type='AdamW', + lr=0.0001, + weight_decay=0.05, + eps=1e-8, + betas=(0.9, 0.999)), + + # 参数层面的学习率和正则化设置 + paramwise_cfg=dict( + custom_keys={ + 'backbone': dict(lr_mult=0.1, decay_mult=1.0), + }, + norm_decay_mult=0.0), + + # 梯度裁剪 + clip_grad=dict(max_norm=0.01, norm_type=2)) +``` + +### 自定义 Pytorch 中优化器设置 + +我们已经支持了 Pytorch 中实现的所有优化器,要使用这些优化器唯一要做就是修改配置文件中的 `optimi_wrapper` 中的 `optimzer` 域。比如,如果想要使用 `ADAM` 作为优化器(可能会导致性能下降),所需要做的修改如下。 + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='Adam', lr=0.0003, weight_decay=0.0001)) +``` + +要修改模型的学习率,用户只需要修改 `optimizer` 中的 `lr` 域。用户可以直接参考 PyToch 的 [API doc](https://pytorch.org/docs/stable/optim.html?highlight=optim#module-torch.optim) 来进行参数的设置。 + +### 自定义优化器 + +#### 1. 定义一个新优化器 + +自定义优化器可以定义的方式如下: + +假设你想要添加一个名为 `MyOptimizer` 的优化器,它包含三个参数 `a`,`b`,`c`。你需要新建一个名为 +`mmdet/engine/optimizers` 的文件夹。然后在文件(比如,`mmdet/engine/optimizers/my_optimizer.py`)实现一个新的优化器。 + +```python +from mmdet.registry import OPTIMIZERS +from torch.optim import Optimizer + + +@OPTIMIZERS.register_module() +class MyOptimizer(Optimizer): + + def __init__(self, a, b, c) + +``` + +#### 2. 导入自定义的优化器 + +为了能找到上面的所定义的模块,这个模块必须要先导入到主命名空间中。有两种方式可以实现这一点。 + +- 修改 `mmdet/engine/optimizers/__init__.py` 来导入模块。 + + 新定义的模块必须导入到 `mmdet/engine/optimizers/__init__.py`,这样注册器才能找到该模块并添加它。 + +```python +from .my_optimizer import MyOptimizer +``` + +- 在配置文件使用 `custom_imports` 来手动导入模块。 + +```python +custom_imports = dict(imports=['mmdet.engine.optimizers.my_optimizer'], allow_failed_imports=False) +``` + +`mmdet.engine.optimizers.my_optimizer` 模块将在程序开始时导入,之后 `MyOptimizer` 类会被自动注册。注意:应该导入 `MyOptimizer` 所在的文件,即 `mmdet.engine.optimizers.my_optimizer`,而不是 `mmdet.engine.optimizers.my_optimizer.MyOptimizer`。 + +实际上,用户也可以在别的目录结构下来进行导入模块,只要改模块可以在 `PYTHONPATH` 中找到。 + +#### 3. 在配置文件中指定优化器 + +接下来,你可以在配置文件中的 `optim_wrapper` 域中的中 `optimizer` 域中设置你实现的优化器 `MyOptimizer`。在配置文件中,优化器在 `optimizer` 域中的配置方式如下: + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) +``` + +为了使用你的优化器,可以进行如下修改 + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='MyOptimizer', a=a_value, b=b_value, c=c_value)) +``` + +### 自定义优化器包装构造类 + +一些模型可能存在一些特定参数的优化设置,比如,BN 层的权重衰减。用户可以通过自定义优化器包装构造类来实现这些精细化的参数调整。 + +```python +from mmengine.optim import DefaultOptiWrapperConstructor + +from mmdet.registry import OPTIM_WRAPPER_CONSTRUCTORS +from .my_optimizer import MyOptimizer + + +@OPTIM_WRAPPER_CONSTRUCTORS.register_module() +class MyOptimizerWrapperConstructor(DefaultOptimWrapperConstructor): + + def __init__(self, + optim_wrapper_cfg: dict, + paramwise_cfg: Optional[dict] = None): + + def __call__(self, model: nn.Module) -> OptimWrapper: + + return optim_wrapper + +``` + +优化器包装构造类的具体实现见[这里](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/optimizer/default_constructor.py#L18),用户以它为模板,来实现新的优化器包装构造类。 + +### 额外的设置 + +一些没有被优化器实现的技巧(比如,参数层面的学习率设置)应该通过优化器包装构造类来实现或者钩子。我们列出了一些常用的设置用于稳定训练或者加速训练。请随意创建 PR,发布更多设置。 + +- __使用梯度裁剪来稳定训练__: + 一些模型需要进行梯度裁剪来稳定训练过程,例子如下: + + ```python + optim_wrapper = dict( + _delete_=True, clip_grad=dict(max_norm=35, norm_type=2)) + ``` + + 如果你的配置已经集成了基础配置(包含了 `optim_wrapper` 的配置),那么你需要添加 `_delete_=True` 来覆盖掉不需要的设置。具体见[配置相关的文档](https://mmdetection.readthedocs.io/en/latest/tutorials/config.html)。 + +- __使用动量调度加速模型收敛__: + 我们支持动量调度器根据学习率修改模型的动量,这可以使模型以更快的方式收敛。动量调度器通常与学习率调度器一起使用,例如 [3D 检测](https://github.com/open-mmlab/mmdetection3d/blob/dev-1.x/configs/_base_/schedules/cyclic-20e.py) 中使用以下配置以加速收敛。 + 更多细节请参考 [CosineAnnealingLR](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py#L43) 和 [CosineAnnealingMomentum](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/momentum_scheduler.py#L71) 的具体实现。 + + ```python + param_scheduler = [ + # 学习率调度器 + # 在前 8 个 epoch, 学习率从 0 增大到 lr * 10 + # 在接下来 12 个 epoch, 学习率从 lr * 10 减小到 lr * 1e-4 + dict( + type='CosineAnnealingLR', + T_max=8, + eta_min=lr * 10, + begin=0, + end=8, + by_epoch=True, + convert_to_iter_based=True), + dict( + type='CosineAnnealingLR', + T_max=12, + eta_min=lr * 1e-4, + begin=8, + end=20, + by_epoch=True, + convert_to_iter_based=True), + # 动量调度器 + # 在前 8 个 epoch, 动量从 0 增大到 0.85 / 0.95 + # 在接下来 12 个 epoch, 学习率从 0.85 / 0.95 增大到 1 + dict( + type='CosineAnnealingMomentum', + T_max=8, + eta_min=0.85 / 0.95, + begin=0, + end=8, + by_epoch=True, + convert_to_iter_based=True), + dict( + type='CosineAnnealingMomentum', + T_max=12, + eta_min=1, + begin=8, + end=20, + by_epoch=True, + convert_to_iter_based=True) + ] + ``` + +## 自定义训练策略 + +默认情况下,我们使用 1x 的学习率调整策略,这会条用 MMEngine 中的 [MultiStepLR](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py#L139)。 +我们支持许多其他学习率调整策略,具体见[这里](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py),例如 `CosineAnnealingLR` 和 `PolyLR` 策略。下面有些例子 + +- 多项式学习率调整策略: + + ```python + param_scheduler = [ + dict( + type='PolyLR', + power=0.9, + eta_min=1e-4, + begin=0, + end=8, + by_epoch=True)] + ``` + +- 余弦退火学习率调整策略 + + ```python + param_scheduler = [ + dict( + type='CosineAnnealingLR', + T_max=8, + eta_min=lr * 1e-5, + begin=0, + end=8, + by_epoch=True)] + + ``` + +## 自定义训练循环 + +默认情况下,在 `train_cfg` 中使用 `EpochBasedTrainLoop`,并且在每个 epoch 训练之后进行验证,如下所示。 + +```python +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_begin=1, val_interval=1) +``` + +实际上,[`IterBasedTrainLoop`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py#L183%5D) 和\[`EpochBasedTrainLoop`\](https:// github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py#L18) 支持动态区间的方式进行验证,见下例。 + +```python +# 在第 365001 次迭代之前,我们每 5000 次迭代进行一次评估。 +# 在第 365000 次迭代后,我们每 368750 次迭代进行一次评估, +# 这意味着我们在训练结束时进行评估。 + +interval = 5000 +max_iters = 368750 +dynamic_intervals = [(max_iters // interval * interval + 1, max_iters)] +train_cfg = dict( + type='IterBasedTrainLoop', + max_iters=max_iters, + val_interval=interval, + dynamic_intervals=dynamic_intervals) +``` + +## 自定义钩子 + +### 自定义自行实现的钩子 + +#### 1. 实现一个新的钩子 + +MMEngine 提供了许多有用的[钩子](https://mmdetection.readthedocs.io/en/latest/tutorials/hooks.html),但在某些情况下用户可能需要实现新的钩子。MMDetection 在 v3.0 中支持自定义钩子。因此,用户可以直接在 mmdet 或其基于 mmdet 的代码库中实现钩子,并通过仅在训练中修改配置来使用钩子。 +这里我们给出一个在 mmdet 中创建一个新的钩子并在训练中使用它的例子。 + +```python +from mmengine.hooks import Hook +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class MyHook(Hook): + + def __init__(self, a, b): + + def before_run(self, runner) -> None: + + def after_run(self, runner) -> None: + + def before_train(self, runner) -> None: + + def after_train(self, runner) -> None: + + def before_train_epoch(self, runner) -> None: + + def after_train_epoch(self, runner) -> None: + + def before_train_iter(self, + runner, + batch_idx: int, + data_batch: DATA_BATCH = None) -> None: + + def after_train_iter(self, + runner, + batch_idx: int, + data_batch: DATA_BATCH = None, + outputs: Optional[dict] = None) -> None: +``` + +根据钩子的功能,用户需要在 `before_run`、`after_run`、`before_train`、`after_train`、`before_train_epoch`、`after_train_epoch`、`before_train_iter` 和 `after_train_iter`。还有更多可以插入钩子的点,更多细节请参考 [base hook class](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/hook.py#L9)。 + +#### 2. 注册新钩子 + +然后我们需要导入 `MyHook`。假设该文件位于 `mmdet/engine/hooks/my_hook.py` 中,有两种方法可以做到这一点: + +- 修改 `mmdet/engine/hooks/__init__.py` 以导入它。 + + 新定义的模块应该在 `mmdet/engine/hooks/__init__.py` 中导入,以便注册表找到新模块并添加它: + +```python +from .my_hook import MyHook +``` + +- 在配置中使用 `custom_imports` 手动导入它 + +```python +custom_imports = dict(imports=['mmdet.engine.hooks.my_hook'], allow_failed_imports=False) +``` + +#### 3. 修改配置 + +```python +custom_hooks = [ + dict(type='MyHook', a=a_value, b=b_value) +] +``` + +你还可以通过修改键 `priority` 的值为 `NORMAL` 或 `HIGHEST` 来设置挂钩的优先级,如下所示 + +```python +custom_hooks = [ + dict(type='MyHook', a=a_value, b=b_value, priority='NORMAL') +] +``` + +默认情况下,钩子的优先级在注册期间设置为 `NORMAL`。 + +### 使用 MMDetection 中实现的钩子 + +如果 MMDetection 中已经实现了该钩子,你可以直接修改配置以使用该钩子,如下所示 + +#### 例子: `NumClassCheckHook` + +我们实现了一个名为 [NumClassCheckHook](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/engine/hooks/num_class_check_hook.py) 的自定义钩子来检查 `num_classes` 是否在 head 中和 `dataset` 中的 `classes` 的长度相匹配。 + +我们在 [default_runtime.py](https://github.com/open-mmlab/mmdetection/blob/main/configs/_base_/default_runtime.py) 中设置它。 + +```python +custom_hooks = [dict(type='NumClassCheckHook')] +``` + +### 修改默认运行时钩子 + +有一些常见的钩子是通过 `default_hooks` 注册的,它们是 + +- `IterTimerHook`:记录 “data_time” 用于加载数据和 “time” 用于模型训练步骤的钩子。 +- `LoggerHook`:从`Runner`的不同组件收集日志并将它们写入终端、JSON文件、tensorboard和 wandb 等的钩子。 +- `ParamSchedulerHook`:更新优化器中一些超参数的钩子,例如学习率和动量。 +- `CheckpointHook`:定期保存检查点的钩子。 +- `DistSamplerSeedHook`:为采样器和批处理采样器设置种子的钩子。 +- `DetVisualizationHook`:用于可视化验证和测试过程预测结果的钩子。 + +`IterTimerHook`、`ParamSchedulerHook` 和 `DistSamplerSeedHook` 很简单,通常不需要修改,所以这里我们将展示如何使用 `LoggerHook`、`CheckpointHook` 和 `DetVisualizationHook`。 + +#### CheckpointHook + +除了定期保存检查点,[`CheckpointHook`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py#L19) 提供了其他选项,例如`max_keep_ckpts`、`save_optimizer ` 等。用户可以设置 `max_keep_ckpts` 只保存少量检查点或通过 `save_optimizer` 决定是否存储优化器的状态字典。参数的更多细节在[这里](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py#L19)可以找到。 + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + interval=1, + max_keep_ckpts=3, + save_optimizer=True)) +``` + +#### LoggerHook + +`LoggerHook` 可以设置间隔。详细用法可以在 [docstring](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/logger_hook.py#L18) 中找到。 + +```python +default_hooks = dict(logger=dict(type='LoggerHook', interval=50)) +``` + +#### DetVisualizationHook + +`DetVisualizationHook` 使用 `DetLocalVisualizer` 来可视化预测结果,`DetLocalVisualizer` 支持不同的后端,例如 `TensorboardVisBackend` 和 `WandbVisBackend` (见 [docstring](https://github.com/open-mmlab/mmengine/blob/main/mmengine/visualization/vis_backend.py) 了解更多细节)。用户可以添加多个后端来进行可视化,如下所示。 + +```python +default_hooks = dict( + visualization=dict(type='DetVisualizationHook', draw=True)) + +vis_backends = [dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_transforms.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_transforms.md new file mode 100644 index 0000000000000000000000000000000000000000..aa40717904a9ac34fd5640af6947aa09a85bcd11 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/customize_transforms.md @@ -0,0 +1,47 @@ +# 自定义数据预处理流程 + +1. 在任意文件里写一个新的流程,例如在 `my_pipeline.py`,它以一个字典作为输入并且输出一个字典: + + ```python + import random + from mmcv.transforms import BaseTransform + from mmdet.registry import TRANSFORMS + + + @TRANSFORMS.register_module() + class MyTransform(BaseTransform): + """Add your transform + + Args: + p (float): Probability of shifts. Default 0.5. + """ + + def __init__(self, prob=0.5): + self.prob = prob + + def transform(self, results): + if random.random() > self.prob: + results['dummy'] = True + return results + ``` + +2. 在配置文件里调用并使用你写的数据处理流程,需要确保你的训练脚本能够正确导入新增模块: + + ```python + custom_imports = dict(imports=['path.to.my_pipeline'], allow_failed_imports=False) + + train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='MyTransform', prob=0.2), + dict(type='PackDetInputs') + ] + ``` + +3. 可视化数据增强处理流程的结果 + + 如果想要可视化数据增强处理流程的结果,可以使用 `tools/misc/browse_dataset.py` 直观 + 地浏览检测数据集(图像和标注信息),或将图像保存到指定目录。 + 使用方法请参考[可视化文档](../user_guides/visualization.md) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/data_flow.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/data_flow.md new file mode 100644 index 0000000000000000000000000000000000000000..ccc734f77fa3206520a47140a4780769e04313ae --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/data_flow.md @@ -0,0 +1 @@ +# 数据流(待更新) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/datasets.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/datasets.md new file mode 100644 index 0000000000000000000000000000000000000000..16cc9bfc17baaaa718b4557f402d7628270c6642 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/datasets.md @@ -0,0 +1 @@ +# 数据集(待更新) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/engine.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/engine.md new file mode 100644 index 0000000000000000000000000000000000000000..fa1a2561ea5c87722776745bc874d37496a462bd --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/engine.md @@ -0,0 +1 @@ +# 执行引擎(待更新) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/evaluation.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..0b4954488bb25497e558098575d62325a0f17aa0 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/evaluation.md @@ -0,0 +1 @@ +# 精度评测(待更新) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/how_to.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/how_to.md new file mode 100644 index 0000000000000000000000000000000000000000..6705dafdeabeb443fa2a7a5ef4e0af554556fa2d --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/how_to.md @@ -0,0 +1,220 @@ +本教程收集了任何如何使用 MMDetection 进行 xxx 的答案。 如果您遇到有关`如何做`的问题及答案,请随时更新此文档! + +## 使用 MMPretrain 的骨干网络 + +MMDet、MMPretrain、MMSeg 中的模型注册表都继承自 MMEngine 中的根注册表,允许这些存储库直接使用彼此已经实现的模块。 因此用户可以在 MMDetection 中使用来自 MMPretrain 的骨干网络,而无需实现MMPretrain 中已经存在的网络。 + +### 使用在 MMPretrain 中实现的骨干网络 + +假设想将 `MobileNetV3-small` 作为 `RetinaNet` 的骨干网络,则配置文件如下。 + +```python +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict(imports=['mmpretrain.models'], allow_failed_imports=False) +pretrained = 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v3/convert/mobilenet_v3_small-8427ecf0.pth' +model = dict( + backbone=dict( + _delete_=True, # 将 _base_ 中关于 backbone 的字段删除 + type='mmpretrain.MobileNetV3', # 使用 mmpretrain 中的 MobileNetV3 + arch='small', + out_indices=(3, 8, 11), # 修改 out_indices + init_cfg=dict( + type='Pretrained', + checkpoint=pretrained, + prefix='backbone.')), # mmpretrain 中骨干网络的预训练权重含义 prefix='backbone.',为了正常加载权重,需要把这个 prefix 去掉。 + # 修改 in_channels + neck=dict(in_channels=[24, 48, 96], start_level=0)) +``` + +### 通过 MMPretrain 使用 TIMM 中实现的骨干网络 + +由于 MMPretrain 提供了 Py**T**orch **Im**age **M**odels (`timm`) 骨干网络的封装,用户也可以通过 MMPretrain 直接使用 `timm` 中的骨干网络。假设想将 [`EfficientNet-B1`](../../../configs/timm_example/retinanet_timm-efficientnet-b1_fpn_1x_coco.py) 作为 `RetinaNet` 的骨干网络,则配置文件如下。 + +```python +# https://github.com/open-mmlab/mmdetection/blob/main/configs/timm_example/retinanet_timm_efficientnet_b1_fpn_1x_coco.py +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict(imports=['mmpretrain.models'], allow_failed_imports=False) +model = dict( + backbone=dict( + _delete_=True, # 将 _base_ 中关于 backbone 的字段删除 + type='mmpretrain.TIMMBackbone', # 使用 mmpretrain 中 timm 骨干网络 + model_name='efficientnet_b1', + features_only=True, + pretrained=True, + out_indices=(1, 2, 3, 4)), # 修改 out_indices + neck=dict(in_channels=[24, 40, 112, 320])) # 修改 in_channels + +optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) +``` + +`type='mmpretrain.TIMMBackbone'` 表示在 MMDetection 中使用 MMPretrain 中的 `TIMMBackbone` 类,并且使用的模型为` EfficientNet-B1`,其中 `mmpretrain` 表示 MMPretrain 库,而 `TIMMBackbone ` 表示 MMPretrain 中实现的 TIMMBackbone 包装器。 + +关于层次注册器的具体原理可以参考 [MMEngine 文档](https://mmengine.readthedocs.io/zh_cn/latest/tutorials/config.md#跨项目继承配置文件),关于如何使用 MMPretrain 中的其他 backbone,可以参考 [MMPretrain 文档](https://mmpretrain.readthedocs.io/en/latest/user_guides/config.html)。 + +## 使用马赛克数据增强 + +如果你想在训练中使用 `Mosaic`,那么请确保你同时使用 `MultiImageMixDataset`。以 `Faster R-CNN` 算法为例,你可以通过如下做法实现: + +```python +# 直接打开 configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py ,增添如下字段 +data_root = 'data/coco/' +dataset_type = 'CocoDataset' +img_scale=(1333, 800) + +train_pipeline = [ + dict(type='Mosaic', img_scale=img_scale, pad_val=114.0), + dict( + type='RandomAffine', + scaling_ratio_range=(0.1, 2), + border=(-img_scale[0] // 2, -img_scale[1] // 2)), # 图像经过马赛克处理后会放大4倍,所以我们使用仿射变换来恢复图像的大小。 + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs')) +] + +train_dataset = dict( + _delete_ = True, # 删除不必要的设置 + type='MultiImageMixDataset', + dataset=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=[ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True) + ], + filter_empty_gt=False, + ), + pipeline=train_pipeline + ) + +data = dict( + train=train_dataset + ) +``` + +## 在配置文件中冻结骨干网络后在训练中解冻骨干网络 + +如果你在配置文件中已经冻结了骨干网络并希望在几个训练周期后解冻它,你可以通过 hook 来实现这个功能。以用 ResNet 为骨干网络的 Faster R-CNN 为例,你可以冻结一个骨干网络的一个层并在配置文件中添加如下 `custom_hooks`: + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +model = dict( + # freeze one stage of the backbone network. + backbone=dict(frozen_stages=1), +) +custom_hooks = [dict(type="UnfreezeBackboneEpochBasedHook", unfreeze_epoch=1)] +``` + +同时在 `mmdet/core/hook/unfreeze_backbone_epoch_based_hook.py` 当中书写 `UnfreezeBackboneEpochBasedHook` 类 + +```python +from mmengine.model import is_model_wrapper +from mmengine.hooks import Hook +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class UnfreezeBackboneEpochBasedHook(Hook): + """Unfreeze backbone network Hook. + + Args: + unfreeze_epoch (int): The epoch unfreezing the backbone network. + """ + + def __init__(self, unfreeze_epoch=1): + self.unfreeze_epoch = unfreeze_epoch + + def before_train_epoch(self, runner): + # Unfreeze the backbone network. + # Only valid for resnet. + if runner.epoch == self.unfreeze_epoch: + model = runner.model + if is_module_wrapper(model): + model = model.module + backbone = model.backbone + if backbone.frozen_stages >= 0: + if backbone.deep_stem: + backbone.stem.train() + for param in backbone.stem.parameters(): + param.requires_grad = True + else: + backbone.norm1.train() + for m in [backbone.conv1, backbone.norm1]: + for param in m.parameters(): + param.requires_grad = True + + for i in range(1, backbone.frozen_stages + 1): + m = getattr(backbone, f'layer{i}') + m.train() + for param in m.parameters(): + param.requires_grad = True +``` + +## 获得新的骨干网络的通道数 + +如果你想获得一个新骨干网络的通道数,你可以单独构建这个骨干网络并输入一个伪造的图片来获取每一个阶段的输出。 + +以 `ResNet` 为例: + +```python +from mmdet.models import ResNet +import torch +self = ResNet(depth=18) +self.eval() +inputs = torch.rand(1, 3, 32, 32) +level_outputs = self.forward(inputs) +for level_out in level_outputs: + print(tuple(level_out.shape)) + +``` + +以上脚本的输出为: + +```python +(1, 64, 8, 8) +(1, 128, 4, 4) +(1, 256, 2, 2) +(1, 512, 1, 1) +``` + +用户可以通过将脚本中的 `ResNet(depth=18)` 替换为自己的骨干网络配置来得到新的骨干网络的通道数。 + +# MMDetection 中训练 Detectron2 的模型 + +用户可以使用 `Detectron2Wrapper` 从而在 MMDetection 中使用 Detectron2 的模型。 +我们提供了 [Faster R-CNN](../../../configs/misc/d2_faster-rcnn_r50-caffe_fpn_ms-90k_coco.py), +[Mask R-CNN](../../../configs/misc/d2_mask-rcnn_r50-caffe_fpn_ms-90k_coco.py) 和 [RetinaNet](../../../configs/misc/d2_retinanet_r50-caffe_fpn_ms-90k_coco.py) 的示例来在 MMDetection 中训练/测试 Detectron2 的模型。 + +使用过程中需要注意配置文件中算法组件要和 Detectron2 中的相同。模型初始化时,我们首先初始化 [Detectron2](https://github.com/facebookresearch/detectron2/blob/main/detectron2/config/defaults.py) 的默认设置,然后配置文件中的设置将覆盖默认设置,模型将基于更新过的设置来建立。 +输入数据首先转换成 Detectron2 的类型并输入进 Detectron2 的模型中。在推理阶段,Detectron2 的模型结果将会转换回 MMDetection 的类型。 + +## 使用 Detectron2 的预训练权重 + +`Detectron2Wrapper` 中的权重初始化将不使用 MMDetection 的逻辑。用户可以设置 `model.d2_detector.weights=xxx` 来加载预训练的权重。 +例如,我们可以使用 `model.d2_detector.weights='detectron2://ImageNetPretrained/MSRA/R-50.pkl'` 来加载 ResNet-50 的预训练权重,或者使用 +`model.d2_detector.weights='detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/137260431/model_final_a54504.pkl'` 来加载 Detectron2 中提出的预训练的Mask R-CNN权重。 + +**注意:** 不能直接使用 `load_from` 来加载 Detectron2 的预训练模型,但可以通过 `tools/model_converters/detectron2_to_mmdet.py` 先对该预训练模型进行转换。 + +在测试时,用户应该首先使用 `tools/model_converters/detectron2_to_mmdet.py` 将 Detectron2 的预训练权重转换为 MMDetection 可读取的结构。 + +```shell +python tools/model_converters/detectron2_to_mmdet.py ${Detectron2 ckpt path} ${MMDetectron ckpt path}。 +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/index.rst b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..8e925394a7da2ea4f70b23a2517432b02c8e97fe --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/index.rst @@ -0,0 +1,34 @@ +基础概念 +*************** + +.. toctree:: + :maxdepth: 1 + + data_flow.md + structures.md + models.md + datasets.md + transforms.md + evaluation.md + engine.md + conventions.md + +组件定制 +************************ + +.. toctree:: + :maxdepth: 1 + + customize_models.md + customize_losses.md + customize_dataset.md + customize_transforms.md + customize_runtime.md + +How to +************************ + +.. toctree:: + :maxdepth: 1 + + how_to.md diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/models.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/models.md new file mode 100644 index 0000000000000000000000000000000000000000..c5119d06374fd335e09666f438729b5acf72ea25 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/models.md @@ -0,0 +1 @@ +# 模型(待更新) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/structures.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/structures.md new file mode 100644 index 0000000000000000000000000000000000000000..c2118c34a3f47ae46a173dc099f8d3c0ccfb5456 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/structures.md @@ -0,0 +1 @@ +# 数据结构(待更新) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/transforms.md b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/transforms.md new file mode 100644 index 0000000000000000000000000000000000000000..07d7db2432a39580acd5f1fe6dcdde593bc8ac05 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/advanced_guides/transforms.md @@ -0,0 +1,43 @@ +# 数据变换(待更新) + +按照惯例,我们使用 `Dataset` 和 `DataLoader` 进行多进程的数据加载。`Dataset` 返回字典类型的数据,数据内容为模型 `forward` 方法的各个参数。由于在目标检测中,输入的图像数据具有不同的大小,我们在 `MMCV` 里引入一个新的 `DataContainer` 类去收集和分发不同大小的输入数据。更多细节请参考[这里](https://github.com/open-mmlab/mmcv/blob/master/mmcv/parallel/data_container.py)。 + +数据的准备流程和数据集是解耦的。通常一个数据集定义了如何处理标注数据(annotations)信息,而一个数据流程定义了准备一个数据字典的所有步骤。一个流程包括一系列的操作,每个操作都把一个字典作为输入,然后再输出一个新的字典给下一个变换操作。 + +我们在下图展示了一个经典的数据处理流程。蓝色块是数据处理操作,随着数据流程的处理,每个操作都可以在结果字典中加入新的键(标记为绿色)或更新现有的键(标记为橙色)。 + +![pipeline figure](../../../resources/data_pipeline.png) + +这些操作可以分为数据加载(data loading)、预处理(pre-processing)、格式变化(formatting)和测试时数据增强(test-time augmentation)。 + +下面的例子是 `Faster R-CNN` 的一个流程: + +```python +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=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', flip_ratio=0.5), + dict(type='Normalize', **img_norm_cfg), + 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=(1333, 800), + flip=False, + transforms=[ + dict(type='Resize', keep_ratio=True), + dict(type='RandomFlip'), + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='ImageToTensor', keys=['img']), + dict(type='Collect', keys=['img']), + ]) +] +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/api.rst b/mmdet_code/SR-TOD/docs/zh_cn/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..1b1273219e8ac7af1a9e2e27a3f80d6a18c630e5 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/api.rst @@ -0,0 +1,161 @@ +mmdet.apis +-------------- +.. automodule:: mmdet.apis + :members: + +mmdet.datasets +-------------- + +datasets +^^^^^^^^^^ +.. automodule:: mmdet.datasets + :members: + +api_wrappers +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.datasets.api_wrappers + :members: + +samplers +^^^^^^^^^^ +.. automodule:: mmdet.datasets.samplers + :members: + +transforms +^^^^^^^^^^^^ +.. automodule:: mmdet.datasets.transforms + :members: + +mmdet.engine +-------------- + +hooks +^^^^^^^^^^ +.. automodule:: mmdet.engine.hooks + :members: + +optimizers +^^^^^^^^^^^^^^^ +.. automodule:: mmdet.engine.optimizers + :members: + +runner +^^^^^^^^^^ +.. automodule:: mmdet.engine.runner + :members: + +schedulers +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.engine.schedulers + :members: + +mmdet.evaluation +-------------------- + +functional +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.evaluation.functional + :members: + +metrics +^^^^^^^^^^ +.. automodule:: mmdet.evaluation.metrics + :members: + + +mmdet.models +-------------- + +backbones +^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.backbones + :members: + +data_preprocessors +^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.data_preprocessors + :members: + +dense_heads +^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.dense_heads + :members: + +detectors +^^^^^^^^^^ +.. automodule:: mmdet.models.detectors + :members: + +layers +^^^^^^^^^^ +.. automodule:: mmdet.models.layers + :members: + +losses +^^^^^^^^^^ +.. automodule:: mmdet.models.losses + :members: + +necks +^^^^^^^^^^^^ +.. automodule:: mmdet.models.necks + :members: + +roi_heads +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.roi_heads + :members: + +seg_heads +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.seg_heads + :members: + +task_modules +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.task_modules + :members: + +test_time_augs +^^^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.test_time_augs + :members: + +utils +^^^^^^^^^^ +.. automodule:: mmdet.models.utils + :members: + + +mmdet.structures +-------------------- + +structures +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.structures + :members: + +bbox +^^^^^^^^^^ +.. automodule:: mmdet.structures.bbox + :members: + +mask +^^^^^^^^^^ +.. automodule:: mmdet.structures.mask + :members: + +mmdet.testing +---------------- +.. automodule:: mmdet.testing + :members: + +mmdet.visualization +-------------------- +.. automodule:: mmdet.visualization + :members: + +mmdet.utils +-------------- +.. automodule:: mmdet.utils + :members: diff --git a/mmdet_code/SR-TOD/docs/zh_cn/article.md b/mmdet_code/SR-TOD/docs/zh_cn/article.md new file mode 100644 index 0000000000000000000000000000000000000000..3b698308d6b96bd4df1df356bf2119e9174bc204 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/article.md @@ -0,0 +1,53 @@ +## 中文解读文案汇总(待更新) + +### 1 官方解读文案(v2.x) + +#### 1.1 框架解读 + +- **[轻松掌握 MMDetection 整体构建流程(一)](https://zhuanlan.zhihu.com/p/337375549)** +- **[轻松掌握 MMDetection 整体构建流程(二)](https://zhuanlan.zhihu.com/p/341954021)** +- **[轻松掌握 MMDetection 中 Head 流程](https://zhuanlan.zhihu.com/p/343433169)** + +#### 1.2 算法解读 + +- **[轻松掌握 MMDetection 中常用算法(一):RetinaNet 及配置详解](https://zhuanlan.zhihu.com/p/346198300)** +- **[轻松掌握 MMDetection 中常用算法(二):Faster R-CNN|Mask R-CNN](https://zhuanlan.zhihu.com/p/349807581)** +- [轻松掌握 MMDetection 中常用算法(三):FCOS](https://zhuanlan.zhihu.com/p/358056615) +- [轻松掌握 MMDetection 中常用算法(四):ATSS](https://zhuanlan.zhihu.com/p/358125611) +- [轻松掌握 MMDetection 中常用算法(五):Cascade R-CNN](https://zhuanlan.zhihu.com/p/360952172) +- [轻松掌握 MMDetection 中常用算法(六):YOLOF](https://zhuanlan.zhihu.com/p/370758213) +- [轻松掌握 MMDetection 中常用算法(七):CenterNet](https://zhuanlan.zhihu.com/p/374891478) +- [轻松掌握 MMDetection 中常用算法(八):YOLACT](https://zhuanlan.zhihu.com/p/376347955) +- [轻松掌握 MMDetection 中常用算法(九):AutoAssign](https://zhuanlan.zhihu.com/p/378581552) +- [YOLOX 在 MMDetection 中复现全流程解析](https://zhuanlan.zhihu.com/p/398545304) +- [喂喂喂!你可以减重了!小模型 - MMDetection 新增SSDLite 、 MobileNetV2YOLOV3 两大经典算法](https://zhuanlan.zhihu.com/p/402781143) + +#### 1.3 工具解读 + +- [OpenMMLab 中混合精度训练 AMP 的正确打开方式](https://zhuanlan.zhihu.com/p/375224982) +- [小白都能看懂!手把手教你使用混淆矩阵分析目标检测](https://zhuanlan.zhihu.com/p/443499860) +- [MMDetection 图像缩放 Resize 详细说明 OpenMMLab](https://zhuanlan.zhihu.com/p/381117525) +- [拿什么拯救我的 4G 显卡](https://zhuanlan.zhihu.com/p/430123077) +- [MMDet居然能用MMCls的Backbone?论配置文件的打开方式](https://zhuanlan.zhihu.com/p/436865195) + +#### 1.4 知乎问答 + +- [COCO数据集上1x模式下为什么不采用多尺度训练?](https://www.zhihu.com/question/462170786/answer/1915119662) +- [MMDetection中SOTA论文源码中将训练过程中BN层的eval打开?](https://www.zhihu.com/question/471189603/answer/2195540892) +- [基于PyTorch的MMDetection中训练的随机性来自何处?](https://www.zhihu.com/question/453511684/answer/1839683634) +- [单阶段、双阶段、anchor-based、anchor-free 这四者之间有什么联系吗?](https://www.zhihu.com/question/428972054/answer/1619925296) +- [目标检测的深度学习方法,有推荐的书籍或资料吗?](https://www.zhihu.com/question/391577080/answer/1612593817) +- [大佬们,刚入学研究生,想入门目标检测,有什么学习路线可以入门的?](https://www.zhihu.com/question/343768934/answer/1612580715) +- [目标检测领域还有什么可以做的?](https://www.zhihu.com/question/280703314/answer/1627885518) +- [如何看待Transformer在CV上的应用前景,未来有可能替代CNN吗?](https://www.zhihu.com/question/437495132/answer/1686380553) +- [MMDetection如何学习源码?](https://www.zhihu.com/question/451585041/answer/1832498963) +- [如何具体上手实现目标检测呢?](https://www.zhihu.com/question/341401981/answer/1848561187) + +#### 1.5 其他 + +- **[不得不知的 MMDetection 学习路线(个人经验版)](https://zhuanlan.zhihu.com/p/369826931)** +- [OpenMMLab 社区专访之 YOLOX 复现篇](https://zhuanlan.zhihu.com/p/405913343) + +### 2 社区解读文案(v2.x) + +- [手把手带你实现经典检测网络 Mask R-CNN 的推理](https://zhuanlan.zhihu.com/p/414082071) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/conf.py b/mmdet_code/SR-TOD/docs/zh_cn/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..e687840897186406911e8e5166a5620606b016a4 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/conf.py @@ -0,0 +1,118 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import subprocess +import sys + +import pytorch_sphinx_theme + +sys.path.insert(0, os.path.abspath('../../')) + +# -- Project information ----------------------------------------------------- + +project = 'MMDetection' +copyright = '2018-2021, OpenMMLab' +author = 'MMDetection Authors' +version_file = '../../mmdet/version.py' + + +def get_version(): + with open(version_file, 'r') as f: + exec(compile(f.read(), version_file, 'exec')) + return locals()['__version__'] + + +# The full version, including alpha/beta/rc tags +release = get_version() + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.napoleon', + 'sphinx.ext.viewcode', + 'myst_parser', + 'sphinx_markdown_tables', + 'sphinx_copybutton', +] + +myst_enable_extensions = ['colon_fence'] +myst_heading_anchors = 3 + +autodoc_mock_imports = [ + 'matplotlib', 'pycocotools', 'terminaltables', 'mmdet.version', 'mmcv.ops' +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +source_suffix = { + '.rst': 'restructuredtext', + '.md': 'markdown', +} + +# The main toctree document. +master_doc = 'index' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +# html_theme = 'sphinx_rtd_theme' +html_theme = 'pytorch_sphinx_theme' +html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()] + +html_theme_options = { + 'menu': [ + { + 'name': 'GitHub', + 'url': 'https://github.com/open-mmlab/mmdetection' + }, + ], + # Specify the language of shared menu + 'menu_lang': + 'cn', +} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] +html_css_files = ['css/readthedocs.css'] + +language = 'zh_CN' + +# -- Extension configuration ------------------------------------------------- +# Ignore >>> when copying code +copybutton_prompt_text = r'>>> |\.\.\. ' +copybutton_prompt_is_regexp = True + + +def builder_inited_handler(app): + subprocess.run(['./stat.py']) + + +def setup(app): + app.connect('builder-inited', builder_inited_handler) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/get_started.md b/mmdet_code/SR-TOD/docs/zh_cn/get_started.md new file mode 100644 index 0000000000000000000000000000000000000000..52d061ef50f8a2a18a212fa575930f103facf619 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/get_started.md @@ -0,0 +1,230 @@ +# 开始你的第一步 + +## 依赖 + +本节中,我们将演示如何用 PyTorch 准备一个环境。 + +MMDetection 支持在 Linux,Windows 和 macOS 上运行。它需要 Python 3.7 以上,CUDA 9.2 以上和 PyTorch 1.8 及其以上。 + +```{note} +如果你对 PyTorch 有经验并且已经安装了它,你可以直接跳转到[下一小节](#安装流程)。否则,你可以按照下述步骤进行准备。 +``` + +**步骤 0.** 从[官方网站](https://docs.conda.io/en/latest/miniconda.html)下载并安装 Miniconda。 + +**步骤 1.** 创建并激活一个 conda 环境。 + +```shell +conda create --name openmmlab python=3.8 -y +conda activate openmmlab +``` + +**步骤 2.** 基于 [PyTorch 官方说明](https://pytorch.org/get-started/locally/)安装 PyTorch。 + +在 GPU 平台上: + +```shell +conda install pytorch torchvision -c pytorch +``` + +在 CPU 平台上: + +```shell +conda install pytorch torchvision cpuonly -c pytorch +``` + +## 安装流程 + +我们推荐用户参照我们的最佳实践安装 MMDetection。不过,整个过程也是可定制化的,更多信息请参考[自定义安装](#自定义安装)章节。 + +### 最佳实践 + +**步骤 0.** 使用 [MIM](https://github.com/open-mmlab/mim) 安装 [MMEngine](https://github.com/open-mmlab/mmengine) 和 [MMCV](https://github.com/open-mmlab/mmcv)。 + +```shell +pip install -U openmim +mim install mmengine +mim install "mmcv>=2.0.0" +``` + +**注意:** 在 MMCV-v2.x 中,`mmcv-full` 改名为 `mmcv`,如果你想安装不包含 CUDA 算子精简版,可以通过 `mim install "mmcv-lite>=2.0.0rc1"` 来安装。 + +**步骤 1.** 安装 MMDetection。 + +方案 a:如果你开发并直接运行 mmdet,从源码安装它: + +```shell +git clone https://github.com/open-mmlab/mmdetection.git +cd mmdetection +pip install -v -e . +# "-v" 指详细说明,或更多的输出 +# "-e" 表示在可编辑模式下安装项目,因此对代码所做的任何本地修改都会生效,从而无需重新安装。 +``` + +方案 b:如果你将 mmdet 作为依赖或第三方 Python 包,使用 MIM 安装: + +```shell +mim install mmdet +``` + +## 验证安装 + +为了验证 MMDetection 是否安装正确,我们提供了一些示例代码来执行模型推理。 + +**步骤 1.** 我们需要下载配置文件和模型权重文件。 + +```shell +mim download mmdet --config rtmdet_tiny_8xb32-300e_coco --dest . +``` + +下载将需要几秒钟或更长时间,这取决于你的网络环境。完成后,你会在当前文件夹中发现两个文件 `rtmdet_tiny_8xb32-300e_coco.py` 和 `rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth`。 + +**步骤 2.** 推理验证。 + +方案 a:如果你通过源码安装的 MMDetection,那么直接运行以下命令进行验证: + +```shell +python demo/image_demo.py demo/demo.jpg rtmdet_tiny_8xb32-300e_coco.py --weights rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --device cpu +``` + +你会在当前文件夹中的 `outputs/vis` 文件夹中看到一个新的图像 `demo.jpg`,图像中包含有网络预测的检测框。 + +方案 b:如果你通过 MIM 安装的 MMDetection,那么可以打开你的 Python 解析器,复制并粘贴以下代码: + +```python +from mmdet.apis import init_detector, inference_detector + +config_file = 'rtmdet_tiny_8xb32-300e_coco.py' +checkpoint_file = 'rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth' +model = init_detector(config_file, checkpoint_file, device='cpu') # or device='cuda:0' +inference_detector(model, 'demo/demo.jpg') +``` + +你将会看到一个包含 `DetDataSample` 的列表,预测结果在 `pred_instance` 里,包含有检测框,类别和得分。 + +### 自定义安装 + +#### CUDA 版本 + +在安装 PyTorch 时,你需要指定 CUDA 的版本。如果你不清楚应该选择哪一个,请遵循我们的建议: + +- 对于 Ampere 架构的 NVIDIA GPU,例如 GeForce 30 系列以及 NVIDIA A100,CUDA 11 是必需的。 +- 对于更早的 NVIDIA GPU,CUDA 11 是向后兼容 (backward compatible) 的,但 CUDA 10.2 能够提供更好的兼容性,也更加轻量。 + +请确保你的 GPU 驱动版本满足最低的版本需求,参阅 NVIDIA 官方的 [CUDA 工具箱和相应的驱动版本关系表](https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cuda-major-component-versions__table-cuda-toolkit-driver-versions)。 + +```{note} +如果按照我们的最佳实践,安装 CUDA 运行时库就足够了,这是因为不需要在本地编译 CUDA 代码。但如果你希望从源码编译 MMCV,或是开发其他 CUDA 算子,那么就必须安装完整的 CUDA 工具链,参见 [NVIDIA 官网](https://developer.nvidia.com/cuda-downloads),另外还需要确保该 CUDA 工具链的版本与 PyTorch 安装时的配置相匹配(如用 `conda install` 安装 PyTorch 时指定的 cudatoolkit 版本)。 +``` + +#### 不使用 MIM 安装 MMEngine + +要使用 pip 而不是 MIM 来安装 MMEngine,请遵照 [MMEngine 安装指南](https://mmengine.readthedocs.io/zh_CN/latest/get_started/installation.html)。 + +例如,你可以通过以下命令安装 MMEngine。 + +```shell +pip install mmengine +``` + +#### 不使用 MIM 安装 MMCV + +MMCV 包含 C++ 和 CUDA 扩展,因此其对 PyTorch 的依赖比较复杂。MIM 会自动解析这些依赖,选择合适的 MMCV 预编译包,使安装更简单,但它并不是必需的。 + +要使用 pip 而不是 MIM 来安装 MMCV,请遵照 [MMCV 安装指南](https://mmcv.readthedocs.io/zh_CN/2.x/get_started/installation.html)。它需要您用指定 url 的形式手动指定对应的 PyTorch 和 CUDA 版本。 + +例如,下述命令将会安装基于 PyTorch 1.12.x 和 CUDA 11.6 编译的 MMCV。 + +```shell +pip install "mmcv>=2.0.0" -f https://download.openmmlab.com/mmcv/dist/cu116/torch1.12.0/index.html +``` + +#### 在 CPU 环境中安装 + +MMDetection 可以在 CPU 环境中构建。在 CPU 模式下,可以进行模型训练(需要 MMCV 版本 >= 2.0.0rc1)、测试或者推理。 + +但是,以下功能在该模式下不能使用: + +- Deformable Convolution +- Modulated Deformable Convolution +- ROI pooling +- Deformable ROI pooling +- CARAFE +- SyncBatchNorm +- CrissCrossAttention +- MaskedConv2d +- Temporal Interlace Shift +- nms_cuda +- sigmoid_focal_loss_cuda +- bbox_overlaps + +因此,如果尝试训练/测试/推理包含上述算子的模型,将会报错。下表列出了将会受影响的相关算法。 + +| 操作 | 模型 | +| :-----------------------------------------------------: | :--------------------------------------------------------------------------------------: | +| Deformable Convolution/Modulated Deformable Convolution | DCN、Guided Anchoring、RepPoints、CentripetalNet、VFNet、CascadeRPN、NAS-FCOS、DetectoRS | +| MaskedConv2d | Guided Anchoring | +| CARAFE | CARAFE | +| SyncBatchNorm | ResNeSt | + +#### 在 Google Colab 中安装 + +[Google Colab](https://colab.research.google.com/) 通常已经包含了 PyTorch 环境,因此我们只需要安装 MMEngine,MMCV 和 MMDetection 即可,命令如下: + +**步骤 1.** 使用 [MIM](https://github.com/open-mmlab/mim) 安装 [MMEngine](https://github.com/open-mmlab/mmengine) 和 [MMCV](https://github.com/open-mmlab/mmcv)。 + +```shell +!pip3 install openmim +!mim install mmengine +!mim install "mmcv>=2.0.0,<2.1.0" +``` + +**步骤 2.** 使用源码安装 MMDetection。 + +```shell +!git clone https://github.com/open-mmlab/mmdetection.git +%cd mmdetection +!pip install -e . +``` + +**步骤 3.** 验证安装是否成功。 + +```python +import mmdet +print(mmdet.__version__) +# 预期输出:3.0.0 或其他版本号 +``` + +```{note} +在 Jupyter Notebook 中,感叹号 `!` 用于执行外部命令,而 `%cd` 是一个[魔术命令](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-cd),用于切换 Python 的工作路径。 +``` + +#### 通过 Docker 使用 MMDetection + +我们提供了一个 [Dockerfile](../../docker/Dockerfile) 来构建一个镜像。请确保你的 [docker 版本](https://docs.docker.com/engine/install/) >=19.03。 + +```shell +# 基于 PyTorch 1.9,CUDA 11.1 构建镜像 +# 如果你想要其他版本,只需要修改 Dockerfile +docker build -t mmdetection docker/ +``` + +用以下命令运行 Docker 镜像: + +```shell +docker run --gpus all --shm-size=8g -it -v {DATA_DIR}:/mmdetection/data mmdetection +``` + +### 排除故障 + +如果你在安装过程中遇到一些问题,请先查看 [FAQ](notes/faq.md) 页面。如果没有找到解决方案,你也可以在 GitHub 上[提出一个问题](https://github.com/open-mmlab/mmdetection/issues/new/choose)。 + +### 使用多个 MMDetection 版本进行开发 + +训练和测试的脚本已经在 `PYTHONPATH` 中进行了修改,以确保脚本使用当前目录中的 MMDetection。 + +要使环境中安装默认版本的 MMDetection 而不是当前正在使用的,可以删除出现在相关脚本中的代码: + +```shell +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/index.rst b/mmdet_code/SR-TOD/docs/zh_cn/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..58a4d8a52d3f457033f6691411f1078d9491faef --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/index.rst @@ -0,0 +1,67 @@ +Welcome to MMDetection's documentation! +======================================= + +.. toctree:: + :maxdepth: 1 + :caption: 开始你的第一步 + + overview.md + get_started.md + +.. toctree:: + :maxdepth: 2 + :caption: 使用指南 + + user_guides/index.rst + +.. toctree:: + :maxdepth: 2 + :caption: 进阶教程 + + advanced_guides/index.rst + +.. toctree:: + :maxdepth: 1 + :caption: 迁移版本 + + migration/migration.md + +.. toctree:: + :maxdepth: 1 + :caption: 接口文档(英文) + + api.rst + +.. toctree:: + :maxdepth: 1 + :caption: 模型仓库 + + model_zoo.md + +.. toctree:: + :maxdepth: 1 + :caption: 说明 + + notes/contribution_guide.md + notes/projects.md + notes/faq.md + notes/compatibility.md + +.. toctree:: + :maxdepth: 1 + :caption: 文章 + + article.md + +.. toctree:: + :caption: 语言切换 + + switch_language.md + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`search` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/make.bat b/mmdet_code/SR-TOD/docs/zh_cn/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..922152e96a04a242e6fc40f124261d74890617d8 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/mmdet_code/SR-TOD/docs/zh_cn/migration/api_and_registry_migration.md b/mmdet_code/SR-TOD/docs/zh_cn/migration/api_and_registry_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..66e1c3408063ca0d40bf28bbf96143a0a5c14938 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/migration/api_and_registry_migration.md @@ -0,0 +1 @@ +# 将 API 和注册器从 MMDetection 2.x 迁移至 3.x diff --git a/mmdet_code/SR-TOD/docs/zh_cn/migration/config_migration.md b/mmdet_code/SR-TOD/docs/zh_cn/migration/config_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..c4f9c8e3d2df72ee352d7af20072645154004db6 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/migration/config_migration.md @@ -0,0 +1,814 @@ +# 将配置文件从 MMDetection 2.x 迁移至 3.x + +MMDetection 3.x 的配置文件与 2.x 相比有较大变化,这篇文档将介绍如何将 2.x 的配置文件迁移到 3.x。 + +在前面的[配置文件教程](../user_guides/config.md)中,我们以 Mask R-CNN 为例介绍了 MMDetection 3.x 的配置文件结构,这里我们将按同样的结构介绍如何将 2.x 的配置文件迁移至 3.x。 + +## 模型配置 + +模型的配置与 2.x 相比并没有太大变化,对于模型的 backbone,neck,head,以及 train_cfg 和 test_cfg,它们的参数与 2.x 版本的参数保持一致。 + +不同的是,我们在 3.x 版本的模型中新增了 `DataPreprocessor` 模块。 +`DataPreprocessor` 模块的配置位于 `model.data_preprocessor` 中,它用于对输入数据进行预处理,例如对输入图像进行归一化,将不同大小的图片进行 padding 从而组成 batch,将图像从内存中读取到显存中等。这部分配置取代了原本存在于 train_pipeline 和 test_pipeline 中的 `Normalize` 和 `Pad`。 + + + + + + + + + +
原配置 + +```python +# 图像归一化参数 +img_norm_cfg = dict( + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True) +pipeline=[ + ..., + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), # 图像 padding 到 32 的倍数 + ... +] +``` + +
新配置 + +```python +model = dict( + data_preprocessor=dict( + type='DetDataPreprocessor', + # 图像归一化参数 + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + # 图像 padding 参数 + pad_mask=True, # 在实例分割中,需要将 mask 也进行 padding + pad_size_divisor=32) # 图像 padding 到 32 的倍数 +) +``` + +
+ +## 数据集和评测器配置 + +数据集和评测部分的配置相比 2.x 版本有较大的变化。我们将从 Dataloader 和 Dataset,Data transform pipeline,以及评测器配置三个方面介绍如何将 2.x 版本的配置迁移到 3.x 版本。 + +### Dataloader 和 Dataset 配置 + +在新版本中,我们将数据加载的设置与 PyTorch 官方的 DataLoader 保持一致,这样可以使用户更容易理解和上手。 +我们将训练、验证和测试的数据加载设置分别放在 `train_dataloader`,`val_dataloader` 和 `test_dataloader` 中,用户可以分别对这些 dataloader 设置不同的参数,其输入参数与 [PyTorch 的 Dataloader](https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader) 所需要的参数基本一致。 + +通过这种方式,我们将 2.x 版本中不可配置的 `sampler`,`batch_sampler`,`persistent_workers` 等参数都放到了配置文件中,使得用户可以更加灵活地设置数据加载的参数。 + +用户可以通过 `train_dataloader.dataset`,`val_dataloader.dataset` 和 `test_dataloader.dataset` 来设置数据集的配置,它们分别对应 2.x 版本中的 `data.train`,`data.val` 和 `data.test`。 + + + + + + + + + +
原配置 + +```python +data = dict( + samples_per_gpu=2, + workers_per_gpu=2, + train=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=train_pipeline), + val=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline), + test=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline)) +``` + +
新配置 + +```python +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, # 避免每次迭代后 dataloader 重新创建子进程 + sampler=dict(type='DefaultSampler', shuffle=True), # 默认的 sampler,同时支持分布式训练和非分布式训练 + batch_sampler=dict(type='AspectRatioBatchSampler'), # 默认的 batch_sampler,用于保证 batch 中的图片具有相似的长宽比,从而可以更好地利用显存 + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline)) +# 在 3.x 版本中可以独立配置验证和测试的 dataloader +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader # 测试 dataloader 的配置与验证 dataloader 的配置相同,这里省略 +``` + +
+ +### Data transform pipeline 配置 + +上文中提到,我们将图像 normalize 和 padding 的配置从 `train_pipeline` 和 `test_pipeline` 中独立出来,放到了 `model.data_preprocessor` 中,因此在 3.x 版本的 pipeline 中,我们不再需要 `Normalize` 和 `Pad` 这两个 transform。 + +同时,我们也对负责数据格式打包的 transform 进行了重构,将 `Collect` 和 `DefaultFormatBundle` 这两个 transform 合并为了 `PackDetInputs`,它负责将 data pipeline 中的数据打包成模型的输入格式,关于输入格式的转换,详见[数据流文档](../advanced_guides/data_flow.md)。 + +下面以 Mask R-CNN 1x 的 train_pipeline 为例,介绍如何将 2.x 版本的配置迁移到 3.x 版本: + + + + + + + + + +
原配置 + +```python +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=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', flip_ratio=0.5), + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='DefaultFormatBundle'), + dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), +] +``` + +
新配置 + +```python +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +``` + +
+ +对于 test_pipeline,除了将 `Normalize` 和 `Pad` 这两个 transform 去掉之外,我们也将测试时的数据增强(TTA)与普通的测试流程分开,移除了 `MultiScaleFlipAug`。关于新版的 TTA 如何使用,详见[TTA 文档](../advanced_guides/tta.md)。 + +下面同样以 Mask R-CNN 1x 的 test_pipeline 为例,介绍如何将 2.x 版本的配置迁移到 3.x 版本: + + + + + + + + + +
原配置 + +```python +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', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='ImageToTensor', keys=['img']), + dict(type='Collect', keys=['img']), + ]) +] +``` + +
新配置 + +```python +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +``` + +
+ +除此之外,我们还对一些数据增强进行了重构,下表列出了 2.x 版本中的 transform 与 3.x 版本中的 transform 的对应关系: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称原配置新配置
Resize + +```python +dict(type='Resize', + img_scale=(1333, 800), + keep_ratio=True) +``` + + + +```python +dict(type='Resize', + scale=(1333, 800), + keep_ratio=True) +``` + +
RandomResize + +```python +dict( + type='Resize', + img_scale=[ + (1333, 640), (1333, 800)], + multiscale_mode='range', + keep_ratio=True) +``` + + + +```python +dict( + type='RandomResize', + scale=[ + (1333, 640), (1333, 800)], + keep_ratio=True) +``` + +
RandomChoiceResize + +```python +dict( + type='Resize', + img_scale=[ + (1333, 640), (1333, 672), + (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + multiscale_mode='value', + keep_ratio=True) +``` + + + +```python +dict( + type='RandomChoiceResize', + scales=[ + (1333, 640), (1333, 672), + (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True) +``` + +
RandomFlip + +```python +dict(type='RandomFlip', + flip_ratio=0.5) +``` + + + +```python +dict(type='RandomFlip', + prob=0.5) +``` + +
+ +### 评测器配置 + +在 3.x 版本中,模型精度评测不再与数据集绑定,而是通过评测器(Evaluator)来完成。 +评测器配置分为 val_evaluator 和 test_evaluator 两部分,其中 val_evaluator 用于验证集评测,test_evaluator 用于测试集评测,对应 2.x 版本中的 evaluation 字段。 +下表列出了 2.x 版本与 3.x 版本中的评测器的对应关系: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
评测指标名称原配置新配置
COCO + +```python +data = dict( + val=dict( + type='CocoDataset', + ann_file=data_root + 'annotations/instances_val2017.json')) +evaluation = dict(metric=['bbox', 'segm']) +``` + + + +```python +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False) +``` + +
Pascal VOC + +```python +data = dict( + val=dict( + type=dataset_type, + ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt')) +evaluation = dict(metric='mAP') +``` + + + +```python +val_evaluator = dict( + type='VOCMetric', + metric='mAP', + eval_mode='11points') +``` + +
OpenImages + +```python +data = dict( + val=dict( + type='OpenImagesDataset', + ann_file=data_root + 'annotations/validation-annotations-bbox.csv', + img_prefix=data_root + 'OpenImages/validation/', + label_file=data_root + 'annotations/class-descriptions-boxable.csv', + hierarchy_file=data_root + + 'annotations/bbox_labels_600_hierarchy.json', + meta_file=data_root + 'annotations/validation-image-metas.pkl', + image_level_ann_file=data_root + + 'annotations/validation-annotations-human-imagelabels-boxable.csv')) +evaluation = dict(interval=1, metric='mAP') +``` + + + +```python +val_evaluator = dict( + type='OpenImagesMetric', + iou_thrs=0.5, + ioa_thrs=0.5, + use_group_of=True, + get_supercategory=True) +``` + +
CityScapes + +```python +data = dict( + val=dict( + type='CityScapesDataset', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + img_prefix=data_root + 'leftImg8bit/val/', + pipeline=test_pipeline)) +evaluation = dict(metric=['bbox', 'segm']) +``` + + + +```python +val_evaluator = [ + dict( + type='CocoMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + metric=['bbox', 'segm']), + dict( + type='CityScapesMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + seg_prefix=data_root + '/gtFine/val', + outfile_prefix='./work_dirs/cityscapes_metric/instance') +] +``` + +
+ +## 训练和测试的配置 + + + + + + + + + +
原配置 + +```python +runner = dict( + type='EpochBasedRunner', # 训练循环的类型 + max_epochs=12) # 最大训练轮次 +evaluation = dict(interval=2) # 验证间隔。每 2 个 epoch 验证一次 +``` + +
新配置 + +```python +train_cfg = dict( + type='EpochBasedTrainLoop', # 训练循环的类型,请参考 https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py + max_epochs=12, # 最大训练轮次 + val_interval=2) # 验证间隔。每 2 个 epoch 验证一次 +val_cfg = dict(type='ValLoop') # 验证循环的类型 +test_cfg = dict(type='TestLoop') # 测试循环的类型 +``` + +
+ +## 优化相关配置 + +优化器以及梯度裁剪的配置都移至 optim_wrapper 字段中。下表列出了 2.x 版本与 3.x 版本中的优化器配置的对应关系: + + + + + + + + + +
原配置 + +```python +optimizer = dict( + type='SGD', # 随机梯度下降优化器 + lr=0.02, # 基础学习率 + momentum=0.9, # 带动量的随机梯度下降 + weight_decay=0.0001) # 权重衰减 +optimizer_config = dict(grad_clip=None) # 梯度裁剪的配置,设置为 None 关闭梯度裁剪 +``` + +
新配置 + +```python +optim_wrapper = dict( # 优化器封装的配置 + type='OptimWrapper', # 优化器封装的类型。可以切换至 AmpOptimWrapper 来启用混合精度训练 + optimizer=dict( # 优化器配置。支持 PyTorch 的各种优化器。请参考 https://pytorch.org/docs/stable/optim.html#algorithms + type='SGD', # 随机梯度下降优化器 + lr=0.02, # 基础学习率 + momentum=0.9, # 带动量的随机梯度下降 + weight_decay=0.0001), # 权重衰减 + clip_grad=None, # 梯度裁剪的配置,设置为 None 关闭梯度裁剪。使用方法请见 https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html + ) +``` + +
+ +学习率的配置也从 lr_config 字段中移至 param_scheduler 字段中。param_scheduler 的配置更贴近 PyTorch 的学习率调整策略,更加灵活。下表列出了 2.x 版本与 3.x 版本中的学习率配置的对应关系: + + + + + + + + + +
原配置 + +```python +lr_config = dict( + policy='step', # 在训练过程中使用 multi step 学习率策略 + warmup='linear', # 使用线性学习率预热 + warmup_iters=500, # 到第 500 个 iteration 结束预热 + warmup_ratio=0.001, # 学习率预热的系数 + step=[8, 11], # 在哪几个 epoch 进行学习率衰减 + gamma=0.1) # 学习率衰减系数 +``` + +
新配置 + +```python +param_scheduler = [ + dict( + type='LinearLR', # 使用线性学习率预热 + start_factor=0.001, # 学习率预热的系数 + by_epoch=False, # 按 iteration 更新预热学习率 + begin=0, # 从第一个 iteration 开始 + end=500), # 到第 500 个 iteration 结束 + dict( + type='MultiStepLR', # 在训练过程中使用 multi step 学习率策略 + by_epoch=True, # 按 epoch 更新学习率 + begin=0, # 从第一个 epoch 开始 + end=12, # 到第 12 个 epoch 结束 + milestones=[8, 11], # 在哪几个 epoch 进行学习率衰减 + gamma=0.1) # 学习率衰减系数 +] +``` + +
+ +关于其他的学习率调整策略的迁移,请参考 MMEngine 的[学习率迁移文档](https://mmengine.readthedocs.io/zh_CN/latest/migration/param_scheduler.html)。 + +## 其他配置的迁移 + +### 保存 checkpoint 的配置 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能原配置新配置
设置保存间隔 + +```python +checkpoint_config = dict( + interval=1) +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + interval=1)) +``` + +
保存最佳模型 + +```python +evaluation = dict( + save_best='auto') +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + save_best='auto')) +``` + +
只保留最新的几个模型 + +```python +checkpoint_config = dict( + max_keep_ckpts=3) +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + max_keep_ckpts=3)) +``` + +
+ +### 日志的配置 + +3.x 版本中,日志的打印和可视化由 MMEngine 中的 logger 和 visualizer 分别完成。下表列出了 2.x 版本与 3.x 版本中的日志配置的对应关系: + + + + + + + + + + + + + + + + + + + + + + + + +
功能原配置新配置
设置日志打印间隔 + +```python +log_config = dict( + interval=50) +``` + + + +```python +default_hooks = dict( + logger=dict( + type='LoggerHook', + interval=50)) +# 可选: 配置日志打印数值的平滑窗口大小 +log_processor = dict( + type='LogProcessor', + window_size=50) +``` + +
使用 TensorBoard 或 WandB 可视化日志 + +```python +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook'), + dict(type='MMDetWandbHook', + init_kwargs={ + 'project': 'mmdetection', + 'group': 'maskrcnn-r50-fpn-1x-coco' + }, + interval=50, + log_checkpoint=True, + log_checkpoint_metadata=True, + num_eval_images=100) + ]) +``` + + + +```python +vis_backends = [ + dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend'), + dict(type='WandbVisBackend', + init_kwargs={ + 'project': 'mmdetection', + 'group': 'maskrcnn-r50-fpn-1x-coco' + }) +] +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +``` + +
+ +关于可视化相关的教程,请参考 MMDetection 的[可视化教程](../user_guides/visualization.md)。 + +### Runtime 的配置 + +3.x 版本中 runtime 的配置字段有所调整,具体的对应关系如下: + + + + + + + + + + + + + + + + +
原配置新配置
+ +```python +cudnn_benchmark = False +opencv_num_threads = 0 +mp_start_method = 'fork' +dist_params = dict(backend='nccl') +log_level = 'INFO' +load_from = None +resume_from = None + + +``` + + + +```python +env_cfg = dict( + cudnn_benchmark=False, + mp_cfg=dict(mp_start_method='fork', + opencv_num_threads=0), + dist_cfg=dict(backend='nccl')) +log_level = 'INFO' +load_from = None +resume = False +``` + +
diff --git a/mmdet_code/SR-TOD/docs/zh_cn/migration/dataset_migration.md b/mmdet_code/SR-TOD/docs/zh_cn/migration/dataset_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..c379b9f1b7b6a4829b1a678c74861b3226d130bb --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/migration/dataset_migration.md @@ -0,0 +1 @@ +# 将数据集从 MMDetection 2.x 迁移至 3.x diff --git a/mmdet_code/SR-TOD/docs/zh_cn/migration/migration.md b/mmdet_code/SR-TOD/docs/zh_cn/migration/migration.md new file mode 100644 index 0000000000000000000000000000000000000000..d706856fa828f051c7ec9dfdb4c79fccdc03b867 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/migration/migration.md @@ -0,0 +1,12 @@ +# 从 MMDetection 2.x 迁移至 3.x + +MMDetection 3.x 版本是一个重大更新,包含了许多 API 和配置文件的变化。本文档旨在帮助用户从 MMDetection 2.x 版本迁移到 3.x 版本。 +我们将迁移指南分为以下几个部分: + +- [配置文件迁移](./config_migration.md) +- [API 和 Registry 迁移](./api_and_registry_migration.md) +- [数据集迁移](./dataset_migration.md) +- [模型迁移](./model_migration.md) +- [常见问题](./migration_faq.md) + +如果您在迁移过程中遇到任何问题,欢迎在 issue 中提出。我们也欢迎您为本文档做出贡献。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/migration/migration_faq.md b/mmdet_code/SR-TOD/docs/zh_cn/migration/migration_faq.md new file mode 100644 index 0000000000000000000000000000000000000000..208a138b25d707a81d491af4fe82aaff024cac2f --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/migration/migration_faq.md @@ -0,0 +1 @@ +# 迁移 FAQ diff --git a/mmdet_code/SR-TOD/docs/zh_cn/migration/model_migration.md b/mmdet_code/SR-TOD/docs/zh_cn/migration/model_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..d7992440228a811ce75023414f7fd7364516563a --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/migration/model_migration.md @@ -0,0 +1 @@ +# 将模型从 MMDetection 2.x 迁移至 3.x diff --git a/mmdet_code/SR-TOD/docs/zh_cn/model_zoo.md b/mmdet_code/SR-TOD/docs/zh_cn/model_zoo.md new file mode 100644 index 0000000000000000000000000000000000000000..b5376152d9c17634ab2b32bf1e1cc9baa7a1cff9 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/model_zoo.md @@ -0,0 +1,333 @@ +# 模型库 + +## 镜像地址 + +从 MMDetection V2.0 起,我们只通过阿里云维护模型库。V1.x 版本的模型已经弃用。 + +## 共同设置 + +- 所有模型都是在 `coco_2017_train` 上训练,在 `coco_2017_val` 上测试。 +- 我们使用分布式训练。 +- 所有 pytorch-style 的 ImageNet 预训练主干网络来自 PyTorch 的模型库,caffe-style 的预训练主干网络来自 detectron2 最新开源的模型。 +- 为了与其他代码库公平比较,文档中所写的 GPU 内存是8个 GPU 的 `torch.cuda.max_memory_allocated()` 的最大值,此值通常小于 nvidia-smi 显示的值。 +- 我们以网络 forward 和后处理的时间加和作为推理时间,不包含数据加载时间。所有结果通过 [benchmark.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/benchmark.py) 脚本计算所得。该脚本会计算推理 2000 张图像的平均时间。 + +## ImageNet 预训练模型 + +通过 ImageNet 分类任务预训练的主干网络进行初始化是很常见的操作。所有预训练模型的链接都可以在 [open_mmlab](https://github.com/open-mmlab/mmcv/blob/master/mmcv/model_zoo/open_mmlab.json) 中找到。根据 `img_norm_cfg` 和原始权重,我们可以将所有 ImageNet 预训练模型分为以下几种情况: + +- TorchVision:torchvision 模型权重,包含 ResNet50, ResNet101。`img_norm_cfg` 为 `dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)`。 +- Pycls:[pycls](https://github.com/facebookresearch/pycls) 模型权重,包含 RegNetX。`img_norm_cfg` 为 `dict( mean=[103.530, 116.280, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False)`。 +- MSRA styles:[MSRA](https://github.com/KaimingHe/deep-residual-networks) 模型权重,包含 ResNet50_Caffe,ResNet101_Caffe。`img_norm_cfg` 为 `dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)`。 +- Caffe2 styles:现阶段只包含 ResNext101_32x8d。`img_norm_cfg` 为 `dict(mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395], to_rgb=False)`。 +- Other styles: SSD 的 `img_norm_cfg` 为 `dict(mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True)`,YOLOv3 的 `img_norm_cfg` 为 `dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True)`。 + +MMdetection 常用到的主干网络细节如下表所示: + +| 模型 | 来源 | 链接 | 描述 | +| ---------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ResNet50 | TorchVision | [torchvision 中的 ResNet-50](https://download.pytorch.org/models/resnet50-19c8e357.pth) | 来自 [torchvision 中的 ResNet-50](https://download.pytorch.org/models/resnet50-19c8e357.pth)。 | +| ResNet101 | TorchVision | [torchvision 中的 ResNet-101](https://download.pytorch.org/models/resnet101-5d3b4d8f.pth) | 来自 [torchvision 中的 ResNet-101](https://download.pytorch.org/models/resnet101-5d3b4d8f.pth)。 | +| RegNetX | Pycls | [RegNetX_3.2gf](https://download.openmmlab.com/pretrain/third_party/regnetx_3.2gf-c2599b0f.pth),[RegNetX_800mf](https://download.openmmlab.com/pretrain/third_party/regnetx_800mf-1f4be4c7.pth) 等 | 来自 [pycls](https://github.com/facebookresearch/pycls)。 | +| ResNet50_Caffe | MSRA | [MSRA 中的 ResNet-50](https://download.openmmlab.com/pretrain/third_party/resnet50_caffe-788b5fa3.pth) | 由 [Detectron2 中的 R-50.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-50.pkl) 转化的副本。原始权重文件来自 [MSRA 中的原始 ResNet-50](https://github.com/KaimingHe/deep-residual-networks)。 | +| ResNet101_Caffe | MSRA | [MSRA 中的 ResNet-101](https://download.openmmlab.com/pretrain/third_party/resnet101_caffe-3ad79236.pth) | 由 [Detectron2 中的 R-101.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-101.pkl) 转化的副本。原始权重文件来自 [MSRA 中的原始 ResNet-101](https://github.com/KaimingHe/deep-residual-networks)。 | +| ResNext101_32x8d | Caffe2 | [Caffe2 ResNext101_32x8d](https://download.openmmlab.com/pretrain/third_party/resnext101_32x8d-1516f1aa.pth) | 由 [Detectron2 中的 X-101-32x8d.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/FAIR/X-101-32x8d.pkl) 转化的副本。原始 ResNeXt-101-32x8d 由 FB 使用 Caffe2 训练。 | + +## Baselines + +### RPN + +请参考 [RPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/rpn)。 + +### Faster R-CNN + +请参考 [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn)。 + +### Mask R-CNN + +请参考 [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn)。 + +### Fast R-CNN (使用提前计算的 proposals) + +请参考 [Fast R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/fast_rcnn)。 + +### RetinaNet + +请参考 [RetinaNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/retinanet)。 + +### Cascade R-CNN and Cascade Mask R-CNN + +请参考 [Cascade R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/cascade_rcnn)。 + +### Hybrid Task Cascade (HTC) + +请参考 [HTC](https://github.com/open-mmlab/mmdetection/blob/main/configs/htc)。 + +### SSD + +请参考 [SSD](https://github.com/open-mmlab/mmdetection/blob/main/configs/ssd)。 + +### Group Normalization (GN) + +请参考 [Group Normalization](https://github.com/open-mmlab/mmdetection/blob/main/configs/gn)。 + +### Weight Standardization + +请参考 [Weight Standardization](https://github.com/open-mmlab/mmdetection/blob/main/configs/gn+ws)。 + +### Deformable Convolution v2 + +请参考 [Deformable Convolutional Networks](https://github.com/open-mmlab/mmdetection/blob/main/configs/dcn)。 + +### CARAFE: Content-Aware ReAssembly of FEatures + +请参考 [CARAFE](https://github.com/open-mmlab/mmdetection/blob/main/configs/carafe)。 + +### Instaboost + +请参考 [Instaboost](https://github.com/open-mmlab/mmdetection/blob/main/configs/instaboost)。 + +### Libra R-CNN + +请参考 [Libra R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/libra_rcnn)。 + +### Guided Anchoring + +请参考 [Guided Anchoring](https://github.com/open-mmlab/mmdetection/blob/main/configs/guided_anchoring)。 + +### FCOS + +请参考 [FCOS](https://github.com/open-mmlab/mmdetection/blob/main/configs/fcos)。 + +### FoveaBox + +请参考 [FoveaBox](https://github.com/open-mmlab/mmdetection/blob/main/configs/foveabox)。 + +### RepPoints + +请参考 [RepPoints](https://github.com/open-mmlab/mmdetection/blob/main/configs/reppoints)。 + +### FreeAnchor + +请参考 [FreeAnchor](https://github.com/open-mmlab/mmdetection/blob/main/configs/free_anchor)。 + +### Grid R-CNN (plus) + +请参考 [Grid R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/grid_rcnn)。 + +### GHM + +请参考 [GHM](https://github.com/open-mmlab/mmdetection/blob/main/configs/ghm)。 + +### GCNet + +请参考 [GCNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/gcnet)。 + +### HRNet + +请参考 [HRNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/hrnet)。 + +### Mask Scoring R-CNN + +请参考 [Mask Scoring R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/ms_rcnn)。 + +### Train from Scratch + +请参考 [Rethinking ImageNet Pre-training](https://github.com/open-mmlab/mmdetection/blob/main/configs/scratch)。 + +### NAS-FPN + +请参考 [NAS-FPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/nas_fpn)。 + +### ATSS + +请参考 [ATSS](https://github.com/open-mmlab/mmdetection/blob/main/configs/atss)。 + +### FSAF + +请参考 [FSAF](https://github.com/open-mmlab/mmdetection/blob/main/configs/fsaf)。 + +### RegNetX + +请参考 [RegNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/regnet)。 + +### Res2Net + +请参考 [Res2Net](https://github.com/open-mmlab/mmdetection/blob/main/configs/res2net)。 + +### GRoIE + +请参考 [GRoIE](https://github.com/open-mmlab/mmdetection/blob/main/configs/groie)。 + +### Dynamic R-CNN + +请参考 [Dynamic R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/dynamic_rcnn)。 + +### PointRend + +请参考 [PointRend](https://github.com/open-mmlab/mmdetection/blob/main/configs/point_rend)。 + +### DetectoRS + +请参考 [DetectoRS](https://github.com/open-mmlab/mmdetection/blob/main/configs/detectors)。 + +### Generalized Focal Loss + +请参考 [Generalized Focal Loss](https://github.com/open-mmlab/mmdetection/blob/main/configs/gfl)。 + +### CornerNet + +请参考 [CornerNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/cornernet)。 + +### YOLOv3 + +请参考 [YOLOv3](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolo)。 + +### PAA + +请参考 [PAA](https://github.com/open-mmlab/mmdetection/blob/main/configs/paa)。 + +### SABL + +请参考 [SABL](https://github.com/open-mmlab/mmdetection/blob/main/configs/sabl)。 + +### CentripetalNet + +请参考 [CentripetalNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/centripetalnet)。 + +### ResNeSt + +请参考 [ResNeSt](https://github.com/open-mmlab/mmdetection/blob/main/configs/resnest)。 + +### DETR + +请参考 [DETR](https://github.com/open-mmlab/mmdetection/blob/main/configs/detr)。 + +### Deformable DETR + +请参考 [Deformable DETR](https://github.com/open-mmlab/mmdetection/blob/main/configs/deformable_detr)。 + +### AutoAssign + +请参考 [AutoAssign](https://github.com/open-mmlab/mmdetection/blob/main/configs/autoassign)。 + +### YOLOF + +请参考 [YOLOF](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolof)。 + +### Seesaw Loss + +请参考 [Seesaw Loss](https://github.com/open-mmlab/mmdetection/blob/main/configs/seesaw_loss)。 + +### CenterNet + +请参考 [CenterNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/centernet)。 + +### YOLOX + +请参考 [YOLOX](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolox)。 + +### PVT + +请参考 [PVT](https://github.com/open-mmlab/mmdetection/blob/main/configs/pvt)。 + +### SOLO + +请参考 [SOLO](https://github.com/open-mmlab/mmdetection/blob/main/configs/solo)。 + +### QueryInst + +请参考 [QueryInst](https://github.com/open-mmlab/mmdetection/blob/main/configs/queryinst)。 + +### Other datasets + +我们还在 [PASCAL VOC](https://github.com/open-mmlab/mmdetection/blob/main/configs/pascal_voc),[Cityscapes](https://github.com/open-mmlab/mmdetection/blob/main/configs/cityscapes) 和 [WIDER FACE](https://github.com/open-mmlab/mmdetection/blob/main/configs/wider_face) 上对一些方法进行了基准测试。 + +### Pre-trained Models + +我们还通过多尺度训练和更长的训练策略来训练用 ResNet-50 和 [RegNetX-3.2G](https://github.com/open-mmlab/mmdetection/blob/main/configs/regnet) 作为主干网络的 [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn) 和 [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn)。这些模型可以作为下游任务的预训练模型。 + +## 速度基准 + +### 训练速度基准 + +我们提供 [analyze_logs.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/analyze_logs.py) 来得到训练中每一次迭代的平均时间。示例请参考 [Log Analysis](https://mmdetection.readthedocs.io/en/latest/useful_tools.html#log-analysis)。 + +我们与其他流行框架的 Mask R-CNN 训练速度进行比较(数据是从 [detectron2](https://github.com/facebookresearch/detectron2/blob/main/docs/notes/benchmarks.md/) 复制而来)。在 mmdetection 中,我们使用 [mask-rcnn_r50-caffe_fpn_poly-1x_coco_v1.py](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn/mask-rcnn_r50-caffe_fpn_poly-1x_coco_v1.py) 进行基准测试。它与 detectron2 的 [mask_rcnn_R_50_FPN_noaug_1x.yaml](https://github.com/facebookresearch/detectron2/blob/main/configs/Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x.yaml) 设置完全一样。同时,我们还提供了[模型权重](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug_compare_20200518-10127928.pth)和[训练 log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug_20200518_105755.log.json) 作为参考。为了跳过 GPU 预热时间,吞吐量按照100-500次迭代之间的平均吞吐量来计算。 + +| 框架 | 吞吐量 (img/s) | +| -------------------------------------------------------------------------------------- | -------------- | +| [Detectron2](https://github.com/facebookresearch/detectron2) | 62 | +| [MMDetection](https://github.com/open-mmlab/mmdetection) | 61 | +| [maskrcnn-benchmark](https://github.com/facebookresearch/maskrcnn-benchmark/) | 53 | +| [tensorpack](https://github.com/tensorpack/tensorpack/tree/master/examples/FasterRCNN) | 50 | +| [simpledet](https://github.com/TuSimple/simpledet/) | 39 | +| [Detectron](https://github.com/facebookresearch/Detectron) | 19 | +| [matterport/Mask_RCNN](https://github.com/matterport/Mask_RCNN/) | 14 | + +### 推理时间基准 + +我们提供 [benchmark.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/benchmark.py) 对推理时间进行基准测试。此脚本将推理 2000 张图片并计算忽略前 5 次推理的平均推理时间。可以通过设置 `LOG-INTERVAL` 来改变 log 输出间隔(默认为 50)。 + +```shell +python tools/benchmark.py ${CONFIG} ${CHECKPOINT} [--log-interval $[LOG-INTERVAL]] [--fuse-conv-bn] +``` + +模型库中,所有模型在基准测量推理时间时都没设置 `fuse-conv-bn`, 此设置可以使推理时间更短。 + +## 与 Detectron2 对比 + +我们在速度和精度方面对 mmdetection 和 [Detectron2](https://github.com/facebookresearch/detectron2.git) 进行对比。对比所使用的 detectron2 的 commit id 为 [185c27e](https://github.com/facebookresearch/detectron2/tree/185c27e4b4d2d4c68b5627b3765420c6d7f5a659)(30/4/2020)。 +为了公平对比,我们所有的实验都在同一机器下进行。 + +### 硬件 + +- 8 NVIDIA Tesla V100 (32G) GPUs +- Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz + +### 软件环境 + +- Python 3.7 +- PyTorch 1.4 +- CUDA 10.1 +- CUDNN 7.6.03 +- NCCL 2.4.08 + +### 精度 + +| 模型 | 训练策略 | Detectron2 | mmdetection | 下载 | +| ------------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_ms-1x_coco.py) | 1x | [37.9](https://github.com/facebookresearch/detectron2/blob/main/configs/COCO-Detection/faster_rcnn_R_50_FPN_1x.yaml) | 38.0 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco-5324cff8.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco_20200429_234554.log.json) | +| [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_coco.py) | 1x | [38.6 & 35.2](https://github.com/facebookresearch/detectron2/blob/master/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml) | 38.8 & 35.4 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco-dbecf295.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco_20200430_054239.log.json) | +| [Retinanet](https://github.com/open-mmlab/mmdetection/blob/main/configs/retinanet/retinanet_r50-caffe_fpn_ms-1x_coco.py) | 1x | [36.5](https://github.com/facebookresearch/detectron2/blob/master/configs/COCO-Detection/retinanet_R_50_FPN_1x.yaml) | 37.0 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/retinanet_r50_caffe_fpn_mstrain_1x_coco/retinanet_r50_caffe_fpn_mstrain_1x_coco-586977a0.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/retinanet_r50_caffe_fpn_mstrain_1x_coco/retinanet_r50_caffe_fpn_mstrain_1x_coco_20200430_014748.log.json) | + +### 训练速度 + +训练速度使用 s/iter 来度量。结果越低越好。 + +| 模型 | Detectron2 | mmdetection | +| ------------ | ---------- | ----------- | +| Faster R-CNN | 0.210 | 0.216 | +| Mask R-CNN | 0.261 | 0.265 | +| Retinanet | 0.200 | 0.205 | + +### 推理速度 + +推理速度通过单张 GPU 下的 fps(img/s) 来度量,越高越好。 +为了与 Detectron2 保持一致,我们所写的推理时间除去了数据加载时间。 +对于 Mask RCNN,我们去除了后处理中 RLE 编码的时间。 +我们在括号中给出了官方给出的速度。由于硬件差异,官方给出的速度会比我们所测试得到的速度快一些。 + +| 模型 | Detectron2 | mmdetection | +| ------------ | ----------- | ----------- | +| Faster R-CNN | 25.6 (26.3) | 22.2 | +| Mask R-CNN | 22.5 (23.3) | 19.6 | +| Retinanet | 17.8 (18.2) | 20.6 | + +### 训练内存 + +| 模型 | Detectron2 | mmdetection | +| ------------ | ---------- | ----------- | +| Faster R-CNN | 3.0 | 3.8 | +| Mask R-CNN | 3.4 | 3.9 | +| Retinanet | 3.9 | 3.4 | diff --git a/mmdet_code/SR-TOD/docs/zh_cn/notes/compatibility.md b/mmdet_code/SR-TOD/docs/zh_cn/notes/compatibility.md new file mode 100644 index 0000000000000000000000000000000000000000..e9ebdd97e84c5ab109dbb64f978e741c1fb42c15 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/notes/compatibility.md @@ -0,0 +1,177 @@ +# MMDetection v2.x 兼容性说明 + +## MMDetection 2.25.0 + +为了加入 Mask2Former 实例分割模型,对 Mask2Former 的配置文件进行了重命名 [PR #7571](https://github.com/open-mmlab/mmdetection/pull/7571): + + + + + + + + + + + +
在 v2.25.0 之前v2.25.0 及之后
+ +``` +'mask2former_xxx_coco.py' 代表全景分割的配置文件 +``` + + + +``` +'mask2former_xxx_coco.py' 代表实例分割的配置文件 +'mask2former_xxx_coco-panoptic.py' 代表全景分割的配置文件 +``` + +
+ +## MMDetection 2.21.0 + +为了支持 CPU 训练,MMCV 中进行批处理的 scatter 的代码逻辑已经被修改。我们推荐使用 MMCV v1.4.4 或更高版本, +更多信息请参考 [MMCV PR #1621](https://github.com/open-mmlab/mmcv/pull/1621). + +## MMDetection 2.18.1 + +### MMCV compatibility + +为了修复 BaseTransformerLayer 中的权重引用问题, MultiheadAttention 中 batch first 的逻辑有所改变。 +我们推荐使用 MMCV v1.3.17 或更高版本。 更多信息请参考 [MMCV PR #1418](https://github.com/open-mmlab/mmcv/pull/1418) 。 + +## MMDetection 2.18.0 + +### DIIHead 兼容性 + +为了支持 QueryInst,在 DIIHead 的返回元组中加入了 attn_feats。 + +## MMDetection v2.14.0 + +### MMCV 版本 + +为了修复 EvalHook 优先级过低的问题,MMCV v1.3.8 中所有 hook 的优先级都重新进行了调整,因此 MMDetection v2.14.0 需要依赖最新的 MMCV v1.3.8 版本。 相关信息请参考[PR #1120](https://github.com/open-mmlab/mmcv/pull/1120) ,相关问题请参考[#5343](https://github.com/open-mmlab/mmdetection/issues/5343) 。 + +### SSD 兼容性 + +在 v2.14.0 中,为了使 SSD 能够被更灵活地使用,[PR #5291](https://github.com/open-mmlab/mmdetection/pull/5291) 重构了 SSD 的 backbone、neck 和 head。用户可以使用 tools/model_converters/upgrade_ssd_version.py 转换旧版本训练的模型。 + +```shell +python tools/model_converters/upgrade_ssd_version.py ${OLD_MODEL_PATH} ${NEW_MODEL_PATH} + +``` + +- OLD_MODEL_PATH:旧版 SSD 模型的路径。 +- NEW_MODEL_PATH:保存转换后模型权重的路径。 + +## MMDetection v2.12.0 + +在 v2.12.0 到 v2.18.0(或以上)版本的这段时间,为了提升通用性和便捷性,MMDetection 正在进行大规模重构。在升级到 v2.12.0 后 MMDetection 不可避免地带来了一些 BC Breaking,包括 MMCV 的版本依赖、模型初始化方式、模型 registry 和 mask AP 的评估。 + +### MMCV 版本 + +MMDetection v2.12.0 依赖 MMCV v1.3.3 中新增加的功能,包括:使用 `BaseModule` 统一参数初始化,模型 registry,以及[Deformable DETR](https://arxiv.org/abs/2010.04159) 中的 `MultiScaleDeformableAttn` CUDA 算子。 +注意,尽管 MMCV v1.3.2 已经包含了 MMDet 所需的功能,但是存在一些已知的问题。我们建议用户跳过 MMCV v1.3.2 使用 v1.3.3 版本。 + +### 统一模型初始化 + +为了统一 OpenMMLab 项目中的参数初始化方式,MMCV 新增加了 `BaseModule` 类,使用 `init_cfg` 参数对模块进行统一且灵活的初始化配置管理。 +现在用户需要在训练脚本中显式调用 `model.init_weights()` 来初始化模型(例如 [这行代码](https://github.com/open-mmlab/mmdetection/blob/master/tools/train.py#L162) ,在这之前则是在 detector 中进行处理的。 +**下游项目必须相应地更新模型初始化方式才能使用 MMDetection v2.12.0**。请参阅 [PR #4750](https://github.com/open-mmlab/mmdetection/pull/4750) 了解详情。 + +### 统一模型 registry + +为了能够使用在其他 OpenMMLab 项目中实现的 backbone,MMDetection v2.12.0 继承了在 MMCV (#760) 中创建的模型 registry。 +这样,只要 OpenMMLab 项目实现了某个 backbone,并且该项目也使用 MMCV 中的 registry,那么用户只需修改配置即可在 MMDetection 中使用该 backbone,不再需要将代码复制到 MMDetection 中。 更多详细信息,请参阅 [PR #5059](https://github.com/open-mmlab/mmdetection/pull/5059) 。 + +### Mask AP 评估 + +在 [PR #4898](https://github.com/open-mmlab/mmdetection/pull/4898) 和 v2.12.0 之前,对小、中、大目标的 mask AP 的评估是基于其边界框区域而不是真正的 mask 区域。 +这导致 `APs` 和 `APm` 变得更高但 `APl` 变得更低,但是不会影响整体的 mask AP。 [PR #4898](https://github.com/open-mmlab/mmdetection/pull/4898) 删除了 mask AP 计算中的 `bbox` ,改为使用 mask 区域。 +新的计算方式不会影响整体的 mask AP 评估,与 [Detectron2](https://github.com/facebookresearch/detectron2/)一致。 + +## 与 MMDetection v1.x 的兼容性 + +MMDetection v2.0 经过了大规模重构并解决了许多遗留问题。 MMDetection v2.0 不兼容 v1.x 版本,在这两个版本中使用相同的模型权重运行推理会产生不同的结果。 因此,MMDetection v2.0 重新对所有模型进行了 benchmark,并在 model zoo 中提供了新模型的权重和训练记录。 + +新旧版本的主要的区别有四方面:坐标系、代码库约定、训练超参和模块设计。 + +### 坐标系 + +新坐标系与 [Detectron2](https://github.com/facebookresearch/detectron2/) 一致, +将最左上角的像素的中心视为坐标原点 (0, 0) 而不是最左上角像素的左上角。 因此 COCO 边界框和分割标注中的坐标被解析为范围 `[0,width]` 和 `[0,height]` 中的坐标。 这个修改影响了所有与 bbox 及像素选择相关的计算,变得更加自然且更加准确。 + +- 在新坐标系中,左上角和右下角为 (x1, y1) (x2, y2) 的框的宽度及高度计算公式为 `width = x2 - x1` 和 `height = y2 - y1`。 + 在 MMDetection v1.x 和之前的版本中,高度和宽度都多了 `+ 1` 的操作。 + 本次修改包括三部分: + + 1. box 回归中的检测框变换以及编码/解码。 + 2. IoU 计算。这会影响 ground truth 和检测框之间的匹配以及 NMS 。但对兼容性的影响可以忽略不计。 + 3. Box 的角点坐标为浮点型,不再取整。这能使得检测结果更为准确,也使得检测框和 RoI 的最小尺寸不再为 1,但影响很小。 + +- Anchor 的中心与特征图的网格点对齐,类型变为 float。 + 在 MMDetection v1.x 和之前的版本中,anchors 是 `int` 类型且没有居中对齐。 + 这会影响 RPN 中的 Anchor 生成和所有基于 Anchor 的方法。 + +- ROIAlign 更好地与图像坐标系对齐。新的实现来自 [Detectron2](https://github.com/facebookresearch/detectron2/tree/master/detectron2/layers/csrc/ROIAlign) 。 + 当 RoI 用于提取 RoI 特征时,与 MMDetection v1.x 相比默认情况下相差半个像素。 + 能够通过设置 `aligned=False` 而不是 `aligned=True` 来维持旧版本的设置。 + +- Mask 的裁剪和粘贴更准确。 + + 1. 我们使用新的 RoIAlign 来提取 mask 目标。 在 MMDetection v1.x 中,bounding box 在提取 mask 目标之前被取整,裁剪过程是 numpy 实现的。 而在新版本中,裁剪的边界框不经过取整直接输入 RoIAlign。 此实现大大加快了训练速度(每次迭代约加速 0.1 秒,1x schedule 训练 Mask R50 时加速约 2 小时)并且理论上会更准确。 + 2. 在 MMDetection v2.0 中,修改后的 `paste_mask()` 函数应该比之前版本更准确。 此更改参考了 [Detectron2](https://github.com/facebookresearch/detectron2/blob/master/detectron2/structures/masks.py) 中的修改,可以将 COCO 上的 mask AP 提高约 0.5%。 + +### 代码库约定 + +- MMDetection v2.0 更改了类别标签的顺序,减少了回归和 mask 分支里的无用参数并使得顺序更加自然(没有 +1 和 -1)。 + 这会影响模型的所有分类层,使其输出的类别标签顺序发生改变。回归分支和 mask head 的最后一层不再为 K 个类别保留 K+1 个通道,类别顺序与分类分支一致。 + + - 在 MMDetection v2.0 中,标签 “K” 表示背景,标签 \[0, K-1\] 对应于 K = num_categories 个对象类别。 + + - 在 MMDetection v1.x 及之前的版本中,标签 “0” 表示背景,标签 \[1, K\] 对应 K 个类别。 + + - **注意**:softmax RPN 的类顺序在 version\<=2.4.0 中仍然和 1.x 中的一样,而 sigmoid RPN 不受影响。从 MMDetection v2.5.0 开始,所有 head 中的类顺序是统一的。 + +- 不使用 R-CNN 中的低质量匹配。在 MMDetection v1.x 和之前的版本中,`max_iou_assigner` 会在 RPN 和 R-CNN 训练时给每个 ground truth 匹配低质量框。我们发现这会导致最佳的 GT 框不会被分配给某些边界框, + 因此,在MMDetection v2.0 的 R-CNN 训练中默认不允许低质量匹配。这有时可能会稍微改善 box AP(约为 0.1%)。 + +- 单独的宽高比例系数。在 MMDetection v1.x 和以前的版本中,`keep_ratio=True` 时比例系数是单个浮点数,这并不准确,因为宽度和高度的比例系数会有一定的差异。 MMDetection v2.0 对宽度和高度使用单独的比例系数,对 AP 的提升约为 0.1%。 + +- 修改了 config 文件名称的规范。 由于 model zoo 中模型不断增多, MMDetection v2.0 采用新的命名规则: + + ```shell + [model]_(model setting)_[backbone]_[neck]_(norm setting)_(misc)_(gpu x batch)_[schedule]_[dataset].py + ``` + + 其中 (`misc`) 包括 DCN 和 GCBlock 等。更多详细信息在 [配置文件说明文档](config.md) 中说明 + +- MMDetection v2.0 使用新的 ResNet Caffe backbone 来减少加载预训练模型时的警告。新 backbone 中的大部分权重与以前的相同,但没有 `conv.bias`,且它们使用不同的 `img_norm_cfg`。因此,新的 backbone 不会报 `unexpected keys` 的警告。 + +### 训练超参 + +训练超参的调整不会影响模型的兼容性,但会略微提高性能。主要有: + +- 通过设置 `nms_post=1000` 和 `max_num=1000`,将 nms 之后的 proposal 数量从 2000 更改为 1000。使 mask AP 和 bbox AP 提高了约 0.2%。 + +- Mask R-CNN、Faster R-CNN 和 RetinaNet 的默认回归损失从 smooth L1 损失更改为 L1 损失,使得 box AP 整体上都有所提升(约 0.6%)。但是,将 L1-loss 用在 Cascade R-CNN 和 HTC 等其他方法上并不能提高性能,因此我们保留这些方法的原始设置。 + +- 为简单起见,RoIAlign 层的 `sampling_ratio` 设置为 0。略微提升了 AP(约 0.2% 绝对值)。 + +- 为了提升训练速度,默认设置在训练过程中不再使用梯度裁剪。大多数模型的性能不会受到影响。对于某些模型(例如 RepPoints),我们依旧使用梯度裁剪来稳定训练过程从而获得更好的性能。 + +- 因为不再默认使用梯度裁剪,默认 warmup 比率从 1/3 更改为 0.001,以使模型训练预热更加平缓。不过我们重新进行基准测试时发现这种影响可以忽略不计。 + +### 将模型从 v1.x 升级至 v2.0 + +用户可以使用脚本 `tools/model_converters/upgrade_model_version.py` 来将 MMDetection 1.x 训练的模型转换为 MMDetection v2.0。转换后的模型可以在 MMDetection v2.0 中运行,但性能略有下降(小于 1% AP)。 +详细信息可以在 `configs/legacy` 中找到。 + +## pycocotools 兼容性 + +`mmpycocotools` 是 OpenMMLab 维护的 `pycocotools` 的复刻版,适用于 MMDetection 和 Detectron2。 +在 [PR #4939](https://github.com/open-mmlab/mmdetection/pull/4939) 之前,由于 `pycocotools` 和 `mmpycocotool` 具有相同的包名,如果用户已经安装了 `pyccocotools`(在相同环境下先安装了 Detectron2 ),那么 MMDetection 的安装过程会跳过安装 `mmpycocotool`。 导致 MMDetection 缺少 `mmpycocotools` 而报错。 +但如果在 Detectron2 之前安装 MMDetection,则可以在相同的环境下工作。 +[PR #4939](https://github.com/open-mmlab/mmdetection/pull/4939) 弃用 mmpycocotools,使用官方 pycocotools。 +在 [PR #4939](https://github.com/open-mmlab/mmdetection/pull/4939) 之后,用户能够在相同环境下安装 MMDetection 和 Detectron2,不再需要关注安装顺序。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/notes/faq.md b/mmdet_code/SR-TOD/docs/zh_cn/notes/faq.md new file mode 100644 index 0000000000000000000000000000000000000000..67e2e42968aa5073ace18994fd9ef2d2de546f9d --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/notes/faq.md @@ -0,0 +1,258 @@ +# 常见问题解答 + +我们在这里列出了使用时的一些常见问题及其相应的解决方案。 如果您发现有一些问题被遗漏,请随时提 PR 丰富这个列表。 如果您无法在此获得帮助,请使用 [issue模板](https://github.com/open-mmlab/mmdetection/blob/main/.github/ISSUE_TEMPLATE/error-report.md/)创建问题,但是请在模板中填写所有必填信息,这有助于我们更快定位问题。 + +## PyTorch 2.0 支持 + +MMDetection 目前绝大部分算法已经支持了 PyTorch 2.0 及其 `torch.compile` 功能, 用户只需要安装 MMDetection 3.0.0rc7 及其以上版本即可。如果你在使用中发现有不支持的算法,欢迎给我们反馈。我们也非常欢迎社区贡献者来 benchmark 对比 `torch.compile` 功能所带来的速度提升。 + +如果你想启动 `torch.compile` 功能,只需要在 `train.py` 或者 `test.py` 后面加上 `--cfg-options compile=True`。 以 RTMDet 为例,你可以使用以下命令启动 `torch.compile` 功能: + +```shell +# 单卡 +python tools/train.py configs/rtmdet/rtmdet_s_8xb32-300e_coco.py --cfg-options compile=True + +# 单机 8 卡 +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True + +# 单机 8 卡 + AMP 混合精度训练 +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True --amp +``` + +需要特别注意的是,PyTorch 2.0 对于动态 shape 支持不是非常完善,目标检测算法中大部分不仅输入 shape 是动态的,而且 loss 计算和后处理过程中也是动态的,这会导致在开启 `torch.compile` 功能后训练速度会变慢。基于此,如果你想启动 `torch.compile` 功能,则应该遵循如下原则: + +1. 输入到网络的图片是固定 shape 的,而非多尺度的 +2. 设置 `torch._dynamo.config.cache_size_limit` 参数。TorchDynamo 会将 Python 字节码转换并缓存,已编译的函数会被存入缓存中。当下一次检查发现需要重新编译时,该函数会被重新编译并缓存。但是如果重编译次数超过预设的最大值(64),则该函数将不再被缓存或重新编译。前面说过目标检测算法中的 loss 计算和后处理部分也是动态计算的,这些函数需要在每次迭代中重新编译。因此将 `torch._dynamo.config.cache_size_limit` 参数设置得更小一些可以有效减少编译时间 + +在 MMDetection 中可以通过环境变量 `DYNAMO_CACHE_SIZE_LIMIT` 设置 `torch._dynamo.config.cache_size_limit` 参数,以 RTMDet 为例,命令如下所示: + +```shell +# 单卡 +export DYNAMO_CACHE_SIZE_LIMIT = 4 +python tools/train.py configs/rtmdet/rtmdet_s_8xb32-300e_coco.py --cfg-options compile=True + +# 单机 8 卡 +export DYNAMO_CACHE_SIZE_LIMIT = 4 +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True +``` + +关于 PyTorch 2.0 的 dynamo 常见问题,可以参考 [这里](https://pytorch.org/docs/stable/dynamo/faq.html) + +## 安装 + +- MMCV 与 MMDetection 的兼容问题: "ConvWS is already registered in conv layer"; "AssertionError: MMCV==xxx is used but incompatible. Please install mmcv>=xxx, \<=xxx." + + MMDetection,MMEngine 和 MMCV 的版本兼容关系如下。请选择合适的版本避免安装错误 。 + + | MMDetection 版本 | MMCV 版本 | MMEngine 版本 | + | :--------------: | :---------------------: | :----------------------: | + | main | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | + | 3.1.0 | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | + | 3.0.0 | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | + | 3.0.0rc6 | mmcv>=2.0.0rc4, \<2.1.0 | mmengine>=0.6.0, \<1.0.0 | + | 3.0.0rc5 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | + | 3.0.0rc4 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | + | 3.0.0rc3 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | + | 3.0.0rc2 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | + | 3.0.0rc1 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | + | 3.0.0rc0 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | + + **注意:** + + 1. 如果你希望安装 mmdet-v2.x, MMDetection 和 MMCV 版本兼容表可以在 [这里](https://mmdetection.readthedocs.io/en/stable/faq.html#installation) 找到,请选择合适的版本避免安装错误。 + 2. 在 MMCV-v2.x 中,`mmcv-full` 改名为 `mmcv`,如果你想安装不包含 CUDA 算子的版本,可以选择安装 MMCV 精简版 `mmcv-lite`。 + +- "No module named 'mmcv.ops'"; "No module named 'mmcv.\_ext'". + + 原因是安装了 `mmcv-lite` 而不是 `mmcv`。 + + 1. `pip uninstall mmcv-lite` 卸载安装的 `mmcv-lite` + + 2. 安装 `mmcv` 根据 [安装说明](https://mmcv.readthedocs.io/zh_CN/2.x/get_started/installation.html)。 + +- 在 Windows 环境下安装过程中遇到 "Microsoft Visual C++ 14.0 or graeter is required" error . + + 这个错误发生在 pycotools 的 'pycocotools.\_mask' 扩展构建过程,其原因是缺少了对应 C++ 环境依赖。你需要到微软官方下载[对应工具](https://visualstudio.microsoft.com/zh-hans/visual-cpp-build-tools/),选择“使用 C++ 的桌面开发”选项安装最小依赖,随后重新安装 pycocotools。 + +- 使用 albumentations + +如果你希望使用 `albumentations`,我们建议使用 `pip install -r requirements/albu.txt` +或者 `pip install -U albumentations --no-binary qudida,albumentations` 进行安装。 +如果简单地使用 `pip install albumentations>=0.3.2` 进行安装, +则会同时安装 `opencv-python-headless`(即便已经安装了 `opencv-python` 也会再次安装)。 +我们建议在安装 `albumentations` 后检查环境,以确保没有同时安装 `opencv-python` 和 `opencv-python-headless`, +因为同时安装可能会导致一些问题。更多细节请参考[官方文档](https://albumentations.ai/docs/getting_started/installation/#note-on-opencv-dependencies) 。 + +- 在某些算法中出现 ModuleNotFoundError 错误 + +一些算法或者数据需要额外的依赖,例如 Instaboost、 Panoptic Segmentation、 LVIS dataset 等。请注意错误信息并安装相应的包,例如: + +```shell +# 安装 instaboost 依赖 +pip install instaboostfast +# 安装 panoptic segmentation 依赖 +pip install git+https://github.com/cocodataset/panopticapi.git +# 安装 LVIS dataset 依赖 +pip install git+https://github.com/lvis-dataset/lvis-api.git +``` + +## 代码 + +- 修改一些代码后是否需要重新安装 mmdet + +如果你遵循最佳实践,即使用 `pip install -v -e .` 安装的 mmdet,则对本地代码所作的任何修改都会生效,无需重新安装 + +- 如何使用多个 MMDetection 版本进行开发 + +你可以拥有多个文件夹,例如 mmdet-3.0,mmdet-3.1。 + +要使环境中安装默认的 MMDetection 而不是当前正在在使用的,可以删除出现在相关脚本中的代码: + +```shell +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH +``` + +## PyTorch/CUDA 环境相关 + +- "RTX 30 series card fails when building MMCV or MMDet" + + 1. 临时解决方案为使用命令 `MMCV_WITH_OPS=1 MMCV_CUDA_ARGS='-gencode=arch=compute_80,code=sm_80' pip install -e .` 进行编译。 常见报错信息为 `nvcc fatal : Unsupported gpu architecture 'compute_86'` 意思是你的编译器不支持 sm_86 架构(包括英伟达 30 系列的显卡)的优化,至 CUDA toolkit 11.0 依旧未支持. 这个命令是通过增加宏 `MMCV_CUDA_ARGS='-gencode=arch=compute_80,code=sm_80` 让 nvcc 编译器为英伟达 30 系列显卡进行 `sm_80` 的优化,虽然这有可能会无法发挥出显卡所有性能。 + + 2. 有开发者已经在 [pytorch/pytorch#47585](https://github.com/pytorch/pytorch/pull/47585) 更新了 PyTorch 默认的编译 flag, 但是我们对此并没有进行测试。 + +- "invalid device function" 或者 "no kernel image is available for execution". + + 1. 检查您正常安装了 CUDA runtime (一般在`/usr/local/`),或者使用 `nvcc --version` 检查本地版本,有时安装 PyTorch 会顺带安装一个 CUDA runtime,并且实际优先使用 conda 环境中的版本,你可以使用 `conda list cudatoolkit` 查看其版本。 + + 2. 编译 extension 的 CUDA Toolkit 版本与运行时的 CUDA Toolkit 版本是否相符, + + - 如果您从源码自己编译的,使用 `python mmdet/utils/collect_env.py` 检查编译编译 extension 的 CUDA Toolkit 版本,然后使用 `conda list cudatoolkit` 检查当前 conda 环境是否有 CUDA Toolkit,若有检查版本是否匹配, 如不匹配,更换 conda 环境的 CUDA Toolkit,或者使用匹配的 CUDA Toolkit 中的 nvcc 编译即可,如环境中无 CUDA Toolkit,可以使用 `nvcc -V`。 + + 等命令查看当前使用的 CUDA runtime。 + + - 如果您是通过 pip 下载的预编译好的版本,请确保与当前 CUDA runtime 一致。 + + 3. 运行 `python mmdet/utils/collect_env.py` 检查是否为正确的 GPU 架构编译的 PyTorch, torchvision, 与 MMCV。 你或许需要设置 `TORCH_CUDA_ARCH_LIST` 来重新安装 MMCV,可以参考 [GPU 架构表](https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#gpu-feature-list), + 例如, 运行 `TORCH_CUDA_ARCH_LIST=7.0 pip install mmcv` 为 Volta GPU 编译 MMCV。这种架构不匹配的问题一般会出现在使用一些旧型号的 GPU 时候出现, 例如, Tesla K80。 + +- "undefined symbol" 或者 "cannot open xxx.so". + + 1. 如果这些 symbol 属于 CUDA/C++ (如 libcudart.so 或者 GLIBCXX),使用 `python mmdet/utils/collect_env.py`检查 CUDA/GCC runtime 与编译 MMCV 的 CUDA 版本是否相同。 + 2. 如果这些 symbols 属于 PyTorch,(例如, symbols containing caffe, aten, and TH), 检查当前 Pytorch 版本是否与编译 MMCV 的版本一致。 + 3. 运行 `python mmdet/utils/collect_env.py` 检查 PyTorch, torchvision, MMCV 等的编译环境与运行环境一致。 + +- setuptools.sandbox.UnpickleableException: DistutilsSetupError("each element of 'ext_modules' option must be an Extension instance or 2-tuple") + + 1. 如果你在使用 miniconda 而不是 anaconda,检查是否正确的安装了 Cython 如 [#3379](https://github.com/open-mmlab/mmdetection/issues/3379). + 2. 检查环境中的 `setuptools`, `Cython`, and `PyTorch` 相互之间版本是否匹配。 + +- "Segmentation fault". + + 1. 检查 GCC 的版本,通常是因为 PyTorch 版本与 GCC 版本不匹配 (例如 GCC \< 4.9 ),我们推荐用户使用 GCC 5.4,我们也不推荐使用 GCC 5.5, 因为有反馈 GCC 5.5 会导致 "segmentation fault" 并且切换到 GCC 5.4 就可以解决问题。 + + 2. 检查是否正确安装了 CUDA 版本的 PyTorch 。 + + ```shell + python -c 'import torch; print(torch.cuda.is_available())' + ``` + + 是否返回True。 + + 3. 如果 `torch` 的安装是正确的,检查是否正确编译了 MMCV。 + + ```shell + python -c 'import mmcv; import mmcv.ops' + ``` + + 4. 如果 MMCV 与 PyTorch 都被正确安装了,则使用 `ipdb`, `pdb` 设置断点,直接查找哪一部分的代码导致了 `segmentation fault`。 + +## Training 相关 + +- "Loss goes Nan" + + 1. 检查数据的标注是否正常, 长或宽为 0 的框可能会导致回归 loss 变为 nan,一些小尺寸(宽度或高度小于 1)的框在数据增强(例如,instaboost)后也会导致此问题。 因此,可以检查标注并过滤掉那些特别小甚至面积为 0 的框,并关闭一些可能会导致 0 面积框出现数据增强。 + 2. 降低学习率:由于某些原因,例如 batch size 大小的变化, 导致当前学习率可能太大。 您可以降低为可以稳定训练模型的值。 + 3. 延长 warm up 的时间:一些模型在训练初始时对学习率很敏感,您可以把 `warmup_iters` 从 500 更改为 1000 或 2000。 + 4. 添加 gradient clipping: 一些模型需要梯度裁剪来稳定训练过程。 默认的 `grad_clip` 是 `None`, 你可以在 config 设置 `optimizer_config=dict(_delete_=True, grad_clip=dict(max_norm=35, norm_type=2))` 如果你的 config 没有继承任何包含 `optimizer_config=dict(grad_clip=None)`, 你可以直接设置`optimizer_config=dict(grad_clip=dict(max_norm=35, norm_type=2))`. + +- "GPU out of memory" + + 1. 存在大量 ground truth boxes 或者大量 anchor 的场景,可能在 assigner 会 OOM。 您可以在 assigner 的配置中设置 `gpu_assign_thr=N`,这样当超过 N 个 GT boxes 时,assigner 会通过 CPU 计算 IOU。 + + 2. 在 backbone 中设置 `with_cp=True`。 这使用 PyTorch 中的 `sublinear strategy` 来降低 backbone 占用的 GPU 显存。 + + 3. 使用 `config/fp16` 中的示例尝试混合精度训练。`loss_scale` 可能需要针对不同模型进行调整。 + + 4. 你也可以尝试使用 `AvoidCUDAOOM` 来避免该问题。首先它将尝试调用 `torch.cuda.empty_cache()`。如果失败,将会尝试把输入类型转换到 FP16。如果仍然失败,将会把输入从 GPUs 转换到 CPUs 进行计算。这里提供了两个使用的例子: + + ```python + from mmdet.utils import AvoidCUDAOOM + + output = AvoidCUDAOOM.retry_if_cuda_oom(some_function)(input1, input2) + ``` + + 你也可也使用 `AvoidCUDAOOM` 作为装饰器让代码遇到 OOM 的时候继续运行: + + ```python + from mmdet.utils import AvoidCUDAOOM + + @AvoidCUDAOOM.retry_if_cuda_oom + def function(*args, **kwargs): + ... + return xxx + ``` + +- "RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one" + + 1. 这个错误出现在存在参数没有在 forward 中使用,容易在 DDP 中运行不同分支时发生。 + 2. 你可以在 config 设置 `find_unused_parameters = True` 进行训练 (会降低训练速度)。 + 3. 你也可以通过在 config 中的 `optimizer_config` 里设置 `detect_anomalous_params=True` 查找哪些参数没有用到,但是需要 MMCV 的版本 >= 1.4.1。 + +- 训练中保存最好模型 + + 可以通过配置 `default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=1, save_best='auto')`开启。在 `auto` 参数情况下会根据返回的验证结果中的第一个 key 作为选择最优模型的依据,你也可以直接设置评估结果中的 key 来手动设置,例如 `save_best='coco/bbox_mAP'`。 + +- 在 Resume 训练中使用 `ExpMomentumEMAHook` + + 如果在训练中使用了 `ExpMomentumEMAHook`,那么 resume 时候不能仅仅通过命令行参数 `--resume-from` 或 `--cfg-options resume_from` 实现恢复模型参数功能例如 `python tools/train.py configs/yolox/yolox_s_8x8_300e_coco.py --resume-from ./work_dir/yolox_s_8x8_300e_coco/epoch_x.pth`。以 `yolox_s` 算法为例,由于 `ExpMomentumEMAHook` 需要重新加载权重,你可以通过如下做法实现: + + ```python + # 直接打开 configs/yolox/yolox_s_8x8_300e_coco.py 修改所有 resume_from 字段 + resume_from=./work_dir/yolox_s_8x8_300e_coco/epoch_x.pth + custom_hooks=[... + dict( + type='ExpMomentumEMAHook', + resume_from=./work_dir/yolox_s_8x8_300e_coco/epoch_x.pth, + momentum=0.0001, + priority=49) + ] + ``` + +## Evaluation 相关 + +- 使用 COCO Dataset 的测评接口时, 测评结果中 AP 或者 AR = -1 + 1. 根据COCO数据集的定义,一张图像中的中等物体与小物体面积的阈值分别为 9216(96\*96)与 1024(32\*32)。 + 2. 如果在某个区间没有检测框 AP 与 AR 认定为 -1. + +## Model 相关 + +- **ResNet style 参数说明** + + ResNet style 可选参数允许 `pytorch` 和 `caffe`,其差别在于 Bottleneck 模块。Bottleneck 是 `1x1-3x3-1x1` 堆叠结构,在 `caffe` 模式模式下 stride=2 参数放置在第一个 `1x1` 卷积处,而 `pyorch` 模式下 stride=2 放在第二个 `3x3` 卷积处。一个简单示例如下: + + ```python + if self.style == 'pytorch': + self.conv1_stride = 1 + self.conv2_stride = stride + else: + self.conv1_stride = stride + self.conv2_stride = 1 + ``` + +- **ResNeXt 参数说明** + + ResNeXt 来自论文 [`Aggregated Residual Transformations for Deep Neural Networks`](https://arxiv.org/abs/1611.05431). 其引入分组卷积,并且通过变量基数来控制组的数量达到精度和复杂度的平衡,其有两个超参 `baseWidth` 和 `cardinality `来控制内部 Bottleneck 模块的基本宽度和分组数参数。以 MMDetection 中配置名为 `mask_rcnn_x101_64x4d_fpn_mstrain-poly_3x_coco.py` 为例,其中 `mask_rcnn` 代表算法采用 Mask R-CNN,`x101` 代表骨架网络采用 ResNeXt-101,`64x4d`代表 Bottleneck 一共分成 64 组,每组的基本宽度是 4。 + +- **骨架网络 eval 模式说明** + + 因为检测模型通常比较大且输入图片分辨率很高,这会导致检测模型的 batch 很小,通常是 2,这会使得 BatchNorm 在训练过程计算的统计量方差非常大,不如主干网络预训练时得到的统计量稳定,因此在训练是一般都会使用 `norm_eval=True` 模式,直接使用预训练主干网络中的 BatchNorm 统计量,少数使用大 batch 的算法是 `norm_eval=False` 模式,例如 NASFPN。对于没有 ImageNet 预训练的骨架网络,如果 batch 比较小,可以考虑使用 `SyncBN`。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/notes/projects.md b/mmdet_code/SR-TOD/docs/zh_cn/notes/projects.md new file mode 100644 index 0000000000000000000000000000000000000000..6b9d300d33bb46b9ae816fb865bef9b27310c7e8 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/notes/projects.md @@ -0,0 +1,48 @@ +# 基于 MMDetection 的项目 + +有许多开源项目都是基于 MMDetection 搭建的,我们在这里列举一部分作为样例,展示如何基于 MMDetection 搭建您自己的项目。 +由于这个页面列举的项目并不完全,我们欢迎社区提交 Pull Request 来更新这个文档。 + +## MMDetection 的拓展项目 + +一些项目拓展了 MMDetection 的边界,如将 MMDetection 拓展支持 3D 检测或者将 MMDetection 用于部署。 +它们展示了 MMDetection 的许多可能性,所以我们在这里也列举一些。 + +- [OTEDetection](https://github.com/opencv/mmdetection): OpenVINO training extensions for object detection. +- [MMDetection3d](https://github.com/open-mmlab/mmdetection3d): OpenMMLab's next-generation platform for general 3D object detection. + +## 研究项目 + +同样有许多研究论文是基于 MMDetection 进行的。许多论文都发表在了顶级的会议或期刊上,或者对社区产生了深远的影响。 +为了向社区提供一个可以参考的论文列表,帮助大家开发或者比较新的前沿算法,我们在这里也遵循会议的时间顺序列举了一些论文。 +MMDetection 中已经支持的算法不在此列。 + +- Involution: Inverting the Inherence of Convolution for Visual Recognition, CVPR21. [\[paper\]](https://arxiv.org/abs/2103.06255)[\[github\]](https://github.com/d-li14/involution) +- Multiple Instance Active Learning for Object Detection, CVPR 2021. [\[paper\]](https://openaccess.thecvf.com/content/CVPR2021/papers/Yuan_Multiple_Instance_Active_Learning_for_Object_Detection_CVPR_2021_paper.pdf)[\[github\]](https://github.com/yuantn/MI-AOD) +- Adaptive Class Suppression Loss for Long-Tail Object Detection, CVPR 2021. [\[paper\]](https://arxiv.org/abs/2104.00885)[\[github\]](https://github.com/CASIA-IVA-Lab/ACSL) +- Generalizable Pedestrian Detection: The Elephant In The Room, CVPR2021. [\[paper\]](https://arxiv.org/abs/2003.08799)[\[github\]](https://github.com/hasanirtiza/Pedestron) +- Group Fisher Pruning for Practical Network Compression, ICML2021. [\[paper\]](https://github.com/jshilong/FisherPruning/blob/main/resources/paper.pdf)[\[github\]](https://github.com/jshilong/FisherPruning) +- Overcoming Classifier Imbalance for Long-tail Object Detection with Balanced Group Softmax, CVPR2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/papers/Li_Overcoming_Classifier_Imbalance_for_Long-Tail_Object_Detection_With_Balanced_Group_CVPR_2020_paper.pdf)[\[github\]](https://github.com/FishYuLi/BalancedGroupSoftmax) +- Coherent Reconstruction of Multiple Humans from a Single Image, CVPR2020. [\[paper\]](https://jiangwenpl.github.io/multiperson/)[\[github\]](https://github.com/JiangWenPL/multiperson) +- Look-into-Object: Self-supervised Structure Modeling for Object Recognition, CVPR 2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/papers/Zhou_Look-Into-Object_Self-Supervised_Structure_Modeling_for_Object_Recognition_CVPR_2020_paper.pdf)[\[github\]](https://github.com/JDAI-CV/LIO) +- Video Panoptic Segmentation, CVPR2020. [\[paper\]](https://arxiv.org/abs/2006.11339)[\[github\]](https://github.com/mcahny/vps) +- D2Det: Towards High Quality Object Detection and Instance Segmentation, CVPR2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/html/Cao_D2Det_Towards_High_Quality_Object_Detection_and_Instance_Segmentation_CVPR_2020_paper.html)[\[github\]](https://github.com/JialeCao001/D2Det) +- CentripetalNet: Pursuing High-quality Keypoint Pairs for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.09119)[\[github\]](https://github.com/KiveeDong/CentripetalNet) +- Learning a Unified Sample Weighting Network for Object Detection, CVPR 2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/html/Cai_Learning_a_Unified_Sample_Weighting_Network_for_Object_Detection_CVPR_2020_paper.html)[\[github\]](https://github.com/caiqi/sample-weighting-network) +- Scale-equalizing Pyramid Convolution for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2005.03101) [\[github\]](https://github.com/jshilong/SEPC) +- Revisiting the Sibling Head in Object Detector, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.07540)[\[github\]](https://github.com/Sense-X/TSD) +- PolarMask: Single Shot Instance Segmentation with Polar Representation, CVPR2020. [\[paper\]](https://arxiv.org/abs/1909.13226)[\[github\]](https://github.com/xieenze/PolarMask) +- Hit-Detector: Hierarchical Trinity Architecture Search for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.11818)[\[github\]](https://github.com/ggjy/HitDet.pytorch) +- ZeroQ: A Novel Zero Shot Quantization Framework, CVPR2020. [\[paper\]](https://arxiv.org/abs/2001.00281)[\[github\]](https://github.com/amirgholami/ZeroQ) +- CBNet: A Novel Composite Backbone Network Architecture for Object Detection, AAAI2020. [\[paper\]](https://aaai.org/Papers/AAAI/2020GB/AAAI-LiuY.1833.pdf)[\[github\]](https://github.com/VDIGPKU/CBNet) +- RDSNet: A New Deep Architecture for Reciprocal Object Detection and Instance Segmentation, AAAI2020. [\[paper\]](https://arxiv.org/abs/1912.05070)[\[github\]](https://github.com/wangsr126/RDSNet) +- Training-Time-Friendly Network for Real-Time Object Detection, AAAI2020. [\[paper\]](https://arxiv.org/abs/1909.00700)[\[github\]](https://github.com/ZJULearning/ttfnet) +- Cascade RPN: Delving into High-Quality Region Proposal Network with Adaptive Convolution, NeurIPS 2019. [\[paper\]](https://arxiv.org/abs/1909.06720)[\[github\]](https://github.com/thangvubk/Cascade-RPN) +- Reasoning R-CNN: Unifying Adaptive Global Reasoning into Large-scale Object Detection, CVPR2019. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2019/papers/Xu_Reasoning-RCNN_Unifying_Adaptive_Global_Reasoning_Into_Large-Scale_Object_Detection_CVPR_2019_paper.pdf)[\[github\]](https://github.com/chanyn/Reasoning-RCNN) +- Learning RoI Transformer for Oriented Object Detection in Aerial Images, CVPR2019. [\[paper\]](https://arxiv.org/abs/1812.00155)[\[github\]](https://github.com/dingjiansw101/AerialDetection) +- SOLO: Segmenting Objects by Locations. [\[paper\]](https://arxiv.org/abs/1912.04488)[\[github\]](https://github.com/WXinlong/SOLO) +- SOLOv2: Dynamic, Faster and Stronger. [\[paper\]](https://arxiv.org/abs/2003.10152)[\[github\]](https://github.com/WXinlong/SOLO) +- Dense Peppoints: Representing Visual Objects with Dense Point Sets. [\[paper\]](https://arxiv.org/abs/1912.11473)[\[github\]](https://github.com/justimyhxu/Dense-RepPoints) +- IterDet: Iterative Scheme for Object Detection in Crowded Environments. [\[paper\]](https://arxiv.org/abs/2005.05708)[\[github\]](https://github.com/saic-vul/iterdet) +- Cross-Iteration Batch Normalization. [\[paper\]](https://arxiv.org/abs/2002.05712)[\[github\]](https://github.com/Howal/Cross-iterationBatchNorm) +- A Ranking-based, Balanced Loss Function Unifying Classification and Localisation in Object Detection, NeurIPS2020 [\[paper\]](https://arxiv.org/abs/2009.13592)[\[github\]](https://github.com/kemaloksuz/aLRPLoss) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/overview.md b/mmdet_code/SR-TOD/docs/zh_cn/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..5269aed896df8863594295fcf4b64633faf9db1a --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/overview.md @@ -0,0 +1,54 @@ +# 概述 + +本章向您介绍 MMDetection 的整体框架,并提供详细的教程链接。 + +## 什么是 MMDetection + +![图片](https://user-images.githubusercontent.com/12907710/137271636-56ba1cd2-b110-4812-8221-b4c120320aa9.png) + +MMDetection 是一个目标检测工具箱,包含了丰富的目标检测、实例分割、全景分割算法以及相关的组件和模块,下面是它的整体框架: + +MMDetection 由 7 个主要部分组成,apis、structures、datasets、models、engine、evaluation 和 visualization。 + +- **apis** 为模型推理提供高级 API。 +- **structures** 提供 bbox、mask 和 DetDataSample 等数据结构。 +- **datasets** 支持用于目标检测、实例分割和全景分割的各种数据集。 + - **transforms** 包含各种数据增强变换。 + - **samplers** 定义了不同的数据加载器采样策略。 +- **models** 是检测器最重要的部分,包含检测器的不同组件。 + - **detectors** 定义所有检测模型类。 + - **data_preprocessors** 用于预处理模型的输入数据。 + - **backbones** 包含各种骨干网络。 + - **necks** 包含各种模型颈部组件。 + - **dense_heads** 包含执行密集预测的各种检测头。 + - **roi_heads** 包含从 RoI 预测的各种检测头。 + - **seg_heads** 包含各种分割头。 + - **losses** 包含各种损失函数。 + - **task_modules** 为检测任务提供模块,例如 assigners、samplers、box coders 和 prior generators。 + - **layers** 提供了一些基本的神经网络层。 +- **engine** 是运行时组件的一部分。 + - **runner** 为 [MMEngine 的执行器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/runner.html)提供扩展。 + - **schedulers** 提供用于调整优化超参数的调度程序。 + - **optimizers** 提供优化器和优化器封装。 + - **hooks** 提供执行器的各种钩子。 +- **evaluation** 为评估模型性能提供不同的指标。 +- **visualization** 用于可视化检测结果。 + +## 如何使用本指南 + +以下是 MMDetection 的详细指南: + +1. 安装说明见[开始你的第一步](get_started.md)。 + +2. MMDetection 的基本使用方法请参考以下教程。 + + - [训练和测试](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/index.html#train-test) + + - [实用工具](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/index.html#useful-tools) + +3. 参考以下教程深入了解: + + - [基础概念](https://mmdetection.readthedocs.io/zh_CN/latest/advanced_guides/index.html#basic-concepts) + - [组件定制](https://mmdetection.readthedocs.io/zh_CN/latest/advanced_guides/index.html#component-customization) + +4. 对于 MMDetection 2.x 版本的用户,我们提供了[迁移指南](./migration/migration.md),帮助您完成新版本的适配。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/stat.py b/mmdet_code/SR-TOD/docs/zh_cn/stat.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea5fbd25b89e5d3d0925e85a63e2d56d1f58678 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/stat.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +import functools as func +import glob +import os.path as osp +import re + +import numpy as np + +url_prefix = 'https://github.com/open-mmlab/mmdetection/blob/main/' + +files = sorted(glob.glob('../configs/*/README.md')) + +stats = [] +titles = [] +num_ckpts = 0 + +for f in files: + url = osp.dirname(f.replace('../', url_prefix)) + + with open(f, 'r') as content_file: + content = content_file.read() + + title = content.split('\n')[0].replace('# ', '').strip() + ckpts = set(x.lower().strip() + for x in re.findall(r'\[model\]\((https?.*)\)', content)) + + if len(ckpts) == 0: + continue + + _papertype = [x for x in re.findall(r'\[([A-Z]+)\]', content)] + assert len(_papertype) > 0 + papertype = _papertype[0] + + paper = set([(papertype, title)]) + + titles.append(title) + num_ckpts += len(ckpts) + + statsmsg = f""" +\t* [{papertype}] [{title}]({url}) ({len(ckpts)} ckpts) +""" + stats.append((paper, ckpts, statsmsg)) + +allpapers = func.reduce(lambda a, b: a.union(b), [p for p, _, _ in stats]) +msglist = '\n'.join(x for _, _, x in stats) + +papertypes, papercounts = np.unique([t for t, _ in allpapers], + return_counts=True) +countstr = '\n'.join( + [f' - {t}: {c}' for t, c in zip(papertypes, papercounts)]) + +modelzoo = f""" +# Model Zoo Statistics + +* Number of papers: {len(set(titles))} +{countstr} + +* Number of checkpoints: {num_ckpts} + +{msglist} +""" + +with open('modelzoo_statistics.md', 'w') as f: + f.write(modelzoo) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/switch_language.md b/mmdet_code/SR-TOD/docs/zh_cn/switch_language.md new file mode 100644 index 0000000000000000000000000000000000000000..b2c4ad9db394a147483388b245ffb3c72f81642e --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/switch_language.md @@ -0,0 +1,3 @@ +## English + +## 简体中文 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/config.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/config.md new file mode 100644 index 0000000000000000000000000000000000000000..3a670bf8adacee2ddf3e463b5fd7d2ecc7ff6541 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/config.md @@ -0,0 +1,589 @@ +# 学习配置文件 + +MMDetection 和其他 OpenMMLab 仓库使用 [MMEngine 的配置文件系统](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html)。 配置文件使用了模块化和继承设计,以便于进行各类实验。 + +## 配置文件的内容 + +MMDetection 采用模块化设计,所有功能的模块都可以通过配置文件进行配置。 以 Mask R-CNN 为例,我们将根据不同的功能模块介绍配置文件中的各个字段: + +### 模型配置 + +在 mmdetection 的配置中,我们使用 `model` 字段来配置检测算法的组件。 除了 `backbone`、`neck` 等神经网络组件外,还需要 `data_preprocessor`、`train_cfg` 和 `test_cfg`。 `data_preprocessor` 负责对 dataloader 输出的每一批数据进行预处理。 模型配置中的 `train_cfg` 和 `test_cfg` 用于设置训练和测试组件的超参数。 + +```python +model = dict( + type='MaskRCNN', # 检测器名 + data_preprocessor=dict( # 数据预处理器的配置,通常包括图像归一化和 padding + type='DetDataPreprocessor', # 数据预处理器的类型,参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.data_preprocessors.DetDataPreprocessor + mean=[123.675, 116.28, 103.53], # 用于预训练骨干网络的图像归一化通道均值,按 R、G、B 排序 + std=[58.395, 57.12, 57.375], # 用于预训练骨干网络的图像归一化通道标准差,按 R、G、B 排序 + bgr_to_rgb=True, # 是否将图片通道从 BGR 转为 RGB + pad_mask=True, # 是否填充实例分割掩码 + pad_size_divisor=32), # padding 后的图像的大小应该可以被 ``pad_size_divisor`` 整除 + backbone=dict( # 主干网络的配置文件 + type='ResNet', # 主干网络的类别,可用选项请参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.backbones.ResNet + depth=50, # 主干网络的深度,对于 ResNet 和 ResNext 通常设置为 50 或 101 + num_stages=4, # 主干网络状态(stages)的数目,这些状态产生的特征图作为后续的 head 的输入 + out_indices=(0, 1, 2, 3), # 每个状态产生的特征图输出的索引 + frozen_stages=1, # 第一个状态的权重被冻结 + norm_cfg=dict( # 归一化层(norm layer)的配置项 + type='BN', # 归一化层的类别,通常是 BN 或 GN + requires_grad=True), # 是否训练归一化里的 gamma 和 beta + norm_eval=True, # 是否冻结 BN 里的统计项 + style='pytorch', # 主干网络的风格,'pytorch' 意思是步长为2的层为 3x3 卷积, 'caffe' 意思是步长为2的层为 1x1 卷积 + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), # 加载通过 ImageNet 预训练的模型 + neck=dict( + type='FPN', # 检测器的 neck 是 FPN,我们同样支持 'NASFPN', 'PAFPN' 等,更多细节可以参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.necks.FPN + in_channels=[256, 512, 1024, 2048], # 输入通道数,这与主干网络的输出通道一致 + out_channels=256, # 金字塔特征图每一层的输出通道 + num_outs=5), # 输出的范围(scales) + rpn_head=dict( + type='RPNHead', # rpn_head 的类型是 'RPNHead', 我们也支持 'GARPNHead' 等,更多细节可以参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.dense_heads.RPNHead + in_channels=256, # 每个输入特征图的输入通道,这与 neck 的输出通道一致 + feat_channels=256, # head 卷积层的特征通道 + anchor_generator=dict( # 锚点(Anchor)生成器的配置 + type='AnchorGenerator', # 大多数方法使用 AnchorGenerator 作为锚点生成器, SSD 检测器使用 `SSDAnchorGenerator`。更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/prior_generators/anchor_generator.py#L18 + scales=[8], # 锚点的基本比例,特征图某一位置的锚点面积为 scale * base_sizes + ratios=[0.5, 1.0, 2.0], # 高度和宽度之间的比率 + strides=[4, 8, 16, 32, 64]), # 锚生成器的步幅。这与 FPN 特征步幅一致。 如果未设置 base_sizes,则当前步幅值将被视为 base_sizes + bbox_coder=dict( # 在训练和测试期间对框进行编码和解码 + type='DeltaXYWHBBoxCoder', # 框编码器的类别,'DeltaXYWHBBoxCoder' 是最常用的,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/coders/delta_xywh_bbox_coder.py#L13 + 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', # 分类分支的损失类型,我们也支持 FocalLoss 等,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/cross_entropy_loss.py#L201 + use_sigmoid=True, # RPN 通常进行二分类,所以通常使用 sigmoid 函数 + los_weight=1.0), # 分类分支的损失权重 + loss_bbox=dict( # 回归分支的损失函数配置 + type='L1Loss', # 损失类型,我们还支持许多 IoU Losses 和 Smooth L1-loss 等,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/smooth_l1_loss.py#L56 + loss_weight=1.0)), # 回归分支的损失权重 + roi_head=dict( # RoIHead 封装了两步(two-stage)/级联(cascade)检测器的第二步 + type='StandardRoIHead', # RoI head 的类型,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/standard_roi_head.py#L17 + bbox_roi_extractor=dict( # 用于 bbox 回归的 RoI 特征提取器 + type='SingleRoIExtractor', # RoI 特征提取器的类型,大多数方法使用 SingleRoIExtractor,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/roi_extractors/single_level_roi_extractor.py#L13 + roi_layer=dict( # RoI 层的配置 + type='RoIAlign', # RoI 层的类别, 也支持 DeformRoIPoolingPack 和 ModulatedDeformRoIPoolingPack,更多细节请参考 https://mmcv.readthedocs.io/en/latest/api.html#mmcv.ops.RoIAlign + output_size=7, # 特征图的输出大小 + sampling_ratio=0), # 提取 RoI 特征时的采样率。0 表示自适应比率 + out_channels=256, # 提取特征的输出通道 + featmap_strides=[4, 8, 16, 32]), # 多尺度特征图的步幅,应该与主干的架构保持一致 + bbox_head=dict( # RoIHead 中 box head 的配置 + type='Shared2FCBBoxHead', # bbox head 的类别,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py#L220 + in_channels=256, # bbox head 的输入通道。 这与 roi_extractor 中的 out_channels 一致 + fc_out_channels=1024, # FC 层的输出特征通道 + roi_feat_size=7, # 候选区域(Region of Interest)特征的大小 + num_classes=80, # 分类的类别数量 + bbox_coder=dict( # 第二阶段使用的框编码器 + type='DeltaXYWHBBoxCoder', # 框编码器的类别,大多数情况使用 'DeltaXYWHBBoxCoder' + target_means=[0.0, 0.0, 0.0, 0.0], # 用于编码和解码框的均值 + target_stds=[0.1, 0.1, 0.2, 0.2]), # 编码和解码的标准差。因为框更准确,所以值更小,常规设置时 [0.1, 0.1, 0.2, 0.2]。 + reg_class_agnostic=False, # 回归是否与类别无关 + loss_cls=dict( # 分类分支的损失函数配 + type='CrossEntropyLoss', # 分类分支的损失类型,我们也支持 FocalLoss 等 + use_sigmoid=False, # 是否使用 sigmoid + loss_weight=1.0), # 分类分支的损失权重 + loss_bbox=dict( # 回归分支的损失函数配置 + type='L1Loss', # 损失类型,我们还支持许多 IoU Losses 和 Smooth L1-loss 等 + loss_weight=1.0)), # 回归分支的损失权重 + mask_roi_extractor=dict( # 用于 mask 生成的 RoI 特征提取器 + type='SingleRoIExtractor', # RoI 特征提取器的类型,大多数方法使用 SingleRoIExtractor + roi_layer=dict( # 提取实例分割特征的 RoI 层配置 + type='RoIAlign', # RoI 层的类型,也支持 DeformRoIPoolingPack 和 ModulatedDeformRoIPoolingPack + output_size=14, # 特征图的输出大小 + sampling_ratio=0), # 提取 RoI 特征时的采样率 + out_channels=256, # 提取特征的输出通道 + featmap_strides=[4, 8, 16, 32]), # 多尺度特征图的步幅 + mask_head=dict( # mask 预测 head 模型 + type='FCNMaskHead', # mask head 的类型,更多细节请参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.roi_heads.FCNMaskHead + num_convs=4, # mask head 中的卷积层数 + in_channels=256, # 输入通道,应与 mask roi extractor 的输出通道一致 + conv_out_channels=256, # 卷积层的输出通道 + num_classes=80, # 要分割的类别数 + loss_mask=dict( # mask 分支的损失函数配置 + type='CrossEntropyLoss', # 用于分割的损失类型 + use_mask=True, # 是否只在正确的类中训练 mask + loss_weight=1.0))), # mask 分支的损失权重 + train_cfg = dict( # rpn 和 rcnn 训练超参数的配置 + rpn=dict( # rpn 的训练配置 + assigner=dict( # 分配器(assigner)的配置 + type='MaxIoUAssigner', # 分配器的类型,MaxIoUAssigner 用于许多常见的检测器,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/assigners/max_iou_assigner.py#L14 + pos_iou_thr=0.7, # IoU >= 0.7(阈值) 被视为正样本 + neg_iou_thr=0.3, # IoU < 0.3(阈值) 被视为负样本 + min_pos_iou=0.3, # 将框作为正样本的最小 IoU 阈值 + match_low_quality=True, # 是否匹配低质量的框(更多细节见 API 文档) + ignore_iof_thr=-1), # 忽略 bbox 的 IoF 阈值 + sampler=dict( # 正/负采样器(sampler)的配置 + type='RandomSampler', # 采样器类型,还支持 PseudoSampler 和其他采样器,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/samplers/random_sampler.py#L14 + num=256, # 样本数量。 + pos_fraction=0.5, # 正样本占总样本的比例 + neg_pos_ub=-1, # 基于正样本数量的负样本上限 + add_gt_as_proposals=False), # 采样后是否添加 GT 作为 proposal + allowed_border=-1, # 填充有效锚点后允许的边框 + pos_weight=-1, # 训练期间正样本的权重 + debug=False), # 是否设置调试(debug)模式 + rpn_proposal=dict( # 在训练期间生成 proposals 的配置 + nms_across_levels=False, # 是否对跨层的 box 做 NMS。仅适用于 `GARPNHead` ,naive rpn 不支持 nms cross levels + nms_pre=2000, # NMS 前的 box 数 + nms_post=1000, # NMS 要保留的 box 的数量,只在 GARPNHHead 中起作用 + max_per_img=1000, # NMS 后要保留的 box 数量 + nms=dict( # NMS 的配置 + type='nms', # NMS 的类别 + iou_threshold=0.7 # NMS 的阈值 + ), + min_bbox_size=0), # 允许的最小 box 尺寸 + rcnn=dict( # roi head 的配置。 + assigner=dict( # 第二阶段分配器的配置,这与 rpn 中的不同 + type='MaxIoUAssigner', # 分配器的类型,MaxIoUAssigner 目前用于所有 roi_heads。更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/assigners/max_iou_assigner.py#L14 + pos_iou_thr=0.5, # IoU >= 0.5(阈值)被认为是正样本 + neg_iou_thr=0.5, # IoU < 0.5(阈值)被认为是负样本 + min_pos_iou=0.5, # 将 box 作为正样本的最小 IoU 阈值 + match_low_quality=False, # 是否匹配低质量下的 box(有关更多详细信息,请参阅 API 文档) + ignore_iof_thr=-1), # 忽略 bbox 的 IoF 阈值 + sampler=dict( + type='RandomSampler', # 采样器的类型,还支持 PseudoSampler 和其他采样器,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/samplers/random_sampler.py#L14 + num=512, # 样本数量 + pos_fraction=0.25, # 正样本占总样本的比例 + neg_pos_ub=-1, # 基于正样本数量的负样本上限 + add_gt_as_proposals=True + ), # 采样后是否添加 GT 作为 proposal + mask_size=28, # mask 的大小 + pos_weight=-1, # 训练期间正样本的权重 + debug=False)), # 是否设置调试模式 + test_cfg = dict( # 用于测试 rpn 和 rcnn 超参数的配置 + rpn=dict( # 测试阶段生成 proposals 的配置 + nms_across_levels=False, # 是否对跨层的 box 做 NMS。仅适用于 `GARPNHead`,naive rpn 不支持做 NMS cross levels + nms_pre=1000, # NMS 前的 box 数 + nms_post=1000, # NMS 要保留的 box 的数量,只在 `GARPNHHead` 中起作用 + max_per_img=1000, # NMS 后要保留的 box 数量 + nms=dict( # NMS 的配置 + type='nms', # NMS 的类型 + iou_threshold=0.7 # NMS 阈值 + ), + min_bbox_size=0), # box 允许的最小尺寸 + rcnn=dict( # roi heads 的配置 + score_thr=0.05, # bbox 的分数阈值 + nms=dict( # 第二步的 NMS 配置 + type='nms', # NMS 的类型 + iou_thr=0.5), # NMS 的阈值 + max_per_img=100, # 每张图像的最大检测次数 + mask_thr_binary=0.5))) # mask 预处的阈值 +``` + +### 数据集和评测器配置 + +在使用[执行器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/runner.html) 进行训练、测试、验证时,我们需要配置 [Dataloader](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/dataset.html)。构建数据 dataloader 需要设置数据集(dataset)和数据处理流程(data pipeline)。 由于这部分的配置较为复杂,我们使用中间变量来简化 dataloader 配置的编写。 + +```python +dataset_type = 'CocoDataset' # 数据集类型,这将被用来定义数据集。 +data_root = 'data/coco/' # 数据的根路径。 + +train_pipeline = [ # 训练数据处理流程 + dict(type='LoadImageFromFile'), # 第 1 个流程,从文件路径里加载图像。 + dict( + type='LoadAnnotations', # 第 2 个流程,对于当前图像,加载它的注释信息。 + with_bbox=True, # 是否使用标注框(bounding box), 目标检测需要设置为 True。 + with_mask=True, # 是否使用 instance mask,实例分割需要设置为 True。 + poly2mask=False), # 是否将 polygon mask 转化为 instance mask, 设置为 False 以加速和节省内存。 + dict( + type='Resize', # 变化图像和其标注大小的流程。 + scale=(1333, 800), # 图像的最大尺寸 + keep_ratio=True # 是否保持图像的长宽比。 + ), + dict( + type='RandomFlip', # 翻转图像和其标注的数据增广流程。 + prob=0.5), # 翻转图像的概率。 + dict(type='PackDetInputs') # 将数据转换为检测器输入格式的流程 +] +test_pipeline = [ # 测试数据处理流程 + dict(type='LoadImageFromFile'), # 第 1 个流程,从文件路径里加载图像。 + dict(type='Resize', scale=(1333, 800), keep_ratio=True), # 变化图像大小的流程。 + dict( + type='PackDetInputs', # 将数据转换为检测器输入格式的流程 + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( # 训练 dataloader 配置 + batch_size=2, # 单个 GPU 的 batch size + num_workers=2, # 单个 GPU 分配的数据加载线程数 + persistent_workers=True, # 如果设置为 True,dataloader 在迭代完一轮之后不会关闭数据读取的子进程,可以加速训练 + sampler=dict( # 训练数据的采样器 + type='DefaultSampler', # 默认的采样器,同时支持分布式和非分布式训练。请参考 https://mmengine.readthedocs.io/zh_CN/latest/api/generated/mmengine.dataset.DefaultSampler.html#mmengine.dataset.DefaultSampler + shuffle=True), # 随机打乱每个轮次训练数据的顺序 + batch_sampler=dict(type='AspectRatioBatchSampler'), # 批数据采样器,用于确保每一批次内的数据拥有相似的长宽比,可用于节省显存 + dataset=dict( # 训练数据集的配置 + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', # 标注文件路径 + data_prefix=dict(img='train2017/'), # 图片路径前缀 + filter_cfg=dict(filter_empty_gt=True, min_size=32), # 图片和标注的过滤配置 + pipeline=train_pipeline)) # 这是由之前创建的 train_pipeline 定义的数据处理流程。 +val_dataloader = dict( # 验证 dataloader 配置 + batch_size=1, # 单个 GPU 的 Batch size。如果 batch-szie > 1,组成 batch 时的额外填充会影响模型推理精度 + num_workers=2, # 单个 GPU 分配的数据加载线程数 + persistent_workers=True, # 如果设置为 True,dataloader 在迭代完一轮之后不会关闭数据读取的子进程,可以加速训练 + drop_last=False, # 是否丢弃最后未能组成一个批次的数据 + sampler=dict( + type='DefaultSampler', + shuffle=False), # 验证和测试时不打乱数据顺序 + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, # 开启测试模式,避免数据集过滤图片和标注 + pipeline=test_pipeline)) +test_dataloader = val_dataloader # 测试 dataloader 配置 +``` + +[评测器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/evaluation.html) 用于计算训练模型在验证和测试数据集上的指标。评测器的配置由一个或一组评价指标(Metric)配置组成: + +```python +val_evaluator = dict( # 验证过程使用的评测器 + type='CocoMetric', # 用于评估检测和实例分割的 AR、AP 和 mAP 的 coco 评价指标 + ann_file=data_root + 'annotations/instances_val2017.json', # 标注文件路径 + metric=['bbox', 'segm'], # 需要计算的评价指标,`bbox` 用于检测,`segm` 用于实例分割 + format_only=False) +test_evaluator = val_evaluator # 测试过程使用的评测器 +``` + +由于测试数据集没有标注文件,因此 MMDetection 中的 test_dataloader 和 test_evaluator 配置通常等于val。 如果要保存在测试数据集上的检测结果,则可以像这样编写配置: + +```python +# 在测试集上推理, +# 并将检测结果转换格式以用于提交结果 +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'annotations/image_info_test-dev2017.json', + data_prefix=dict(img='test2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/image_info_test-dev2017.json', + metric=['bbox', 'segm'], + format_only=True, # 只将模型输出转换为 coco 的 JSON 格式并保存 + outfile_prefix='./work_dirs/coco_detection/test') # 要保存的 JSON 文件的前缀 +``` + +### 训练和测试的配置 + +MMEngine 的 Runner 使用 Loop 来控制训练,验证和测试过程。 +用户可以使用这些字段设置最大训练轮次和验证间隔。 + +```python +train_cfg = dict( + type='EpochBasedTrainLoop', # 训练循环的类型,请参考 https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py + max_epochs=12, # 最大训练轮次 + val_interval=1) # 验证间隔。每个 epoch 验证一次 +val_cfg = dict(type='ValLoop') # 验证循环的类型 +test_cfg = dict(type='TestLoop') # 测试循环的类型 +``` + +### 优化相关配置 + +`optim_wrapper` 是配置优化相关设置的字段。优化器封装(OptimWrapper)不仅提供了优化器的功能,还支持梯度裁剪、混合精度训练等功能。更多内容请看[优化器封装教程](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/optim_wrapper.html) 。 + +```python +optim_wrapper = dict( # 优化器封装的配置 + type='OptimWrapper', # 优化器封装的类型。可以切换至 AmpOptimWrapper 来启用混合精度训练 + optimizer=dict( # 优化器配置。支持 PyTorch 的各种优化器。请参考 https://pytorch.org/docs/stable/optim.html#algorithms + type='SGD', # 随机梯度下降优化器 + lr=0.02, # 基础学习率 + momentum=0.9, # 带动量的随机梯度下降 + weight_decay=0.0001), # 权重衰减 + clip_grad=None, # 梯度裁剪的配置,设置为 None 关闭梯度裁剪。使用方法请见 https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html + ) +``` + +`param_scheduler` 字段用于配置参数调度器(Parameter Scheduler)来调整优化器的超参数(例如学习率和动量)。 用户可以组合多个调度器来创建所需的参数调整策略。 在 [参数调度器教程](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/param_scheduler.html) 和 [参数调度器 API 文档](https://mmengine.readthedocs.io/zh_CN/latest/api/generated/mmengine.optim._ParamScheduler.html#mmengine.optim._ParamScheduler) 中查找更多信息。 + +```python +param_scheduler = [ + dict( + type='LinearLR', # 使用线性学习率预热 + start_factor=0.001, # 学习率预热的系数 + by_epoch=False, # 按 iteration 更新预热学习率 + begin=0, # 从第一个 iteration 开始 + end=500), # 到第 500 个 iteration 结束 + dict( + type='MultiStepLR', # 在训练过程中使用 multi step 学习率策略 + by_epoch=True, # 按 epoch 更新学习率 + begin=0, # 从第一个 epoch 开始 + end=12, # 到第 12 个 epoch 结束 + milestones=[8, 11], # 在哪几个 epoch 进行学习率衰减 + gamma=0.1) # 学习率衰减系数 +] +``` + +### 钩子配置 + +用户可以在训练、验证和测试循环上添加钩子,以便在运行期间插入一些操作。配置中有两种不同的钩子字段,一种是 `default_hooks`,另一种是 `custom_hooks`。 + +`default_hooks` 是一个字典,用于配置运行时必须使用的钩子。这些钩子具有默认优先级,如果未设置,runner 将使用默认值。如果要禁用默认钩子,用户可以将其配置设置为 `None`。更多内容请看 [钩子教程](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/hook.html) 。 + +```python +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', interval=1), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='DetVisualizationHook')) +``` + +`custom_hooks` 是一个列表。用户可以在这个字段中加入自定义的钩子。 + +```python +custom_hooks = [] +``` + +### 运行相关配置 + +```python +default_scope = 'mmdet' # 默认的注册器域名,默认从此注册器域中寻找模块。请参考 https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/registry.html + +env_cfg = dict( + cudnn_benchmark=False, # 是否启用 cudnn benchmark + mp_cfg=dict( # 多进程设置 + mp_start_method='fork', # 使用 fork 来启动多进程。'fork' 通常比 'spawn' 更快,但可能存在隐患。请参考 https://github.com/pytorch/pytorch/issues/1355 + opencv_num_threads=0), # 关闭 opencv 的多线程以避免系统超负荷 + dist_cfg=dict(backend='nccl'), # 分布式相关设置 +) + +vis_backends = [dict(type='LocalVisBackend')] # 可视化后端,请参考 https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/visualization.html +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +log_processor = dict( + type='LogProcessor', # 日志处理器用于处理运行时日志 + window_size=50, # 日志数值的平滑窗口 + by_epoch=True) # 是否使用 epoch 格式的日志。需要与训练循环的类型保存一致。 + +log_level = 'INFO' # 日志等级 +load_from = None # 从给定路径加载模型检查点作为预训练模型。这不会恢复训练。 +resume = False # 是否从 `load_from` 中定义的检查点恢复。 如果 `load_from` 为 None,它将恢复 `work_dir` 中的最新检查点。 +``` + +## Iter-based 配置 + +MMEngine 的 Runner 除了基于轮次的训练循环(epoch)外,还提供了基于迭代(iteration)的训练循环。 +要使用基于迭代的训练,用户应该修改 `train_cfg`、`param_scheduler`、`train_dataloader`、`default_hooks` 和 `log_processor`。 +以下是将基于 epoch 的 RetinaNet 配置更改为基于 iteration 的示例:configs/retinanet/retinanet_r50_fpn_90k_coco.py + +```python +# iter-based 训练配置 +train_cfg = dict( + _delete_=True, # 忽略继承的配置文件中的值(可选) + type='IterBasedTrainLoop', # iter-based 训练循环 + max_iters=90000, # 最大迭代次数 + val_interval=10000) # 每隔多少次进行一次验证 + + +# 将参数调度器修改为 iter-based +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=90000, + by_epoch=False, + milestones=[60000, 80000], + gamma=0.1) +] + +# 切换至 InfiniteSampler 来避免 dataloader 重启 +train_dataloader = dict(sampler=dict(type='InfiniteSampler')) + +# 将模型检查点保存间隔设置为按 iter 保存 +default_hooks = dict(checkpoint=dict(by_epoch=False, interval=10000)) + +# 将日志格式修改为 iter-based +log_processor = dict(by_epoch=False) +``` + +## 配置文件继承 + +在 `config/_base_` 文件夹下有 4 个基本组件类型,分别是:数据集(dataset),模型(model),训练策略(schedule)和运行时的默认设置(default runtime)。许多方法,例如 Faster R-CNN、Mask R-CNN、Cascade R-CNN、RPN、SSD 能够很容易地构建出来。由 `_base_` 下的组件组成的配置,被我们称为 _原始配置(primitive)_。 + +对于同一文件夹下的所有配置,推荐**只有一个**对应的**原始配置**文件。所有其他的配置文件都应该继承自这个**原始配置**文件。这样就能保证配置文件的最大继承深度为 3。 + +为了便于理解,我们建议贡献者继承现有方法。例如,如果在 Faster R-CNN 的基础上做了一些修改,用户首先可以通过指定 `_base_ = ../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py` 来继承基础的 Faster R-CNN 结构,然后修改配置文件中的必要参数以完成继承。 + +如果你在构建一个与任何现有方法不共享结构的全新方法,那么可以在 `configs` 文件夹下创建一个新的例如 `xxx_rcnn` 文件夹。 + +更多细节请参考 [MMEngine 配置文件教程](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html) 。 + +通过设置 `_base_` 字段,我们可以设置当前配置文件继承自哪些文件。 + +当 `_base_` 为文件路径字符串时,表示继承一个配置文件的内容。 + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' +``` + +当 `_base_` 是多个文件路径的列表时,表示继承多个文件。 + +```python +_base_ = [ + '../_base_/models/mask-rcnn_r50_fpn.py', + '../_base_/datasets/coco_instance.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +``` + +如果需要检查配置文件,可以通过运行 `python tools/misc/print_config.py /PATH/TO/CONFIG` 来查看完整的配置。 + +### 忽略基础配置文件里的部分内容 + +有时,您也许会设置 `_delete_=True` 去忽略基础配置文件里的一些域内容。 您也许可以参照 [MMEngine 配置文件教程](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html) 来获得一些简单的指导。 + +在 MMDetection 里,例如为了改变 Mask R-CNN 的主干网络的某些内容: + +```python +model = dict( + type='MaskRCNN', + 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', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict(...), + rpn_head=dict(...), + roi_head=dict(...)) +``` + +基础配置的 `Mask R-CNN` 使用 `ResNet-50`,在需要将主干网络改成 `HRNet` 的时候,因为 `HRNet` 和 `ResNet` 中有不同的字段,需要使用 `_delete_=True` 将新的键去替换 `backbone` 域内所有老的键。 + +```python +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + _delete_=True, + type='HRNet', + extra=dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128)), + stage4=dict( + num_modules=3, + num_branches=4, + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256))), + init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://msra/hrnetv2_w32')), + neck=dict(...)) +``` + +### 使用配置文件里的中间变量 + +配置文件里会使用一些中间变量,例如数据集里的 `train_pipeline`/`test_pipeline`。我们在定义新的 `train_pipeline`/`test_pipeline` 之后,需要将它们传递到 `data` 里。例如,我们想在训练或测试时,改变 Mask R-CNN 的多尺度策略 (multi scale strategy),`train_pipeline`/`test_pipeline` 是我们想要修改的中间变量。 + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', scale=[(1333, 640), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) +val_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +test_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +``` + +我们首先定义新的 `train_pipeline`/`test_pipeline` 然后传递到 `data` 里。 + +同样的,如果我们想从 `SyncBN` 切换到 `BN` 或者 `MMSyncBN`,我们需要修改配置文件里的每一个 `norm_cfg`。 + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' +norm_cfg = dict(type='BN', requires_grad=True) +model = dict( + backbone=dict(norm_cfg=norm_cfg), + neck=dict(norm_cfg=norm_cfg), + ...) +``` + +### 复用 \_base\_ 文件中的变量 + +如果用户希望在当前配置中复用 base 文件中的变量,则可以通过使用 `{{_base_.xxx}}` 的方式来获取对应变量的拷贝。例如: + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' + +a = {{_base_.model}} # 变量 a 等于 _base_ 中定义的 model +``` + +## 通过脚本参数修改配置 + +当运行 `tools/train.py` 和 `tools/test.py` 时,可以通过 `--cfg-options` 来修改配置文件。 + +- 更新字典链中的配置 + + 可以按照原始配置文件中的 dict 键顺序地指定配置预选项。例如,使用 `--cfg-options model.backbone.norm_eval=False` 将模型主干网络中的所有 BN 模块都改为 `train` 模式。 + +- 更新配置列表中的键 + + 在配置文件里,一些字典型的配置被包含在列表中。例如,数据训练流程 `data.train.pipeline` 通常是一个列表,比如 `[dict(type='LoadImageFromFile'), ...]`。如果需要将 `'LoadImageFromFile'` 改成 `'LoadImageFromWebcam'`,需要写成下述形式: `--cfg-options data.train.pipeline.0.type=LoadImageFromNDArray`. + +- 更新列表或元组的值 + + 如果要更新的值是列表或元组。例如,配置文件通常设置 `model.data_preprocessor.mean=[123.675, 116.28, 103.53]`. 如果需要改变这个键,可以通过 `--cfg-options model.data_preprocessor.mean="[127,127,127]"` 来重新设置。需要注意,引号 " 是支持列表或元组数据类型所必需的,并且在指定值的引号内**不允许**有空格。 + +## 配置文件名称风格 + +我们遵循以下样式来命名配置文件。建议贡献者遵循相同的风格。 + +``` +{algorithm name}_{model component names [component1]_[component2]_[...]}_{training settings}_{training dataset information}_{testing dataset information}.py +``` + +文件名分为五个部分。 每个部分用`_`连接,每个部分内的单词应该用`-`连接。 + +- `{algorithm name}`: 算法的名称。 它可以是检测器名称,例如 `faster-rcnn`、`mask-rcnn` 等。也可以是半监督或知识蒸馏算法,例如 `soft-teacher`、`lad` 等等 +- `{component names}`: 算法中使用的组件名称,如 backbone、neck 等。例如 `r50-caffe_fpn_gn-head` 表示在算法中使用 caffe 版本的 ResNet50、FPN 和 使用了 Group Norm 的检测头。 +- `{training settings}`: 训练设置的信息,例如 batch 大小、数据增强、损失、参数调度方式和训练最大轮次/迭代。 例如:`4xb4-mixup-giou-coslr-100e` 表示使用 8 个 gpu 每个 gpu 4 张图、mixup 数据增强、GIoU loss、余弦退火学习率,并训练 100 个 epoch。 + 缩写介绍: + - `{gpu x batch_per_gpu}`: GPU 数和每个 GPU 的样本数。`bN` 表示每个 GPU 上的 batch 大小为 N。例如 `4x4b` 是 4 个 GPU 每个 GPU 4 张图的缩写。如果没有注明,默认为 8 卡每卡 2 张图。 + - `{schedule}`: 训练方案,选项是 `1x`、 `2x`、 `20e` 等。`1x` 和 `2x` 分别代表 12 epoch 和 24 epoch,`20e` 在级联模型中使用,表示 20 epoch。对于 `1x`/`2x`,初始学习率在第 8/16 和第 11/22 epoch 衰减 10 倍;对于 `20e` ,初始学习率在第 16 和第 19 epoch 衰减 10 倍。 +- `{training dataset information}`: 训练数据集,例如 `coco`, `coco-panoptic`, `cityscapes`, `voc-0712`, `wider-face`。 +- `{testing dataset information}` (可选): 测试数据集,用于训练和测试在不同数据集上的模型配置。 如果没有注明,则表示训练和测试的数据集类型相同。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/dataset_prepare.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/dataset_prepare.md new file mode 100644 index 0000000000000000000000000000000000000000..91df4952e8040ece710631ee6f60bda51e43f946 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/dataset_prepare.md @@ -0,0 +1,307 @@ +## 数据集准备 + +### 基础检测数据集准备 + +MMDetection 支持多个公共数据集,包括 [COCO](https://cocodataset.org/), [Pascal VOC](http://host.robots.ox.ac.uk/pascal/VOC), [Cityscapes](https://www.cityscapes-dataset.com/) 和 [其他更多数据集](https://github.com/open-mmlab/mmdetection/tree/main/configs/_base_/datasets)。 + +一些公共数据集,比如 Pascal VOC 及其镜像数据集,或者 COCO 等数据集都可以从官方网站或者镜像网站获取。注意:在检测任务中,Pascal VOC 2012 是 Pascal VOC 2007 的无交集扩展,我们通常将两者一起使用。 我们建议将数据集下载,然后解压到项目外部的某个文件夹内,然后通过符号链接的方式,将数据集根目录链接到 `$MMDETECTION/data` 文件夹下, 如果你的文件夹结构和下方不同的话,你需要在配置文件中改变对应的路径。 + +我们提供了下载 COCO 等数据集的脚本,你可以运行 `python tools/misc/download_dataset.py --dataset-name coco2017` 下载 COCO 数据集。 对于中国境内的用户,我们也推荐通过开源数据平台 [OpenDataLab](https://opendatalab.com/?source=OpenMMLab%20GitHub) 来下载数据,以获得更好的下载体验。 + +更多用法请参考[数据集下载](./useful_tools.md#dataset-download) + +```text +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ ├── cityscapes +│ │ ├── annotations +│ │ ├── leftImg8bit +│ │ │ ├── train +│ │ │ ├── val +│ │ ├── gtFine +│ │ │ ├── train +│ │ │ ├── val +│ ├── VOCdevkit +│ │ ├── VOC2007 +│ │ ├── VOC2012 +``` + +有些模型需要额外的 [COCO-stuff](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip) 数据集,比如 HTC,DetectoRS 和 SCNet,你可以下载并解压它们到 `coco` 文件夹下。文件夹会是如下结构: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +``` + +PanopticFPN 等全景分割模型需要额外的 [COCO Panoptic](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip) 数据集,你可以下载并解压它们到 `coco/annotations` 文件夹下。文件夹会是如下结构: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── panoptic_train2017.json +│ │ │ ├── panoptic_train2017 +│ │ │ ├── panoptic_val2017.json +│ │ │ ├── panoptic_val2017 +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +``` + +Cityscape 数据集的标注格式需要转换,以与 COCO 数据集标注格式保持一致,使用 `tools/dataset_converters/cityscapes.py` 来完成转换: + +```shell +pip install cityscapesscripts + +python tools/dataset_converters/cityscapes.py \ + ./data/cityscapes \ + --nproc 8 \ + --out-dir ./data/cityscapes/annotations +``` + +### COCO Caption 数据集准备 + +COCO Caption 采用的是 COCO2014 数据集作为图片,并且使用了 karpathy 的标注, + +首先你需要下载 COCO2014 数据集 + +```shell +python tools/misc/download_dataset.py --dataset-name coco2014 --unzip +``` + +数据集会下载到当前路径的 `data/coco` 下。然后下载 karpathy 的标注 + +```shell +cd data/coco/annotations +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_train.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val_gt.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test_gt.json +``` + +最终直接可用于训练和测试的数据集文件夹结构如下: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── coco_karpathy_train.json +│ │ │ ├── coco_karpathy_test.json +│ │ │ ├── coco_karpathy_val.json +│ │ │ ├── coco_karpathy_val_gt.json +│ │ │ ├── coco_karpathy_test_gt.json +│ │ ├── train2014 +│ │ ├── val2014 +│ │ ├── test2014 +``` + +### COCO semantic 数据集准备 + +COCO 语义分割有两种类型标注,主要差别在于类别名定义不一样,因此处理方式也有两种,第一种是直接使用 stuffthingmaps 数据集,第二种是使用 panoptic 数据集。 + +**(1) 使用 stuffthingmaps 数据集** + +该数据集的下载地址为 [stuffthingmaps_trainval2017](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip),请下载后解压到 `data/coco` 文件夹下。 + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +``` + +该数据集不同于标准的 COCO 类别标注,其包括 172 个类: 80 thing 类、91 stuff 类和 1 个 'unlabeled',其每个类别的说明见 https://github.com/nightrome/cocostuff/blob/master/labels.md + +虽然只标注了 172 个类别,但是 `stuffthingmaps` 中最大标签 id 是 182,中间有些类别是没有标注的,并且第 0 类的 `unlabeled` 类别被移除。因此最终的 `stuffthingmaps` 图片中每个位置的值对应的类别关系见 https://github.com/kazuto1011/deeplab-pytorch/blob/master/data/datasets/cocostuff/labels.txt + +考虑到训练高效和方便用户,在开启训练或者评估前,我们需要将没有标注的 12 个类移除,这 12 个类的名字为: `street sign、hat、shoe、eye glasses、plate、mirror、window、desk、door、blender、hair brush`,最终可用于训练和评估的类别信息见 `mmdet/datasets/coco_semantic.py` + +你可以使用 `tools/dataset_converters/coco_stuff164k.py` 来完成将下载的 `stuffthingmaps` 转换为直接可以训练和评估的数据集,转换后的数据集文件夹结构如下: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +│ │ ├── stuffthingmaps_semseg +``` + +`stuffthingmaps_semseg` 即为新生成的可以直接训练和测试的 COCO 语义分割数据集。 + +**(2) 使用 panoptic 数据集** + +通过 panoptic 标注生成的语义分割数据集类别数相比使用 `stuffthingmaps` 数据集生成的会少一些。首先你需要准备全景分割标注,然后使用如下脚本完成转换 + +```shell +python tools/dataset_converters/prepare_coco_semantic_annos_from_panoptic_annos.py data/coco +``` + +转换后的数据集文件夹结构如下: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── panoptic_train2017.json +│ │ │ ├── panoptic_train2017 +│ │ │ ├── panoptic_val2017.json +│ │ │ ├── panoptic_val2017 +│ │ │ ├── panoptic_semseg_train2017 +│ │ │ ├── panoptic_semseg_val2017 +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +``` + +`panoptic_semseg_train2017` 和 `panoptic_semseg_val2017` 即为新生成的可以直接训练和测试的 COCO 语义分割数据集。注意其类别信息就是 COCO 全景分割的类别信息,包括 thing 和 stuff。 + +### RefCOCO 数据集准备 + +[RefCOCO](https://github.com/lichengunc/refer)系列数据集的图像和注释可以通过运行 `tools/misc/download_dataset.py` 下载: + +```shell +python tools/misc/download_dataset.py --dataset-name refcoco --save-dir data/coco --unzip +``` + +然后,目录应该是这样的: + +```text +data +├── coco +│ ├── refcoco +│   │   ├── instances.json +│   │   ├── refs(google).p +│   │   └── refs(unc).p +│   ├── refcoco+ +│   │   ├── instances.json +│   │   └── refs(unc).p +│   ├── refcocog +│   │   ├── instances.json +│   │   ├── refs(google).p +│   │   └── refs(umd).p +| |── train2014 +``` + +### ADE20K 数据集准备 + +[ADE20K](http://groups.csail.mit.edu/vision/datasets/ADE20K/)数据集的图像和注释可以通过运行 `tools/misc/download_dataset.py` 下载: + +```shell +python tools/misc/download_dataset.py --dataset-name ade20k_2016 --save-dir data --unzip +``` + +然后将注释移至`data/ADEChallengeData2016`目录,并运行预处理脚本以产生coco格式注释: + +```shell +mv data/annotations_instance data/ADEChallengeData2016/ +mv data/categoryMapping.txt data/ADEChallengeData2016/ +mv data/imgCatIds.json data/ADEChallengeData2016/ +python tools/dataset_converters/ade20k2coco.py data/ADEChallengeData2016 --task panoptic +python tools/dataset_converters/ade20k2coco.py data/ADEChallengeData2016 --task instance +``` + +然后,目录应该是这样的: + +```text +data +├── ADEChallengeData2016 +│   ├── ade20k_instance_train.json +│   ├── ade20k_instance_val.json +│   ├── ade20k_panoptic_train +| | ├── ADE_train_00000001.png +| | ├── ADE_train_00000002.png +| | ├── ... +│   ├── ade20k_panoptic_train.json +│   ├── ade20k_panoptic_val +| | ├── ADE_val_00000001.png +| | ├── ADE_val_00000002.png +| | ├── ... +│   ├── ade20k_panoptic_val.json +│   ├── annotations +| | ├── training +| | | ├── ADE_train_00000001.png +| | | ├── ADE_train_00000002.png +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.png +| | | ├── ADE_val_00000002.png +| | | ├── ... +│   ├── annotations_instance +| | ├── training +| | | ├── ADE_train_00000001.png +| | | ├── ADE_train_00000002.png +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.png +| | | ├── ADE_val_00000002.png +| | | ├── ... +│   ├── categoryMapping.txt +│   ├── images +│   | ├── training +| | | ├── ADE_train_00000001.jpg +| | | ├── ADE_train_00000002.jpg +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.jpg +| | | ├── ADE_val_00000002.jpg +| | | ├── ... +│   ├── imgCatIds.json +│   ├── objectInfo150.txt +| |── sceneCategories.txt +``` + +上述文件夹包括ADE20K的语义分割、实例分割和泛在分割的所有数据。 + +### 从 OpenDataLab 中下载 + +[OpenDataLab](https://opendatalab.com/) 为人工智能研究者提供免费开源的数据集,通过 OpenDataLab,研究者可以获得格式统一的各领域经典数据集。通过平台的搜索功能,研究者可以迅速便捷地找到自己所需数据集;通过平台的统一格式,研究者可以便捷地对跨数据集任务进行开发。 + +目前,MIM 支持使用一条命令行从 OpenDataLab 中下载 VOC 和 COCO 数据集,后续将支持更多数据集。你也可以直接访问 OpenDataLab 平台下载你所需的数据集,然后将其转化为 MMDetection 所要求的格式。 + +如果使用 MIM 下载,请确保版本大于 v0.3.8,你可以使用如下命令更新: + +```Bash +pip install -U openmim +``` + +```Bash +# install OpenDataLab CLI tools +pip install -U opendatalab +# log in OpenDataLab, registry +odl login + +# download voc2007 and preprocess by MIM +mim download mmdet --dataset voc2007 + +# download voc2012 and preprocess by MIM +mim download mmdet --dataset voc2012 + +# download coco2017 and preprocess by MIM +mim download mmdet --dataset coco2017 +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/deploy.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/deploy.md new file mode 100644 index 0000000000000000000000000000000000000000..f796b004f0babb4b965cf96dd7f28cfb10c4caf0 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/deploy.md @@ -0,0 +1,174 @@ +# 模型部署 + +[MMDeploy](https://github.com/open-mmlab/mmdeploy) 是 OpenMMLab 的部署仓库,负责包括 MMPretrain、MMDetection 等在内的各算法库的部署工作。 +你可以从[这里](https://mmdeploy.readthedocs.io/zh_CN/1.x/04-supported-codebases/mmdet.html)获取 MMDeploy 对 MMDetection 部署支持的最新文档。 + +本文的结构如下: + +- [安装](#安装) +- [模型转换](#模型转换) +- [模型规范](#模型规范) +- [模型推理](#模型推理) + - [后端模型推理](#后端模型推理) + - [SDK 模型推理](#sdk-模型推理) +- [模型支持列表](#模型支持列表) +- + +## 安装 + +请参考[此处](https://mmdetection.readthedocs.io/en/latest/get_started.html)安装 mmdet。然后,按照[说明](https://mmdeploy.readthedocs.io/zh_CN/1.x/get_started.html#mmdeploy)安装 mmdeploy。 + +```{note} +如果安装的是 mmdeploy 预编译包,那么也请通过 'git clone https://github.com/open-mmlab/mmdeploy.git --depth=1' 下载 mmdeploy 源码。因为它包含了部署时要用到的配置文件 +``` + +## 模型转换 + +假设在安装步骤中,mmdetection 和 mmdeploy 代码库在同级目录下,并且当前的工作目录为 mmdetection 的根目录,那么以 [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py) 模型为例,你可以从[此处](https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth)下载对应的 checkpoint,并使用以下代码将之转换为 onnx 模型: + +```python +from mmdeploy.apis import torch2onnx +from mmdeploy.backend.sdk.export_info import export2SDK + +img = 'demo/demo.jpg' +work_dir = 'mmdeploy_models/mmdet/onnx' +save_file = 'end2end.onnx' +deploy_cfg = '../mmdeploy/configs/mmdet/detection/detection_onnxruntime_dynamic.py' +model_cfg = 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model_checkpoint = 'faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' +device = 'cpu' + +# 1. convert model to onnx +torch2onnx(img, work_dir, save_file, deploy_cfg, model_cfg, + model_checkpoint, device) + +# 2. extract pipeline info for inference by MMDeploy SDK +export2SDK(deploy_cfg, model_cfg, work_dir, pth=model_checkpoint, + device=device) +``` + +转换的关键之一是使用正确的配置文件。项目中已内置了各后端部署[配置文件](https://github.com/open-mmlab/mmdeploy/tree/1.x/configs/mmdet)。 +文件的命名模式是: + +``` +{task}/{task}_{backend}-{precision}_{static | dynamic}_{shape}.py +``` + +其中: + +- **{task}:** mmdet 中的任务 + + mmdet 任务有2种:物体检测(detection)、实例分割(instance-seg)。例如,`RetinaNet`、`Faster R-CNN`、`DETR`等属于前者。`Mask R-CNN`、`SOLO`等属于后者。更多`模型-任务`的划分,请参考章节[模型支持列表](#模型支持列表)。 + + **请务必**使用 `detection/detection_*.py` 转换检测模型,使用 `instance-seg/instance-seg_*.py` 转换实例分割模型。 + +- **{backend}:** 推理后端名称。比如,onnxruntime、tensorrt、pplnn、ncnn、openvino、coreml 等等 + +- **{precision}:** 推理精度。比如,fp16、int8。不填表示 fp32 + +- **{static | dynamic}:** 动态、静态 shape + +- **{shape}:** 模型输入的 shape 或者 shape 范围 + +在上例中,你也可以把 `Faster R-CNN` 转为其他后端模型。比如使用`detection_tensorrt-fp16_dynamic-320x320-1344x1344.py`,把模型转为 tensorrt-fp16 模型。 + +```{tip} +当转 tensorrt 模型时, --device 需要被设置为 "cuda" +``` + +## 模型规范 + +在使用转换后的模型进行推理之前,有必要了解转换结果的结构。 它存放在 `--work-dir` 指定的路路径下。 + +上例中的`mmdeploy_models/mmdet/onnx`,结构如下: + +``` +mmdeploy_models/mmdet/onnx +├── deploy.json +├── detail.json +├── end2end.onnx +└── pipeline.json +``` + +重要的是: + +- **end2end.onnx**: 推理引擎文件。可用 ONNX Runtime 推理 +- ***xxx*.json**: mmdeploy SDK 推理所需的 meta 信息 + +整个文件夹被定义为**mmdeploy SDK model**。换言之,**mmdeploy SDK model**既包括推理引擎,也包括推理 meta 信息。 + +## 模型推理 + +## 后端模型推理 + +以上述模型转换后的 `end2end.onnx` 为例,你可以使用如下代码进行推理: + +```python +from mmdeploy.apis.utils import build_task_processor +from mmdeploy.utils import get_input_shape, load_config +import torch + +deploy_cfg = '../mmdeploy/configs/mmdet/detection/detection_onnxruntime_dynamic.py' +model_cfg = 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +device = 'cpu' +backend_model = ['mmdeploy_models/mmdet/onnx/end2end.onnx'] +image = 'demo/demo.jpg' + +# read deploy_cfg and model_cfg +deploy_cfg, model_cfg = load_config(deploy_cfg, model_cfg) + +# build task and backend model +task_processor = build_task_processor(model_cfg, deploy_cfg, device) +model = task_processor.build_backend_model(backend_model) + +# process input image +input_shape = get_input_shape(deploy_cfg) +model_inputs, _ = task_processor.create_input(image, input_shape) + +# do model inference +with torch.no_grad(): + result = model.test_step(model_inputs) + +# visualize results +task_processor.visualize( + image=image, + model=model, + result=result[0], + window_name='visualize', + output_file='output_detection.png') +``` + +## SDK 模型推理 + +你也可以参考如下代码,对 SDK model 进行推理: + +```python +from mmdeploy_python import Detector +import cv2 + +img = cv2.imread('demo/demo.jpg') + +# create a detector +detector = Detector(model_path='mmdeploy_models/mmdet/onnx', + device_name='cpu', device_id=0) +# perform inference +bboxes, labels, masks = detector(img) + +# visualize inference result +indices = [i for i in range(len(bboxes))] +for index, bbox, label_id in zip(indices, bboxes, labels): + [left, top, right, bottom], score = bbox[0:4].astype(int), bbox[4] + if score < 0.3: + continue + + cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0)) + +cv2.imwrite('output_detection.png', img) +``` + +除了python API,mmdeploy SDK 还提供了诸如 C、C++、C#、Java等多语言接口。 +你可以参考[样例](https://github.com/open-mmlab/mmdeploy/tree/1.x/demo)学习其他语言接口的使用方法。 + +## 模型支持列表 + +请参考[这里](https://mmdeploy.readthedocs.io/zh_CN/1.x/04-supported-codebases/mmdet.html#id6) diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/finetune.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/finetune.md new file mode 100644 index 0000000000000000000000000000000000000000..66bad94e6013b3f0e3ac08c13d48f8ca7aa8f132 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/finetune.md @@ -0,0 +1,96 @@ +# 模型微调 + +在 COCO 数据集上预训练的检测器可以作为其他数据集(例如 CityScapes 和 KITTI 数据集)优质的预训练模型。 +本教程将指导用户如何把 [ModelZoo](../model_zoo.md) 中提供的模型用于其他数据集中并使得当前所训练的模型获得更好性能。 + +以下是在新数据集中微调模型需要的两个步骤。 + +- 按 [教程2:自定义数据集](../advanced_guides/customize_dataset.md) 中的方法对新数据集添加支持中的方法对新数据集添加支持 +- 按照本教程中所讨论方法,修改配置信息 + +接下来将会以 Cityscapes Dataset 上的微调过程作为例子,具体讲述用户需要在配置中修改的五个部分。 + +## 继承基础配置 + +为了减轻编写整个配置的负担并减少漏洞的数量, MMDetection V3.0 支持从多个现有配置中继承配置信息。微调 MaskRCNN 模型的时候,新的配置信息需要使用从 `_base_/models/mask_rcnn_r50_fpn.py` 中继承的配置信息来构建模型的基本结构。当使用 Cityscapes 数据集时,新的配置信息可以简便地从`_base_/datasets/cityscapes_instance.py` 中继承。对于训练过程的运行设置部分,例如 `logger settings`,配置文件可以从 `_base_/default_runtime.py` 中继承。对于训练计划的配置则可以从`_base_/schedules/schedule_1x.py` 中继承。这些配置文件存放于 `configs` 目录下,用户可以选择全部内容的重新编写而不是使用继承方法。 + +```python +_base_ = [ + '../_base_/models/mask_rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py', + '../_base_/schedules/schedule_1x.py' +] +``` + +## Head 的修改 + +接下来新的配置还需要根据新数据集的类别数量对 Head 进行修改。只需要对 roi_head 中的 `num_classes`进行修改。修改后除了最后的预测模型的 Head 之外,预训练模型的权重的大部分都会被重新使用。 + +```python +model = dict( + roi_head=dict( + bbox_head=dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[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='SmoothL1Loss', beta=1.0, loss_weight=1.0)), + mask_head=dict( + type='FCNMaskHead', + num_convs=4, + in_channels=256, + conv_out_channels=256, + num_classes=8, + loss_mask=dict( + type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) +``` + +## 数据集的修改 + +用户可能还需要准备数据集并编写有关数据集的配置,可在 [Customize Datasets](../advanced_guides/customize_dataset.md) 中获取更多信息。目前 MMDetection V3.0 的配置文件已经支持 VOC、WIDERFACE、COCO、LIVS、OpenImages、DeepFashion、Objects365 和 Cityscapes Dataset 的数据集信息。 + +## 训练策略的修改 + +微调超参数与默认的训练策略不同。它通常需要更小的学习率和更少的训练回合。 + +```python +# 优化器 +# batch size 为 8 时的 lr 配置 +optim_wrapper = dict(optimizer=dict(lr=0.01)) + +# 学习率 +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=8, + by_epoch=True, + milestones=[7], + gamma=0.1) +] + +# 设置 max epoch +train_cfg = dict(max_epochs=8) + +# 设置 log config +default_hooks = dict(logger=dict(interval=100)), + +``` + +## 使用预训练模型 + +如果要使用预训练模型,可以在 `load_from` 中查阅新的配置信息,用户需要在训练开始之前下载好需要的模型权重,从而避免在训练过程中浪费了宝贵时间。 + +```python +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth' # noqa +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/index.rst b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..5abc50ad1cd991bb024503c067d0c99f7e79233d --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/index.rst @@ -0,0 +1,34 @@ +训练 & 测试 +************** + +MMDetection 在 `Model Zoo `_ 中提供了数百个预训练的检测模型, +并支持多种标准数据集格式,包括 Pascal VOC、COCO、CityScapes、LVIS 等。本文档将展示如何使用这些模型和数据集来执行常见的训练和测试任务: + +.. toctree:: + :maxdepth: 1 + + config.md + inference.md + dataset_prepare.md + test.md + train.md + new_model.md + finetune.md + test_results_submission.md + init_cfg.md + single_stage_as_rpn.md + semi_det.md + + +实用工具 +************ + +.. toctree:: + :maxdepth: 1 + + useful_tools.md + useful_hooks.md + visualization.md + robustness_benchmarking.md + deploy.md + label_studio.md diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/inference.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/inference.md new file mode 100644 index 0000000000000000000000000000000000000000..788d9eec2f225cac4eb20cb78073ae33f04779ef --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/inference.md @@ -0,0 +1,285 @@ +# 使用已有模型在标准数据集上进行推理 + +MMDetection 提供了许多预训练好的检测模型,可以在 [Model Zoo](https://mmdetection.readthedocs.io/zh_CN/latest/model_zoo.html) 查看具体有哪些模型。 + +推理具体指使用训练好的模型来检测图像上的目标,本文将会展示具体步骤。 + +在 MMDetection 中,一个模型被定义为一个[配置文件](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/config.html) 和对应被存储在 checkpoint 文件内的模型参数的集合。 + +首先,我们建议从 [RTMDet](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet) 开始,其 [配置](https://github.com/open-mmlab/mmdetection/blob/main/configs/rtmdet/rtmdet_l_8xb32-300e_coco.py) 文件和 [checkpoint](https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_l_8xb32-300e_coco/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth) 文件在此。 +我们建议将 checkpoint 文件下载到 `checkpoints` 文件夹内。 + +## 推理的高层编程接口 + +MMDetection 为在图片上推理提供了 Python 的高层编程接口。下面是建立模型和在图像或视频上进行推理的例子。 + +```python +import cv2 +import mmcv +from mmcv.transforms import Compose +from mmengine.utils import track_iter_progress +from mmdet.registry import VISUALIZERS +from mmdet.apis import init_detector, inference_detector + + +# 指定模型的配置文件和 checkpoint 文件路径 +config_file = 'configs/rtmdet/rtmdet_l_8xb32-300e_coco.py' +checkpoint_file = 'checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth' + +# 根据配置文件和 checkpoint 文件构建模型 +model = init_detector(config_file, checkpoint_file, device='cuda:0') + +# 初始化可视化工具 +visualizer = VISUALIZERS.build(model.cfg.visualizer) +# 从 checkpoint 中加载 Dataset_meta,并将其传递给模型的 init_detector +visualizer.dataset_meta = model.dataset_meta + +# 测试单张图片并展示结果 +img = 'test.jpg' # 或者 img = mmcv.imread(img),这样图片仅会被读一次 +result = inference_detector(model, img) + +# 显示结果 +img = mmcv.imread(img) +img = mmcv.imconvert(img, 'bgr', 'rgb') + + +visualizer.add_datasample( + 'result', + img, + data_sample=result, + draw_gt=False, + show=True) + +# 测试视频并展示结果 +# 构建测试 pipeline +model.cfg.test_dataloader.dataset.pipeline[0].type = 'LoadImageFromNDArray' +test_pipeline = Compose(model.cfg.test_dataloader.dataset.pipeline) + +# 可视化工具在第33行和35行已经初完成了初始化,如果直接在一个 jupyter nodebook 中运行这个 demo, +# 这里则不需要再创建一个可视化工具了。 +# 初始化可视化工具 +visualizer = VISUALIZERS.build(model.cfg.visualizer) +# 从 checkpoint 中加载 Dataset_meta,并将其传递给模型的 init_detector +visualizer.dataset_meta = model.dataset_meta + +# 显示间隔 (ms), 0 表示暂停 +wait_time = 1 + +video = mmcv.VideoReader('video.mp4') + +cv2.namedWindow('video', 0) + +for frame in track_iter_progress(video_reader): + result = inference_detector(model, frame, test_pipeline=test_pipeline) + visualizer.add_datasample( + name='video', + image=frame, + data_sample=result, + draw_gt=False, + show=False) + frame = visualizer.get_image() + mmcv.imshow(frame, 'video', wait_time) + +cv2.destroyAllWindows() +``` + +Jupyter notebook 上的演示样例在 [demo/inference_demo.ipynb](https://github.com/open-mmlab/mmdetection/blob/main/demo/inference_demo.ipynb) 。 + +注意: `inference_detector` 目前仅支持单张图片的推理。 + +## 演示样例 + +我们还提供了三个演示脚本,它们是使用高层编程接口实现的。[源码在此](https://github.com/open-mmlab/mmdetection/blob/main/demo) 。 + +### 图片样例 + +这是在单张图片上进行推理的脚本。 + +```shell +python demo/image_demo.py \ + ${IMAGE_FILE} \ + ${CONFIG_FILE} \ + [--weights ${WEIGHTS}] \ + [--device ${GPU_ID}] \ + [--pred-score-thr ${SCORE_THR}] +``` + +运行样例: + +```shell +python demo/image_demo.py demo/demo.jpg \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + --weights checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --device cpu +``` + +### 摄像头样例 + +这是使用摄像头实时图片的推理脚本。 + +```shell +python demo/webcam_demo.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--camera-id ${CAMERA-ID}] \ + [--score-thr ${SCORE_THR}] +``` + +运行样例: + +```shell +python demo/webcam_demo.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth +``` + +### 视频样例 + +这是在视频样例上进行推理的脚本。 + +```shell +python demo/video_demo.py \ + ${VIDEO_FILE} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--score-thr ${SCORE_THR}] \ + [--out ${OUT_FILE}] \ + [--show] \ + [--wait-time ${WAIT_TIME}] +``` + +运行样例: + +```shell +python demo/video_demo.py demo/demo.mp4 \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --out result.mp4 +``` + +### 视频样例,显卡加速版本 + +这是在视频样例上进行推理的脚本,使用显卡加速。 + +```shell +python demo/video_gpuaccel_demo.py \ + ${VIDEO_FILE} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--score-thr ${SCORE_THR}] \ + [--nvdecode] \ + [--out ${OUT_FILE}] \ + [--show] \ + [--wait-time ${WAIT_TIME}] + +``` + +运行样例: + +```shell +python demo/video_gpuaccel_demo.py demo/demo.mp4 \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --nvdecode --out result.mp4 +``` + +## 多模态算法的推理和验证 + +随着多模态视觉算法的不断发展,MMDetection 也完成了对这类算法的支持。这一小节我们通过 GLIP 算法和模型来演示如何使用对应多模态算法的 demo 和 eval 脚本。同时 MMDetection 也在 projects 下完成了 [gradio_demo 项目](../../../projects/gradio_demo/),用户可以参照[文档](../../../projects/gradio_demo/README.md)在本地快速体验 MMDetection 中支持的各类图片输入的任务。 + +### 模型准备 + +首先需要安装多模态依赖: + +```shell +# if source +pip install -r requirements/multimodal.txt + +# if wheel +mim install mmdet[multimodal] +``` + +MMDetection 已经集成了 glip 算法和模型,可以直接使用链接下载使用: + +```shell +cd mmdetection +wget https://download.openmmlab.com/mmdetection/v3.0/glip/glip_tiny_a_mmdet-b3654169.pth +``` + +### 推理演示 + +下载完成后我们就可以利用 `demo` 下的多模态推理脚本完成推理: + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts bench +``` + +demo 效果如下图所示: + +
+ +
+ +如果想进行多种类型的识别,需要使用 `xx . xx .` 的格式在 `--texts` 字段后声明目标类型: + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts 'bench . car .' +``` + +结果如下图所示: + +
+ +
+ +推理脚本还支持输入一个句子作为 `--texts` 字段的输入: + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts 'There are a lot of cars here.' +``` + +结果可以参考下图: + +
+ +
+ +### 验证演示 + +MMDetection 支持后的 GLIP 算法对比官方版本没有精度上的损失, benchmark 如下所示: + +| Model | official mAP | mmdet mAP | +| ----------------------- | :----------: | :-------: | +| glip_A_Swin_T_O365.yaml | 42.9 | 43.0 | +| glip_Swin_T_O365.yaml | 44.9 | 44.9 | +| glip_Swin_L.yaml | 51.4 | 51.3 | + +用户可以使用 `test.py` 脚本对模型精度进行验证,使用如下所示: + +```shell +# 1 gpu +python tools/test.py configs/glip/glip_atss_swin-t_fpn_dyhead_pretrain_obj365.py glip_tiny_a_mmdet-b3654169.pth + +# 8 GPU +./tools/dist_test.sh configs/glip/glip_atss_swin-t_fpn_dyhead_pretrain_obj365.py glip_tiny_a_mmdet-b3654169.pth 8 +``` + +验证结果大致如下: + +```shell +Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.428 +Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1000 ] = 0.594 +Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=1000 ] = 0.466 +Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.300 +Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.477 +Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.534 +Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.634 +Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=300 ] = 0.634 +Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=1000 ] = 0.634 +Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.473 +Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.690 +Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.789 +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/init_cfg.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/init_cfg.md new file mode 100644 index 0000000000000000000000000000000000000000..b58b19d5ab0f4db06cc7467dc9b5e97e39416e19 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/init_cfg.md @@ -0,0 +1,161 @@ +# 权重初始化 + +在训练过程中,适当的初始化策略有利于加快训练速度或获得更⾼的性能。 [MMCV](https://github.com/open-mmlab/mmcv/blob/master/mmcv/cnn/utils/weight_init.py) 提供了一些常⽤的初始化模块的⽅法,如 `nn.Conv2d`。 MMdetection 中的模型初始化主要使⽤ `init_cfg`。⽤⼾可以通过以下两个步骤来初始化模型: + +1. 在 `model_cfg` 中为模型或其组件定义 `init_cfg`,但⼦组件的 `init_cfg` 优先级更⾼,会覆盖⽗模块的 `init_cfg` 。 +2. 像往常一样构建模型,然后显式调⽤ `model.init_weights()` ⽅法,此时模型参数将会被按照配置文件写法进行初始化。 + +MMdetection 初始化工作流的高层 API 调用流程是: + +model_cfg(init_cfg) -> build_from_cfg -> model -> init_weight() -> initialize(self, self.init_cfg) -> children's init_weight() + +### 描述 + +它的数据类型是 dict 或者 list\[dict\],包含了下列键值: + +- `type` (str),包含 `INTIALIZERS` 中的初始化器名称,后面跟着初始化器的参数。 +- `layer`(str 或 list\[str\]),包含 Pytorch 或 MMCV 中基本层的名称,以及将被初始化的可学习参数,例如 `'Conv2d'`,`'DeformConv2d'`。 +- `override` (dict 或 list\[dict\]),包含不继承⾃ `BaseModule` 且其初始化配置与 `layer` 键中的其他层不同的⼦模块。 `type` 中定义的初始化器将适⽤于 `layer` 中定义的所有层,因此如果⼦模块不是 `BaseModule` 的派⽣类但可以与 `layer` 中的层相同的⽅式初始化,则不需要使⽤ `override`。`override` 包含了: + - `type` 后跟初始化器的参数; + - `name` 用以指⽰将被初始化的⼦模块。 + +### 初始化参数 + +从 `mmcv.runner.BaseModule` 或 `mmdet.models` 继承一个新模型。这里我们用 FooModel 来举个例子。 + +```python +import torch.nn as nn +from mmcv.runner import BaseModule + +class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=None): + super(FooModel, self).__init__(init_cfg) + ... +``` + +- 直接在代码中使⽤ `init_cfg` 初始化模型 + + ```python + import torch.nn as nn + from mmcv.runner import BaseModule + # or directly inherit mmdet models + + class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=XXX): + super(FooModel, self).__init__(init_cfg) + ... + ``` + +- 在 `mmcv.Sequential` 或 `mmcv.ModuleList` 代码中直接使⽤ `init_cfg` 初始化模型 + + ```python + from mmcv.runner import BaseModule, ModuleList + + class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=None): + super(FooModel, self).__init__(init_cfg) + ... + self.conv1 = ModuleList(init_cfg=XXX) + ``` + +- 使⽤配置⽂件中的 `init_cfg` 初始化模型 + + ```python + model = dict( + ... + model = dict( + type='FooModel', + arg1=XXX, + arg2=XXX, + init_cfg=XXX), + ... + ``` + +### init_cfg 的使用 + +1. 用 `layer` 键初始化模型 + + 如果我们只定义了 `layer`, 它只会在 `layer` 键中初始化网络层。 + + 注意: `layer` 键对应的值是 Pytorch 的带有 weights 和 bias 属性的类名(因此不⽀持 `MultiheadAttention` 层)。 + +- 定义⽤于初始化具有相同配置的模块的 `layer` 键。 + + ```python + init_cfg = dict(type='Constant', layer=['Conv1d', 'Conv2d', 'Linear'], val=1) + # ⽤相同的配置初始化整个模块 + ``` + +- 定义⽤于初始化具有不同配置的层的 `layer` 键。 + + ```python + init_cfg = [dict(type='Constant', layer='Conv1d', val=1), + dict(type='Constant', layer='Conv2d', val=2), + dict(type='Constant', layer='Linear', val=3)] + # nn.Conv1d 将被初始化为 dict(type='Constant', val=1) + # nn.Conv2d 将被初始化为 dict(type='Constant', val=2) + # nn.Linear 将被初始化为 dict(type='Constant', val=3) + ``` + +2. 使⽤ `override` 键初始化模型 + +- 当使⽤属性名初始化某些特定部分时,我们可以使⽤ `override` 键, `override` 中的值将忽略 init_cfg 中的值。 + + ```python + # layers: + # self.feat = nn.Conv1d(3, 1, 3) + # self.reg = nn.Conv2d(3, 3, 3) + # self.cls = nn.Linear(1,2) + + init_cfg = dict(type='Constant', + layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(type='Constant', name='reg', val=3, bias=4)) + # self.feat and self.cls 将被初始化为 dict(type='Constant', val=1, bias=2) + # 叫 'reg' 的模块将被初始化为 dict(type='Constant', val=3, bias=4) + ``` + +- 如果 init_cfg 中的 `layer` 为 None,则只会初始化 override 中有 name 的⼦模块,⽽ override 中的 type 和其他参数可以省略。 + + ```python + # layers: + # self.feat = nn.Conv1d(3, 1, 3) + # self.reg = nn.Conv2d(3, 3, 3) + # self.cls = nn.Linear(1,2) + + init_cfg = dict(type='Constant', val=1, bias=2, override=dict(name='reg')) + + # self.feat and self.cls 将被 Pytorch 初始化 + # 叫 'reg' 的模块将被 dict(type='Constant', val=1, bias=2) 初始化 + ``` + +- 如果我们不定义 `layer` 或 `override` 键,它不会初始化任何东西。 + +- 无效的使用 + + ```python + # override 没有 name 键的话是无效的 + init_cfg = dict(type='Constant', layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(type='Constant', val=3, bias=4)) + + # override 有 name 键和其他参数但是没有 type 键也是无效的 + init_cfg = dict(type='Constant', layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(name='reg', val=3, bias=4)) + ``` + +3. 使⽤预训练模型初始化模型 + + ```python + init_cfg = dict(type='Pretrained', + checkpoint='torchvision://resnet50') + ``` + +更多细节可以参考 [MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/initialize.html) 的文档 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/label_studio.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/label_studio.md new file mode 100644 index 0000000000000000000000000000000000000000..202122f685402e41bbfb270b445a7b1c04ccf1a8 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/label_studio.md @@ -0,0 +1,255 @@ +# 使用 MMDetection 和 Label-Studio 进行半自动化目标检测标注 + +标注数据是一个费时费力的任务,本文介绍了如何使用 MMDetection 中的 RTMDet 算法联合 Label-Studio 软件进行半自动化标注。具体来说,使用 RTMDet 预测图片生成标注,然后使用 Label-Studio 进行微调标注,社区用户可以参考此流程和方法,将其应用到其他领域。 + +- RTMDet:RTMDet 是 OpenMMLab 自研的高精度单阶段的目标检测算法,开源于 MMDetection 目标检测工具箱中,其开源协议为 Apache 2.0,工业界的用户可以不受限的免费使用。 +- [Label Studio](https://github.com/heartexlabs/label-studio) 是一款优秀的标注软件,覆盖图像分类、目标检测、分割等领域数据集标注的功能。 + +本文将使用[喵喵数据集](https://download.openmmlab.com/mmyolo/data/cat_dataset.zip)的图片,进行半自动化标注。 + +## 环境配置 + +首先需要创建一个虚拟环境,然后安装 PyTorch 和 MMCV。在本文中,我们将指定 PyTorch 和 MMCV 的版本。接下来安装 MMDetection、Label-Studio 和 label-studio-ml-backend,具体步骤如下: + +创建虚拟环境: + +```shell +conda create -n rtmdet python=3.9 -y +conda activate rtmdet +``` + +安装 PyTorch + +```shell +# Linux and Windows CPU only +pip install torch==1.10.1+cpu torchvision==0.11.2+cpu torchaudio==0.10.1 -f https://download.pytorch.org/whl/cpu/torch_stable.html +# Linux and Windows CUDA 11.3 +pip install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio==0.10.1 -f https://download.pytorch.org/whl/cu113/torch_stable.html +# OSX +pip install torch==1.10.1 torchvision==0.11.2 torchaudio==0.10.1 +``` + +安装 MMCV + +```shell +pip install -U openmim +mim install "mmcv>=2.0.0" +# 安装 mmcv 的过程中会自动安装 mmengine +``` + +安装 MMDetection + +```shell +git clone https://github.com/open-mmlab/mmdetection +cd mmdetection +pip install -v -e . +``` + +安装 Label-Studio 和 label-studio-ml-backend + +```shell +# 安装 label-studio 需要一段时间,如果找不到版本请使用官方源 +pip install label-studio==1.7.2 +pip install label-studio-ml==1.0.9 +``` + +下载rtmdet权重 + +```shell +cd path/to/mmetection +mkdir work_dirs +cd work_dirs +wget https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_m_8xb32-300e_coco/rtmdet_m_8xb32-300e_coco_20220719_112220-229f527c.pth +``` + +## 启动服务 + +启动 RTMDet 后端推理服务: + +```shell +cd path/to/mmetection + +label-studio-ml start projects/LabelStudio/backend_template --with \ +config_file=configs/rtmdet/rtmdet_m_8xb32-300e_coco.py \ +checkpoint_file=./work_dirs/rtmdet_m_8xb32-300e_coco_20220719_112220-229f527c.pth \ +device=cpu \ +--port 8003 +# device=cpu 为使用 CPU 推理,如果使用 GPU 推理,将 cpu 替换为 cuda:0 +``` + +![](https://cdn.vansin.top/picgo20230330131601.png) + +此时,RTMDet 后端推理服务已经启动,后续在 Label-Studio Web 系统中配置 http://localhost:8003 后端推理服务即可。 + +现在启动 Label-Studio 网页服务: + +```shell +label-studio start +``` + +![](https://cdn.vansin.top/picgo20230330132913.png) + +打开浏览器访问 [http://localhost:8080/](http://localhost:8080/) 即可看到 Label-Studio 的界面。 + +![](https://cdn.vansin.top/picgo20230330133118.png) + +我们注册一个用户,然后创建一个 RTMDet-Semiautomatic-Label 项目。 + +![](https://cdn.vansin.top/picgo20230330133333.png) + +我们通过下面的方式下载好示例的喵喵图片,点击 Data Import 导入需要标注的猫图片。 + +```shell +cd path/to/mmetection +mkdir data && cd data + +wget https://download.openmmlab.com/mmyolo/data/cat_dataset.zip && unzip cat_dataset.zip +``` + +![](https://cdn.vansin.top/picgo20230330133628.png) + +![](https://cdn.vansin.top/picgo20230330133715.png) + +然后选择 Object Detection With Bounding Boxes 模板 + +![](https://cdn.vansin.top/picgo20230330133807.png) + +```shell +airplane +apple +backpack +banana +baseball_bat +baseball_glove +bear +bed +bench +bicycle +bird +boat +book +bottle +bowl +broccoli +bus +cake +car +carrot +cat +cell_phone +chair +clock +couch +cow +cup +dining_table +dog +donut +elephant +fire_hydrant +fork +frisbee +giraffe +hair_drier +handbag +horse +hot_dog +keyboard +kite +knife +laptop +microwave +motorcycle +mouse +orange +oven +parking_meter +person +pizza +potted_plant +refrigerator +remote +sandwich +scissors +sheep +sink +skateboard +skis +snowboard +spoon +sports_ball +stop_sign +suitcase +surfboard +teddy_bear +tennis_racket +tie +toaster +toilet +toothbrush +traffic_light +train +truck +tv +umbrella +vase +wine_glass +zebra +``` + +然后将上述类别复制添加到 Label-Studio,然后点击 Save。 + +![](https://cdn.vansin.top/picgo20230330134027.png) + +然后在设置中点击 Add Model 添加 RTMDet 后端推理服务。 + +![](https://cdn.vansin.top/picgo20230330134320.png) + +点击 Validate and Save,然后点击 Start Labeling。 + +![](https://cdn.vansin.top/picgo20230330134424.png) + +看到如下 Connected 就说明后端推理服务添加成功。 + +![](https://cdn.vansin.top/picgo20230330134554.png) + +## 开始半自动化标注 + +点击 Label 开始标注 + +![](https://cdn.vansin.top/picgo20230330134804.png) + +我们可以看到 RTMDet 后端推理服务已经成功返回了预测结果并显示在图片上,我们可以发现这个喵喵预测的框有点大。 + +![](https://cdn.vansin.top/picgo20230403104419.png) + +我们手工拖动框,修正一下框的位置,得到以下修正过后的标注,然后点击 Submit,本张图片就标注完毕了。 + +![](https://cdn.vansin.top/picgo/20230403105923.png) + +我们 submit 完毕所有图片后,点击 exprot 导出 COCO 格式的数据集,就能把标注好的数据集的压缩包导出来了。 + +![](https://cdn.vansin.top/picgo20230330135921.png) + +用 vscode 打开解压后的文件夹,可以看到标注好的数据集,包含了图片和 json 格式的标注文件。 + +![](https://cdn.vansin.top/picgo20230330140321.png) + +到此半自动化标注就完成了,我们可以用这个数据集在 MMDetection 训练精度更高的模型了,训练出更好的模型,然后再用这个模型继续半自动化标注新采集的图片,这样就可以不断迭代,扩充高质量数据集,提高模型的精度。 + +## 使用 MMYOLO 作为后端推理服务 + +如果想在 MMYOLO 中使用 Label-Studio,可以参考在启动后端推理服务时,将 config_file 和 checkpoint_file 替换为 MMYOLO 的配置文件和权重文件即可。 + +```shell +cd path/to/mmetection + +label-studio-ml start projects/LabelStudio/backend_template --with \ +config_file= path/to/mmyolo_config.py \ +checkpoint_file= path/to/mmyolo_weights.pth \ +device=cpu \ +--port 8003 +# device=cpu 为使用 CPU 推理,如果使用 GPU 推理,将 cpu 替换为 cuda:0 +``` + +旋转目标检测和实例分割还在支持中,敬请期待。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/new_model.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/new_model.md new file mode 100644 index 0000000000000000000000000000000000000000..424c4f90f348b6d635644180954f58f5bac85da0 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/new_model.md @@ -0,0 +1,289 @@ +# 在标准数据集上训练自定义模型(待更新) + +在本文中,你将知道如何在标准数据集上训练、测试和推理自定义模型。我们将在 cityscapes 数据集上以自定义 Cascade Mask R-CNN R50 模型为例演示整个过程,为了方便说明,我们将 neck 模块中的 `FPN` 替换为 `AugFPN`,并且在训练中的自动增强类中增加 `Rotate` 或 `TranslateX`。 + +基本步骤如下所示: + +1. 准备标准数据集 +2. 准备你的自定义模型 +3. 准备配置文件 +4. 在标准数据集上对模型进行训练、测试和推理 + +## 准备标准数据集 + +在本文中,我们使用 cityscapes 标准数据集为例进行说明。 + +推荐将数据集根路径采用符号链接方式链接到 `$MMDETECTION/data`。 + +如果你的文件结构不同,你可能需要在配置文件中进行相应的路径更改。标准的文件组织格式如下所示: + +```none +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ ├── cityscapes +│ │ ├── annotations +│ │ ├── leftImg8bit +│ │ │ ├── train +│ │ │ ├── val +│ │ ├── gtFine +│ │ │ ├── train +│ │ │ ├── val +│ ├── VOCdevkit +│ │ ├── VOC2007 +│ │ ├── VOC2012 +``` + +你也可以通过如下方式设定数据集根路径 + +```bash +export MMDET_DATASETS=$data_root +``` + +我们将会使用环境便变量 `$MMDET_DATASETS` 作为数据集的根目录,因此你无需再修改相应配置文件的路径信息。 + +你需要使用脚本 `tools/dataset_converters/cityscapes.py` 将 cityscapes 标注转化为 coco 标注格式。 + +```shell +pip install cityscapesscripts +python tools/dataset_converters/cityscapes.py ./data/cityscapes --nproc 8 --out-dir ./data/cityscapes/annotations +``` + +目前在 `cityscapes `文件夹中的配置文件所对应模型是采用 COCO 预训练权重进行初始化的。 + +如果你的网络不可用或者比较慢,建议你先手动下载对应的预训练权重,否则可能在训练开始时候出现错误。 + +## 准备你的自定义模型 + +第二步是准备你的自定义模型或者训练相关配置。假设你想在已有的 Cascade Mask R-CNN R50 检测模型基础上,新增一个新的 neck 模块 `AugFPN` 去代替默认的 `FPN`,以下是具体实现: + +### 1 定义新的 neck (例如 AugFPN) + +首先创建新文件 `mmdet/models/necks/augfpn.py`. + +```python +import torch.nn as nn +from mmdet.registry import MODELS + +@MODELS.register_module() +class AugFPN(nn.Module): + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False): + pass + + def forward(self, inputs): + # implementation is ignored + pass +``` + +### 2 导入模块 + +你可以采用两种方式导入模块,第一种是在 `mmdet/models/necks/__init__.py` 中添加如下内容 + +```python +from .augfpn import AugFPN +``` + +第二种是增加如下代码到对应配置中,这种方式的好处是不需要改动代码 + +```python +custom_imports = dict( + imports=['mmdet.models.necks.augfpn'], + allow_failed_imports=False) +``` + +### 3 修改配置 + +```python +neck=dict( + type='AugFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5) +``` + +关于自定义模型其余相关细节例如实现新的骨架网络,头部网络、损失函数,以及运行时训练配置例如定义新的优化器、使用梯度裁剪、定制训练调度策略和钩子等,请参考文档 [自定义模型](tutorials/customize_models.md) 和 [自定义运行时训练配置](tutorials/customize_runtime.md)。 + +## 准备配置文件 + +第三步是准备训练配置所需要的配置文件。假设你打算基于 cityscapes 数据集,在 Cascade Mask R-CNN R50 中新增 `AugFPN` 模块,同时增加 `Rotate` 或者 `Translate` 数据增强策略,假设你的配置文件位于 `configs/cityscapes/` 目录下,并且取名为 `cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py`,则配置信息如下: + +```python +# 继承 base 配置,然后进行针对性修改 +_base_ = [ + '../_base_/models/cascade-mask-rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py' +] + +model = dict( + # 设置 `init_cfg` 为 None,表示不加载 ImageNet 预训练权重, + # 后续可以设置 `load_from` 参数用来加载 COCO 预训练权重 + backbone=dict(init_cfg=None), + # 使用新增的 `AugFPN` 模块代替默认的 `FPN` + neck=dict( + type='AugFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5), + # 我们也需要将 num_classes 从 80 修改为 8 来匹配 cityscapes 数据集标注 + # 这个修改包括 `bbox_head` 和 `mask_head`. + roi_head=dict( + bbox_head=[ + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # 将 COCO 类别修改为 cityscapes 类别 + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.1, 0.1, 0.2, 0.2]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, + loss_weight=1.0)), + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # 将 COCO 类别修改为 cityscapes 类别 + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.05, 0.05, 0.1, 0.1]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, + loss_weight=1.0)), + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # 将 COCO 类别修改为 cityscapes 类别 + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.033, 0.033, 0.067, 0.067]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) + ], + mask_head=dict( + type='FCNMaskHead', + num_convs=4, + in_channels=256, + conv_out_channels=256, + # 将 COCO 类别修改为 cityscapes 类别 + num_classes=8, + loss_mask=dict( + type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) + +# 覆写 `train_pipeline`,然后新增 `AutoAugment` 训练配置 +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='AutoAugment', + policies=[ + [dict( + type='Rotate', + level=5, + img_border_value=(124, 116, 104), + prob=0.5) + ], + [dict(type='Rotate', level=7, img_border_value=(124, 116, 104)), + dict( + type='TranslateX', + level=5, + prob=0.5, + img_border_value=(124, 116, 104)) + ], + ]), + dict( + type='RandomResize', + scale=[(2048, 800), (2048, 1024)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs'), +] + +# 设置每张显卡的批处理大小,同时设置新的训练 pipeline +data = dict( + samples_per_gpu=1, + workers_per_gpu=3, + train=dict(dataset=dict(pipeline=train_pipeline))) + +# 设置优化器 +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)) + +# 设置定制的学习率策略 +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=10, + by_epoch=True, + milestones=[8], + gamma=0.1) +] + +# 训练,验证,测试配置 +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=10, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# 我们采用 COCO 预训练过的 Cascade Mask R-CNN R50 模型权重作为初始化权重,可以得到更加稳定的性能 +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco/cascade_mask_rcnn_r50_fpn_1x_coco_20200203-9d4dcb24.pth' +``` + +## 训练新模型 + +为了能够使用新增配置来训练模型,你可以运行如下命令: + +```shell +python tools/train.py configs/cityscapes/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py +``` + +如果想了解更多用法,可以参考 [例子1](1_exist_data_model.md)。 + +## 测试和推理 + +为了能够测试训练好的模型,你可以运行如下命令: + +```shell +python tools/test.py configs/cityscapes/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py work_dirs/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes/epoch_10.pth +``` + +如果想了解更多用法,可以参考 [例子1](1_exist_data_model.md)。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/robustness_benchmarking.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/robustness_benchmarking.md new file mode 100644 index 0000000000000000000000000000000000000000..e95c79a91f1a3bb2bbaedf9838b6293ae53f1b15 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/robustness_benchmarking.md @@ -0,0 +1,109 @@ +# 检测器鲁棒性检查 + +## 介绍 + +我们提供了在 [Benchmarking Robustness in Object Detection: Autonomous Driving when Winter is Coming](https://arxiv.org/abs/1907.07484) 中定义的「图像损坏基准测试」上测试目标检测和实例分割模型的工具。 +此页面提供了如何使用该基准测试的基本教程。 + +```latex +@article{michaelis2019winter, + title={Benchmarking Robustness in Object Detection: + Autonomous Driving when Winter is Coming}, + author={Michaelis, Claudio and Mitzkus, Benjamin and + Geirhos, Robert and Rusak, Evgenia and + Bringmann, Oliver and Ecker, Alexander S. and + Bethge, Matthias and Brendel, Wieland}, + journal={arXiv:1907.07484}, + year={2019} +} +``` + +![image corruption example](../../../resources/corruptions_sev_3.png) + +## 关于基准测试 + +要将结果提交到基准测试,请访问[基准测试主页](https://github.com/bethgelab/robust-detection-benchmark) + +基准测试是仿照 [imagenet-c 基准测试](https://github.com/hendrycks/robustness),由 Dan Hendrycks 和 Thomas Dietterich 在[Benchmarking Neural Network Robustness to Common Corruptions and Perturbations](https://arxiv.org/abs/1903.12261)(ICLR 2019)中发表。 + +图像损坏变换功能包含在此库中,但可以使用以下方法单独安装: + +```shell +pip install imagecorruptions +``` + +与 imagenet-c 相比,我们必须进行一些更改以处理任意大小的图像和灰度图像。 +我们还修改了“运动模糊”和“雪”损坏,以解除对于 linux 特定库的依赖, +否则必须单独安装这些库。有关详细信息,请参阅 [imagecorruptions](https://github.com/bethgelab/imagecorruptions)。 + +## 使用预训练模型进行推理 + +我们提供了一个测试脚本来评估模型在基准测试中提供的各种损坏变换组合下的性能。 + +### 在数据集上测试 + +- [x] 单张 GPU 测试 +- [ ] 多张 GPU 测试 +- [ ] 可视化检测结果 + +您可以使用以下命令在基准测试中使用 15 种损坏变换来测试模型性能。 + +```shell +# single-gpu testing +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] +``` + +也可以选择其它不同类型的损坏变换。 + +```shell +# noise +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions noise + +# blur +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions blur + +# wetaher +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions weather + +# digital +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions digital +``` + +或者使用一组自定义的损坏变换,例如: + +```shell +# gaussian noise, zoom blur and snow +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions gaussian_noise zoom_blur snow +``` + +最后,我们也可以选择施加在图像上的损坏变换的严重程度。 +严重程度从 1 到 5 逐级增强,0 表示不对图像施加损坏变换,即原始图像数据。 + +```shell +# severity 1 +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --severities 1 + +# severities 0,2,4 +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --severities 0 2 4 +``` + +## 模型测试结果 + +下表是各模型在 COCO 2017val 上的测试结果。 + +| Model | Backbone | Style | Lr schd | box AP clean | box AP corr. | box % | mask AP clean | mask AP corr. | mask % | +| :-----------------: | :-----------------: | :-----: | :-----: | :----------: | :----------: | :---: | :-----------: | :-----------: | :----: | +| Faster R-CNN | R-50-FPN | pytorch | 1x | 36.3 | 18.2 | 50.2 | - | - | - | +| Faster R-CNN | R-101-FPN | pytorch | 1x | 38.5 | 20.9 | 54.2 | - | - | - | +| Faster R-CNN | X-101-32x4d-FPN | pytorch | 1x | 40.1 | 22.3 | 55.5 | - | - | - | +| Faster R-CNN | X-101-64x4d-FPN | pytorch | 1x | 41.3 | 23.4 | 56.6 | - | - | - | +| Faster R-CNN | R-50-FPN-DCN | pytorch | 1x | 40.0 | 22.4 | 56.1 | - | - | - | +| Faster R-CNN | X-101-32x4d-FPN-DCN | pytorch | 1x | 43.4 | 26.7 | 61.6 | - | - | - | +| Mask R-CNN | R-50-FPN | pytorch | 1x | 37.3 | 18.7 | 50.1 | 34.2 | 16.8 | 49.1 | +| Mask R-CNN | R-50-FPN-DCN | pytorch | 1x | 41.1 | 23.3 | 56.7 | 37.2 | 20.7 | 55.7 | +| Cascade R-CNN | R-50-FPN | pytorch | 1x | 40.4 | 20.1 | 49.7 | - | - | - | +| Cascade Mask R-CNN | R-50-FPN | pytorch | 1x | 41.2 | 20.7 | 50.2 | 35.7 | 17.6 | 49.3 | +| RetinaNet | R-50-FPN | pytorch | 1x | 35.6 | 17.8 | 50.1 | - | - | - | +| Hybrid Task Cascade | X-101-64x4d-FPN-DCN | pytorch | 1x | 50.6 | 32.7 | 64.7 | 43.8 | 28.1 | 64.0 | + +由于对图像的损坏变换存在随机性,测试结果可能略有不同。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/semi_det.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/semi_det.md new file mode 100644 index 0000000000000000000000000000000000000000..a223523705cd25941aecf5f7ef4bc8119a926d70 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/semi_det.md @@ -0,0 +1,320 @@ +# 半监督目标检测 + +半监督目标检测同时利用标签数据和无标签数据进行训练,一方面可以减少模型对检测框数量的依赖,另一方面也可以利用大量的未标记数据进一步提高模型。 + +按照以下流程进行半监督目标检测: + +- [半监督目标检测](#半监督目标检测) + - [准备和拆分数据集](#准备和拆分数据集) + - [配置多分支数据流程](#配置多分支数据流程) + - [配置半监督数据加载](#配置半监督数据加载) + - [配置半监督模型](#配置半监督模型) + - [配置MeanTeacherHook](#配置meanteacherhook) + - [配置TeacherStudentValLoop](#配置teacherstudentvalloop) + +## 准备和拆分数据集 + +我们提供了数据集下载脚本,默认下载 coco2017 数据集,并且自动解压。 + +```shell +python tools/misc/download_dataset.py +``` + +解压后的数据集目录如下: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +半监督目标检测在 coco 数据集上有两种比较通用的实验设置: + +(1)将 `train2017` 按照固定百分比(1%,2%,5% 和 10%)划分出一部分数据作为标签数据集,剩余的训练集数据作为无标签数据集,同时考虑划分不同的训练集数据作为标签数据集对半监督训练的结果影响较大,所以采用五折交叉验证来评估算法性能。我们提供了数据集划分脚本: + +```shell +python tools/misc/split_coco.py +``` + +该脚本默认会按照 1%,2%,5% 和 10% 的标签数据占比划分 `train2017`,每一种划分会随机重复 5 次,用于交叉验证。生成的半监督标注文件名称格式如下: + +- 标签数据集标注名称格式:`instances_train2017.{fold}@{percent}.json` + +- 无标签数据集名称标注:`instances_train2017.{fold}@{percent}-unlabeled.json` + +其中,`fold` 用于交叉验证,`percent` 表示标签数据的占比。 划分后的数据集目录结构如下: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── semi_anns +│ │ │ ├── instances_train2017.1@1.json +│ │ │ ├── instances_train2017.1@1-unlabeled.json +│ │ │ ├── instances_train2017.1@2.json +│ │ │ ├── instances_train2017.1@2-unlabeled.json +│ │ │ ├── instances_train2017.1@5.json +│ │ │ ├── instances_train2017.1@5-unlabeled.json +│ │ │ ├── instances_train2017.1@10.json +│ │ │ ├── instances_train2017.1@10-unlabeled.json +│ │ │ ├── instances_train2017.2@1.json +│ │ │ ├── instances_train2017.2@1-unlabeled.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +(2)将 `train2017` 作为标签数据集,`unlabeled2017` 作为无标签数据集。由于 `image_info_unlabeled2017.json` 没有 `categories` 信息,无法初始化 `CocoDataset` ,所以需要将 `instances_train2017.json` 的 `categories` 写入 `image_info_unlabeled2017.json` ,另存为 `instances_unlabeled2017.json`,相关脚本如下: + +```python +from mmengine.fileio import load, dump + +anns_train = load('instances_train2017.json') +anns_unlabeled = load('image_info_unlabeled2017.json') +anns_unlabeled['categories'] = anns_train['categories'] +dump(anns_unlabeled, 'instances_unlabeled2017.json') +``` + +处理后的数据集目录如下: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_unlabeled2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +## 配置多分支数据流程 + +半监督学习有两个主要的方法,分别是 +[一致性正则化](https://research.nvidia.com/sites/default/files/publications/laine2017iclr_paper.pdf) +和[伪标签](https://www.researchgate.net/profile/Dong-Hyun-Lee/publication/280581078_Pseudo-Label_The_Simple_and_Efficient_Semi-Supervised_Learning_Method_for_Deep_Neural_Networks/links/55bc4ada08ae092e9660b776/Pseudo-Label-The-Simple-and-Efficient-Semi-Supervised-Learning-Method-for-Deep-Neural-Networks.pdf) 。 +一致性正则化往往需要一些精心的设计,而伪标签的形式比较简单,更容易拓展到下游任务。我们主要采用了基于伪标签的教师学生联合训练的半监督目标检测框架,对于标签数据和无标签数据需要配置不同的数据流程: +(1)标签数据的数据流程: + +```python +# pipeline used to augment labeled data, +# which will be sent to student model for supervised training. +sup_pipeline = [ + dict(type='LoadImageFromFile',backend_args = backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict(type='MultiBranch', sup=dict(type='PackDetInputs')) +] +``` + +(2)无标签的数据流程: + +```python +# pipeline used to augment unlabeled data weakly, +# which will be sent to teacher model for predicting pseudo instances. +weak_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data strongly, +# which will be sent to student model for unsupervised training. +strong_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomOrder', + transforms=[ + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='RandAugment', aug_space=geometric, aug_num=1), + ]), + dict(type='RandomErasing', n_patches=(1, 5), ratio=(0, 0.2)), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data into different views +unsup_pipeline = [ + dict(type='LoadImageFromFile', backend_args = backend_args), + dict(type='LoadEmptyAnnotations'), + dict( + type='MultiBranch', + unsup_teacher=weak_pipeline, + unsup_student=strong_pipeline, + ) +] +``` + +## 配置半监督数据加载 + +(1)构建半监督数据集。使用 `ConcatDataset` 拼接标签数据集和无标签数据集。 + +```python +labeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=sup_pipeline) + +unlabeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_unlabeled2017.json', + data_prefix=dict(img='unlabeled2017/'), + filter_cfg=dict(filter_empty_gt=False), + pipeline=unsup_pipeline) + +train_dataloader = dict( + batch_size=batch_size, + num_workers=num_workers, + persistent_workers=True, + sampler=dict( + type='GroupMultiSourceSampler', + batch_size=batch_size, + source_ratio=[1, 4]), + dataset=dict( + type='ConcatDataset', datasets=[labeled_dataset, unlabeled_dataset])) +``` + +(2)使用多源数据集采样器。 使用 `GroupMultiSourceSampler` 从 `labeled_dataset` 和 `labeled_dataset` 采样数据组成 batch , `source_ratio` 控制 batch 中标签数据和无标签数据的占比。`GroupMultiSourceSampler` 还保证了同一个 batch 中的图片具有相近的长宽比例,如果不需要保证batch内图片的长宽比例,可以使用 `MultiSourceSampler`。`GroupMultiSourceSampler` 采样示意图如下: + +
+ +
+ +`sup=1000` 表示标签数据集的规模为 1000 ,`sup_h=200` 表示标签数据集中长宽比大于等于1的图片规模为 200,`sup_w=800` 表示标签数据集中长宽比小于1的图片规模为 800 ,`unsup=9000` 表示无标签数据集的规模为 9000 ,`unsup_h=1800` 表示无标签数据集中长宽比大于等于1的图片规模为 1800,`unsup_w=7200` 表示标签数据集中长宽比小于1的图片规模为 7200 ,`GroupMultiSourceSampler` 每次按照标签数据集和无标签数据集的图片的总体长宽比分布随机选择一组,然后按照 `source_ratio` 从两个数据集中采样组成 batch ,因此标签数据集和无标签数据集重复采样次数不同。 + +## 配置半监督模型 + +我们选择 `Faster R-CNN` 作为 `detector` 进行半监督训练,以半监督目标检测算法 `SoftTeacher` 为例,模型的配置可以继承 `_base_/models/faster-rcnn_r50_fpn.py`,将检测器的骨干网络替换成 `caffe` 风格。 +注意,与监督训练的配置文件不同的是,`Faster R-CNN` 作为 `detector`,是作为 `model`的一个属性,而不是 `model` 。此外,还需要将`data_preprocessor`设置为`MultiBranchDataPreprocessor`,用于处理不同数据流程图片的填充和归一化。 +最后,可以通过 `semi_train_cfg` 和 `semi_test_cfg` 配置半监督训练和测试需要的参数。 + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', '../_base_/default_runtime.py', + '../_base_/datasets/semi_coco_detection.py' +] + +detector = _base_.model +detector.data_preprocessor = dict( + type='DetDataPreprocessor', + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False, + pad_size_divisor=32) +detector.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=False), + norm_eval=True, + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe')) + +model = dict( + _delete_=True, + type='SoftTeacher', + detector=detector, + data_preprocessor=dict( + type='MultiBranchDataPreprocessor', + data_preprocessor=detector.data_preprocessor), + semi_train_cfg=dict( + freeze_teacher=True, + sup_weight=1.0, + unsup_weight=4.0, + pseudo_label_initial_score_thr=0.5, + rpn_pseudo_thr=0.9, + cls_pseudo_thr=0.9, + reg_pseudo_thr=0.02, + jitter_times=10, + jitter_scale=0.06, + min_pseudo_bbox_wh=(1e-2, 1e-2)), + semi_test_cfg=dict(predict_on='teacher')) +``` + +此外,我们也支持其他检测模型进行半监督训练,比如,`RetinaNet` 和 `Cascade R-CNN`。由于 `SoftTeacher` 仅支持 `Faster R-CNN`,所以需要将其替换为 `SemiBaseDetector`,示例如下: + +```python +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', '../_base_/default_runtime.py', + '../_base_/datasets/semi_coco_detection.py' +] + +detector = _base_.model + +model = dict( + _delete_=True, + type='SemiBaseDetector', + detector=detector, + data_preprocessor=dict( + type='MultiBranchDataPreprocessor', + data_preprocessor=detector.data_preprocessor), + semi_train_cfg=dict( + freeze_teacher=True, + sup_weight=1.0, + unsup_weight=1.0, + cls_pseudo_thr=0.9, + min_pseudo_bbox_wh=(1e-2, 1e-2)), + semi_test_cfg=dict(predict_on='teacher')) +``` + +沿用 `SoftTeacher` 的半监督训练配置,将 `batch_size` 改为 2 ,`source_ratio` 改为 `[1, 1]`,`RetinaNet`,`Faster R-CNN`, `Cascade R-CNN` 以及 `SoftTeacher` 在 10% coco 训练集上的监督训练和半监督训练的实验结果如下: + +| Model | Detector | BackBone | Style | sup-0.1-coco mAP | semi-0.1-coco mAP | +| :--------------: | :-----------: | :------: | :---: | :--------------: | :---------------: | +| SemiBaseDetector | RetinaNet | R-50-FPN | caffe | 23.5 | 27.7 | +| SemiBaseDetector | Faster R-CNN | R-50-FPN | caffe | 26.7 | 28.4 | +| SemiBaseDetector | Cascade R-CNN | R-50-FPN | caffe | 28.0 | 29.7 | +| SoftTeacher | Faster R-CNN | R-50-FPN | caffe | 26.7 | 31.1 | + +## 配置MeanTeacherHook + +通常,教师模型采用对学生模型指数滑动平均(EMA)的方式进行更新,进而教师模型随着学生模型的优化而优化,可以通过配置 `custom_hooks` 实现: + +```python +custom_hooks = [dict(type='MeanTeacherHook')] +``` + +## 配置TeacherStudentValLoop + +由于教师学生联合训练框架存在两个模型,我们可以用 `TeacherStudentValLoop` 替换 `ValLoop`,在训练的过程中同时检验两个模型的精度。 + +```python +val_cfg = dict(type='TeacherStudentValLoop') +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/single_stage_as_rpn.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/single_stage_as_rpn.md new file mode 100644 index 0000000000000000000000000000000000000000..39db35c26830871755ef072d4a3d9ffe6dd628fb --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/single_stage_as_rpn.md @@ -0,0 +1,171 @@ +# 将单阶段检测器作为 RPN + +候选区域网络 (Region Proposal Network, RPN) 作为 [Faster R-CNN](https://arxiv.org/abs/1506.01497) 的一个子模块,将为 Faster R-CNN 的第二阶段产生候选区域。在 MMDetection 里大多数的二阶段检测器使用 [`RPNHead`](../../../mmdet/models/dense_heads/rpn_head.py)作为候选区域网络来产生候选区域。然而,任何的单阶段检测器都可以作为候选区域网络,是因为他们对边界框的预测可以被视为是一种候选区域,并且因此能够在 R-CNN 中得到改进。因此在 MMDetection v3.0 中会支持将单阶段检测器作为 RPN 使用。 + +接下来我们通过一个例子,即如何在 [Faster R-CNN](../../../configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py) 中使用一个无锚框的单阶段的检测器模型 [FCOS](../../../configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py) 作为 RPN ,详细阐述具体的全部流程。 + +主要流程如下: + +1. 在 Faster R-CNN 中使用 `FCOSHead` 作为 `RPNHead` +2. 评估候选区域 +3. 用预先训练的 FCOS 训练定制的 Faster R-CNN + +## 在 Faster R-CNN 中使用 `FCOSHead` 作为` RPNHead` + +为了在 Faster R-CNN 中使用 `FCOSHead` 作为 `RPNHead` ,我们应该创建一个名为 `configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py` 的配置文件,并且在 `configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py` 中将 `rpn_head` 的设置替换为 `bbox_head` 的设置,此外我们仍然使用 FCOS 的瓶颈设置,步幅为`[8,16,32,64,128]`,并且更新 `bbox_roi_extractor` 的 `featmap_stride` 为 ` [8,16,32,64,128]`。为了避免损失变慢,我们在前1000次迭代而不是前500次迭代中应用预热,这意味着 lr 增长得更慢。相关配置如下: + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +model = dict( + # 从 configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py 复制 + neck=dict( + start_level=1, + add_extra_convs='on_output', # 使用 P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # 忽略未使用的旧设置 + type='FCOSHead', + num_classes=1, # 对于 rpn, num_classes = 1,如果 num_classes > 1,它将在 TwoStageDetector 中自动设置为1 + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + roi_head=dict( # featmap_strides 的更新取决于于颈部的步伐 + bbox_roi_extractor=dict(featmap_strides=[8, 16, 32, 64, 128]))) +# 学习率 +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), # 慢慢增加 lr,否则损失变成 NAN + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[8, 11], + gamma=0.1) +] +``` + +然后,我们可以使用下面的命令来训练我们的定制模型。更多训练命令,请参考[这里](train.md)。 + +```python +# 使用8个 GPU 进行训练 +bash +tools/dist_train.sh +configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py +--work-dir /work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco +``` + +## 评估候选区域 + +候选区域的质量对检测器的性能有重要影响,因此,我们也提供了一种评估候选区域的方法。和上面一样创建一个新的名为 `configs/rpn/fcos-rpn_r50_fpn_1x_coco.py` 的配置文件,并且在 `configs/rpn/fcos-rpn_r50_fpn_1x_coco.py` 中将 `rpn_head` 的设置替换为 `bbox_head` 的设置。 + +```python +_base_ = [ + '../_base_/models/rpn_r50_fpn.py', '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +val_evaluator = dict(metric='proposal_fast') +test_evaluator = val_evaluator +model = dict( + # 从 configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py 复制 + neck=dict( + start_level=1, + add_extra_convs='on_output', # 使用 P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # 忽略未使用的旧设置 + type='FCOSHead', + num_classes=1, # 对于 rpn, num_classes = 1,如果 num_classes >为1,它将在 rpn 中自动设置为1 + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) +``` + +假设我们在训练之后有检查点 `./work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco/epoch_12.pth` ,然后,我们可以使用下面的命令来评估建议的质量。 + +```python +# 使用8个 GPU 进行测试 +bash +tools/dist_test.sh +configs/rpn/fcos-rpn_r50_fpn_1x_coco.py +--work_dirs /faster-rcnn_r50_fpn_fcos-rpn_1x_coco/epoch_12.pth +``` + +## 用预先训练的 FCOS 训练定制的 Faster R-CNN + +预训练不仅加快了训练的收敛速度,而且提高了检测器的性能。因此,我们在这里给出一个例子来说明如何使用预先训练的 FCOS 作为 RPN 来加速训练和提高精度。假设我们想在 Faster R-CNN 中使用 `FCOSHead` 作为 `rpn_head`,并加载预先训练权重来进行训练 [`fcos_r50-caffe_fpn_gn-head_1x_coco`](https://download.openmmlab.com/mmdetection/v2.0/fcos/fcos_r50_caffe_fpn_gn-head_1x_coco/fcos_r50_caffe_fpn_gn-head_1x_coco-821213aa.pth)。 配置文件 `configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_fcos- rpn_1x_copy .py` 的内容如下所示。注意,`fcos_r50-caffe_fpn_gn-head_1x_coco` 使用 ResNet50 的 caffe 版本,因此需要更新 `data_preprocessor` 中的像素平均值和 std。 + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +model = dict( + data_preprocessor=dict( + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False), + backbone=dict( + norm_cfg=dict(type='BN', requires_grad=False), + style='caffe', + init_cfg=None), # the checkpoint in ``load_from`` contains the weights of backbone + neck=dict( + start_level=1, + add_extra_convs='on_output', # 使用 P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # 忽略未使用的旧设置 + type='FCOSHead', + num_classes=1, # 对于 rpn, num_classes = 1,如果 num_classes > 1,它将在 TwoStageDetector 中自动设置为1 + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + roi_head=dict( # update featmap_strides due to the strides in neck + bbox_roi_extractor=dict(featmap_strides=[8, 16, 32, 64, 128]))) +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/fcos/fcos_r50_caffe_fpn_gn-head_1x_coco/fcos_r50_caffe_fpn_gn-head_1x_coco-821213aa.pth' +``` + +训练命令如下。 + +```python +bash +tools/dist_train.sh +configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco.py \ +--work-dir /work_dirs/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/test.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/test.md new file mode 100644 index 0000000000000000000000000000000000000000..1b165b049d9c10eefcaf30af0030e1ae220f2c8b --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/test.md @@ -0,0 +1,285 @@ +# 测试现有模型 + +我们提供了测试脚本,能够测试一个现有模型在所有数据集(COCO,Pascal VOC,Cityscapes 等)上的性能。我们支持在如下环境下测试: + +- 单 GPU 测试 +- CPU 测试 +- 单节点多 GPU 测试 +- 多节点测试 + +根据以上测试环境,选择合适的脚本来执行测试过程。 + +```shell +# 单 GPU 测试 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# CPU 测试:禁用 GPU 并运行单 GPU 测试脚本 +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# 单节点多 GPU 测试 +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--out ${RESULT_FILE}] +``` + +`tools/dist_test.sh` 也支持多节点测试,不过需要依赖 PyTorch 的 [启动工具](https://pytorch.org/docs/stable/distributed.html#launch-utility) 。 + +可选参数: + +- `RESULT_FILE`: 结果文件名称,需以 .pkl 形式存储。如果没有声明,则不将结果存储到文件。 +- `--show`: 如果开启,检测结果将被绘制在图像上,以一个新窗口的形式展示。它只适用于单 GPU 的测试,是用于调试和可视化的。请确保使用此功能时,你的 GUI 可以在环境中打开。否则,你可能会遇到这么一个错误 `cannot connect to X server`。 +- `--show-dir`: 如果指明,检测结果将会被绘制在图像上并保存到指定目录。它只适用于单 GPU 的测试,是用于调试和可视化的。即使你的环境中没有 GUI,这个选项也可使用。 +- `--cfg-options`: 如果指明,这里的键值对将会被合并到配置文件中。 + +### 样例 + +假设你已经下载了 checkpoint 文件到 `checkpoints/` 文件下了。 + +1. 测试 RTMDet 并可视化其结果。按任意键继续下张图片的测试。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet) 。 + + ```shell + python tools/test.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --show + ``` + +2. 测试 RTMDet,并为了之后的可视化保存绘制的图像。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet) 。 + + ```shell + python tools/test.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --show-dir rtmdet_l_8xb32-300e_coco_results + ``` + +3. 在 Pascal VOC 数据集上测试 Faster R-CNN,不保存测试结果,测试 `mAP`。配置文件和 checkpoint 文件 [在此](../../../configs/pascal_voc) 。 + + ```shell + python tools/test.py \ + configs/pascal_voc/faster-rcnn_r50_fpn_1x_voc0712.py \ + checkpoints/faster_rcnn_r50_fpn_1x_voc0712_20200624-c9895d40.pth + ``` + +4. 使用 8 块 GPU 测试 Mask R-CNN,测试 `bbox` 和 `mAP` 。配置文件和 checkpoint 文件 [在此](../../../configs/mask_rcnn) 。 + + ```shell + ./tools/dist_test.sh \ + configs/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 \ + --out results.pkl + ``` + +5. 使用 8 块 GPU 测试 Mask R-CNN,测试**每类**的 `bbox` 和 `mAP`。配置文件和 checkpoint 文件 [在此](../../../configs/mask_rcnn) 。 + + ```shell + ./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 + ``` + + 该命令生成两个JSON文件 `./work_dirs/coco_instance/test.bbox.json` 和 `./work_dirs/coco_instance/test.segm.json`。 + +6. 在 COCO test-dev 数据集上,使用 8 块 GPU 测试 Mask R-CNN,并生成 JSON 文件提交到官方评测服务器,配置文件和 checkpoint 文件 [在此](../../../configs/mask_rcnnn) 。你可以在 [config](./././configs/_base_/datasets/coco_instance.py) 的注释中用 test_evaluator 和 test_dataloader 替换原来的 test_evaluator 和 test_dataloader,然后运行: + + ```shell + ./tools/dist_test.sh \ + configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py \ + checkpoints/mask_rcnn_r50_fpn_1x_cityscapes_20200227-afe51d5a.pth \ + 8 + ``` + + 这行命令生成两个 JSON 文件 `mask_rcnn_test-dev_results.bbox.json` 和 `mask_rcnn_test-dev_results.segm.json`。 + +7. 在 Cityscapes 数据集上,使用 8 块 GPU 测试 Mask R-CNN,生成 txt 和 png 文件,并上传到官方评测服务器。配置文件和 checkpoint 文件 [在此](../../../configs/cityscapes) 。 你可以在 [config](./././configs/_base_/datasets/cityscapes_instance.py) 的注释中用 test_evaluator 和 test_dataloader 替换原来的 test_evaluator 和 test_dataloader,然后运行: + + ```shell + ./tools/dist_test.sh \ + configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py \ + checkpoints/mask_rcnn_r50_fpn_1x_cityscapes_20200227-afe51d5a.pth \ + 8 + ``` + + 生成的 png 和 txt 文件在 `./work_dirs/cityscapes_metric` 文件夹下。 + +### 不使用 Ground Truth 标注进行测试 + +MMDetection 支持在不使用 ground-truth 标注的情况下对模型进行测试,这需要用到 `CocoDataset`。如果你的数据集格式不是 COCO 格式的,请将其转化成 COCO 格式。如果你的数据集格式是 VOC 或者 Cityscapes,你可以使用 [tools/dataset_converters](https://github.com/open-mmlab/mmdetection/tree/main/tools/dataset_converters) 内的脚本直接将其转化成 COCO 格式。如果是其他格式,可以使用 [images2coco 脚本](https://github.com/open-mmlab/mmdetection/tree/master/tools/dataset_converters/images2coco.py) 进行转换。 + +```shell +python tools/dataset_converters/images2coco.py \ + ${IMG_PATH} \ + ${CLASSES} \ + ${OUT} \ + [--exclude-extensions] +``` + +参数: + +- `IMG_PATH`: 图片根路径。 +- `CLASSES`: 类列表文本文件名。文本中每一行存储一个类别。 +- `OUT`: 输出 json 文件名。 默认保存目录和 `IMG_PATH` 在同一级。 +- `exclude-extensions`: 待排除的文件后缀名。 + +在转换完成后,使用如下命令进行测试 + +```shell +# 单 GPU 测试 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--show] + +# CPU 测试:禁用 GPU 并运行单 GPU 测试脚本 +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# 单节点多 GPU 测试 +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--show] +``` + +假设 [model zoo](https://mmdetection.readthedocs.io/en/latest/modelzoo_statistics.html) 中的 checkpoint 文件被下载到了 `checkpoints/` 文件夹下, +我们可以使用以下命令,用 8 块 GPU 在 COCO test-dev 数据集上测试 Mask R-CNN,并且生成 JSON 文件。 + +```sh +./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 +``` + +这行命令生成两个 JSON 文件 `./work_dirs/coco_instance/test.bbox.jso` 和 `./work_dirs/coco_instance/test.segm.jsonn`。 + +### 批量推理 + +MMDetection 在测试模式下,既支持单张图片的推理,也支持对图像进行批量推理。默认情况下,我们使用单张图片的测试,你可以通过修改测试数据配置文件中的 `samples_per_gpu` 来开启批量测试。 +开启批量推理的配置文件修改方法为: + +```shell +data = dict(train_dataloader=dict(...), val_dataloader=dict(...), test_dataloader=dict(batch_size=2, ...)) +``` + +或者你可以通过将 `--cfg-options` 设置为 `--cfg-options test_dataloader.batch_size=` 来开启它。 + +## 测试时增强 (TTA) + +测试时增强 (TTA) 是一种在测试阶段使用的数据增强策略。它对同一张图片应用不同的增强,例如翻转和缩放,用于模型推理,然后将每个增强后的图像的预测结果合并,以获得更准确的预测结果。为了让用户更容易使用 TTA,MMEngine 提供了 [BaseTTAModel](https://mmengine.readthedocs.io/en/latest/api/generated/mmengine.model.BaseTTAModel.html#mmengine.model.BaseTTAModel) 类,允许用户根据自己的需求通过简单地扩展 BaseTTAModel 类来实现不同的 TTA 策略。 + +在 MMDetection 中,我们提供了 [DetTTAModel](../../../mmdet/models/test_time_augs/det_tta.py) 类,它继承自 BaseTTAModel。 + +### 使用案例 + +使用 TTA 需要两个步骤。首先,你需要在配置文件中添加 `tta_model` 和 `tta_pipeline`: + +```shell +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict( + type='nms', + iou_threshold=0.5), + max_per_img=100)) + +tta_pipeline = [ + dict(type='LoadImageFromFile', + backend_args=None), + dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=(1333, 800), keep_ratio=True) + ], [ # It uses 2 flipping transformations (flipping and not flipping). + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ]])] +``` + +第二步,运行测试脚本时,设置 `--tta` 参数,如下所示: + +```shell +# 单 GPU 测试 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--tta] + +# CPU 测试:禁用 GPU 并运行单 GPU 测试脚本 +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--tta] + +# 多 GPU 测试 +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--tta] +``` + +你也可以自己修改 TTA 配置,例如添加缩放增强: + +```shell +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict( + type='nms', + iou_threshold=0.5), + max_per_img=100)) + +img_scales = [(1333, 800), (666, 400), (2000, 1200)] +tta_pipeline = [ + dict(type='LoadImageFromFile', + backend_args=None), + dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=s, keep_ratio=True) for s in img_scales + ], [ + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ]])] +``` + +以上数据增强管道将首先对图像执行 3 个多尺度转换,然后执行 2 个翻转转换(翻转和不翻转),最后使用 PackDetInputs 将图像打包到最终结果中。 +这里有更多的 TTA 使用案例供您参考: + +- [RetinaNet](../../../configs/retinanet/retinanet_tta.py) +- [CenterNet](../../../configs/centernet/centernet_tta.py) +- [YOLOX](../../../configs/rtmdet/rtmdet_tta.py) +- [RTMDet](../../../configs/yolox/yolox_tta.py) + +更多高级用法和 TTA 的数据流,请参考 [MMEngine](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/test_time_augmentation.html#data-flow)。我们将在后续支持实例分割 TTA。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/test_results_submission.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/test_results_submission.md new file mode 100644 index 0000000000000000000000000000000000000000..7a07658517011b30f68da722159223995245a316 --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/test_results_submission.md @@ -0,0 +1,174 @@ +# 提交测试结果 + +## 全景分割测试结果提交 + +下面几节介绍如何在 COCO 测试开发集上生成泛视分割模型的预测结果,并将预测提交到 [COCO评估服务器](https://competitions.codalab.org/competitions/19507) + +### 前提条件 + +- 下载 [COCO测试数据集图像](http://images.cocodataset.org/zips/test2017.zip),[测试图像信息](http://images.cocodataset.org/annotations/image_info_test2017.zip),和[全景训练/相关注释](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip),然后解压缩它们,把 `test2017` 放到 `data/coco/`,把 json 文件和注释文件放到 `data/coco/annotations/` 。 + +```shell +# 假设 data/coco/ 不存在 +mkdir -pv data/coco/ +# 下载 test2017 +wget -P data/coco/ http://images.cocodataset.org/zips/test2017.zip +wget -P data/coco/ http://images.cocodataset.org/annotations/image_info_test2017.zip +wget -P data/coco/ http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip +# 解压缩它们 +unzip data/coco/test2017.zip -d data/coco/ +unzip data/coco/image_info_test2017.zip -d data/coco/ +unzip data/coco/panoptic_annotations_trainval2017.zip -d data/coco/ +# 删除 zip 文件(可选) +rm -rf data/coco/test2017.zip data/coco/image_info_test2017.zip data/coco/panoptic_annotations_trainval2017.zip +``` + +- 运行以下代码更新测试图像信息中的类别信息。由于 `image_info_test-dev2017.json` 的类别信息中缺少属性 `isthing` ,我们需要用 `panoptic_val2017.json` 中的类别信息更新它。 + +```shell +python tools/misc/gen_coco_panoptic_test_info.py data/coco/annotations +``` + +在完成上述准备之后,你的 `data` 目录结构应该是这样: + +```text +data +`-- coco + |-- annotations + | |-- image_info_test-dev2017.json + | |-- image_info_test2017.json + | |-- panoptic_image_info_test-dev2017.json + | |-- panoptic_train2017.json + | |-- panoptic_train2017.zip + | |-- panoptic_val2017.json + | `-- panoptic_val2017.zip + `-- test2017 +``` + +### coco 测试开发的推理 + +要在 coco test-dev 上进行推断,我们应该首先更新 `test_dataloder` 和 `test_evaluator` 的设置。有两种方法可以做到这一点:1. 在配置文件中更新它们;2. 在命令行中更新它们。 + +#### 在配置文件中更新它们 + +相关的设置在 `configs/_base_/datasets/ coco_panoptical .py` 的末尾,如下所示。 + +```python +test_dataloader = dict( + batch_size=1, + num_workers=1, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/panoptic_image_info_test-dev2017.json', + data_prefix=dict(img='test2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_evaluator = dict( + type='CocoPanopticMetric', + format_only=True, + ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', + outfile_prefix='./work_dirs/coco_panoptic/test') +``` + +以下任何一种方法都可以用于更新 coco test-dev 集上的推理设置 + +情况1:直接取消注释 `configs/_base_/datasets/ coco_panoptical .py` 中的设置。 + +情况2:将以下设置复制到您现在使用的配置文件中。 + +```python +test_dataloader = dict( + dataset=dict( + ann_file='annotations/panoptic_image_info_test-dev2017.json', + data_prefix=dict(img='test2017/', _delete_=True))) +test_evaluator = dict( + format_only=True, + ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', + outfile_prefix='./work_dirs/coco_panoptic/test') +``` + +然后通过以下命令对 coco test-dev et 进行推断。 + +```shell +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} +``` + +#### 在命令行中更新它们 + +coco test-dev 上更新相关设置和推理的命令如下所示。 + +```shell +# 用一个 gpu 测试 +CUDA_VISIBLE_DEVICES=0 python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results +# 用四个 gpu 测试 +CUDA_VISIBLE_DEVICES=0,1,3,4 bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + 8 \ # eights gpus + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results +# 用 slurm 测试 +GPUS=8 tools/slurm_test.sh \ + ${Partition} \ + ${JOB_NAME} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results +``` + +例子:假设我们使用预先训练的带有 ResNet-50 骨干网的 MaskFormer 对 `test2017` 执行推断。 + +```shell +# 单 gpu 测试 +CUDA_VISIBLE_DEVICES=0 python tools/test.py \ + configs/maskformer/maskformer_r50_mstrain_16x1_75e_coco.py \ + checkpoints/maskformer_r50_mstrain_16x1_75e_coco_20220221_141956-bc2699cb.pth \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=work_dirs/maskformer/results +``` + +### 重命名文件并压缩结果 + +推理之后,全景分割结果(一个 json 文件和一个存储掩码的目录)将在 `WORK_DIR` 中。我们应该按照 [COCO's Website](https://cocodataset.org/#upload)上的命名约定重新命名它们。最后,我们需要将 json 和存储掩码的目录压缩到 zip 文件中,并根据命名约定重命名该 zip 文件。注意, zip 文件应该**直接**包含上述两个文件。 + +重命名文件和压缩结果的命令: + +```shell +# 在 WORK_DIR 中,我们有 panoptic 分割结果: 'panoptic' 和 'results. panoptical .json'。 +cd ${WORK_DIR} +# 将 '[algorithm_name]' 替换为您使用的算法名称 +mv ./panoptic ./panoptic_test-dev2017_[algorithm_name]_results +mv ./results.panoptic.json ./panoptic_test-dev2017_[algorithm_name]_results.json +zip panoptic_test-dev2017_[algorithm_name]_results.zip -ur panoptic_test-dev2017_[algorithm_name]_results panoptic_test-dev2017_[algorithm_name]_results.json +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/train.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/train.md new file mode 100644 index 0000000000000000000000000000000000000000..8feb1aa6912fdff9032a1aba35d2fcaace45dd7f --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/train.md @@ -0,0 +1,451 @@ +# 在标准数据集上训练预定义的模型 + +MMDetection 也为训练检测模型提供了开盖即食的工具。本节将展示在标准数据集(比如 COCO)上如何训练一个预定义的模型。 + +### 数据集 + +训练需要准备好数据集,细节请参考 [数据集准备](#%E6%95%B0%E6%8D%AE%E9%9B%86%E5%87%86%E5%A4%87) 。 + +**注意**: +目前,`configs/cityscapes` 文件夹下的配置文件都是使用 COCO 预训练权值进行初始化的。如果网络连接不可用或者速度很慢,你可以提前下载现存的模型。否则可能在训练的开始会有错误发生。 + +### 学习率自动缩放 + +**注意**:在配置文件中的学习率是在 8 块 GPU,每块 GPU 有 2 张图像(批大小为 8\*2=16)的情况下设置的。其已经设置在 `config/_base_/schedules/schedule_1x.py` 中的 `auto_scale_lr.base_batch_size`。学习率会基于批次大小为 `16`时的值进行自动缩放。同时,为了不影响其他基于 mmdet 的 codebase,启用自动缩放标志 `auto_scale_lr.enable` 默认设置为 `False`。 + +如果要启用此功能,需在命令添加参数 `--auto-scale-lr`。并且在启动命令之前,请检查下即将使用的配置文件的名称,因为配置名称指示默认的批处理大小。 +在默认情况下,批次大小是 `8 x 2 = 16`,例如:`faster_rcnn_r50_caffe_fpn_90k_coco.py` 或者 `pisa_faster_rcnn_x101_32x4d_fpn_1x_coco.py`;若不是默认批次,你可以在配置文件看到像 `_NxM_` 字样的,例如:`cornernet_hourglass104_mstest_32x3_210e_coco.py` 的批次大小是 `32 x 3 = 96`, 或者 `scnet_x101_64x4d_fpn_8x1_20e_coco.py` 的批次大小是 `8 x 1 = 8`。 + +**请记住:如果使用不是默认批次大小为 `16`的配置文件,请检查配置文件中的底部,会有 `auto_scale_lr.base_batch_size`。如果找不到,可以在其继承的 `_base_=[xxx]` 文件中找到。另外,如果想使用自动缩放学习率的功能,请不要修改这些值。** + +学习率自动缩放基本用法如下: + +```shell +python tools/train.py \ + ${CONFIG_FILE} \ + --auto-scale-lr \ + [optional arguments] +``` + +执行命令之后,会根据机器的GPU数量和训练的批次大小对学习率进行自动缩放,缩放方式详见 [线性扩展规则](https://arxiv.org/abs/1706.02677) ,比如:在 4 块 GPU 并且每张 GPU 上有 2 张图片的情况下 `lr=0.01`,那么在 16 块 GPU 并且每张 GPU 上有 4 张图片的情况下, LR 会自动缩放至 `lr=0.08`。 + +如果不启用该功能,则需要根据 [线性扩展规则](https://arxiv.org/abs/1706.02677) 来手动计算并修改配置文件里面 `optimizer.lr` 的值。 + +### 使用单 GPU 训练 + +我们提供了 `tools/train.py` 来开启在单张 GPU 上的训练任务。基本使用如下: + +```shell +python tools/train.py \ + ${CONFIG_FILE} \ + [optional arguments] +``` + +在训练期间,日志文件和 checkpoint 文件将会被保存在工作目录下,它需要通过配置文件中的 `work_dir` 或者 CLI 参数中的 `--work-dir` 来指定。 + +默认情况下,模型将在每轮训练之后在 validation 集上进行测试,测试的频率可以通过设置配置文件来指定: + +```python +# 每 12 轮迭代进行一次测试评估 +train_cfg = dict(val_interval=12) +``` + +这个工具接受以下参数: + +- `--work-dir ${WORK_DIR}`: 覆盖工作目录. +- `--resume`:自动从work_dir中的最新检查点恢复. +- `--resume ${CHECKPOINT_FILE}`: 从某个 checkpoint 文件继续训练. +- `--cfg-options 'Key=value'`: 覆盖使用的配置文件中的其他设置. + +**注意**: +`resume` 和 `load-from` 的区别: + +`resume` 既加载了模型的权重和优化器的状态,也会继承指定 checkpoint 的迭代次数,不会重新开始训练。`load-from` 则是只加载模型的权重,它的训练是从头开始的,经常被用于微调模型。其中load-from需要写入配置文件中,而resume作为命令行参数传入。 + +### 使用 CPU 训练 + +使用 CPU 训练的流程和使用单 GPU 训练的流程一致,我们仅需要在训练流程开始前禁用 GPU。 + +```shell +export CUDA_VISIBLE_DEVICES=-1 +``` + +之后运行单 GPU 训练脚本即可。 + +**注意**: + +我们不推荐用户使用 CPU 进行训练,这太过缓慢。我们支持这个功能是为了方便用户在没有 GPU 的机器上进行调试。 + +### 在多 GPU 上训练 + +我们提供了 `tools/dist_train.sh` 来开启在多 GPU 上的训练。基本使用如下: + +```shell +bash ./tools/dist_train.sh \ + ${CONFIG_FILE} \ + ${GPU_NUM} \ + [optional arguments] +``` + +可选参数和单 GPU 训练的可选参数一致。 + +#### 同时启动多个任务 + +如果你想在一台机器上启动多个任务的话,比如在一个有 8 块 GPU 的机器上启动 2 个需要 4 块GPU的任务,你需要给不同的训练任务指定不同的端口(默认为 29500)来避免冲突。 + +如果你使用 `dist_train.sh` 来启动训练任务,你可以使用命令来设置端口。 + +```shell +CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4 +CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4 +``` + +### 使用多台机器训练 + +如果您想使用由 ethernet 连接起来的多台机器, 您可以使用以下命令: + +在第一台机器上: + +```shell +NNODES=2 NODE_RANK=0 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS +``` + +在第二台机器上: + +```shell +NNODES=2 NODE_RANK=1 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS +``` + +但是,如果您不使用高速网路连接这几台机器的话,训练将会非常慢。 + +### 使用 Slurm 来管理任务 + +Slurm 是一个常见的计算集群调度系统。在 Slurm 管理的集群上,你可以使用 `slurm.sh` 来开启训练任务。它既支持单节点训练也支持多节点训练。 + +基本使用如下: + +```shell +[GPUS=${GPUS}] ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR} +``` + +以下是在一个名称为 _dev_ 的 Slurm 分区上,使用 16 块 GPU 来训练 Mask R-CNN 的例子,并且将 `work-dir` 设置在了某些共享文件系统下。 + +```shell +GPUS=16 ./tools/slurm_train.sh dev mask_r50_1x configs/mask_rcnn_r50_fpn_1x_coco.py /nfs/xxxx/mask_rcnn_r50_fpn_1x +``` + +你可以查看 [源码](https://github.com/open-mmlab/mmdetection/blob/main/tools/slurm_train.sh) 来检查全部的参数和环境变量. + +在使用 Slurm 时,端口需要以下方的某个方法之一来设置。 + +1. 通过 `--options` 来设置端口。我们非常建议用这种方法,因为它无需改变原始的配置文件。 + + ```shell + CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} --cfg-options 'dist_params.port=29500' + CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} --cfg-options 'dist_params.port=29501' + ``` + +2. 修改配置文件来设置不同的交流端口。 + + 在 `config1.py` 中,设置: + + ```python + dist_params = dict(backend='nccl', port=29500) + ``` + + 在 `config2.py` 中,设置: + + ```python + dist_params = dict(backend='nccl', port=29501) + ``` + + 然后你可以使用 `config1.py` 和 `config2.py` 来启动两个任务了。 + + ```shell + CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} + CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} + ``` + +# 在自定义数据集上进行训练 + +通过本文档,你将会知道如何使用自定义数据集对预先定义好的模型进行推理,测试以及训练。我们使用 [balloon dataset](https://github.com/matterport/Mask_RCNN/tree/master/samples/balloon) 作为例子来描述整个过程。 + +基本步骤如下: + +1. 准备自定义数据集 +2. 准备配置文件 +3. 在自定义数据集上进行训练,测试和推理。 + +## 准备自定义数据集 + +MMDetection 一共支持三种形式应用新数据集: + +1. 将数据集重新组织为 COCO 格式。 +2. 将数据集重新组织为一个中间格式。 +3. 实现一个新的数据集。 + +我们通常建议使用前面两种方法,因为它们通常来说比第三种方法要简单。 + +在本文档中,我们展示一个例子来说明如何将数据转化为 COCO 格式。 + +**注意**:在 MMDetection 3.0 之后,数据集和指标已经解耦(除了 CityScapes)。因此,用户在验证阶段使用任意的评价指标来评价模型在任意数据集上的性能。比如,用 VOC 评价指标来评价模型在 COCO 数据集的性能,或者同时使用 VOC 评价指标和 COCO 评价指标来评价模型在 OpenImages 数据集上的性能。 + +### COCO标注格式 + +用于实例分割的 COCO 数据集格式如下所示,其中的键(key)都是必要的,参考[这里](https://cocodataset.org/#format-data)来获取更多细节。 + +```json +{ + "images": [image], + "annotations": [annotation], + "categories": [category] +} + + +image = { + "id": int, + "width": int, + "height": int, + "file_name": str, +} + +annotation = { + "id": int, + "image_id": int, + "category_id": int, + "segmentation": RLE or [polygon], + "area": float, + "bbox": [x,y,width,height], # (x, y) 为 bbox 左上角的坐标 + "iscrowd": 0 or 1, +} + +categories = [{ + "id": int, + "name": str, + "supercategory": str, +}] +``` + +现在假设我们使用 balloon dataset。 + +下载了数据集之后,我们需要实现一个函数将标注格式转化为 COCO 格式。然后我们就可以使用已经实现的 `CocoDataset` 类来加载数据并进行训练以及评测。 + +如果你浏览过新数据集,你会发现格式如下: + +```json +{'base64_img_data': '', + 'file_attributes': {}, + 'filename': '34020010494_e5cb88e1c4_k.jpg', + 'fileref': '', + 'regions': {'0': {'region_attributes': {}, + 'shape_attributes': {'all_points_x': [1020, + 1000, + 994, + 1003, + 1023, + 1050, + 1089, + 1134, + 1190, + 1265, + 1321, + 1361, + 1403, + 1428, + 1442, + 1445, + 1441, + 1427, + 1400, + 1361, + 1316, + 1269, + 1228, + 1198, + 1207, + 1210, + 1190, + 1177, + 1172, + 1174, + 1170, + 1153, + 1127, + 1104, + 1061, + 1032, + 1020], + 'all_points_y': [963, + 899, + 841, + 787, + 738, + 700, + 663, + 638, + 621, + 619, + 643, + 672, + 720, + 765, + 800, + 860, + 896, + 942, + 990, + 1035, + 1079, + 1112, + 1129, + 1134, + 1144, + 1153, + 1166, + 1166, + 1150, + 1136, + 1129, + 1122, + 1112, + 1084, + 1037, + 989, + 963], + 'name': 'polygon'}}}, + 'size': 1115004} +``` + +标注文件时是 JSON 格式的,其中所有键(key)组成了一张图片的所有标注。 + +其中将 balloon dataset 转化为 COCO 格式的代码如下所示。 + +```python +import os.path as osp + +import mmcv + +from mmengine.fileio import dump, load +from mmengine.utils import track_iter_progress + + +def convert_balloon_to_coco(ann_file, out_file, image_prefix): + data_infos = load(ann_file) + + annotations = [] + images = [] + obj_count = 0 + for idx, v in enumerate(track_iter_progress(data_infos.values())): + filename = v['filename'] + img_path = osp.join(image_prefix, filename) + height, width = mmcv.imread(img_path).shape[:2] + + images.append( + dict(id=idx, file_name=filename, height=height, width=width)) + + for _, obj in v['regions'].items(): + assert not obj['region_attributes'] + obj = obj['shape_attributes'] + px = obj['all_points_x'] + py = obj['all_points_y'] + poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)] + poly = [p for x in poly for p in x] + + x_min, y_min, x_max, y_max = (min(px), min(py), max(px), max(py)) + + data_anno = dict( + image_id=idx, + id=obj_count, + category_id=0, + bbox=[x_min, y_min, x_max - x_min, y_max - y_min], + area=(x_max - x_min) * (y_max - y_min), + segmentation=[poly], + iscrowd=0) + annotations.append(data_anno) + obj_count += 1 + + coco_format_json = dict( + images=images, + annotations=annotations, + categories=[{ + 'id': 0, + 'name': 'balloon' + }]) + dump(coco_format_json, out_file) + + +if __name__ == '__main__': + convert_balloon_to_coco(ann_file='data/balloon/train/via_region_data.json', + out_file='data/balloon/train/annotation_coco.json', + image_prefix='data/balloon/train') + convert_balloon_to_coco(ann_file='data/balloon/val/via_region_data.json', + out_file='data/balloon/val/annotation_coco.json', + image_prefix='data/balloon/val') +``` + +使用如上的函数,用户可以成功将标注文件转化为 JSON 格式,之后可以使用 `CocoDataset` 对模型进行训练,并用 `CocoMetric` 评测。 + +## 准备配置文件 + +第二步需要准备一个配置文件来成功加载数据集。假设我们想要用 balloon dataset 来训练配备了 FPN 的 Mask R-CNN ,如下是我们的配置文件。假设配置文件命名为 `mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py`,相应保存路径为 `configs/balloon/`,配置文件内容如下所示。详细的配置文件方法可以参考[学习配置文件 — MMDetection 3.0.0 文档](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/config.html#base)。 + +```python +# 新配置继承了基本配置,并做了必要的修改 +_base_ = '../mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_coco.py' + +# 我们还需要更改 head 中的 num_classes 以匹配数据集中的类别数 +model = dict( + roi_head=dict( + bbox_head=dict(num_classes=1), mask_head=dict(num_classes=1))) + +# 修改数据集相关配置 +data_root = 'data/balloon/' +metainfo = { + 'classes': ('balloon', ), + 'palette': [ + (220, 20, 60), + ] +} +train_dataloader = dict( + batch_size=1, + dataset=dict( + data_root=data_root, + metainfo=metainfo, + ann_file='train/annotation_coco.json', + data_prefix=dict(img='train/'))) +val_dataloader = dict( + dataset=dict( + data_root=data_root, + metainfo=metainfo, + ann_file='val/annotation_coco.json', + data_prefix=dict(img='val/'))) +test_dataloader = val_dataloader + +# 修改评价指标相关配置 +val_evaluator = dict(ann_file=data_root + 'val/annotation_coco.json') +test_evaluator = val_evaluator + +# 使用预训练的 Mask R-CNN 模型权重来做初始化,可以提高模型性能 +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth' + +``` + +## 训练一个新的模型 + +为了使用新的配置方法来对模型进行训练,你只需要运行如下命令。 + +```shell +python tools/train.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py +``` + +参考 [在标准数据集上训练预定义的模型](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/train.html#id1) 来获取更多详细的使用方法。 + +## 测试以及推理 + +为了测试训练完毕的模型,你只需要运行如下命令。 + +```shell +python tools/test.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py work_dirs/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon/epoch_12.pth +``` + +参考 [测试现有模型](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/test.html) 来获取更多详细的使用方法。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/useful_hooks.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/useful_hooks.md new file mode 100644 index 0000000000000000000000000000000000000000..07a59df2a8b25e7ca6a8ff0512542560e98b314e --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/useful_hooks.md @@ -0,0 +1,107 @@ +# 实用的钩子 + +MMDetection 和 MMEngine 为用户提供了多种多样实用的钩子(Hook),包括 `MemoryProfilerHook`、`NumClassCheckHook` 等等。 +这篇教程介绍了 MMDetection 中实现的钩子功能及使用方式。若使用 MMEngine 定义的钩子请参考 [MMEngine 的钩子API文档](https://github.com/open-mmlab/mmengine/tree/main/docs/en/tutorials/hook.md). + +## CheckInvalidLossHook + +## NumClassCheckHook + +## MemoryProfilerHook + +[内存分析钩子](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/engine/hooks/memory_profiler_hook.py) +记录了包括虚拟内存、交换内存、当前进程在内的所有内存信息,它能够帮助捕捉系统的使用状况与发现隐藏的内存泄露问题。为了使用这个钩子,你需要先通过 `pip install memory_profiler psutil` 命令安装 `memory_profiler` 和 `psutil`。 + +### 使用 + +为了使用这个钩子,使用者需要添加如下代码至 config 文件 + +```python +custom_hooks = [ + dict(type='MemoryProfilerHook', interval=50) +] +``` + +### 结果 + +在训练中,你会看到 `MemoryProfilerHook` 记录的如下信息: + +```text +The system has 250 GB (246360 MB + 9407 MB) of memory and 8 GB (5740 MB + 2452 MB) of swap memory in total. Currently 9407 MB (4.4%) of memory and 5740 MB (29.9%) of swap memory were consumed. And the current training process consumed 5434 MB of memory. +``` + +```text +2022-04-21 08:49:56,881 - mmengine - INFO - Memory information available_memory: 246360 MB, used_memory: 9407 MB, memory_utilization: 4.4 %, available_swap_memory: 5740 MB, used_swap_memory: 2452 MB, swap_memory_utilization: 29.9 %, current_process_memory: 5434 MB +``` + +## SetEpochInfoHook + +## SyncNormHook + +## SyncRandomSizeHook + +## YOLOXLrUpdaterHook + +## YOLOXModeSwitchHook + +## 如何实现自定义钩子 + +通常,从模型训练的开始到结束,共有20个点位可以执行钩子。我们可以实现自定义钩子在不同点位执行,以便在训练中实现自定义操作。 + +- global points: `before_run`, `after_run` +- points in training: `before_train`, `before_train_epoch`, `before_train_iter`, `after_train_iter`, `after_train_epoch`, `after_train` +- points in validation: `before_val`, `before_val_epoch`, `before_val_iter`, `after_val_iter`, `after_val_epoch`, `after_val` +- points at testing: `before_test`, `before_test_epoch`, `before_test_iter`, `after_test_iter`, `after_test_epoch`, `after_test` +- other points: `before_save_checkpoint`, `after_save_checkpoint` + +比如,我们要实现一个检查 loss 的钩子,当损失为 NaN 时自动结束训练。我们可以把这个过程分为三步: + +1. 在 MMEngine 实现一个继承于 `Hook` 类的新钩子,并实现 `after_train_iter` 方法用于检查每 `n` 次训练迭代后损失是否变为 NaN 。 +2. 使用 `@HOOKS.register_module()` 注册实现好了的自定义钩子,如下列代码所示。 +3. 在配置文件中添加 `custom_hooks = [dict(type='MemoryProfilerHook', interval=50)]` + +```python +from typing import Optional + +import torch +from mmengine.hooks import Hook +from mmengine.runner import Runner + +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class CheckInvalidLossHook(Hook): + """Check invalid loss hook. + + This hook will regularly check whether the loss is valid + during training. + + Args: + interval (int): Checking interval (every k iterations). + Default: 50. + """ + + def __init__(self, interval: int = 50) -> None: + self.interval = interval + + def after_train_iter(self, + runner: Runner, + batch_idx: int, + data_batch: Optional[dict] = None, + outputs: Optional[dict] = None) -> None: + """Regularly check whether the loss is valid every n iterations. + + Args: + runner (:obj:`Runner`): The runner of the training process. + batch_idx (int): The index of the current batch in the train loop. + data_batch (dict, Optional): Data from dataloader. + Defaults to None. + outputs (dict, Optional): Outputs from model. Defaults to None. + """ + if self.every_n_train_iters(runner, self.interval): + assert torch.isfinite(outputs['loss']), \ + runner.logger.info('loss become infinite or NaN!') +``` + +请参考 [自定义训练配置](../advanced_guides/customize_runtime.md) 了解更多与自定义钩子相关的内容。 diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/useful_tools.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/useful_tools.md new file mode 100644 index 0000000000000000000000000000000000000000..e53ffdfc60acf61c33429a4c6a21af8062e78eff --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/useful_tools.md @@ -0,0 +1,562 @@ +除了训练和测试脚本,我们还在 `tools/` 目录下提供了许多有用的工具。 + +## 日志分析 + +`tools/analysis_tools/analyze_logs.py` 可利用指定的训练 log 文件绘制 loss/mAP 曲线图, +第一次运行前请先运行 `pip install seaborn` 安装必要依赖. + +```shell +python tools/analysis_tools/analyze_logs.py plot_curve [--keys ${KEYS}] [--eval-interval ${EVALUATION_INTERVAL}] [--title ${TITLE}] [--legend ${LEGEND}] [--backend ${BACKEND}] [--style ${STYLE}] [--out ${OUT_FILE}] +``` + +![loss curve image](../../../resources/loss_curve.png) + +样例: + +- 绘制分类损失曲线图 + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log.json --keys loss_cls --legend loss_cls + ``` + +- 绘制分类损失、回归损失曲线图,保存图片为对应的 pdf 文件 + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log.json --keys loss_cls loss_bbox --out losses.pdf + ``` + +- 在相同图像中比较两次运行结果的 bbox mAP + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log1.json log2.json --keys bbox_mAP --legend run1 run2 + ``` + +- 计算平均训练速度 + + ```shell + python tools/analysis_tools/analyze_logs.py cal_train_time log.json [--include-outliers] + ``` + + 输出以如下形式展示 + + ```text + -----Analyze train time of work_dirs/some_exp/20190611_192040.log.json----- + slowest epoch 11, average time is 1.2024 + fastest epoch 1, average time is 1.1909 + time std over epochs is 0.0028 + average iter time: 1.1959 s/iter + ``` + +## 结果分析 + +使用 `tools/analysis_tools/analyze_results.py` 可计算每个图像 mAP,随后根据真实标注框与预测框的比较结果,展示或保存最高与最低 top-k 得分的预测图像。 + +**使用方法** + +```shell +python tools/analysis_tools/analyze_results.py \ + ${CONFIG} \ + ${PREDICTION_PATH} \ + ${SHOW_DIR} \ + [--show] \ + [--wait-time ${WAIT_TIME}] \ + [--topk ${TOPK}] \ + [--show-score-thr ${SHOW_SCORE_THR}] \ + [--cfg-options ${CFG_OPTIONS}] +``` + +各个参数选项的作用: + +- `config`: model config 文件的路径。 +- `prediction_path`: 使用 `tools/test.py` 输出的 pickle 格式结果文件。 +- `show_dir`: 绘制真实标注框与预测框的图像存放目录。 +- `--show`:决定是否展示绘制 box 后的图片,默认值为 `False`。 +- `--wait-time`: show 时间的间隔,若为 0 表示持续显示。 +- `--topk`: 根据最高或最低 `topk` 概率排序保存的图片数量,若不指定,默认设置为 `20`。 +- `--show-score-thr`: 能够展示的概率阈值,默认为 `0`。 +- `--cfg-options`: 如果指定,可根据指定键值对覆盖更新配置文件的对应选项 + +**样例**: +假设你已经通过 `tools/test.py` 得到了 pickle 格式的结果文件,路径为 './result.pkl'。 + +1. 测试 Faster R-CNN 并可视化结果,保存图片至 `results/` + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --show +``` + +2. 测试 Faster R-CNN 并指定 top-k 参数为 50,保存结果图片至 `results/` + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --topk 50 +``` + +3. 如果你想过滤低概率的预测结果,指定 `show-score-thr` 参数 + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --show-score-thr 0.3 +``` + +## 可视化 + +### 可视化数据集 + +`tools/analysis_tools/browse_dataset.py` 可帮助使用者检查所使用的检测数据集(包括图像和标注),或保存图像至指定目录。 + +```shell +python tools/misc/browse_dataset.py ${CONFIG} [-h] [--skip-type ${SKIP_TYPE[SKIP_TYPE...]}] [--output-dir ${OUTPUT_DIR}] [--not-show] [--show-interval ${SHOW_INTERVAL}] +``` + +### 可视化模型 + +在可视化之前,需要先转换模型至 ONNX 格式,[可参考此处](#convert-mmdetection-model-to-onnx-experimental)。 +注意,现在只支持 RetinaNet,之后的版本将会支持其他模型 +转换后的模型可以被其他工具可视化[Netron](https://github.com/lutzroeder/netron)。 + +### 可视化预测结果 + +如果你想要一个轻量 GUI 可视化检测结果,你可以参考 [DetVisGUI project](https://github.com/Chien-Hung/DetVisGUI/tree/mmdetection)。 + +## 误差分析 + +`tools/analysis_tools/coco_error_analysis.py` 使用不同标准分析每个类别的 COCO 评估结果。同时将一些有帮助的信息体现在图表上。 + +```shell +python tools/analysis_tools/coco_error_analysis.py ${RESULT} ${OUT_DIR} [-h] [--ann ${ANN}] [--types ${TYPES[TYPES...]}] +``` + +样例: + +假设你已经把 [Mask R-CNN checkpoint file](https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_fpn_1x_coco/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth) 放置在文件夹 'checkpoint' 中(其他模型请在 [model zoo](./model_zoo.md) 中获取)。 + +为了保存 bbox 结果信息,我们需要用下列方式修改 `test_evaluator` : + +1. 查找当前 config 文件相对应的 'configs/base/datasets' 数据集信息。 +2. 用当前数据集 config 中的 test_evaluator 以及 test_dataloader 替换原始文件的 test_evaluator 以及 test_dataloader。 +3. 使用以下命令得到 bbox 或 segmentation 的 json 格式文件。 + +```shell +python tools/test.py \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoint/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ +``` + +1. 得到每一类的 COCO bbox 误差结果,并保存分析结果图像至指定目录。(在 [config](../../../configs/_base_/datasets/coco_instance.py) 中默认目录是 './work_dirs/coco_instance/test') + +```shell +python tools/analysis_tools/coco_error_analysis.py \ + results.bbox.json \ + results \ + --ann=data/coco/annotations/instances_val2017.json \ +``` + +2. 得到每一类的 COCO 分割误差结果,并保存分析结果图像至指定目录。 + +```shell +python tools/analysis_tools/coco_error_analysis.py \ + results.segm.json \ + results \ + --ann=data/coco/annotations/instances_val2017.json \ + --types='segm' +``` + +## 模型服务部署 + +如果你想使用 [`TorchServe`](https://pytorch.org/serve/) 搭建一个 `MMDetection` 模型服务,可以参考以下步骤: + +### 1. 安装 TorchServe + +假设你已经成功安装了包含 `PyTorch` 和 `MMDetection` 的 `Python` 环境,那么你可以运行以下命令来安装 `TorchServe` 及其依赖项。有关更多其他安装选项,请参考[快速入门](https://github.com/pytorch/serve/blob/master/README.md#serve-a-model)。 + +```shell +python -m pip install torchserve torch-model-archiver torch-workflow-archiver nvgpu +``` + +**注意**: 如果你想在 docker 中使用`TorchServe`,请参考[torchserve docker](https://github.com/pytorch/serve/blob/master/docker/README.md)。 + +### 2. 把 MMDetection 模型转换至 TorchServe + +```shell +python tools/deployment/mmdet2torchserve.py ${CONFIG_FILE} ${CHECKPOINT_FILE} \ +--output-folder ${MODEL_STORE} \ +--model-name ${MODEL_NAME} +``` + +### 3. 启动 `TorchServe` + +```shell +torchserve --start --ncs \ + --model-store ${MODEL_STORE} \ + --models ${MODEL_NAME}.mar +``` + +### 4. 测试部署效果 + +```shell +curl -O curl -O https://raw.githubusercontent.com/pytorch/serve/master/docs/images/3dogs.jpg +curl http://127.0.0.1:8080/predictions/${MODEL_NAME} -T 3dogs.jpg +``` + +你可以得到下列 json 信息: + +```json +[ + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 294.63409423828125, + 203.99111938476562, + 417.048583984375, + 281.62744140625 + ], + "score": 0.9987992644309998 + }, + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 404.26019287109375, + 126.0080795288086, + 574.5091552734375, + 293.6662292480469 + ], + "score": 0.9979367256164551 + }, + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 197.2144775390625, + 93.3067855834961, + 307.8505554199219, + 276.7560119628906 + ], + "score": 0.993338406085968 + } +] +``` + +#### 结果对比 + +你也可以使用 `test_torchserver.py` 来比较 `TorchServe` 和 `PyTorch` 的结果,并可视化: + +```shell +python tools/deployment/test_torchserver.py ${IMAGE_FILE} ${CONFIG_FILE} ${CHECKPOINT_FILE} ${MODEL_NAME} +[--inference-addr ${INFERENCE_ADDR}] [--device ${DEVICE}] [--score-thr ${SCORE_THR}] [--work-dir ${WORK_DIR}] +``` + +样例: + +```shell +python tools/deployment/test_torchserver.py \ +demo/demo.jpg \ +configs/yolo/yolov3_d53_8xb8-320-273e_coco.py \ +checkpoint/yolov3_d53_320_273e_coco-421362b6.pth \ +yolov3 \ +--work-dir ./work-dir +``` + +### 5. 停止 `TorchServe` + +```shell +torchserve --stop +``` + +## 模型复杂度 + +`tools/analysis_tools/get_flops.py` 工具可用于计算指定模型的 FLOPs、参数量大小(改编自 [flops-counter.pytorch](https://github.com/sovrasov/flops-counter.pytorch) )。 + +```shell +python tools/analysis_tools/get_flops.py ${CONFIG_FILE} [--shape ${INPUT_SHAPE}] +``` + +获得的结果如下: + +```text +============================== +Input shape: (3, 1280, 800) +Flops: 239.32 GFLOPs +Params: 37.74 M +============================== +``` + +**注意**:这个工具还只是实验性质,我们不保证这个数值是绝对正确的。你可以将他用于简单的比较,但如果用于科技论文报告需要再三检查确认。 + +1. FLOPs 与输入的形状大小相关,参数量没有这个关系,默认的输入形状大小为 (1, 3, 1280, 800) 。 +2. 一些算子并不计入 FLOPs,比如 GN 或其他自定义的算子。你可以参考 [`mmcv.cnn.get_model_complexity_info()`](https://github.com/open-mmlab/mmcv/blob/2.x/mmcv/cnn/utils/flops_counter.py) 查看更详细的说明。 +3. 两阶段检测的 FLOPs 大小取决于 proposal 的数量。 + +## 模型转换 + +### MMDetection 模型转换至 ONNX 格式 + +我们提供了一个脚本用于转换模型至 [ONNX](https://github.com/onnx/onnx) 格式。同时还支持比较 Pytorch 与 ONNX 模型的输出结果以便对照。更详细的内容可以参考 [mmdeploy](https://github.com/open-mmlab/mmdeploy)。 + +### MMDetection 1.x 模型转换至 MMDetection 2.x 模型 + +`tools/model_converters/upgrade_model_version.py` 可将旧版本的 MMDetection checkpoints 转换至新版本。但要注意此脚本不保证在新版本加入非兼容更新后还能正常转换,建议您直接使用新版本的 checkpoints。 + +```shell +python tools/model_converters/upgrade_model_version.py ${IN_FILE} ${OUT_FILE} [-h] [--num-classes NUM_CLASSES] +``` + +### RegNet 模型转换至 MMDetection 模型 + +`tools/model_converters/regnet2mmdet.py` 将 pycls 编码的预训练 RegNet 模型转换为 MMDetection 风格。 + +```shell +python tools/model_converters/regnet2mmdet.py ${SRC} ${DST} [-h] +``` + +### Detectron ResNet 模型转换至 Pytorch 模型 + +`tools/model_converters/detectron2pytorch.py` 将 detectron 的原始预训练 RegNet 模型转换为 MMDetection 风格。 + +```shell +python tools/model_converters/detectron2pytorch.py ${SRC} ${DST} ${DEPTH} [-h] +``` + +### 制作发布用模型 + +`tools/model_converters/publish_model.py` 可用来制作一个发布用的模型。 + +在发布模型至 AWS 之前,你可能需要: + +1. 将模型转换至 CPU 张量 +2. 删除优化器状态 +3. 计算 checkpoint 文件的 hash 值,并将 hash 号码记录至文件名。 + +```shell +python tools/model_converters/publish_model.py ${INPUT_FILENAME} ${OUTPUT_FILENAME} +``` + +样例: + +```shell +python tools/model_converters/publish_model.py work_dirs/faster_rcnn/latest.pth faster_rcnn_r50_fpn_1x_20190801.pth +``` + +最后输出的文件名如下所示: `faster_rcnn_r50_fpn_1x_20190801-{hash id}.pth`. + +## 数据集转换 + +`tools/data_converters/` 提供了将 Cityscapes 数据集与 Pascal VOC 数据集转换至 COCO 数据集格式的工具 + +```shell +python tools/dataset_converters/cityscapes.py ${CITYSCAPES_PATH} [-h] [--img-dir ${IMG_DIR}] [--gt-dir ${GT_DIR}] [-o ${OUT_DIR}] [--nproc ${NPROC}] +python tools/dataset_converters/pascal_voc.py ${DEVKIT_PATH} [-h] [-o ${OUT_DIR}] +``` + +## 数据集下载 + +`tools/misc/download_dataset.py` 可以下载各类形如 COCO, VOC, LVIS 数据集。 + +```shell +python tools/misc/download_dataset.py --dataset-name coco2017 +python tools/misc/download_dataset.py --dataset-name voc2007 +python tools/misc/download_dataset.py --dataset-name lvis +``` + +对于中国境内的用户,我们也推荐使用开源数据平台 [OpenDataLab](https://opendatalab.com/?source=OpenMMLab%20GitHub) 来获取这些数据集,以获得更好的下载体验: + +- [COCO2017](https://opendatalab.com/COCO_2017/download?source=OpenMMLab%20GitHub) +- [VOC2007](https://opendatalab.com/PASCAL_VOC2007/download?source=OpenMMLab%20GitHub) +- [VOC2012](https://opendatalab.com/PASCAL_VOC2012/download?source=OpenMMLab%20GitHub) +- [LVIS](https://opendatalab.com/LVIS/download?source=OpenMMLab%20GitHub) + +## 基准测试 + +### 鲁棒性测试基准 + +`tools/analysis_tools/test_robustness.py` 及 `tools/analysis_tools/robustness_eval.py` 帮助使用者衡量模型的鲁棒性。其核心思想来源于 [Benchmarking Robustness in Object Detection: Autonomous Driving when Winter is Coming](https://arxiv.org/abs/1907.07484)。如果你想了解如何在污损图像上评估模型的效果,以及参考该基准的一组标准模型,请参照 [robustness_benchmarking.md](robustness_benchmarking.md)。 + +### FPS 测试基准 + +`tools/analysis_tools/benchmark.py` 可帮助使用者计算 FPS,FPS 计算包括了模型向前传播与后处理过程。为了得到更精确的计算值,现在的分布式计算模式只支持一个 GPU。 + +```shell +python -m torch.distributed.launch --nproc_per_node=1 --master_port=${PORT} tools/analysis_tools/benchmark.py \ + ${CONFIG} \ + [--checkpoint ${CHECKPOINT}] \ + [--repeat-num ${REPEAT_NUM}] \ + [--max-iter ${MAX_ITER}] \ + [--log-interval ${LOG_INTERVAL}] \ + --launcher pytorch +``` + +样例:假设你已经下载了 `Faster R-CNN` 模型 checkpoint 并放置在 `checkpoints/` 目录下。 + +```shell +python -m torch.distributed.launch --nproc_per_node=1 --master_port=29500 tools/analysis_tools/benchmark.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \ + --launcher pytorch +``` + +## 更多工具 + +### 以某个评估标准进行评估 + +`tools/analysis_tools/eval_metric.py` 根据配置文件中的评估方式对 pkl 结果文件进行评估。 + +```shell +python tools/analysis_tools/eval_metric.py ${CONFIG} ${PKL_RESULTS} [-h] [--format-only] [--eval ${EVAL[EVAL ...]}] + [--cfg-options ${CFG_OPTIONS [CFG_OPTIONS ...]}] + [--eval-options ${EVAL_OPTIONS [EVAL_OPTIONS ...]}] +``` + +### 打印全部 config + +`tools/misc/print_config.py` 可将所有配置继承关系展开,完全打印相应的配置文件。 + +```shell +python tools/misc/print_config.py ${CONFIG} [-h] [--options ${OPTIONS [OPTIONS...]}] +``` + +## 超参数优化 + +### YOLO Anchor 优化 + +`tools/analysis_tools/optimize_anchors.py` 提供了两种方法优化 YOLO 的 anchors。 + +其中一种方法使用 K 均值 anchor 聚类(k-means anchor cluster),源自 [darknet](https://github.com/AlexeyAB/darknet/blob/master/src/detector.c#L1421)。 + +```shell +python tools/analysis_tools/optimize_anchors.py ${CONFIG} --algorithm k-means --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} --output-dir ${OUTPUT_DIR} +``` + +另一种方法使用差分进化算法优化 anchors。 + +```shell +python tools/analysis_tools/optimize_anchors.py ${CONFIG} --algorithm differential_evolution --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} --output-dir ${OUTPUT_DIR} +``` + +样例: + +```shell +python tools/analysis_tools/optimize_anchors.py configs/yolo/yolov3_d53_8xb8-320-273e_coco.py --algorithm differential_evolution --input-shape 608 608 --device cuda --output-dir work_dirs +``` + +你可能会看到如下结果: + +``` +loading annotations into memory... +Done (t=9.70s) +creating index... +index created! +2021-07-19 19:37:20,951 - mmdet - INFO - Collecting bboxes from annotation... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 117266/117266, 15874.5 task/s, elapsed: 7s, ETA: 0s + +2021-07-19 19:37:28,753 - mmdet - INFO - Collected 849902 bboxes. +differential_evolution step 1: f(x)= 0.506055 +differential_evolution step 2: f(x)= 0.506055 +...... + +differential_evolution step 489: f(x)= 0.386625 +2021-07-19 19:46:40,775 - mmdet - INFO Anchor evolution finish. Average IOU: 0.6133754253387451 +2021-07-19 19:46:40,776 - mmdet - INFO Anchor differential evolution result:[[10, 12], [15, 30], [32, 22], [29, 59], [61, 46], [57, 116], [112, 89], [154, 198], [349, 336]] +2021-07-19 19:46:40,798 - mmdet - INFO Result saved in work_dirs/anchor_optimize_result.json +``` + +## 混淆矩阵 + +混淆矩阵是对检测结果的概览。 +`tools/analysis_tools/confusion_matrix.py` 可对预测结果进行分析,绘制成混淆矩阵表。 +首先,运行 `tools/test.py` 保存 `.pkl` 预测结果。 +之后再运行: + +``` +python tools/analysis_tools/confusion_matrix.py ${CONFIG} ${DETECTION_RESULTS} ${SAVE_DIR} --show +``` + +最后你可以得到如图的混淆矩阵: + +![confusion_matrix_example](https://user-images.githubusercontent.com/12907710/140513068-994cdbf4-3a4a-48f0-8fd8-2830d93fd963.png) + +## COCO 分离和遮挡实例分割性能评估 + +对于最先进的目标检测器来说,检测被遮挡的物体仍然是一个挑战。 +我们实现了论文 [A Tri-Layer Plugin to Improve Occluded Detection](https://arxiv.org/abs/2210.10046) 中提出的指标来计算分离和遮挡目标的召回率。 + +使用此评价指标有两种方法: + +### 离线评测 + +我们提供了一个脚本对存储后的检测结果文件计算指标。 + +首先,使用 `tools/test.py` 脚本存储检测结果: + +```shell +python tools/test.py ${CONFIG} ${MODEL_PATH} --out results.pkl +``` + +然后,运行 `tools/analysis_tools/coco_occluded_separated_recall.py` 脚本来计算分离和遮挡目标的掩码的召回率: + +```shell +python tools/analysis_tools/coco_occluded_separated_recall.py results.pkl --out occluded_separated_recall.json +``` + +输出如下: + +``` +loading annotations into memory... +Done (t=0.51s) +creating index... +index created! +processing detection results... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5000/5000, 109.3 task/s, elapsed: 46s, ETA: 0s +computing occluded mask recall... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5550/5550, 780.5 task/s, elapsed: 7s, ETA: 0s +COCO occluded mask recall: 58.79% +COCO occluded mask success num: 3263 +computing separated mask recall... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 3522/3522, 778.3 task/s, elapsed: 5s, ETA: 0s +COCO separated mask recall: 31.94% +COCO separated mask success num: 1125 + ++-----------+--------+-------------+ +| mask type | recall | num correct | ++-----------+--------+-------------+ +| occluded | 58.79% | 3263 | +| separated | 31.94% | 1125 | ++-----------+--------+-------------+ +Evaluation results have been saved to occluded_separated_recall.json. +``` + +### 在线评测 + +我们实现继承自 `CocoMetic` 的 `CocoOccludedSeparatedMetric`。 +要在训练期间评估分离和遮挡掩码的召回率,只需在配置中将 evaluator 类型替换为 `CocoOccludedSeparatedMetric`: + +```python +val_evaluator = dict( + type='CocoOccludedSeparatedMetric', # 修改此处 + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False) +test_evaluator = val_evaluator +``` + +如果您使用了此指标,请引用论文: + +```latex +@article{zhan2022triocc, + title={A Tri-Layer Plugin to Improve Occluded Detection}, + author={Zhan, Guanqi and Xie, Weidi and Zisserman, Andrew}, + journal={British Machine Vision Conference}, + year={2022} +} +``` diff --git a/mmdet_code/SR-TOD/docs/zh_cn/user_guides/visualization.md b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..f90ab6d49fd5857a1a1f4ec695d4b42bcbb76acc --- /dev/null +++ b/mmdet_code/SR-TOD/docs/zh_cn/user_guides/visualization.md @@ -0,0 +1,93 @@ +# 可视化 + +在阅读本教程之前,建议先阅读 MMEngine 的 [Visualization](https://github.com/open-mmlab/mmengine/blob/main/docs/en/advanced_tutorials/visualization.md) 文档,以对 `Visualizer` 的定义和用法有一个初步的了解。 + +简而言之,`Visualizer` 在 MMEngine 中实现以满足日常可视化需求,并包含以下三个主要功能: + +- 实现通用的绘图 API,例如 [`draw_bboxes`](mmengine.visualization.Visualizer.draw_bboxes) 实现了绘制边界框的功能,[`draw_lines`](mmengine.visualization.Visualizer.draw_lines) 实现了绘制线条的功能。 +- 支持将可视化结果、学习率曲线、损失函数曲线以及验证精度曲线写入到各种后端中,包括本地磁盘以及常见的深度学习训练日志工具,例如 [TensorBoard](https://www.tensorflow.org/tensorboard) 和 [Wandb](https://wandb.ai/site)。 +- 支持在代码的任何位置调用以可视化或记录模型在训练或测试期间的中间状态,例如特征图和验证结果。 + +基于 MMEngine 的 `Visualizer`,MMDet 提供了各种预构建的可视化工具,用户可以通过简单地修改以下配置文件来使用它们。 + +- `tools/analysis_tools/browse_dataset.py` 脚本提供了一个数据集可视化功能,可以在数据经过数据转换后绘制图像和相应的注释,具体描述请参见[`browse_dataset.py`](useful_tools.md#Visualization)。 + +- MMEngine实现了`LoggerHook`,使用`Visualizer`将学习率、损失和评估结果写入由`Visualizer`设置的后端。因此,通过修改配置文件中的`Visualizer`后端,例如修改为`TensorBoardVISBackend`或`WandbVISBackend`,可以实现日志记录到常用的训练日志工具,如`TensorBoard`或`WandB`,从而方便用户使用这些可视化工具来分析和监控训练过程。 + +- 在MMDet中实现了`VisualizerHook`,它使用`Visualizer`将验证或预测阶段的预测结果可视化或存储到由`Visualizer`设置的后端。因此,通过修改配置文件中的`Visualizer`后端,例如修改为`TensorBoardVISBackend`或`WandbVISBackend`,可以将预测图像存储到`TensorBoard`或`Wandb`中。 + +## 配置 + +由于使用了注册机制,在MMDet中我们可以通过修改配置文件来设置`Visualizer`的行为。通常,我们会在`configs/_base_/default_runtime.py`中为可视化器定义默认配置,详细信息请参见[配置教程](config.md)。 + +```Python +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', + vis_backends=vis_backends, + name='visualizer') +``` + +基于上面的例子,我们可以看到`Visualizer`的配置由两个主要部分组成,即`Visualizer`类型和其使用的可视化后端`vis_backends`。 + +- 用户可直接使用`DetLocalVisualizer`来可视化支持任务的标签或预测结果。 +- MMDet默认将可视化后端`vis_backend`设置为本地可视化后端`LocalVisBackend`,将所有可视化结果和其他训练信息保存在本地文件夹中。 + +## 存储 + +MMDet默认使用本地可视化后端[`LocalVisBackend`](mmengine.visualization.LocalVisBackend),`VisualizerHook`和`LoggerHook`中存储的模型损失、学习率、模型评估精度和可视化信息,包括损失、学习率、评估精度将默认保存到`{work_dir}/{config_name}/{time}/{vis_data}`文件夹中。此外,MMDet还支持其他常见的可视化后端,例如`TensorboardVisBackend`和`WandbVisBackend`,您只需要在配置文件中更改`vis_backends`类型为相应的可视化后端即可。例如,只需在配置文件中插入以下代码块即可将数据存储到`TensorBoard`和`Wandb`中。 + +```Python +# https://mmengine.readthedocs.io/en/latest/api/visualization.html +_base_.visualizer.vis_backends = [ + dict(type='LocalVisBackend'), # + dict(type='TensorboardVisBackend'), + dict(type='WandbVisBackend'),] +``` + +## 绘图 + +### 绘制预测结果 + +MMDet主要使用[`DetVisualizationHook`](mmdet.engine.hooks.DetVisualizationHook)来绘制验证和测试的预测结果,默认情况下`DetVisualizationHook`是关闭的,其默认配置如下。 + +```Python +visualization=dict( #用户可视化验证和测试结果 + type='DetVisualizationHook', + draw=False, + interval=1, + show=False) +``` + +以下表格展示了`DetVisualizationHook`支持的参数。 + +| 参数 | 描述 | +| :------: | :------------------------------------------------------------------------------: | +| draw | DetVisualizationHook通过enable参数打开和关闭,默认状态为关闭。 | +| interval | 控制在DetVisualizationHook启用时存储或显示验证或测试结果的间隔,单位为迭代次数。 | +| show | 控制是否可视化验证或测试的结果。 | + +如果您想在训练或测试期间启用 `DetVisualizationHook` 相关功能和配置,您只需要修改配置文件,以 `configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py` 为例,同时绘制注释和预测,并显示图像,配置文件可以修改如下: + +```Python +visualization = _base_.default_hooks.visualization +visualization.update(dict(draw=True, show=True)) +``` + +
+ +
+ +`test.py`程序提供了`--show`和`--show-dir`参数,可以在测试过程中可视化注释和预测结果,而不需要修改配置文件,从而进一步简化了测试过程。 + +```Shell +# 展示测试结果 +python tools/test.py configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_tiny_8xb32-300e_coco/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --show + +# 指定存储预测结果的位置 +python tools/test.py configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_tiny_8xb32-300e_coco/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --show-dir imgs/ +``` + +
+ +
diff --git a/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_detection.py b/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..45041f6d236be95eb7592035d31f155c61bfcb25 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_detection.py @@ -0,0 +1,104 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms import LoadImageFromFile +from mmengine.dataset.sampler import DefaultSampler + +from mmdet.datasets import AspectRatioBatchSampler, CocoDataset +from mmdet.datasets.transforms import (LoadAnnotations, PackDetInputs, + RandomFlip, Resize) +from mmdet.evaluation import CocoMetric + +# dataset settings +dataset_type = CocoDataset +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadAnnotations, with_bbox=True), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=RandomFlip, prob=0.5), + dict(type=PackDetInputs) +] +test_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type=LoadAnnotations, with_bbox=True), + dict( + type=PackDetInputs, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=DefaultSampler, shuffle=True), + batch_sampler=dict(type=AspectRatioBatchSampler), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type=DefaultSampler, shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type=CocoMetric, + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type=DefaultSampler, shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type=CocoMetric, +# metric='bbox', +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_detection/test') diff --git a/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_instance.py b/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..b9575432e26b7e861c4dfcf535773b7a1990eeab --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_instance.py @@ -0,0 +1,106 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms.loading import LoadImageFromFile +from mmengine.dataset.sampler import DefaultSampler + +from mmdet.datasets.coco import CocoDataset +from mmdet.datasets.samplers.batch_sampler import AspectRatioBatchSampler +from mmdet.datasets.transforms.formatting import PackDetInputs +from mmdet.datasets.transforms.loading import LoadAnnotations +from mmdet.datasets.transforms.transforms import RandomFlip, Resize +from mmdet.evaluation.metrics.coco_metric import CocoMetric + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadAnnotations, with_bbox=True, with_mask=True), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=RandomFlip, prob=0.5), + dict(type=PackDetInputs) +] +test_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type=LoadAnnotations, with_bbox=True, with_mask=True), + dict( + type=PackDetInputs, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=DefaultSampler, shuffle=True), + batch_sampler=dict(type=AspectRatioBatchSampler), + dataset=dict( + type=CocoDataset, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type=DefaultSampler, shuffle=False), + dataset=dict( + type=CocoDataset, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type=CocoMetric, + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type=DefaultSampler, shuffle=False), +# dataset=dict( +# type=CocoDataset, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type=CocoMetric, +# metric=['bbox', 'segm'], +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_instance/test') diff --git a/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_instance_semantic.py b/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_instance_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf5b2cfab8a98a6c97e23a8df663e8f1e90b355 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_instance_semantic.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms.loading import LoadImageFromFile +from mmengine.dataset.sampler import DefaultSampler + +from mmdet.datasets.coco import CocoDataset +from mmdet.datasets.samplers.batch_sampler import AspectRatioBatchSampler +from mmdet.datasets.transforms.formatting import PackDetInputs +from mmdet.datasets.transforms.loading import LoadAnnotations +from mmdet.datasets.transforms.transforms import RandomFlip, Resize +from mmdet.evaluation.metrics.coco_metric import CocoMetric + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadAnnotations, with_bbox=True, with_mask=True, with_seg=True), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=RandomFlip, prob=0.5), + dict(type=PackDetInputs) +] +test_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type=LoadAnnotations, with_bbox=True, with_mask=True, with_seg=True), + dict( + type=PackDetInputs, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=DefaultSampler, shuffle=True), + batch_sampler=dict(type=AspectRatioBatchSampler), + dataset=dict( + type=CocoDataset, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/', seg='stuffthingmaps/train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type=DefaultSampler, shuffle=False), + dataset=dict( + type=CocoDataset, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = dict( + type=CocoMetric, + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_panoptic.py b/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..29d655ff619c74c5976d5f06c0c623a0d3459997 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/configs/_base_/datasets/coco_panoptic.py @@ -0,0 +1,105 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms.loading import LoadImageFromFile +from mmengine.dataset.sampler import DefaultSampler + +from mmdet.datasets.coco_panoptic import CocoPanopticDataset +from mmdet.datasets.samplers.batch_sampler import AspectRatioBatchSampler +from mmdet.datasets.transforms.formatting import PackDetInputs +from mmdet.datasets.transforms.loading import LoadPanopticAnnotations +from mmdet.datasets.transforms.transforms import RandomFlip, Resize +from mmdet.evaluation.metrics.coco_panoptic_metric import CocoPanopticMetric + +# dataset settings +dataset_type = 'CocoPanopticDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadPanopticAnnotations, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=RandomFlip, prob=0.5), + dict(type=PackDetInputs) +] +test_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=LoadPanopticAnnotations, backend_args=backend_args), + dict( + type=PackDetInputs, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=DefaultSampler, shuffle=True), + batch_sampler=dict(type=AspectRatioBatchSampler), + dataset=dict( + type=CocoPanopticDataset, + data_root=data_root, + ann_file='annotations/panoptic_train2017.json', + data_prefix=dict( + img='train2017/', seg='annotations/panoptic_train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type=DefaultSampler, shuffle=False), + dataset=dict( + type=CocoPanopticDataset, + data_root=data_root, + ann_file='annotations/panoptic_val2017.json', + data_prefix=dict(img='val2017/', seg='annotations/panoptic_val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type=CocoPanopticMetric, + ann_file=data_root + 'annotations/panoptic_val2017.json', + seg_prefix=data_root + 'annotations/panoptic_val2017/', + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=1, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type=DefaultSampler, shuffle=False), +# dataset=dict( +# type=CocoPanopticDataset, +# data_root=data_root, +# ann_file='annotations/panoptic_image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type=CocoPanopticMetric, +# format_only=True, +# ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_panoptic/test') diff --git a/mmdet_code/SR-TOD/mmdet/datasets/__init__.py b/mmdet_code/SR-TOD/mmdet/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a0929e888115b66f176806ad2adc9f797f6f94dc --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/__init__.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .ade20k import (ADE20KInstanceDataset, ADE20KPanopticDataset, + ADE20KSegDataset) +from .base_det_dataset import BaseDetDataset +from .base_semseg_dataset import BaseSegDataset +from .base_video_dataset import BaseVideoDataset +from .cityscapes import CityscapesDataset +from .coco import CocoDataset +from .coco_caption import CocoCaptionDataset +from .coco_panoptic import CocoPanopticDataset +from .coco_semantic import CocoSegDataset +from .crowdhuman import CrowdHumanDataset +from .dataset_wrappers import MultiImageMixDataset +from .deepfashion import DeepFashionDataset +from .dsdl import DSDLDetDataset +from .isaid import iSAIDDataset +from .lvis import LVISDataset, LVISV1Dataset, LVISV05Dataset +from .mot_challenge_dataset import MOTChallengeDataset +from .objects365 import Objects365V1Dataset, Objects365V2Dataset +from .openimages import OpenImagesChallengeDataset, OpenImagesDataset +from .refcoco import RefCocoDataset +from .reid_dataset import ReIDDataset +from .samplers import (AspectRatioBatchSampler, ClassAwareSampler, + GroupMultiSourceSampler, MultiSourceSampler, + TrackAspectRatioBatchSampler, TrackImgSampler) +from .utils import get_loading_pipeline +from .voc import VOCDataset +from .wider_face import WIDERFaceDataset +from .xml_style import XMLDataset +from .youtube_vis_dataset import YouTubeVISDataset +from .drones import DronesDataset +from .visdrone import VisDroneDataset +from .aitod import AITODDataset +from .tinyperson import TinyPersonDataset +from .dota import DOTADataset +from .airbus import AirBusDataset +from .dior import DiorDataset +from .soda_d import SODA_DDataset + +__all__ = [ + 'XMLDataset', 'CocoDataset', 'DeepFashionDataset', 'VOCDataset', + 'CityscapesDataset', 'LVISDataset', 'LVISV05Dataset', 'LVISV1Dataset', + 'WIDERFaceDataset', 'get_loading_pipeline', 'CocoPanopticDataset', + 'MultiImageMixDataset', 'OpenImagesDataset', 'OpenImagesChallengeDataset', + 'AspectRatioBatchSampler', 'ClassAwareSampler', 'MultiSourceSampler', + 'GroupMultiSourceSampler', 'BaseDetDataset', 'CrowdHumanDataset', + 'Objects365V1Dataset', 'Objects365V2Dataset', 'DSDLDetDataset', + 'BaseVideoDataset', 'MOTChallengeDataset', 'TrackImgSampler', + 'ReIDDataset', 'YouTubeVISDataset', 'TrackAspectRatioBatchSampler', + 'ADE20KPanopticDataset', 'CocoCaptionDataset', 'RefCocoDataset', + 'BaseSegDataset', 'ADE20KSegDataset', 'CocoSegDataset', + 'ADE20KInstanceDataset', 'iSAIDDataset', 'DronesDataset', 'VisDroneDataset', 'AITODDataset', 'TinyPersonDataset', 'DOTADataset', 'AirBusDataset', 'DiorDataset', 'SODA_DDataset' +] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/ade20k.py b/mmdet_code/SR-TOD/mmdet/datasets/ade20k.py new file mode 100644 index 0000000000000000000000000000000000000000..573271cb5d0cb83571564272895bddde9a5f6ad7 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/ade20k.py @@ -0,0 +1,260 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List + +from mmengine import fileio + +from mmdet.registry import DATASETS +from .base_semseg_dataset import BaseSegDataset +from .coco import CocoDataset +from .coco_panoptic import CocoPanopticDataset + +ADE_PALETTE = [(120, 120, 120), (180, 120, 120), (6, 230, 230), (80, 50, 50), + (4, 200, 3), (120, 120, 80), (140, 140, 140), (204, 5, 255), + (230, 230, 230), (4, 250, 7), (224, 5, 255), (235, 255, 7), + (150, 5, 61), (120, 120, 70), (8, 255, 51), (255, 6, 82), + (143, 255, 140), (204, 255, 4), (255, 51, 7), (204, 70, 3), + (0, 102, 200), (61, 230, 250), (255, 6, 51), (11, 102, 255), + (255, 7, 71), (255, 9, 224), (9, 7, 230), (220, 220, 220), + (255, 9, 92), (112, 9, 255), (8, 255, 214), (7, 255, 224), + (255, 184, 6), (10, 255, 71), (255, 41, 10), (7, 255, 255), + (224, 255, 8), (102, 8, 255), (255, 61, 6), (255, 194, 7), + (255, 122, 8), (0, 255, 20), (255, 8, 41), (255, 5, 153), + (6, 51, 255), (235, 12, 255), (160, 150, 20), (0, 163, 255), + (140, 140, 140), (250, 10, 15), (20, 255, 0), (31, 255, 0), + (255, 31, 0), (255, 224, 0), (153, 255, 0), (0, 0, 255), + (255, 71, 0), (0, 235, 255), (0, 173, 255), (31, 0, 255), + (11, 200, 200), (255, 82, 0), (0, 255, 245), (0, 61, 255), + (0, 255, 112), (0, 255, 133), (255, 0, 0), (255, 163, 0), + (255, 102, 0), (194, 255, 0), (0, 143, 255), (51, 255, 0), + (0, 82, 255), (0, 255, 41), (0, 255, 173), (10, 0, 255), + (173, 255, 0), (0, 255, 153), (255, 92, 0), (255, 0, 255), + (255, 0, 245), (255, 0, 102), (255, 173, 0), (255, 0, 20), + (255, 184, 184), (0, 31, 255), (0, 255, 61), (0, 71, 255), + (255, 0, 204), (0, 255, 194), (0, 255, 82), (0, 10, 255), + (0, 112, 255), (51, 0, 255), (0, 194, 255), (0, 122, 255), + (0, 255, 163), (255, 153, 0), (0, 255, 10), (255, 112, 0), + (143, 255, 0), (82, 0, 255), (163, 255, 0), (255, 235, 0), + (8, 184, 170), (133, 0, 255), (0, 255, 92), (184, 0, 255), + (255, 0, 31), (0, 184, 255), (0, 214, 255), (255, 0, 112), + (92, 255, 0), (0, 224, 255), (112, 224, 255), (70, 184, 160), + (163, 0, 255), (153, 0, 255), (71, 255, 0), (255, 0, 163), + (255, 204, 0), (255, 0, 143), (0, 255, 235), (133, 255, 0), + (255, 0, 235), (245, 0, 255), (255, 0, 122), (255, 245, 0), + (10, 190, 212), (214, 255, 0), (0, 204, 255), (20, 0, 255), + (255, 255, 0), (0, 153, 255), (0, 41, 255), (0, 255, 204), + (41, 0, 255), (41, 255, 0), (173, 0, 255), (0, 245, 255), + (71, 0, 255), (122, 0, 255), (0, 255, 184), (0, 92, 255), + (184, 255, 0), (0, 133, 255), (255, 214, 0), (25, 194, 194), + (102, 255, 0), (92, 0, 255)] + + +@DATASETS.register_module() +class ADE20KPanopticDataset(CocoPanopticDataset): + METAINFO = { + 'classes': + ('bed', 'window', 'cabinet', 'person', 'door', 'table', 'curtain', + 'chair', 'car', 'painting, picture', 'sofa', 'shelf', 'mirror', + 'armchair', 'seat', 'fence', 'desk', 'wardrobe, closet, press', + 'lamp', 'tub', 'rail', 'cushion', 'box', 'column, pillar', + 'signboard, sign', 'chest of drawers, chest, bureau, dresser', + 'counter', 'sink', 'fireplace', 'refrigerator, icebox', 'stairs', + 'case, display case, showcase, vitrine', + 'pool table, billiard table, snooker table', 'pillow', + 'screen door, screen', 'bookcase', 'coffee table', + 'toilet, can, commode, crapper, pot, potty, stool, throne', 'flower', + 'book', 'bench', 'countertop', 'stove', 'palm, palm tree', + 'kitchen island', 'computer', 'swivel chair', 'boat', + 'arcade machine', 'bus', 'towel', 'light', 'truck', 'chandelier', + 'awning, sunshade, sunblind', 'street lamp', 'booth', 'tv', + 'airplane', 'clothes', 'pole', + 'bannister, banister, balustrade, balusters, handrail', + 'ottoman, pouf, pouffe, puff, hassock', 'bottle', 'van', 'ship', + 'fountain', 'washer, automatic washer, washing machine', + 'plaything, toy', 'stool', 'barrel, cask', 'basket, handbasket', + 'bag', 'minibike, motorbike', 'oven', 'ball', 'food, solid food', + 'step, stair', 'trade name', 'microwave', 'pot', 'animal', 'bicycle', + 'dishwasher', 'screen', 'sculpture', 'hood, exhaust hood', 'sconce', + 'vase', 'traffic light', 'tray', 'trash can', 'fan', 'plate', + 'monitor', 'bulletin board', 'radiator', 'glass, drinking glass', + 'clock', 'flag', 'wall', 'building', 'sky', 'floor', 'tree', + 'ceiling', 'road, route', 'grass', 'sidewalk, pavement', + 'earth, ground', 'mountain, mount', 'plant', 'water', 'house', 'sea', + 'rug', 'field', 'rock, stone', 'base, pedestal, stand', 'sand', + 'skyscraper', 'grandstand, covered stand', 'path', 'runway', + 'stairway, staircase', 'river', 'bridge, span', 'blind, screen', + 'hill', 'bar', 'hovel, hut, hutch, shack, shanty', 'tower', + 'dirt track', 'land, ground, soil', + 'escalator, moving staircase, moving stairway', + 'buffet, counter, sideboard', + 'poster, posting, placard, notice, bill, card', 'stage', + 'conveyer belt, conveyor belt, conveyer, conveyor, transporter', + 'canopy', 'pool', 'falls', 'tent', 'cradle', 'tank, storage tank', + 'lake', 'blanket, cover', 'pier', 'crt screen', 'shower'), + 'thing_classes': + ('bed', 'window', 'cabinet', 'person', 'door', 'table', 'curtain', + 'chair', 'car', 'painting, picture', 'sofa', 'shelf', 'mirror', + 'armchair', 'seat', 'fence', 'desk', 'wardrobe, closet, press', + 'lamp', 'tub', 'rail', 'cushion', 'box', 'column, pillar', + 'signboard, sign', 'chest of drawers, chest, bureau, dresser', + 'counter', 'sink', 'fireplace', 'refrigerator, icebox', 'stairs', + 'case, display case, showcase, vitrine', + 'pool table, billiard table, snooker table', 'pillow', + 'screen door, screen', 'bookcase', 'coffee table', + 'toilet, can, commode, crapper, pot, potty, stool, throne', 'flower', + 'book', 'bench', 'countertop', 'stove', 'palm, palm tree', + 'kitchen island', 'computer', 'swivel chair', 'boat', + 'arcade machine', 'bus', 'towel', 'light', 'truck', 'chandelier', + 'awning, sunshade, sunblind', 'street lamp', 'booth', 'tv', + 'airplane', 'clothes', 'pole', + 'bannister, banister, balustrade, balusters, handrail', + 'ottoman, pouf, pouffe, puff, hassock', 'bottle', 'van', 'ship', + 'fountain', 'washer, automatic washer, washing machine', + 'plaything, toy', 'stool', 'barrel, cask', 'basket, handbasket', + 'bag', 'minibike, motorbike', 'oven', 'ball', 'food, solid food', + 'step, stair', 'trade name', 'microwave', 'pot', 'animal', 'bicycle', + 'dishwasher', 'screen', 'sculpture', 'hood, exhaust hood', 'sconce', + 'vase', 'traffic light', 'tray', 'trash can', 'fan', 'plate', + 'monitor', 'bulletin board', 'radiator', 'glass, drinking glass', + 'clock', 'flag'), + 'stuff_classes': + ('wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road, route', + 'grass', 'sidewalk, pavement', 'earth, ground', 'mountain, mount', + 'plant', 'water', 'house', 'sea', 'rug', 'field', 'rock, stone', + 'base, pedestal, stand', 'sand', 'skyscraper', + 'grandstand, covered stand', 'path', 'runway', 'stairway, staircase', + 'river', 'bridge, span', 'blind, screen', 'hill', 'bar', + 'hovel, hut, hutch, shack, shanty', 'tower', 'dirt track', + 'land, ground, soil', 'escalator, moving staircase, moving stairway', + 'buffet, counter, sideboard', + 'poster, posting, placard, notice, bill, card', 'stage', + 'conveyer belt, conveyor belt, conveyer, conveyor, transporter', + 'canopy', 'pool', 'falls', 'tent', 'cradle', 'tank, storage tank', + 'lake', 'blanket, cover', 'pier', 'crt screen', 'shower'), + 'palette': + ADE_PALETTE + } + + +@DATASETS.register_module() +class ADE20KInstanceDataset(CocoDataset): + METAINFO = { + 'classes': + ('bed', 'windowpane', 'cabinet', 'person', 'door', 'table', 'curtain', + 'chair', 'car', 'painting', 'sofa', 'shelf', 'mirror', 'armchair', + 'seat', 'fence', 'desk', 'wardrobe', 'lamp', 'bathtub', 'railing', + 'cushion', 'box', 'column', 'signboard', 'chest of drawers', + 'counter', 'sink', 'fireplace', 'refrigerator', 'stairs', 'case', + 'pool table', 'pillow', 'screen door', 'bookcase', 'coffee table', + 'toilet', 'flower', 'book', 'bench', 'countertop', 'stove', 'palm', + 'kitchen island', 'computer', 'swivel chair', 'boat', + 'arcade machine', 'bus', 'towel', 'light', 'truck', 'chandelier', + 'awning', 'streetlight', 'booth', 'television receiver', 'airplane', + 'apparel', 'pole', 'bannister', 'ottoman', 'bottle', 'van', 'ship', + 'fountain', 'washer', 'plaything', 'stool', 'barrel', 'basket', 'bag', + 'minibike', 'oven', 'ball', 'food', 'step', 'trade name', 'microwave', + 'pot', 'animal', 'bicycle', 'dishwasher', 'screen', 'sculpture', + 'hood', 'sconce', 'vase', 'traffic light', 'tray', 'ashcan', 'fan', + 'plate', 'monitor', 'bulletin board', 'radiator', 'glass', 'clock', + 'flag'), + 'palette': [(204, 5, 255), (230, 230, 230), (224, 5, 255), + (150, 5, 61), (8, 255, 51), (255, 6, 82), (255, 51, 7), + (204, 70, 3), (0, 102, 200), (255, 6, 51), (11, 102, 255), + (255, 7, 71), (220, 220, 220), (8, 255, 214), + (7, 255, 224), (255, 184, 6), (10, 255, 71), (7, 255, 255), + (224, 255, 8), (102, 8, 255), (255, 61, 6), (255, 194, 7), + (0, 255, 20), (255, 8, 41), (255, 5, 153), (6, 51, 255), + (235, 12, 255), (0, 163, 255), (250, 10, 15), (20, 255, 0), + (255, 224, 0), (0, 0, 255), (255, 71, 0), (0, 235, 255), + (0, 173, 255), (0, 255, 245), (0, 255, 112), (0, 255, 133), + (255, 0, 0), (255, 163, 0), (194, 255, 0), (0, 143, 255), + (51, 255, 0), (0, 82, 255), (0, 255, 41), (0, 255, 173), + (10, 0, 255), (173, 255, 0), (255, 92, 0), (255, 0, 245), + (255, 0, 102), (255, 173, 0), (255, 0, 20), (0, 31, 255), + (0, 255, 61), (0, 71, 255), (255, 0, 204), (0, 255, 194), + (0, 255, 82), (0, 112, 255), (51, 0, 255), (0, 122, 255), + (255, 153, 0), (0, 255, 10), (163, 255, 0), (255, 235, 0), + (8, 184, 170), (184, 0, 255), (255, 0, 31), (0, 214, 255), + (255, 0, 112), (92, 255, 0), (70, 184, 160), (163, 0, 255), + (71, 255, 0), (255, 0, 163), (255, 204, 0), (255, 0, 143), + (133, 255, 0), (255, 0, 235), (245, 0, 255), (255, 0, 122), + (255, 245, 0), (214, 255, 0), (0, 204, 255), (255, 255, 0), + (0, 153, 255), (0, 41, 255), (0, 255, 204), (41, 0, 255), + (41, 255, 0), (173, 0, 255), (0, 245, 255), (0, 255, 184), + (0, 92, 255), (184, 255, 0), (255, 214, 0), (25, 194, 194), + (102, 255, 0), (92, 0, 255)], + } + + +@DATASETS.register_module() +class ADE20KSegDataset(BaseSegDataset): + """ADE20K dataset. + + In segmentation map annotation for ADE20K, 0 stands for background, which + is not included in 150 categories. The ``img_suffix`` is fixed to '.jpg', + and ``seg_map_suffix`` is fixed to '.png'. + """ + METAINFO = dict( + classes=('wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', + 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk', + 'person', 'earth', 'door', 'table', 'mountain', 'plant', + 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', + 'shelf', 'house', 'sea', 'mirror', 'rug', 'field', 'armchair', + 'seat', 'fence', 'desk', 'rock', 'wardrobe', 'lamp', + 'bathtub', 'railing', 'cushion', 'base', 'box', 'column', + 'signboard', 'chest of drawers', 'counter', 'sand', 'sink', + 'skyscraper', 'fireplace', 'refrigerator', 'grandstand', + 'path', 'stairs', 'runway', 'case', 'pool table', 'pillow', + 'screen door', 'stairway', 'river', 'bridge', 'bookcase', + 'blind', 'coffee table', 'toilet', 'flower', 'book', 'hill', + 'bench', 'countertop', 'stove', 'palm', 'kitchen island', + 'computer', 'swivel chair', 'boat', 'bar', 'arcade machine', + 'hovel', 'bus', 'towel', 'light', 'truck', 'tower', + 'chandelier', 'awning', 'streetlight', 'booth', + 'television receiver', 'airplane', 'dirt track', 'apparel', + 'pole', 'land', 'bannister', 'escalator', 'ottoman', 'bottle', + 'buffet', 'poster', 'stage', 'van', 'ship', 'fountain', + 'conveyer belt', 'canopy', 'washer', 'plaything', + 'swimming pool', 'stool', 'barrel', 'basket', 'waterfall', + 'tent', 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food', + 'step', 'tank', 'trade name', 'microwave', 'pot', 'animal', + 'bicycle', 'lake', 'dishwasher', 'screen', 'blanket', + 'sculpture', 'hood', 'sconce', 'vase', 'traffic light', + 'tray', 'ashcan', 'fan', 'pier', 'crt screen', 'plate', + 'monitor', 'bulletin board', 'shower', 'radiator', 'glass', + 'clock', 'flag'), + palette=ADE_PALETTE) + + def __init__(self, + img_suffix='.jpg', + seg_map_suffix='.png', + return_classes=False, + **kwargs) -> None: + self.return_classes = return_classes + super().__init__( + img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotation from directory or annotation file. + + Returns: + List[dict]: All data info of dataset. + """ + data_list = [] + img_dir = self.data_prefix.get('img_path', None) + ann_dir = self.data_prefix.get('seg_map_path', None) + for img in fileio.list_dir_or_file( + dir_path=img_dir, + list_dir=False, + suffix=self.img_suffix, + recursive=True, + backend_args=self.backend_args): + data_info = dict(img_path=osp.join(img_dir, img)) + if ann_dir is not None: + seg_map = img.replace(self.img_suffix, self.seg_map_suffix) + data_info['seg_map_path'] = osp.join(ann_dir, seg_map) + data_info['label_map'] = self.label_map + if self.return_classes: + data_info['text'] = list(self._metainfo['classes']) + data_list.append(data_info) + return data_list diff --git a/mmdet_code/SR-TOD/mmdet/datasets/airbus.py b/mmdet_code/SR-TOD/mmdet/datasets/airbus.py new file mode 100644 index 0000000000000000000000000000000000000000..2b59c027dba89475bd8ffc8a6fc537767d33f651 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/airbus.py @@ -0,0 +1,188 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class AirBusDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('ship',), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/aitod.py b/mmdet_code/SR-TOD/mmdet/datasets/aitod.py new file mode 100644 index 0000000000000000000000000000000000000000..2f6c2845a49c5fb63384038085544593b11a9bbb --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/aitod.py @@ -0,0 +1,188 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class AITODDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('airplane', 'bridge', 'storage-tank', 'ship', 'swimming-pool', 'vehicle', 'person', 'wind-mill'), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/api_wrappers/__init__.py b/mmdet_code/SR-TOD/mmdet/datasets/api_wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a27afc46028ae184cb121caad6b320c5acd50790 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/api_wrappers/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .coco_api import COCO, COCOeval, COCOPanoptic + +__all__ = ['COCO', 'COCOeval', 'COCOPanoptic'] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/api_wrappers/coco_api.py b/mmdet_code/SR-TOD/mmdet/datasets/api_wrappers/coco_api.py new file mode 100644 index 0000000000000000000000000000000000000000..40f7f2c9b930de3dadd967db9d131913fc9bf54c --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/api_wrappers/coco_api.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# This file add snake case alias for coco api + +import warnings +from collections import defaultdict +from typing import List, Optional, Union + +import pycocotools +from pycocotools.coco import COCO as _COCO +from pycocotools.cocoeval import COCOeval as _COCOeval + + +class COCO(_COCO): + """This class is almost the same as official pycocotools package. + + It implements some snake case function aliases. So that the COCO class has + the same interface as LVIS class. + """ + + def __init__(self, annotation_file=None): + if getattr(pycocotools, '__version__', '0') >= '12.0.2': + warnings.warn( + 'mmpycocotools is deprecated. Please install official pycocotools by "pip install pycocotools"', # noqa: E501 + UserWarning) + super().__init__(annotation_file=annotation_file) + self.img_ann_map = self.imgToAnns + self.cat_img_map = self.catToImgs + + def get_ann_ids(self, img_ids=[], cat_ids=[], area_rng=[], iscrowd=None): + return self.getAnnIds(img_ids, cat_ids, area_rng, iscrowd) + + def get_cat_ids(self, cat_names=[], sup_names=[], cat_ids=[]): + return self.getCatIds(cat_names, sup_names, cat_ids) + + def get_img_ids(self, img_ids=[], cat_ids=[]): + return self.getImgIds(img_ids, cat_ids) + + def load_anns(self, ids): + return self.loadAnns(ids) + + def load_cats(self, ids): + return self.loadCats(ids) + + def load_imgs(self, ids): + return self.loadImgs(ids) + + +# just for the ease of import +COCOeval = _COCOeval + + +class COCOPanoptic(COCO): + """This wrapper is for loading the panoptic style annotation file. + + The format is shown in the CocoPanopticDataset class. + + Args: + annotation_file (str, optional): Path of annotation file. + Defaults to None. + """ + + def __init__(self, annotation_file: Optional[str] = None) -> None: + super(COCOPanoptic, self).__init__(annotation_file) + + def createIndex(self) -> None: + """Create index.""" + # create index + print('creating index...') + # anns stores 'segment_id -> annotation' + anns, cats, imgs = {}, {}, {} + img_to_anns, cat_to_imgs = defaultdict(list), defaultdict(list) + if 'annotations' in self.dataset: + for ann in self.dataset['annotations']: + for seg_ann in ann['segments_info']: + # to match with instance.json + seg_ann['image_id'] = ann['image_id'] + img_to_anns[ann['image_id']].append(seg_ann) + # segment_id is not unique in coco dataset orz... + # annotations from different images but + # may have same segment_id + if seg_ann['id'] in anns.keys(): + anns[seg_ann['id']].append(seg_ann) + else: + anns[seg_ann['id']] = [seg_ann] + + # filter out annotations from other images + img_to_anns_ = defaultdict(list) + for k, v in img_to_anns.items(): + img_to_anns_[k] = [x for x in v if x['image_id'] == k] + img_to_anns = img_to_anns_ + + if 'images' in self.dataset: + for img_info in self.dataset['images']: + img_info['segm_file'] = img_info['file_name'].replace( + 'jpg', 'png') + imgs[img_info['id']] = img_info + + if 'categories' in self.dataset: + for cat in self.dataset['categories']: + cats[cat['id']] = cat + + if 'annotations' in self.dataset and 'categories' in self.dataset: + for ann in self.dataset['annotations']: + for seg_ann in ann['segments_info']: + cat_to_imgs[seg_ann['category_id']].append(ann['image_id']) + + print('index created!') + + self.anns = anns + self.imgToAnns = img_to_anns + self.catToImgs = cat_to_imgs + self.imgs = imgs + self.cats = cats + + def load_anns(self, + ids: Union[List[int], int] = []) -> Optional[List[dict]]: + """Load anns with the specified ids. + + ``self.anns`` is a list of annotation lists instead of a + list of annotations. + + Args: + ids (Union[List[int], int]): Integer ids specifying anns. + + Returns: + anns (List[dict], optional): Loaded ann objects. + """ + anns = [] + + if hasattr(ids, '__iter__') and hasattr(ids, '__len__'): + # self.anns is a list of annotation lists instead of + # a list of annotations + for id in ids: + anns += self.anns[id] + return anns + elif type(ids) == int: + return self.anns[ids] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/base_det_dataset.py b/mmdet_code/SR-TOD/mmdet/datasets/base_det_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..57bc7098387ee0bec2d53641c1ea7ce2c3cdf618 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/base_det_dataset.py @@ -0,0 +1,124 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List, Optional + +from mmengine.dataset import BaseDataset +from mmengine.fileio import load +from mmengine.utils import is_abs + +from ..registry import DATASETS + + +@DATASETS.register_module() +class BaseDetDataset(BaseDataset): + """Base dataset for detection. + + Args: + proposal_file (str, optional): Proposals file path. Defaults to None. + file_client_args (dict): Arguments to instantiate the + corresponding backend in mmdet <= 3.0.0rc6. Defaults to None. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + return_classes (bool): Whether to return class information + for open vocabulary-based algorithms. Defaults to False. + """ + + def __init__(self, + *args, + seg_map_suffix: str = '.png', + proposal_file: Optional[str] = None, + file_client_args: dict = None, + backend_args: dict = None, + return_classes: bool = False, + **kwargs) -> None: + self.seg_map_suffix = seg_map_suffix + self.proposal_file = proposal_file + self.backend_args = backend_args + self.return_classes = return_classes + if file_client_args is not None: + raise RuntimeError( + 'The `file_client_args` is deprecated, ' + 'please use `backend_args` instead, please refer to' + 'https://github.com/open-mmlab/mmdetection/blob/main/configs/_base_/datasets/coco_detection.py' # noqa: E501 + ) + super().__init__(*args, **kwargs) + + def full_init(self) -> None: + """Load annotation file and set ``BaseDataset._fully_initialized`` to + True. + + If ``lazy_init=False``, ``full_init`` will be called during the + instantiation and ``self._fully_initialized`` will be set to True. If + ``obj._fully_initialized=False``, the class method decorated by + ``force_full_init`` will call ``full_init`` automatically. + + Several steps to initialize annotation: + + - load_data_list: Load annotations from annotation file. + - load_proposals: Load proposals from proposal file, if + `self.proposal_file` is not None. + - filter data information: Filter annotations according to + filter_cfg. + - slice_data: Slice dataset according to ``self._indices`` + - serialize_data: Serialize ``self.data_list`` if + ``self.serialize_data`` is True. + """ + if self._fully_initialized: + return + # load data information + self.data_list = self.load_data_list() + # get proposals from file + if self.proposal_file is not None: + self.load_proposals() + # filter illegal data, such as data that has no annotations. + self.data_list = self.filter_data() + + # Get subset data according to indices. + if self._indices is not None: + self.data_list = self._get_unserialized_subset(self._indices) + + # serialize data_list + if self.serialize_data: + self.data_bytes, self.data_address = self._serialize_data() + + self._fully_initialized = True + + def load_proposals(self) -> None: + """Load proposals from proposals file. + + The `proposals_list` should be a dict[img_path: proposals] + with the same length as `data_list`. And the `proposals` should be + a `dict` or :obj:`InstanceData` usually contains following keys. + + - bboxes (np.ndarry): Has a shape (num_instances, 4), + the last dimension 4 arrange as (x1, y1, x2, y2). + - scores (np.ndarry): Classification scores, has a shape + (num_instance, ). + """ + # TODO: Add Unit Test after fully support Dump-Proposal Metric + if not is_abs(self.proposal_file): + self.proposal_file = osp.join(self.data_root, self.proposal_file) + proposals_list = load( + self.proposal_file, backend_args=self.backend_args) + assert len(self.data_list) == len(proposals_list) + for data_info in self.data_list: + img_path = data_info['img_path'] + # `file_name` is the key to obtain the proposals from the + # `proposals_list`. + file_name = osp.join( + osp.split(osp.split(img_path)[0])[-1], + osp.split(img_path)[-1]) + proposals = proposals_list[file_name] + data_info['proposals'] = proposals + + def get_cat_ids(self, idx: int) -> List[int]: + """Get COCO category ids by index. + + Args: + idx (int): Index of data. + + Returns: + List[int]: All categories in the image of specified index. + """ + instances = self.get_data_info(idx)['instances'] + return [instance['bbox_label'] for instance in instances] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/base_semseg_dataset.py b/mmdet_code/SR-TOD/mmdet/datasets/base_semseg_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..d10f762a21a897ab8274fbe9eefab054691a7c60 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/base_semseg_dataset.py @@ -0,0 +1,265 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import Callable, Dict, List, Optional, Sequence, Union + +import mmengine +import mmengine.fileio as fileio +import numpy as np +from mmengine.dataset import BaseDataset, Compose + +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class BaseSegDataset(BaseDataset): + """Custom dataset for semantic segmentation. An example of file structure + is as followed. + + .. code-block:: none + + ├── data + │ ├── my_dataset + │ │ ├── img_dir + │ │ │ ├── train + │ │ │ │ ├── xxx{img_suffix} + │ │ │ │ ├── yyy{img_suffix} + │ │ │ │ ├── zzz{img_suffix} + │ │ │ ├── val + │ │ ├── ann_dir + │ │ │ ├── train + │ │ │ │ ├── xxx{seg_map_suffix} + │ │ │ │ ├── yyy{seg_map_suffix} + │ │ │ │ ├── zzz{seg_map_suffix} + │ │ │ ├── val + + The img/gt_semantic_seg pair of BaseSegDataset should be of the same + except suffix. A valid img/gt_semantic_seg filename pair should be like + ``xxx{img_suffix}`` and ``xxx{seg_map_suffix}`` (extension is also included + in the suffix). If split is given, then ``xxx`` is specified in txt file. + Otherwise, all files in ``img_dir/``and ``ann_dir`` will be loaded. + Please refer to ``docs/en/tutorials/new_dataset.md`` for more details. + + + Args: + ann_file (str): Annotation file path. Defaults to ''. + metainfo (dict, optional): Meta information for dataset, such as + specify classes to load. Defaults to None. + data_root (str, optional): The root directory for ``data_prefix`` and + ``ann_file``. Defaults to None. + data_prefix (dict, optional): Prefix for training data. Defaults to + dict(img_path=None, seg_map_path=None). + img_suffix (str): Suffix of images. Default: '.jpg' + seg_map_suffix (str): Suffix of segmentation maps. Default: '.png' + filter_cfg (dict, optional): Config for filter data. Defaults to None. + indices (int or Sequence[int], optional): Support using first few + data in annotation file to facilitate training/testing on a smaller + dataset. Defaults to None which means using all ``data_infos``. + serialize_data (bool, optional): Whether to hold memory using + serialized objects, when enabled, data loader workers can use + shared RAM from master process instead of making a copy. Defaults + to True. + pipeline (list, optional): Processing pipeline. Defaults to []. + test_mode (bool, optional): ``test_mode=True`` means in test phase. + Defaults to False. + lazy_init (bool, optional): Whether to load annotation during + instantiation. In some cases, such as visualization, only the meta + information of the dataset is needed, which is not necessary to + load annotation file. ``Basedataset`` can skip load annotations to + save time by set ``lazy_init=True``. Defaults to False. + use_label_map (bool, optional): Whether to use label map. + Defaults to False. + max_refetch (int, optional): If ``Basedataset.prepare_data`` get a + None img. The maximum extra number of cycles to get a valid + image. Defaults to 1000. + backend_args (dict, Optional): Arguments to instantiate a file backend. + See https://mmengine.readthedocs.io/en/latest/api/fileio.htm + for details. Defaults to None. + Notes: mmcv>=2.0.0rc4 required. + """ + METAINFO: dict = dict() + + def __init__(self, + ann_file: str = '', + img_suffix='.jpg', + seg_map_suffix='.png', + metainfo: Optional[dict] = None, + data_root: Optional[str] = None, + data_prefix: dict = dict(img_path='', seg_map_path=''), + filter_cfg: Optional[dict] = None, + indices: Optional[Union[int, Sequence[int]]] = None, + serialize_data: bool = True, + pipeline: List[Union[dict, Callable]] = [], + test_mode: bool = False, + lazy_init: bool = False, + use_label_map: bool = False, + max_refetch: int = 1000, + backend_args: Optional[dict] = None) -> None: + + self.img_suffix = img_suffix + self.seg_map_suffix = seg_map_suffix + self.backend_args = backend_args.copy() if backend_args else None + + self.data_root = data_root + self.data_prefix = copy.copy(data_prefix) + self.ann_file = ann_file + self.filter_cfg = copy.deepcopy(filter_cfg) + self._indices = indices + self.serialize_data = serialize_data + self.test_mode = test_mode + self.max_refetch = max_refetch + self.data_list: List[dict] = [] + self.data_bytes: np.ndarray + + # Set meta information. + self._metainfo = self._load_metainfo(copy.deepcopy(metainfo)) + + # Get label map for custom classes + new_classes = self._metainfo.get('classes', None) + self.label_map = self.get_label_map( + new_classes) if use_label_map else None + self._metainfo.update(dict(label_map=self.label_map)) + + # Update palette based on label map or generate palette + # if it is not defined + updated_palette = self._update_palette() + self._metainfo.update(dict(palette=updated_palette)) + + # Join paths. + if self.data_root is not None: + self._join_prefix() + + # Build pipeline. + self.pipeline = Compose(pipeline) + # Full initialize the dataset. + if not lazy_init: + self.full_init() + + if test_mode: + assert self._metainfo.get('classes') is not None, \ + 'dataset metainfo `classes` should be specified when testing' + + @classmethod + def get_label_map(cls, + new_classes: Optional[Sequence] = None + ) -> Union[Dict, None]: + """Require label mapping. + + The ``label_map`` is a dictionary, its keys are the old label ids and + its values are the new label ids, and is used for changing pixel + labels in load_annotations. If and only if old classes in cls.METAINFO + is not equal to new classes in self._metainfo and nether of them is not + None, `label_map` is not None. + + Args: + new_classes (list, tuple, optional): The new classes name from + metainfo. Default to None. + + + Returns: + dict, optional: The mapping from old classes in cls.METAINFO to + new classes in self._metainfo + """ + old_classes = cls.METAINFO.get('classes', None) + if (new_classes is not None and old_classes is not None + and list(new_classes) != list(old_classes)): + + label_map = {} + if not set(new_classes).issubset(cls.METAINFO['classes']): + raise ValueError( + f'new classes {new_classes} is not a ' + f'subset of classes {old_classes} in METAINFO.') + for i, c in enumerate(old_classes): + if c not in new_classes: + # 0 is background + label_map[i] = 0 + else: + label_map[i] = new_classes.index(c) + return label_map + else: + return None + + def _update_palette(self) -> list: + """Update palette after loading metainfo. + + If length of palette is equal to classes, just return the palette. + If palette is not defined, it will randomly generate a palette. + If classes is updated by customer, it will return the subset of + palette. + + Returns: + Sequence: Palette for current dataset. + """ + palette = self._metainfo.get('palette', []) + classes = self._metainfo.get('classes', []) + # palette does match classes + if len(palette) == len(classes): + return palette + + if len(palette) == 0: + # Get random state before set seed, and restore + # random state later. + # It will prevent loss of randomness, as the palette + # may be different in each iteration if not specified. + # See: https://github.com/open-mmlab/mmdetection/issues/5844 + state = np.random.get_state() + np.random.seed(42) + # random palette + new_palette = np.random.randint( + 0, 255, size=(len(classes), 3)).tolist() + np.random.set_state(state) + elif len(palette) >= len(classes) and self.label_map is not None: + new_palette = [] + # return subset of palette + for old_id, new_id in sorted( + self.label_map.items(), key=lambda x: x[1]): + # 0 is background + if new_id != 0: + new_palette.append(palette[old_id]) + new_palette = type(palette)(new_palette) + elif len(palette) >= len(classes): + # Allow palette length is greater than classes. + return palette + else: + raise ValueError('palette does not match classes ' + f'as metainfo is {self._metainfo}.') + return new_palette + + def load_data_list(self) -> List[dict]: + """Load annotation from directory or annotation file. + + Returns: + list[dict]: All data info of dataset. + """ + data_list = [] + img_dir = self.data_prefix.get('img_path', None) + ann_dir = self.data_prefix.get('seg_map_path', None) + if not osp.isdir(self.ann_file) and self.ann_file: + assert osp.isfile(self.ann_file), \ + f'Failed to load `ann_file` {self.ann_file}' + lines = mmengine.list_from_file( + self.ann_file, backend_args=self.backend_args) + for line in lines: + img_name = line.strip() + data_info = dict( + img_path=osp.join(img_dir, img_name + self.img_suffix)) + if ann_dir is not None: + seg_map = img_name + self.seg_map_suffix + data_info['seg_map_path'] = osp.join(ann_dir, seg_map) + data_info['label_map'] = self.label_map + data_list.append(data_info) + else: + for img in fileio.list_dir_or_file( + dir_path=img_dir, + list_dir=False, + suffix=self.img_suffix, + recursive=True, + backend_args=self.backend_args): + data_info = dict(img_path=osp.join(img_dir, img)) + if ann_dir is not None: + seg_map = img.replace(self.img_suffix, self.seg_map_suffix) + data_info['seg_map_path'] = osp.join(ann_dir, seg_map) + data_info['label_map'] = self.label_map + data_list.append(data_info) + data_list = sorted(data_list, key=lambda x: x['img_path']) + return data_list diff --git a/mmdet_code/SR-TOD/mmdet/datasets/base_video_dataset.py b/mmdet_code/SR-TOD/mmdet/datasets/base_video_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0a4a7a25f16206f06c7b64a7ce4c3588efd5455e --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/base_video_dataset.py @@ -0,0 +1,304 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from collections import defaultdict +from typing import Any, List, Tuple + +import mmengine.fileio as fileio +from mmengine.dataset import BaseDataset +from mmengine.logging import print_log + +from mmdet.datasets.api_wrappers import COCO +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class BaseVideoDataset(BaseDataset): + """Base video dataset for VID, MOT and VIS tasks.""" + + META = dict(classes=None) + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def __init__(self, *args, backend_args: dict = None, **kwargs): + self.backend_args = backend_args + super().__init__(*args, **kwargs) + + def load_data_list(self) -> Tuple[List[dict], List]: + """Load annotations from an annotation file named as ``self.ann_file``. + + Returns: + tuple(list[dict], list): A list of annotation and a list of + valid data indices. + """ + with fileio.get_local_path(self.ann_file) as local_path: + self.coco = COCO(local_path) + # The order of returned `cat_ids` will not + # change with the order of the classes + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + # used in `filter_data` + self.img_ids_with_ann = set() + + img_ids = self.coco.get_img_ids() + total_ann_ids = [] + # if ``video_id`` is not in the annotation file, we will assign a big + # unique video_id for this video. + single_video_id = 100000 + videos = {} + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + if 'video_id' not in raw_img_info: + single_video_id = single_video_id + 1 + video_id = single_video_id + else: + video_id = raw_img_info['video_id'] + + if video_id not in videos: + videos[video_id] = { + 'video_id': video_id, + 'images': [], + 'video_length': 0 + } + + videos[video_id]['video_length'] += 1 + ann_ids = self.coco.get_ann_ids( + img_ids=[img_id], cat_ids=self.cat_ids) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info( + dict(raw_img_info=raw_img_info, raw_ann_info=raw_ann_info)) + + if len(parsed_data_info['instances']) > 0: + self.img_ids_with_ann.add(parsed_data_info['img_id']) + + videos[video_id]['images'].append(parsed_data_info) + + data_list = [v for v in videos.values()] + + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> dict: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information loaded from + ``ann_file``. + + Returns: + dict: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + data_info = {} + + data_info.update(img_info) + if self.data_prefix.get('img_path', None) is not None: + img_path = osp.join(self.data_prefix['img_path'], + img_info['file_name']) + else: + img_path = img_info['file_name'] + data_info['img_path'] = img_path + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + if ann.get('instance_id', None): + instance['instance_id'] = ann['instance_id'] + else: + # image dataset usually has no `instance_id`. + # Therefore, we set it to `i`. + instance['instance_id'] = i + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[int]: + """Filter image annotations according to filter_cfg. + + Returns: + list[int]: Filtered results. + """ + if self.test_mode: + return self.data_list + + num_imgs_before_filter = sum( + [len(info['images']) for info in self.data_list]) + num_imgs_after_filter = 0 + + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= self.img_ids_with_ann + + new_data_list = [] + for video_data_info in self.data_list: + imgs_data_info = video_data_info['images'] + valid_imgs_data_info = [] + + for data_info in imgs_data_info: + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + # TODO: simplify these conditions + if self.filter_cfg is None: + if img_id not in ids_in_cat: + video_data_info['video_length'] -= 1 + continue + if min(width, height) >= 32: + valid_imgs_data_info.append(data_info) + num_imgs_after_filter += 1 + else: + video_data_info['video_length'] -= 1 + else: + if self.filter_cfg.get('filter_empty_gt', + True) and img_id not in ids_in_cat: + video_data_info['video_length'] -= 1 + continue + if min(width, height) >= self.filter_cfg.get( + 'min_size', 32): + valid_imgs_data_info.append(data_info) + num_imgs_after_filter += 1 + else: + video_data_info['video_length'] -= 1 + video_data_info['images'] = valid_imgs_data_info + new_data_list.append(video_data_info) + + print_log( + 'The number of samples before and after filtering: ' + f'{num_imgs_before_filter} / {num_imgs_after_filter}', 'current') + return new_data_list + + def prepare_data(self, idx) -> Any: + """Get date processed by ``self.pipeline``. Note that ``idx`` is a + video index in default since the base element of video dataset is a + video. However, in some cases, we need to specific both the video index + and frame index. For example, in traing mode, we may want to sample the + specific frames and all the frames must be sampled once in a epoch; in + test mode, we may want to output data of a single image rather than the + whole video for saving memory. + + Args: + idx (int): The index of ``data_info``. + + Returns: + Any: Depends on ``self.pipeline``. + """ + if isinstance(idx, tuple): + assert len(idx) == 2, 'The length of idx must be 2: ' + '(video_index, frame_index)' + video_idx, frame_idx = idx[0], idx[1] + else: + video_idx, frame_idx = idx, None + + data_info = self.get_data_info(video_idx) + if self.test_mode: + # Support two test_mode: frame-level and video-level + final_data_info = defaultdict(list) + if frame_idx is None: + frames_idx_list = list(range(data_info['video_length'])) + else: + frames_idx_list = [frame_idx] + for index in frames_idx_list: + frame_ann = data_info['images'][index] + frame_ann['video_id'] = data_info['video_id'] + # Collate data_list (list of dict to dict of list) + for key, value in frame_ann.items(): + final_data_info[key].append(value) + # copy the info in video-level into img-level + # TODO: the value of this key is the same as that of + # `video_length` in test mode + final_data_info['ori_video_length'].append( + data_info['video_length']) + + final_data_info['video_length'] = [len(frames_idx_list) + ] * len(frames_idx_list) + return self.pipeline(final_data_info) + else: + # Specify `key_frame_id` for the frame sampling in the pipeline + if frame_idx is not None: + data_info['key_frame_id'] = frame_idx + return self.pipeline(data_info) + + def get_cat_ids(self, index) -> List[int]: + """Following image detection, we provide this interface function. Get + category ids by video index and frame index. + + Args: + index: The index of the dataset. It support two kinds of inputs: + Tuple: + video_idx (int): Index of video. + frame_idx (int): Index of frame. + Int: Index of video. + + Returns: + List[int]: All categories in the image of specified video index + and frame index. + """ + if isinstance(index, tuple): + assert len( + index + ) == 2, f'Expect the length of index is 2, but got {len(index)}' + video_idx, frame_idx = index + instances = self.get_data_info( + video_idx)['images'][frame_idx]['instances'] + return [instance['bbox_label'] for instance in instances] + else: + cat_ids = [] + for img in self.get_data_info(index)['images']: + for instance in img['instances']: + cat_ids.append(instance['bbox_label']) + return cat_ids + + @property + def num_all_imgs(self): + """Get the number of all the images in this video dataset.""" + return sum( + [len(self.get_data_info(i)['images']) for i in range(len(self))]) + + def get_len_per_video(self, idx): + """Get length of one video. + + Args: + idx (int): Index of video. + + Returns: + int (int): The length of the video. + """ + return len(self.get_data_info(idx)['images']) diff --git a/mmdet_code/SR-TOD/mmdet/datasets/cityscapes.py b/mmdet_code/SR-TOD/mmdet/datasets/cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..09755eb1e8b0f0c278085bd2fafbb7247a3fc946 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/cityscapes.py @@ -0,0 +1,61 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Modified from https://github.com/facebookresearch/detectron2/blob/master/detectron2/data/datasets/cityscapes.py # noqa +# and https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalInstanceLevelSemanticLabeling.py # noqa + +from typing import List + +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class CityscapesDataset(CocoDataset): + """Dataset for Cityscapes.""" + + METAINFO = { + 'classes': ('person', 'rider', 'car', 'truck', 'bus', 'train', + 'motorcycle', 'bicycle'), + 'palette': [(220, 20, 60), (255, 0, 0), (0, 0, 142), (0, 0, 70), + (0, 60, 100), (0, 80, 100), (0, 0, 230), (119, 11, 32)] + } + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + all_is_crowd = all([ + instance['ignore_flag'] == 1 + for instance in data_info['instances'] + ]) + if filter_empty_gt and (img_id not in ids_in_cat or all_is_crowd): + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/coco.py b/mmdet_code/SR-TOD/mmdet/datasets/coco.py new file mode 100644 index 0000000000000000000000000000000000000000..277b75988da6accc54973b4983bf5a08c379b668 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/coco.py @@ -0,0 +1,200 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class CocoDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', + 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', + 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', + 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', + 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', + 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', + 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', + 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', + 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', + 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush'), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/coco_caption.py b/mmdet_code/SR-TOD/mmdet/datasets/coco_caption.py new file mode 100644 index 0000000000000000000000000000000000000000..ee695fe9a768f2be5345c6ad6bafc74177f252c0 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/coco_caption.py @@ -0,0 +1,32 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from pathlib import Path +from typing import List + +import mmengine +from mmengine.dataset import BaseDataset +from mmengine.fileio import get_file_backend + +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class CocoCaptionDataset(BaseDataset): + """COCO2014 Caption dataset.""" + + def load_data_list(self) -> List[dict]: + """Load data list.""" + img_prefix = self.data_prefix['img_path'] + annotations = mmengine.load(self.ann_file) + file_backend = get_file_backend(img_prefix) + + data_list = [] + for ann in annotations: + data_info = { + 'img_id': Path(ann['image']).stem.split('_')[-1], + 'img_path': file_backend.join_path(img_prefix, ann['image']), + 'gt_caption': ann['caption'], + } + + data_list.append(data_info) + + return data_list diff --git a/mmdet_code/SR-TOD/mmdet/datasets/coco_panoptic.py b/mmdet_code/SR-TOD/mmdet/datasets/coco_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ca78555095f8266c402be885a31cdfc24e5925 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/coco_panoptic.py @@ -0,0 +1,292 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import Callable, List, Optional, Sequence, Union + +from mmdet.registry import DATASETS +from .api_wrappers import COCOPanoptic +from .coco import CocoDataset + + +@DATASETS.register_module() +class CocoPanopticDataset(CocoDataset): + """Coco dataset for Panoptic segmentation. + + The annotation format is shown as follows. The `ann` field is optional + for testing. + + .. code-block:: none + + [ + { + 'filename': f'{image_id:012}.png', + 'image_id':9 + 'segments_info': + [ + { + 'id': 8345037, (segment_id in panoptic png, + convert from rgb) + 'category_id': 51, + 'iscrowd': 0, + 'bbox': (x1, y1, w, h), + 'area': 24315 + }, + ... + ] + }, + ... + ] + + Args: + ann_file (str): Annotation file path. Defaults to ''. + metainfo (dict, optional): Meta information for dataset, such as class + information. Defaults to None. + data_root (str, optional): The root directory for ``data_prefix`` and + ``ann_file``. Defaults to None. + data_prefix (dict, optional): Prefix for training data. Defaults to + ``dict(img=None, ann=None, seg=None)``. The prefix ``seg`` which is + for panoptic segmentation map must be not None. + filter_cfg (dict, optional): Config for filter data. Defaults to None. + indices (int or Sequence[int], optional): Support using first few + data in annotation file to facilitate training/testing on a smaller + dataset. Defaults to None which means using all ``data_infos``. + serialize_data (bool, optional): Whether to hold memory using + serialized objects, when enabled, data loader workers can use + shared RAM from master process instead of making a copy. Defaults + to True. + pipeline (list, optional): Processing pipeline. Defaults to []. + test_mode (bool, optional): ``test_mode=True`` means in test phase. + Defaults to False. + lazy_init (bool, optional): Whether to load annotation during + instantiation. In some cases, such as visualization, only the meta + information of the dataset is needed, which is not necessary to + load annotation file. ``Basedataset`` can skip load annotations to + save time by set ``lazy_init=False``. Defaults to False. + max_refetch (int, optional): If ``Basedataset.prepare_data`` get a + None img. The maximum extra number of cycles to get a valid + image. Defaults to 1000. + """ + + METAINFO = { + 'classes': + ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', + 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', + 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', + 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', + 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', + 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', + 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', + 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', + 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', + 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner', + 'blanket', 'bridge', 'cardboard', 'counter', 'curtain', 'door-stuff', + 'floor-wood', 'flower', 'fruit', 'gravel', 'house', 'light', + 'mirror-stuff', 'net', 'pillow', 'platform', 'playingfield', + 'railroad', 'river', 'road', 'roof', 'sand', 'sea', 'shelf', 'snow', + 'stairs', 'tent', 'towel', 'wall-brick', 'wall-stone', 'wall-tile', + 'wall-wood', 'water-other', 'window-blind', 'window-other', + 'tree-merged', 'fence-merged', 'ceiling-merged', 'sky-other-merged', + 'cabinet-merged', 'table-merged', 'floor-other-merged', + 'pavement-merged', 'mountain-merged', 'grass-merged', 'dirt-merged', + 'paper-merged', 'food-other-merged', 'building-other-merged', + 'rock-merged', 'wall-other-merged', 'rug-merged'), + 'thing_classes': + ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', + 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', + 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', + 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', + 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', + 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', + 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', + 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', + 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', + 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush'), + 'stuff_classes': + ('banner', 'blanket', 'bridge', 'cardboard', 'counter', 'curtain', + 'door-stuff', 'floor-wood', 'flower', 'fruit', 'gravel', 'house', + 'light', 'mirror-stuff', 'net', 'pillow', 'platform', 'playingfield', + 'railroad', 'river', 'road', 'roof', 'sand', 'sea', 'shelf', 'snow', + 'stairs', 'tent', 'towel', 'wall-brick', 'wall-stone', 'wall-tile', + 'wall-wood', 'water-other', 'window-blind', 'window-other', + 'tree-merged', 'fence-merged', 'ceiling-merged', 'sky-other-merged', + 'cabinet-merged', 'table-merged', 'floor-other-merged', + 'pavement-merged', 'mountain-merged', 'grass-merged', 'dirt-merged', + 'paper-merged', 'food-other-merged', 'building-other-merged', + 'rock-merged', 'wall-other-merged', 'rug-merged'), + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208), (255, 255, 128), (147, 211, 203), + (150, 100, 100), (168, 171, 172), (146, 112, 198), (210, 170, 100), + (92, 136, 89), (218, 88, 184), (241, 129, 0), (217, 17, 255), + (124, 74, 181), (70, 70, 70), (255, 228, 255), (154, 208, 0), + (193, 0, 92), (76, 91, 113), (255, 180, 195), (106, 154, 176), + (230, 150, 140), (60, 143, 255), (128, 64, 128), (92, 82, 55), + (254, 212, 124), (73, 77, 174), (255, 160, 98), (255, 255, 255), + (104, 84, 109), (169, 164, 131), (225, 199, 255), (137, 54, 74), + (135, 158, 223), (7, 246, 231), (107, 255, 200), (58, 41, 149), + (183, 121, 142), (255, 73, 97), (107, 142, 35), (190, 153, 153), + (146, 139, 141), (70, 130, 180), (134, 199, 156), (209, 226, 140), + (96, 36, 108), (96, 96, 96), (64, 170, 64), (152, 251, 152), + (208, 229, 228), (206, 186, 171), (152, 161, 64), (116, 112, 0), + (0, 114, 143), (102, 102, 156), (250, 141, 255)] + } + COCOAPI = COCOPanoptic + # ann_id is not unique in coco panoptic dataset. + ANN_ID_UNIQUE = False + + def __init__(self, + ann_file: str = '', + metainfo: Optional[dict] = None, + data_root: Optional[str] = None, + data_prefix: dict = dict(img=None, ann=None, seg=None), + filter_cfg: Optional[dict] = None, + indices: Optional[Union[int, Sequence[int]]] = None, + serialize_data: bool = True, + pipeline: List[Union[dict, Callable]] = [], + test_mode: bool = False, + lazy_init: bool = False, + max_refetch: int = 1000, + backend_args: dict = None, + **kwargs) -> None: + super().__init__( + ann_file=ann_file, + metainfo=metainfo, + data_root=data_root, + data_prefix=data_prefix, + filter_cfg=filter_cfg, + indices=indices, + serialize_data=serialize_data, + pipeline=pipeline, + test_mode=test_mode, + lazy_init=lazy_init, + max_refetch=max_refetch, + backend_args=backend_args, + **kwargs) + + def parse_data_info(self, raw_data_info: dict) -> dict: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file``. + + Returns: + dict: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + # filter out unmatched annotations which have + # same segment_id but belong to other image + ann_info = [ + ann for ann in ann_info if ann['image_id'] == img_info['img_id'] + ] + data_info = {} + + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].replace('jpg', 'png')) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['thing_classes'] + data_info['stuff_text'] = self.metainfo['stuff_classes'] + data_info['custom_entities'] = True # no important + + instances = [] + segments_info = [] + for ann in ann_info: + instance = {} + x1, y1, w, h = ann['bbox'] + if ann['area'] <= 0 or w < 1 or h < 1: + continue + bbox = [x1, y1, x1 + w, y1 + h] + category_id = ann['category_id'] + contiguous_cat_id = self.cat2label[category_id] + + is_thing = self.coco.load_cats(ids=category_id)[0]['isthing'] + if is_thing: + is_crowd = ann.get('iscrowd', False) + instance['bbox'] = bbox + instance['bbox_label'] = contiguous_cat_id + if not is_crowd: + instance['ignore_flag'] = 0 + else: + instance['ignore_flag'] = 1 + is_thing = False + + segment_info = { + 'id': ann['id'], + 'category': contiguous_cat_id, + 'is_thing': is_thing + } + segments_info.append(segment_info) + if len(instance) > 0 and is_thing: + instances.append(instance) + data_info['instances'] = instances + data_info['segments_info'] = segments_info + return data_info + + def filter_data(self) -> List[dict]: + """Filter images too small or without ground truth. + + Returns: + List[dict]: ``self.data_list`` after filtering. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + ids_with_ann = set() + # check whether images have legal thing annotations. + for data_info in self.data_list: + for segment_info in data_info['segments_info']: + if not segment_info['is_thing']: + continue + ids_with_ann.add(data_info['img_id']) + + valid_data_list = [] + for data_info in self.data_list: + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_with_ann: + continue + if min(width, height) >= min_size: + valid_data_list.append(data_info) + + return valid_data_list diff --git a/mmdet_code/SR-TOD/mmdet/datasets/coco_semantic.py b/mmdet_code/SR-TOD/mmdet/datasets/coco_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..752568454456c1e5edcb2a24c6c2b46f042cb334 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/coco_semantic.py @@ -0,0 +1,90 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .ade20k import ADE20KSegDataset + + +@DATASETS.register_module() +class CocoSegDataset(ADE20KSegDataset): + """COCO dataset. + + In segmentation map annotation for COCO. The ``img_suffix`` is fixed to + '.jpg', and ``seg_map_suffix`` is fixed to '.png'. + """ + + METAINFO = dict( + classes=( + 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', + 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', + 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', + 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', + 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', + 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', + 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', + 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', + 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', + 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', + 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner', + 'blanket', 'branch', 'bridge', 'building-other', 'bush', 'cabinet', + 'cage', 'cardboard', 'carpet', 'ceiling-other', 'ceiling-tile', + 'cloth', 'clothes', 'clouds', 'counter', 'cupboard', 'curtain', + 'desk-stuff', 'dirt', 'door-stuff', 'fence', 'floor-marble', + 'floor-other', 'floor-stone', 'floor-tile', 'floor-wood', 'flower', + 'fog', 'food-other', 'fruit', 'furniture-other', 'grass', 'gravel', + 'ground-other', 'hill', 'house', 'leaves', 'light', 'mat', 'metal', + 'mirror-stuff', 'moss', 'mountain', 'mud', 'napkin', 'net', + 'paper', 'pavement', 'pillow', 'plant-other', 'plastic', + 'platform', 'playingfield', 'railing', 'railroad', 'river', 'road', + 'rock', 'roof', 'rug', 'salad', 'sand', 'sea', 'shelf', + 'sky-other', 'skyscraper', 'snow', 'solid-other', 'stairs', + 'stone', 'straw', 'structural-other', 'table', 'tent', + 'textile-other', 'towel', 'tree', 'vegetable', 'wall-brick', + 'wall-concrete', 'wall-other', 'wall-panel', 'wall-stone', + 'wall-tile', 'wall-wood', 'water-other', 'waterdrops', + 'window-blind', 'window-other', 'wood'), + palette=[(120, 120, 120), (180, 120, 120), (6, 230, 230), (80, 50, 50), + (4, 200, 3), (120, 120, 80), (140, 140, 140), (204, 5, 255), + (230, 230, 230), (4, 250, 7), (224, 5, 255), (235, 255, 7), + (150, 5, 61), (120, 120, 70), (8, 255, 51), (255, 6, 82), + (143, 255, 140), (204, 255, 4), (255, 51, 7), (204, 70, 3), + (0, 102, 200), (61, 230, 250), (255, 6, 51), (11, 102, 255), + (255, 7, 71), (255, 9, 224), (9, 7, 230), (220, 220, 220), + (255, 9, 92), (112, 9, 255), (8, 255, 214), (7, 255, 224), + (255, 184, 6), (10, 255, 71), (255, 41, 10), (7, 255, 255), + (224, 255, 8), (102, 8, 255), (255, 61, 6), (255, 194, 7), + (255, 122, 8), (0, 255, 20), (255, 8, 41), (255, 5, 153), + (6, 51, 255), (235, 12, 255), (160, 150, 20), (0, 163, 255), + (140, 140, 140), (250, 10, 15), (20, 255, 0), (31, 255, 0), + (255, 31, 0), (255, 224, 0), (153, 255, 0), (0, 0, 255), + (255, 71, 0), (0, 235, 255), (0, 173, 255), (31, 0, 255), + (11, 200, 200), (255, 82, 0), (0, 255, 245), (0, 61, 255), + (0, 255, 112), (0, 255, 133), (255, 0, 0), (255, 163, 0), + (255, 102, 0), (194, 255, 0), (0, 143, 255), (51, 255, 0), + (0, 82, 255), (0, 255, 41), (0, 255, 173), (10, 0, 255), + (173, 255, 0), (0, 255, 153), (255, 92, 0), (255, 0, 255), + (255, 0, 245), (255, 0, 102), (255, 173, 0), (255, 0, 20), + (255, 184, 184), (0, 31, 255), (0, 255, 61), (0, 71, 255), + (255, 0, 204), (0, 255, 194), (0, 255, 82), (0, 10, 255), + (0, 112, 255), (51, 0, 255), (0, 194, 255), (0, 122, 255), + (0, 255, 163), (255, 153, 0), (0, 255, 10), (255, 112, 0), + (143, 255, 0), (82, 0, 255), (163, 255, 0), (255, 235, 0), + (8, 184, 170), (133, 0, 255), (0, 255, 92), (184, 0, 255), + (255, 0, 31), (0, 184, 255), (0, 214, 255), (255, 0, 112), + (92, 255, 0), (0, 224, 255), (112, 224, 255), (70, 184, 160), + (163, 0, 255), (153, 0, 255), (71, 255, 0), (255, 0, 163), + (255, 204, 0), (255, 0, 143), (0, 255, 235), (133, 255, 0), + (255, 0, 235), (245, 0, 255), (255, 0, 122), (255, 245, 0), + (10, 190, 212), (214, 255, 0), (0, 204, 255), (20, 0, 255), + (255, 255, 0), (0, 153, 255), (0, 41, 255), (0, 255, 204), + (41, 0, 255), (41, 255, 0), (173, 0, 255), (0, 245, 255), + (71, 0, 255), (122, 0, 255), (0, 255, 184), (0, 92, 255), + (184, 255, 0), (0, 133, 255), (255, 214, 0), (25, 194, 194), + (102, 255, 0), (92, 0, 255), (107, 255, 200), (58, 41, 149), + (183, 121, 142), (255, 73, 97), (107, 142, 35), + (190, 153, 153), (146, 139, 141), (70, 130, 180), + (134, 199, 156), (209, 226, 140), (96, 36, 108), (96, 96, 96), + (64, 170, 64), (152, 251, 152), (208, 229, 228), + (206, 186, 171), (152, 161, 64), (116, 112, 0), (0, 114, 143), + (102, 102, 156), (250, 141, 255)]) diff --git a/mmdet_code/SR-TOD/mmdet/datasets/crowdhuman.py b/mmdet_code/SR-TOD/mmdet/datasets/crowdhuman.py new file mode 100644 index 0000000000000000000000000000000000000000..650176ee545ba6a10a816517553b3b77718d945b --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/crowdhuman.py @@ -0,0 +1,159 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import json +import logging +import os.path as osp +import warnings +from typing import List, Union + +import mmcv +from mmengine.dist import get_rank +from mmengine.fileio import dump, get, get_text, load +from mmengine.logging import print_log +from mmengine.utils import ProgressBar + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class CrowdHumanDataset(BaseDetDataset): + r"""Dataset for CrowdHuman. + + Args: + data_root (str): The root directory for + ``data_prefix`` and ``ann_file``. + ann_file (str): Annotation file path. + extra_ann_file (str | optional):The path of extra image metas + for CrowdHuman. It can be created by CrowdHumanDataset + automatically or by tools/misc/get_crowdhuman_id_hw.py + manually. Defaults to None. + """ + + METAINFO = { + 'classes': ('person', ), + # palette is a list of color tuples, which is used for visualization. + 'palette': [(220, 20, 60)] + } + + def __init__(self, data_root, ann_file, extra_ann_file=None, **kwargs): + # extra_ann_file record the size of each image. This file is + # automatically created when you first load the CrowdHuman + # dataset by mmdet. + if extra_ann_file is not None: + self.extra_ann_exist = True + self.extra_anns = load(extra_ann_file) + else: + ann_file_name = osp.basename(ann_file) + if 'train' in ann_file_name: + self.extra_ann_file = osp.join(data_root, 'id_hw_train.json') + elif 'val' in ann_file_name: + self.extra_ann_file = osp.join(data_root, 'id_hw_val.json') + self.extra_ann_exist = False + if not osp.isfile(self.extra_ann_file): + print_log( + 'extra_ann_file does not exist, prepare to collect ' + 'image height and width...', + level=logging.INFO) + self.extra_anns = {} + else: + self.extra_ann_exist = True + self.extra_anns = load(self.extra_ann_file) + super().__init__(data_root=data_root, ann_file=ann_file, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + anno_strs = get_text( + self.ann_file, backend_args=self.backend_args).strip().split('\n') + print_log('loading CrowdHuman annotation...', level=logging.INFO) + data_list = [] + prog_bar = ProgressBar(len(anno_strs)) + for i, anno_str in enumerate(anno_strs): + anno_dict = json.loads(anno_str) + parsed_data_info = self.parse_data_info(anno_dict) + data_list.append(parsed_data_info) + prog_bar.update() + if not self.extra_ann_exist and get_rank() == 0: + # TODO: support file client + try: + dump(self.extra_anns, self.extra_ann_file, file_format='json') + except: # noqa + warnings.warn( + 'Cache files can not be saved automatically! To speed up' + 'loading the dataset, please manually generate the cache' + ' file by file tools/misc/get_crowdhuman_id_hw.py') + + print_log( + f'\nsave extra_ann_file in {self.data_root}', + level=logging.INFO) + + del self.extra_anns + print_log('\nDone', level=logging.INFO) + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + data_info = {} + img_path = osp.join(self.data_prefix['img'], + f"{raw_data_info['ID']}.jpg") + data_info['img_path'] = img_path + data_info['img_id'] = raw_data_info['ID'] + + if not self.extra_ann_exist: + img_bytes = get(img_path, backend_args=self.backend_args) + img = mmcv.imfrombytes(img_bytes, backend='cv2') + data_info['height'], data_info['width'] = img.shape[:2] + self.extra_anns[raw_data_info['ID']] = img.shape[:2] + del img, img_bytes + else: + data_info['height'], data_info['width'] = self.extra_anns[ + raw_data_info['ID']] + + instances = [] + for i, ann in enumerate(raw_data_info['gtboxes']): + instance = {} + if ann['tag'] not in self.metainfo['classes']: + instance['bbox_label'] = -1 + instance['ignore_flag'] = 1 + else: + instance['bbox_label'] = self.metainfo['classes'].index( + ann['tag']) + instance['ignore_flag'] = 0 + if 'extra' in ann: + if 'ignore' in ann['extra']: + if ann['extra']['ignore'] != 0: + instance['bbox_label'] = -1 + instance['ignore_flag'] = 1 + + x1, y1, w, h = ann['fbox'] + bbox = [x1, y1, x1 + w, y1 + h] + instance['bbox'] = bbox + + # Record the full bbox(fbox), head bbox(hbox) and visible + # bbox(vbox) as additional information. If you need to use + # this information, you just need to design the pipeline + # instead of overriding the CrowdHumanDataset. + instance['fbox'] = bbox + hbox = ann['hbox'] + instance['hbox'] = [ + hbox[0], hbox[1], hbox[0] + hbox[2], hbox[1] + hbox[3] + ] + vbox = ann['vbox'] + instance['vbox'] = [ + vbox[0], vbox[1], vbox[0] + vbox[2], vbox[1] + vbox[3] + ] + + instances.append(instance) + + data_info['instances'] = instances + return data_info diff --git a/mmdet_code/SR-TOD/mmdet/datasets/dataset_wrappers.py b/mmdet_code/SR-TOD/mmdet/datasets/dataset_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..64f7e1ad6b510012578cbbbc2c9435692ebecee7 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/dataset_wrappers.py @@ -0,0 +1,169 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import collections +import copy +from typing import Sequence, Union + +from mmengine.dataset import BaseDataset, force_full_init + +from mmdet.registry import DATASETS, TRANSFORMS + + +@DATASETS.register_module() +class MultiImageMixDataset: + """A wrapper of multiple images mixed dataset. + + Suitable for training on multiple images mixed data augmentation like + mosaic and mixup. For the augmentation pipeline of mixed image data, + the `get_indexes` method needs to be provided to obtain the image + indexes, and you can set `skip_flags` to change the pipeline running + process. At the same time, we provide the `dynamic_scale` parameter + to dynamically change the output image size. + + Args: + dataset (:obj:`CustomDataset`): The dataset to be mixed. + pipeline (Sequence[dict]): Sequence of transform object or + config dict to be composed. + dynamic_scale (tuple[int], optional): The image scale can be changed + dynamically. Default to None. It is deprecated. + skip_type_keys (list[str], optional): Sequence of type string to + be skip pipeline. Default to None. + max_refetch (int): The maximum number of retry iterations for getting + valid results from the pipeline. If the number of iterations is + greater than `max_refetch`, but results is still None, then the + iteration is terminated and raise the error. Default: 15. + """ + + def __init__(self, + dataset: Union[BaseDataset, dict], + pipeline: Sequence[str], + skip_type_keys: Union[Sequence[str], None] = None, + max_refetch: int = 15, + lazy_init: bool = False) -> None: + assert isinstance(pipeline, collections.abc.Sequence) + if skip_type_keys is not None: + assert all([ + isinstance(skip_type_key, str) + for skip_type_key in skip_type_keys + ]) + self._skip_type_keys = skip_type_keys + + self.pipeline = [] + self.pipeline_types = [] + for transform in pipeline: + if isinstance(transform, dict): + self.pipeline_types.append(transform['type']) + transform = TRANSFORMS.build(transform) + self.pipeline.append(transform) + else: + raise TypeError('pipeline must be a dict') + + self.dataset: BaseDataset + if isinstance(dataset, dict): + self.dataset = DATASETS.build(dataset) + elif isinstance(dataset, BaseDataset): + self.dataset = dataset + else: + raise TypeError( + 'elements in datasets sequence should be config or ' + f'`BaseDataset` instance, but got {type(dataset)}') + + self._metainfo = self.dataset.metainfo + if hasattr(self.dataset, 'flag'): + self.flag = self.dataset.flag + self.num_samples = len(self.dataset) + self.max_refetch = max_refetch + + self._fully_initialized = False + if not lazy_init: + self.full_init() + + @property + def metainfo(self) -> dict: + """Get the meta information of the multi-image-mixed dataset. + + Returns: + dict: The meta information of multi-image-mixed dataset. + """ + return copy.deepcopy(self._metainfo) + + def full_init(self): + """Loop to ``full_init`` each dataset.""" + if self._fully_initialized: + return + + self.dataset.full_init() + self._ori_len = len(self.dataset) + self._fully_initialized = True + + @force_full_init + def get_data_info(self, idx: int) -> dict: + """Get annotation by index. + + Args: + idx (int): Global index of ``ConcatDataset``. + + Returns: + dict: The idx-th annotation of the datasets. + """ + return self.dataset.get_data_info(idx) + + @force_full_init + def __len__(self): + return self.num_samples + + def __getitem__(self, idx): + results = copy.deepcopy(self.dataset[idx]) + for (transform, transform_type) in zip(self.pipeline, + self.pipeline_types): + if self._skip_type_keys is not None and \ + transform_type in self._skip_type_keys: + continue + + if hasattr(transform, 'get_indexes'): + for i in range(self.max_refetch): + # Make sure the results passed the loading pipeline + # of the original dataset is not None. + indexes = transform.get_indexes(self.dataset) + if not isinstance(indexes, collections.abc.Sequence): + indexes = [indexes] + mix_results = [ + copy.deepcopy(self.dataset[index]) for index in indexes + ] + if None not in mix_results: + results['mix_results'] = mix_results + break + else: + raise RuntimeError( + 'The loading pipeline of the original dataset' + ' always return None. Please check the correctness ' + 'of the dataset and its pipeline.') + + for i in range(self.max_refetch): + # To confirm the results passed the training pipeline + # of the wrapper is not None. + updated_results = transform(copy.deepcopy(results)) + if updated_results is not None: + results = updated_results + break + else: + raise RuntimeError( + 'The training pipeline of the dataset wrapper' + ' always return None.Please check the correctness ' + 'of the dataset and its pipeline.') + + if 'mix_results' in results: + results.pop('mix_results') + + return results + + def update_skip_type_keys(self, skip_type_keys): + """Update skip_type_keys. It is called by an external hook. + + Args: + skip_type_keys (list[str], optional): Sequence of type + string to be skip pipeline. + """ + assert all([ + isinstance(skip_type_key, str) for skip_type_key in skip_type_keys + ]) + self._skip_type_keys = skip_type_keys diff --git a/mmdet_code/SR-TOD/mmdet/datasets/deepfashion.py b/mmdet_code/SR-TOD/mmdet/datasets/deepfashion.py new file mode 100644 index 0000000000000000000000000000000000000000..f853fc63398d598b90a88323e660ba6f4d81e2df --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/deepfashion.py @@ -0,0 +1,19 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class DeepFashionDataset(CocoDataset): + """Dataset for DeepFashion.""" + + METAINFO = { + 'classes': ('top', 'skirt', 'leggings', 'dress', 'outer', 'pants', + 'bag', 'neckwear', 'headwear', 'eyeglass', 'belt', + 'footwear', 'hair', 'skin', 'face'), + # palette is a list of color tuples, which is used for visualization. + 'palette': [(0, 192, 64), (0, 64, 96), (128, 192, 192), (0, 64, 64), + (0, 192, 224), (0, 192, 192), (128, 192, 64), (0, 192, 96), + (128, 32, 192), (0, 0, 224), (0, 0, 64), (0, 160, 192), + (128, 0, 96), (128, 0, 192), (0, 32, 192)] + } diff --git a/mmdet_code/SR-TOD/mmdet/datasets/dior.py b/mmdet_code/SR-TOD/mmdet/datasets/dior.py new file mode 100644 index 0000000000000000000000000000000000000000..2d73204d882cc66da5a00ed9522bf35dc8b63124 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/dior.py @@ -0,0 +1,190 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class DiorDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('Airplane', 'Airport', 'Baseball field', 'Basketball court', 'Bridge', 'Chimney', 'Dam', 'Expressway service area', + 'Expressway toll station', 'Golf course', 'Ground track field', 'Harbor', 'Overpass','ship', 'Stadium', 'Storage tank', + 'Tennis court','Train station','Vehicle','Wind mill'), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/dota.py b/mmdet_code/SR-TOD/mmdet/datasets/dota.py new file mode 100644 index 0000000000000000000000000000000000000000..73accc1c11629ddf468e91758f518e176fb139f4 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/dota.py @@ -0,0 +1,189 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class DOTADataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('plane', 'baseball-diamond', 'bridge', 'ground-track-field', 'small-vehicle', 'large-vehicle', 'ship', 'tennis-court', + 'basketball-court', 'storage-tank', 'soccer-ball-field', 'roundabout', 'harbor', 'swimming-pool', 'helicopter'), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/drones.py b/mmdet_code/SR-TOD/mmdet/datasets/drones.py new file mode 100644 index 0000000000000000000000000000000000000000..c11367086f66fa7ef5bc9075236be899f943d326 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/drones.py @@ -0,0 +1,188 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class DronesDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('drone',), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/dsdl.py b/mmdet_code/SR-TOD/mmdet/datasets/dsdl.py new file mode 100644 index 0000000000000000000000000000000000000000..75570a2a6396e0e7a4ce5cac5dbf2a23cd164629 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/dsdl.py @@ -0,0 +1,192 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +from typing import List + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + +try: + from dsdl.dataset import DSDLDataset +except ImportError: + DSDLDataset = None + + +@DATASETS.register_module() +class DSDLDetDataset(BaseDetDataset): + """Dataset for dsdl detection. + + Args: + with_bbox(bool): Load bbox or not, defaults to be True. + with_polygon(bool): Load polygon or not, defaults to be False. + with_mask(bool): Load seg map mask or not, defaults to be False. + with_imagelevel_label(bool): Load image level label or not, + defaults to be False. + with_hierarchy(bool): Load hierarchy information or not, + defaults to be False. + specific_key_path(dict): Path of specific key which can not + be loaded by it's field name. + pre_transform(dict): pre-transform functions before loading. + """ + + METAINFO = {} + + def __init__(self, + with_bbox: bool = True, + with_polygon: bool = False, + with_mask: bool = False, + with_imagelevel_label: bool = False, + with_hierarchy: bool = False, + specific_key_path: dict = {}, + pre_transform: dict = {}, + **kwargs) -> None: + + if DSDLDataset is None: + raise RuntimeError( + 'Package dsdl is not installed. Please run "pip install dsdl".' + ) + + self.with_hierarchy = with_hierarchy + self.specific_key_path = specific_key_path + + loc_config = dict(type='LocalFileReader', working_dir='') + if kwargs.get('data_root'): + kwargs['ann_file'] = os.path.join(kwargs['data_root'], + kwargs['ann_file']) + self.required_fields = ['Image', 'ImageShape', 'Label', 'ignore_flag'] + if with_bbox: + self.required_fields.append('Bbox') + if with_polygon: + self.required_fields.append('Polygon') + if with_mask: + self.required_fields.append('LabelMap') + if with_imagelevel_label: + self.required_fields.append('image_level_labels') + assert 'image_level_labels' in specific_key_path.keys( + ), '`image_level_labels` not specified in `specific_key_path` !' + + self.extra_keys = [ + key for key in self.specific_key_path.keys() + if key not in self.required_fields + ] + + self.dsdldataset = DSDLDataset( + dsdl_yaml=kwargs['ann_file'], + location_config=loc_config, + required_fields=self.required_fields, + specific_key_path=specific_key_path, + transform=pre_transform, + ) + + BaseDetDataset.__init__(self, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load data info from an dsdl yaml file named as ``self.ann_file`` + + Returns: + List[dict]: A list of data info. + """ + if self.with_hierarchy: + # get classes_names and relation_matrix + classes_names, relation_matrix = \ + self.dsdldataset.class_dom.get_hierarchy_info() + self._metainfo['classes'] = tuple(classes_names) + self._metainfo['RELATION_MATRIX'] = relation_matrix + + else: + self._metainfo['classes'] = tuple(self.dsdldataset.class_names) + + data_list = [] + + for i, data in enumerate(self.dsdldataset): + # basic image info, including image id, path and size. + datainfo = dict( + img_id=i, + img_path=os.path.join(self.data_prefix['img_path'], + data['Image'][0].location), + width=data['ImageShape'][0].width, + height=data['ImageShape'][0].height, + ) + + # get image label info + if 'image_level_labels' in data.keys(): + if self.with_hierarchy: + # get leaf node name when using hierarchy classes + datainfo['image_level_labels'] = [ + self._metainfo['classes'].index(i.leaf_node_name) + for i in data['image_level_labels'] + ] + else: + datainfo['image_level_labels'] = [ + self._metainfo['classes'].index(i.name) + for i in data['image_level_labels'] + ] + + # get semantic segmentation info + if 'LabelMap' in data.keys(): + datainfo['seg_map_path'] = data['LabelMap'] + + # load instance info + instances = [] + if 'Bbox' in data.keys(): + for idx in range(len(data['Bbox'])): + bbox = data['Bbox'][idx] + if self.with_hierarchy: + # get leaf node name when using hierarchy classes + label = data['Label'][idx].leaf_node_name + label_index = self._metainfo['classes'].index(label) + else: + label = data['Label'][idx].name + label_index = self._metainfo['classes'].index(label) + + instance = {} + instance['bbox'] = bbox.xyxy + instance['bbox_label'] = label_index + + if 'ignore_flag' in data.keys(): + # get ignore flag + instance['ignore_flag'] = data['ignore_flag'][idx] + else: + instance['ignore_flag'] = 0 + + if 'Polygon' in data.keys(): + # get polygon info + polygon = data['Polygon'][idx] + instance['mask'] = polygon.openmmlabformat + + for key in self.extra_keys: + # load extra instance info + instance[key] = data[key][idx] + + instances.append(instance) + + datainfo['instances'] = instances + # append a standard sample in data list + if len(datainfo['instances']) > 0: + data_list.append(datainfo) + + return data_list + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) \ + if self.filter_cfg is not None else False + min_size = self.filter_cfg.get('min_size', 0) \ + if self.filter_cfg is not None else 0 + + valid_data_list = [] + for i, data_info in enumerate(self.data_list): + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and len(data_info['instances']) == 0: + continue + if min(width, height) >= min_size: + valid_data_list.append(data_info) + + return valid_data_list diff --git a/mmdet_code/SR-TOD/mmdet/datasets/isaid.py b/mmdet_code/SR-TOD/mmdet/datasets/isaid.py new file mode 100644 index 0000000000000000000000000000000000000000..87067d8459c4dd6e80e5f808f613e0bd600b5f2f --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/isaid.py @@ -0,0 +1,25 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class iSAIDDataset(CocoDataset): + """Dataset for iSAID instance segmentation. + + iSAID: A Large-scale Dataset for Instance Segmentation + in Aerial Images. + + For more detail, please refer to "projects/iSAID/README.md" + """ + + METAINFO = dict( + classes=('background', 'ship', 'store_tank', 'baseball_diamond', + 'tennis_court', 'basketball_court', 'Ground_Track_Field', + 'Bridge', 'Large_Vehicle', 'Small_Vehicle', 'Helicopter', + 'Swimming_pool', 'Roundabout', 'Soccer_ball_field', 'plane', + 'Harbor'), + palette=[(0, 0, 0), (0, 0, 63), (0, 63, 63), (0, 63, 0), (0, 63, 127), + (0, 63, 191), (0, 63, 255), (0, 127, 63), (0, 127, 127), + (0, 0, 127), (0, 0, 191), (0, 0, 255), (0, 191, 127), + (0, 127, 191), (0, 127, 255), (0, 100, 155)]) diff --git a/mmdet_code/SR-TOD/mmdet/datasets/lvis.py b/mmdet_code/SR-TOD/mmdet/datasets/lvis.py new file mode 100644 index 0000000000000000000000000000000000000000..b9629f5d463da183f0b4ab4c5d0f7ff7b07e4348 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/lvis.py @@ -0,0 +1,638 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import warnings +from typing import List + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class LVISV05Dataset(CocoDataset): + """LVIS v0.5 dataset for detection.""" + + METAINFO = { + 'classes': + ('acorn', 'aerosol_can', 'air_conditioner', 'airplane', 'alarm_clock', + 'alcohol', 'alligator', 'almond', 'ambulance', 'amplifier', 'anklet', + 'antenna', 'apple', 'apple_juice', 'applesauce', 'apricot', 'apron', + 'aquarium', 'armband', 'armchair', 'armoire', 'armor', 'artichoke', + 'trash_can', 'ashtray', 'asparagus', 'atomizer', 'avocado', 'award', + 'awning', 'ax', 'baby_buggy', 'basketball_backboard', 'backpack', + 'handbag', 'suitcase', 'bagel', 'bagpipe', 'baguet', 'bait', 'ball', + 'ballet_skirt', 'balloon', 'bamboo', 'banana', 'Band_Aid', 'bandage', + 'bandanna', 'banjo', 'banner', 'barbell', 'barge', 'barrel', + 'barrette', 'barrow', 'baseball_base', 'baseball', 'baseball_bat', + 'baseball_cap', 'baseball_glove', 'basket', 'basketball_hoop', + 'basketball', 'bass_horn', 'bat_(animal)', 'bath_mat', 'bath_towel', + 'bathrobe', 'bathtub', 'batter_(food)', 'battery', 'beachball', + 'bead', 'beaker', 'bean_curd', 'beanbag', 'beanie', 'bear', 'bed', + 'bedspread', 'cow', 'beef_(food)', 'beeper', 'beer_bottle', + 'beer_can', 'beetle', 'bell', 'bell_pepper', 'belt', 'belt_buckle', + 'bench', 'beret', 'bib', 'Bible', 'bicycle', 'visor', 'binder', + 'binoculars', 'bird', 'birdfeeder', 'birdbath', 'birdcage', + 'birdhouse', 'birthday_cake', 'birthday_card', 'biscuit_(bread)', + 'pirate_flag', 'black_sheep', 'blackboard', 'blanket', 'blazer', + 'blender', 'blimp', 'blinker', 'blueberry', 'boar', 'gameboard', + 'boat', 'bobbin', 'bobby_pin', 'boiled_egg', 'bolo_tie', 'deadbolt', + 'bolt', 'bonnet', 'book', 'book_bag', 'bookcase', 'booklet', + 'bookmark', 'boom_microphone', 'boot', 'bottle', 'bottle_opener', + 'bouquet', 'bow_(weapon)', 'bow_(decorative_ribbons)', 'bow-tie', + 'bowl', 'pipe_bowl', 'bowler_hat', 'bowling_ball', 'bowling_pin', + 'boxing_glove', 'suspenders', 'bracelet', 'brass_plaque', 'brassiere', + 'bread-bin', 'breechcloth', 'bridal_gown', 'briefcase', + 'bristle_brush', 'broccoli', 'broach', 'broom', 'brownie', + 'brussels_sprouts', 'bubble_gum', 'bucket', 'horse_buggy', 'bull', + 'bulldog', 'bulldozer', 'bullet_train', 'bulletin_board', + 'bulletproof_vest', 'bullhorn', 'corned_beef', 'bun', 'bunk_bed', + 'buoy', 'burrito', 'bus_(vehicle)', 'business_card', 'butcher_knife', + 'butter', 'butterfly', 'button', 'cab_(taxi)', 'cabana', 'cabin_car', + 'cabinet', 'locker', 'cake', 'calculator', 'calendar', 'calf', + 'camcorder', 'camel', 'camera', 'camera_lens', 'camper_(vehicle)', + 'can', 'can_opener', 'candelabrum', 'candle', 'candle_holder', + 'candy_bar', 'candy_cane', 'walking_cane', 'canister', 'cannon', + 'canoe', 'cantaloup', 'canteen', 'cap_(headwear)', 'bottle_cap', + 'cape', 'cappuccino', 'car_(automobile)', 'railcar_(part_of_a_train)', + 'elevator_car', 'car_battery', 'identity_card', 'card', 'cardigan', + 'cargo_ship', 'carnation', 'horse_carriage', 'carrot', 'tote_bag', + 'cart', 'carton', 'cash_register', 'casserole', 'cassette', 'cast', + 'cat', 'cauliflower', 'caviar', 'cayenne_(spice)', 'CD_player', + 'celery', 'cellular_telephone', 'chain_mail', 'chair', + 'chaise_longue', 'champagne', 'chandelier', 'chap', 'checkbook', + 'checkerboard', 'cherry', 'chessboard', + 'chest_of_drawers_(furniture)', 'chicken_(animal)', 'chicken_wire', + 'chickpea', 'Chihuahua', 'chili_(vegetable)', 'chime', 'chinaware', + 'crisp_(potato_chip)', 'poker_chip', 'chocolate_bar', + 'chocolate_cake', 'chocolate_milk', 'chocolate_mousse', 'choker', + 'chopping_board', 'chopstick', 'Christmas_tree', 'slide', 'cider', + 'cigar_box', 'cigarette', 'cigarette_case', 'cistern', 'clarinet', + 'clasp', 'cleansing_agent', 'clementine', 'clip', 'clipboard', + 'clock', 'clock_tower', 'clothes_hamper', 'clothespin', 'clutch_bag', + 'coaster', 'coat', 'coat_hanger', 'coatrack', 'cock', 'coconut', + 'coffee_filter', 'coffee_maker', 'coffee_table', 'coffeepot', 'coil', + 'coin', 'colander', 'coleslaw', 'coloring_material', + 'combination_lock', 'pacifier', 'comic_book', 'computer_keyboard', + 'concrete_mixer', 'cone', 'control', 'convertible_(automobile)', + 'sofa_bed', 'cookie', 'cookie_jar', 'cooking_utensil', + 'cooler_(for_food)', 'cork_(bottle_plug)', 'corkboard', 'corkscrew', + 'edible_corn', 'cornbread', 'cornet', 'cornice', 'cornmeal', 'corset', + 'romaine_lettuce', 'costume', 'cougar', 'coverall', 'cowbell', + 'cowboy_hat', 'crab_(animal)', 'cracker', 'crape', 'crate', 'crayon', + 'cream_pitcher', 'credit_card', 'crescent_roll', 'crib', 'crock_pot', + 'crossbar', 'crouton', 'crow', 'crown', 'crucifix', 'cruise_ship', + 'police_cruiser', 'crumb', 'crutch', 'cub_(animal)', 'cube', + 'cucumber', 'cufflink', 'cup', 'trophy_cup', 'cupcake', 'hair_curler', + 'curling_iron', 'curtain', 'cushion', 'custard', 'cutting_tool', + 'cylinder', 'cymbal', 'dachshund', 'dagger', 'dartboard', + 'date_(fruit)', 'deck_chair', 'deer', 'dental_floss', 'desk', + 'detergent', 'diaper', 'diary', 'die', 'dinghy', 'dining_table', + 'tux', 'dish', 'dish_antenna', 'dishrag', 'dishtowel', 'dishwasher', + 'dishwasher_detergent', 'diskette', 'dispenser', 'Dixie_cup', 'dog', + 'dog_collar', 'doll', 'dollar', 'dolphin', 'domestic_ass', 'eye_mask', + 'doorbell', 'doorknob', 'doormat', 'doughnut', 'dove', 'dragonfly', + 'drawer', 'underdrawers', 'dress', 'dress_hat', 'dress_suit', + 'dresser', 'drill', 'drinking_fountain', 'drone', 'dropper', + 'drum_(musical_instrument)', 'drumstick', 'duck', 'duckling', + 'duct_tape', 'duffel_bag', 'dumbbell', 'dumpster', 'dustpan', + 'Dutch_oven', 'eagle', 'earphone', 'earplug', 'earring', 'easel', + 'eclair', 'eel', 'egg', 'egg_roll', 'egg_yolk', 'eggbeater', + 'eggplant', 'electric_chair', 'refrigerator', 'elephant', 'elk', + 'envelope', 'eraser', 'escargot', 'eyepatch', 'falcon', 'fan', + 'faucet', 'fedora', 'ferret', 'Ferris_wheel', 'ferry', 'fig_(fruit)', + 'fighter_jet', 'figurine', 'file_cabinet', 'file_(tool)', + 'fire_alarm', 'fire_engine', 'fire_extinguisher', 'fire_hose', + 'fireplace', 'fireplug', 'fish', 'fish_(food)', 'fishbowl', + 'fishing_boat', 'fishing_rod', 'flag', 'flagpole', 'flamingo', + 'flannel', 'flash', 'flashlight', 'fleece', 'flip-flop_(sandal)', + 'flipper_(footwear)', 'flower_arrangement', 'flute_glass', 'foal', + 'folding_chair', 'food_processor', 'football_(American)', + 'football_helmet', 'footstool', 'fork', 'forklift', 'freight_car', + 'French_toast', 'freshener', 'frisbee', 'frog', 'fruit_juice', + 'fruit_salad', 'frying_pan', 'fudge', 'funnel', 'futon', 'gag', + 'garbage', 'garbage_truck', 'garden_hose', 'gargle', 'gargoyle', + 'garlic', 'gasmask', 'gazelle', 'gelatin', 'gemstone', 'giant_panda', + 'gift_wrap', 'ginger', 'giraffe', 'cincture', + 'glass_(drink_container)', 'globe', 'glove', 'goat', 'goggles', + 'goldfish', 'golf_club', 'golfcart', 'gondola_(boat)', 'goose', + 'gorilla', 'gourd', 'surgical_gown', 'grape', 'grasshopper', 'grater', + 'gravestone', 'gravy_boat', 'green_bean', 'green_onion', 'griddle', + 'grillroom', 'grinder_(tool)', 'grits', 'grizzly', 'grocery_bag', + 'guacamole', 'guitar', 'gull', 'gun', 'hair_spray', 'hairbrush', + 'hairnet', 'hairpin', 'ham', 'hamburger', 'hammer', 'hammock', + 'hamper', 'hamster', 'hair_dryer', 'hand_glass', 'hand_towel', + 'handcart', 'handcuff', 'handkerchief', 'handle', 'handsaw', + 'hardback_book', 'harmonium', 'hat', 'hatbox', 'hatch', 'veil', + 'headband', 'headboard', 'headlight', 'headscarf', 'headset', + 'headstall_(for_horses)', 'hearing_aid', 'heart', 'heater', + 'helicopter', 'helmet', 'heron', 'highchair', 'hinge', 'hippopotamus', + 'hockey_stick', 'hog', 'home_plate_(baseball)', 'honey', 'fume_hood', + 'hook', 'horse', 'hose', 'hot-air_balloon', 'hotplate', 'hot_sauce', + 'hourglass', 'houseboat', 'hummingbird', 'hummus', 'polar_bear', + 'icecream', 'popsicle', 'ice_maker', 'ice_pack', 'ice_skate', + 'ice_tea', 'igniter', 'incense', 'inhaler', 'iPod', + 'iron_(for_clothing)', 'ironing_board', 'jacket', 'jam', 'jean', + 'jeep', 'jelly_bean', 'jersey', 'jet_plane', 'jewelry', 'joystick', + 'jumpsuit', 'kayak', 'keg', 'kennel', 'kettle', 'key', 'keycard', + 'kilt', 'kimono', 'kitchen_sink', 'kitchen_table', 'kite', 'kitten', + 'kiwi_fruit', 'knee_pad', 'knife', 'knight_(chess_piece)', + 'knitting_needle', 'knob', 'knocker_(on_a_door)', 'koala', 'lab_coat', + 'ladder', 'ladle', 'ladybug', 'lamb_(animal)', 'lamb-chop', 'lamp', + 'lamppost', 'lampshade', 'lantern', 'lanyard', 'laptop_computer', + 'lasagna', 'latch', 'lawn_mower', 'leather', 'legging_(clothing)', + 'Lego', 'lemon', 'lemonade', 'lettuce', 'license_plate', 'life_buoy', + 'life_jacket', 'lightbulb', 'lightning_rod', 'lime', 'limousine', + 'linen_paper', 'lion', 'lip_balm', 'lipstick', 'liquor', 'lizard', + 'Loafer_(type_of_shoe)', 'log', 'lollipop', 'lotion', + 'speaker_(stereo_equipment)', 'loveseat', 'machine_gun', 'magazine', + 'magnet', 'mail_slot', 'mailbox_(at_home)', 'mallet', 'mammoth', + 'mandarin_orange', 'manger', 'manhole', 'map', 'marker', 'martini', + 'mascot', 'mashed_potato', 'masher', 'mask', 'mast', + 'mat_(gym_equipment)', 'matchbox', 'mattress', 'measuring_cup', + 'measuring_stick', 'meatball', 'medicine', 'melon', 'microphone', + 'microscope', 'microwave_oven', 'milestone', 'milk', 'minivan', + 'mint_candy', 'mirror', 'mitten', 'mixer_(kitchen_tool)', 'money', + 'monitor_(computer_equipment) computer_monitor', 'monkey', 'motor', + 'motor_scooter', 'motor_vehicle', 'motorboat', 'motorcycle', + 'mound_(baseball)', 'mouse_(animal_rodent)', + 'mouse_(computer_equipment)', 'mousepad', 'muffin', 'mug', 'mushroom', + 'music_stool', 'musical_instrument', 'nailfile', 'nameplate', + 'napkin', 'neckerchief', 'necklace', 'necktie', 'needle', 'nest', + 'newsstand', 'nightshirt', 'nosebag_(for_animals)', + 'noseband_(for_animals)', 'notebook', 'notepad', 'nut', 'nutcracker', + 'oar', 'octopus_(food)', 'octopus_(animal)', 'oil_lamp', 'olive_oil', + 'omelet', 'onion', 'orange_(fruit)', 'orange_juice', 'oregano', + 'ostrich', 'ottoman', 'overalls_(clothing)', 'owl', 'packet', + 'inkpad', 'pad', 'paddle', 'padlock', 'paintbox', 'paintbrush', + 'painting', 'pajamas', 'palette', 'pan_(for_cooking)', + 'pan_(metal_container)', 'pancake', 'pantyhose', 'papaya', + 'paperclip', 'paper_plate', 'paper_towel', 'paperback_book', + 'paperweight', 'parachute', 'parakeet', 'parasail_(sports)', + 'parchment', 'parka', 'parking_meter', 'parrot', + 'passenger_car_(part_of_a_train)', 'passenger_ship', 'passport', + 'pastry', 'patty_(food)', 'pea_(food)', 'peach', 'peanut_butter', + 'pear', 'peeler_(tool_for_fruit_and_vegetables)', 'pegboard', + 'pelican', 'pen', 'pencil', 'pencil_box', 'pencil_sharpener', + 'pendulum', 'penguin', 'pennant', 'penny_(coin)', 'pepper', + 'pepper_mill', 'perfume', 'persimmon', 'baby', 'pet', 'petfood', + 'pew_(church_bench)', 'phonebook', 'phonograph_record', 'piano', + 'pickle', 'pickup_truck', 'pie', 'pigeon', 'piggy_bank', 'pillow', + 'pin_(non_jewelry)', 'pineapple', 'pinecone', 'ping-pong_ball', + 'pinwheel', 'tobacco_pipe', 'pipe', 'pistol', 'pita_(bread)', + 'pitcher_(vessel_for_liquid)', 'pitchfork', 'pizza', 'place_mat', + 'plate', 'platter', 'playing_card', 'playpen', 'pliers', + 'plow_(farm_equipment)', 'pocket_watch', 'pocketknife', + 'poker_(fire_stirring_tool)', 'pole', 'police_van', 'polo_shirt', + 'poncho', 'pony', 'pool_table', 'pop_(soda)', 'portrait', + 'postbox_(public)', 'postcard', 'poster', 'pot', 'flowerpot', + 'potato', 'potholder', 'pottery', 'pouch', 'power_shovel', 'prawn', + 'printer', 'projectile_(weapon)', 'projector', 'propeller', 'prune', + 'pudding', 'puffer_(fish)', 'puffin', 'pug-dog', 'pumpkin', 'puncher', + 'puppet', 'puppy', 'quesadilla', 'quiche', 'quilt', 'rabbit', + 'race_car', 'racket', 'radar', 'radiator', 'radio_receiver', 'radish', + 'raft', 'rag_doll', 'raincoat', 'ram_(animal)', 'raspberry', 'rat', + 'razorblade', 'reamer_(juicer)', 'rearview_mirror', 'receipt', + 'recliner', 'record_player', 'red_cabbage', 'reflector', + 'remote_control', 'rhinoceros', 'rib_(food)', 'rifle', 'ring', + 'river_boat', 'road_map', 'robe', 'rocking_chair', 'roller_skate', + 'Rollerblade', 'rolling_pin', 'root_beer', + 'router_(computer_equipment)', 'rubber_band', 'runner_(carpet)', + 'plastic_bag', 'saddle_(on_an_animal)', 'saddle_blanket', 'saddlebag', + 'safety_pin', 'sail', 'salad', 'salad_plate', 'salami', + 'salmon_(fish)', 'salmon_(food)', 'salsa', 'saltshaker', + 'sandal_(type_of_shoe)', 'sandwich', 'satchel', 'saucepan', 'saucer', + 'sausage', 'sawhorse', 'saxophone', 'scale_(measuring_instrument)', + 'scarecrow', 'scarf', 'school_bus', 'scissors', 'scoreboard', + 'scrambled_eggs', 'scraper', 'scratcher', 'screwdriver', + 'scrubbing_brush', 'sculpture', 'seabird', 'seahorse', 'seaplane', + 'seashell', 'seedling', 'serving_dish', 'sewing_machine', 'shaker', + 'shampoo', 'shark', 'sharpener', 'Sharpie', 'shaver_(electric)', + 'shaving_cream', 'shawl', 'shears', 'sheep', 'shepherd_dog', + 'sherbert', 'shield', 'shirt', 'shoe', 'shopping_bag', + 'shopping_cart', 'short_pants', 'shot_glass', 'shoulder_bag', + 'shovel', 'shower_head', 'shower_curtain', 'shredder_(for_paper)', + 'sieve', 'signboard', 'silo', 'sink', 'skateboard', 'skewer', 'ski', + 'ski_boot', 'ski_parka', 'ski_pole', 'skirt', 'sled', 'sleeping_bag', + 'sling_(bandage)', 'slipper_(footwear)', 'smoothie', 'snake', + 'snowboard', 'snowman', 'snowmobile', 'soap', 'soccer_ball', 'sock', + 'soda_fountain', 'carbonated_water', 'sofa', 'softball', + 'solar_array', 'sombrero', 'soup', 'soup_bowl', 'soupspoon', + 'sour_cream', 'soya_milk', 'space_shuttle', 'sparkler_(fireworks)', + 'spatula', 'spear', 'spectacles', 'spice_rack', 'spider', 'sponge', + 'spoon', 'sportswear', 'spotlight', 'squirrel', + 'stapler_(stapling_machine)', 'starfish', 'statue_(sculpture)', + 'steak_(food)', 'steak_knife', 'steamer_(kitchen_appliance)', + 'steering_wheel', 'stencil', 'stepladder', 'step_stool', + 'stereo_(sound_system)', 'stew', 'stirrer', 'stirrup', + 'stockings_(leg_wear)', 'stool', 'stop_sign', 'brake_light', 'stove', + 'strainer', 'strap', 'straw_(for_drinking)', 'strawberry', + 'street_sign', 'streetlight', 'string_cheese', 'stylus', 'subwoofer', + 'sugar_bowl', 'sugarcane_(plant)', 'suit_(clothing)', 'sunflower', + 'sunglasses', 'sunhat', 'sunscreen', 'surfboard', 'sushi', 'mop', + 'sweat_pants', 'sweatband', 'sweater', 'sweatshirt', 'sweet_potato', + 'swimsuit', 'sword', 'syringe', 'Tabasco_sauce', 'table-tennis_table', + 'table', 'table_lamp', 'tablecloth', 'tachometer', 'taco', 'tag', + 'taillight', 'tambourine', 'army_tank', 'tank_(storage_vessel)', + 'tank_top_(clothing)', 'tape_(sticky_cloth_or_paper)', 'tape_measure', + 'tapestry', 'tarp', 'tartan', 'tassel', 'tea_bag', 'teacup', + 'teakettle', 'teapot', 'teddy_bear', 'telephone', 'telephone_booth', + 'telephone_pole', 'telephoto_lens', 'television_camera', + 'television_set', 'tennis_ball', 'tennis_racket', 'tequila', + 'thermometer', 'thermos_bottle', 'thermostat', 'thimble', 'thread', + 'thumbtack', 'tiara', 'tiger', 'tights_(clothing)', 'timer', + 'tinfoil', 'tinsel', 'tissue_paper', 'toast_(food)', 'toaster', + 'toaster_oven', 'toilet', 'toilet_tissue', 'tomato', 'tongs', + 'toolbox', 'toothbrush', 'toothpaste', 'toothpick', 'cover', + 'tortilla', 'tow_truck', 'towel', 'towel_rack', 'toy', + 'tractor_(farm_equipment)', 'traffic_light', 'dirt_bike', + 'trailer_truck', 'train_(railroad_vehicle)', 'trampoline', 'tray', + 'tree_house', 'trench_coat', 'triangle_(musical_instrument)', + 'tricycle', 'tripod', 'trousers', 'truck', 'truffle_(chocolate)', + 'trunk', 'vat', 'turban', 'turkey_(bird)', 'turkey_(food)', 'turnip', + 'turtle', 'turtleneck_(clothing)', 'typewriter', 'umbrella', + 'underwear', 'unicycle', 'urinal', 'urn', 'vacuum_cleaner', 'valve', + 'vase', 'vending_machine', 'vent', 'videotape', 'vinegar', 'violin', + 'vodka', 'volleyball', 'vulture', 'waffle', 'waffle_iron', 'wagon', + 'wagon_wheel', 'walking_stick', 'wall_clock', 'wall_socket', 'wallet', + 'walrus', 'wardrobe', 'wasabi', 'automatic_washer', 'watch', + 'water_bottle', 'water_cooler', 'water_faucet', 'water_filter', + 'water_heater', 'water_jug', 'water_gun', 'water_scooter', + 'water_ski', 'water_tower', 'watering_can', 'watermelon', + 'weathervane', 'webcam', 'wedding_cake', 'wedding_ring', 'wet_suit', + 'wheel', 'wheelchair', 'whipped_cream', 'whiskey', 'whistle', 'wick', + 'wig', 'wind_chime', 'windmill', 'window_box_(for_plants)', + 'windshield_wiper', 'windsock', 'wine_bottle', 'wine_bucket', + 'wineglass', 'wing_chair', 'blinder_(for_horses)', 'wok', 'wolf', + 'wooden_spoon', 'wreath', 'wrench', 'wristband', 'wristlet', 'yacht', + 'yak', 'yogurt', 'yoke_(animal_equipment)', 'zebra', 'zucchini'), + 'palette': + None + } + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + try: + import lvis + if getattr(lvis, '__version__', '0') >= '10.5.3': + warnings.warn( + 'mmlvis is deprecated, please install official lvis-api by "pip install git+https://github.com/lvis-dataset/lvis-api.git"', # noqa: E501 + UserWarning) + from lvis import LVIS + except ImportError: + raise ImportError( + 'Package lvis is not installed. Please run "pip install git+https://github.com/lvis-dataset/lvis-api.git".' # noqa: E501 + ) + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.lvis = LVIS(local_path) + self.cat_ids = self.lvis.get_cat_ids() + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.lvis.cat_img_map) + + img_ids = self.lvis.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.lvis.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + if raw_img_info['file_name'].startswith('COCO'): + # Convert form the COCO 2014 file naming convention of + # COCO_[train/val/test]2014_000000000000.jpg to the 2017 + # naming convention of 000000000000.jpg + # (LVIS v1 will fix this naming issue) + raw_img_info['file_name'] = raw_img_info['file_name'][-16:] + ann_ids = self.lvis.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.lvis.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.lvis + + return data_list + + +LVISDataset = LVISV05Dataset +DATASETS.register_module(name='LVISDataset', module=LVISDataset) + + +@DATASETS.register_module() +class LVISV1Dataset(LVISDataset): + """LVIS v1 dataset for detection.""" + + METAINFO = { + 'classes': + ('aerosol_can', 'air_conditioner', 'airplane', 'alarm_clock', + 'alcohol', 'alligator', 'almond', 'ambulance', 'amplifier', 'anklet', + 'antenna', 'apple', 'applesauce', 'apricot', 'apron', 'aquarium', + 'arctic_(type_of_shoe)', 'armband', 'armchair', 'armoire', 'armor', + 'artichoke', 'trash_can', 'ashtray', 'asparagus', 'atomizer', + 'avocado', 'award', 'awning', 'ax', 'baboon', 'baby_buggy', + 'basketball_backboard', 'backpack', 'handbag', 'suitcase', 'bagel', + 'bagpipe', 'baguet', 'bait', 'ball', 'ballet_skirt', 'balloon', + 'bamboo', 'banana', 'Band_Aid', 'bandage', 'bandanna', 'banjo', + 'banner', 'barbell', 'barge', 'barrel', 'barrette', 'barrow', + 'baseball_base', 'baseball', 'baseball_bat', 'baseball_cap', + 'baseball_glove', 'basket', 'basketball', 'bass_horn', 'bat_(animal)', + 'bath_mat', 'bath_towel', 'bathrobe', 'bathtub', 'batter_(food)', + 'battery', 'beachball', 'bead', 'bean_curd', 'beanbag', 'beanie', + 'bear', 'bed', 'bedpan', 'bedspread', 'cow', 'beef_(food)', 'beeper', + 'beer_bottle', 'beer_can', 'beetle', 'bell', 'bell_pepper', 'belt', + 'belt_buckle', 'bench', 'beret', 'bib', 'Bible', 'bicycle', 'visor', + 'billboard', 'binder', 'binoculars', 'bird', 'birdfeeder', 'birdbath', + 'birdcage', 'birdhouse', 'birthday_cake', 'birthday_card', + 'pirate_flag', 'black_sheep', 'blackberry', 'blackboard', 'blanket', + 'blazer', 'blender', 'blimp', 'blinker', 'blouse', 'blueberry', + 'gameboard', 'boat', 'bob', 'bobbin', 'bobby_pin', 'boiled_egg', + 'bolo_tie', 'deadbolt', 'bolt', 'bonnet', 'book', 'bookcase', + 'booklet', 'bookmark', 'boom_microphone', 'boot', 'bottle', + 'bottle_opener', 'bouquet', 'bow_(weapon)', + 'bow_(decorative_ribbons)', 'bow-tie', 'bowl', 'pipe_bowl', + 'bowler_hat', 'bowling_ball', 'box', 'boxing_glove', 'suspenders', + 'bracelet', 'brass_plaque', 'brassiere', 'bread-bin', 'bread', + 'breechcloth', 'bridal_gown', 'briefcase', 'broccoli', 'broach', + 'broom', 'brownie', 'brussels_sprouts', 'bubble_gum', 'bucket', + 'horse_buggy', 'bull', 'bulldog', 'bulldozer', 'bullet_train', + 'bulletin_board', 'bulletproof_vest', 'bullhorn', 'bun', 'bunk_bed', + 'buoy', 'burrito', 'bus_(vehicle)', 'business_card', 'butter', + 'butterfly', 'button', 'cab_(taxi)', 'cabana', 'cabin_car', 'cabinet', + 'locker', 'cake', 'calculator', 'calendar', 'calf', 'camcorder', + 'camel', 'camera', 'camera_lens', 'camper_(vehicle)', 'can', + 'can_opener', 'candle', 'candle_holder', 'candy_bar', 'candy_cane', + 'walking_cane', 'canister', 'canoe', 'cantaloup', 'canteen', + 'cap_(headwear)', 'bottle_cap', 'cape', 'cappuccino', + 'car_(automobile)', 'railcar_(part_of_a_train)', 'elevator_car', + 'car_battery', 'identity_card', 'card', 'cardigan', 'cargo_ship', + 'carnation', 'horse_carriage', 'carrot', 'tote_bag', 'cart', 'carton', + 'cash_register', 'casserole', 'cassette', 'cast', 'cat', + 'cauliflower', 'cayenne_(spice)', 'CD_player', 'celery', + 'cellular_telephone', 'chain_mail', 'chair', 'chaise_longue', + 'chalice', 'chandelier', 'chap', 'checkbook', 'checkerboard', + 'cherry', 'chessboard', 'chicken_(animal)', 'chickpea', + 'chili_(vegetable)', 'chime', 'chinaware', 'crisp_(potato_chip)', + 'poker_chip', 'chocolate_bar', 'chocolate_cake', 'chocolate_milk', + 'chocolate_mousse', 'choker', 'chopping_board', 'chopstick', + 'Christmas_tree', 'slide', 'cider', 'cigar_box', 'cigarette', + 'cigarette_case', 'cistern', 'clarinet', 'clasp', 'cleansing_agent', + 'cleat_(for_securing_rope)', 'clementine', 'clip', 'clipboard', + 'clippers_(for_plants)', 'cloak', 'clock', 'clock_tower', + 'clothes_hamper', 'clothespin', 'clutch_bag', 'coaster', 'coat', + 'coat_hanger', 'coatrack', 'cock', 'cockroach', 'cocoa_(beverage)', + 'coconut', 'coffee_maker', 'coffee_table', 'coffeepot', 'coil', + 'coin', 'colander', 'coleslaw', 'coloring_material', + 'combination_lock', 'pacifier', 'comic_book', 'compass', + 'computer_keyboard', 'condiment', 'cone', 'control', + 'convertible_(automobile)', 'sofa_bed', 'cooker', 'cookie', + 'cooking_utensil', 'cooler_(for_food)', 'cork_(bottle_plug)', + 'corkboard', 'corkscrew', 'edible_corn', 'cornbread', 'cornet', + 'cornice', 'cornmeal', 'corset', 'costume', 'cougar', 'coverall', + 'cowbell', 'cowboy_hat', 'crab_(animal)', 'crabmeat', 'cracker', + 'crape', 'crate', 'crayon', 'cream_pitcher', 'crescent_roll', 'crib', + 'crock_pot', 'crossbar', 'crouton', 'crow', 'crowbar', 'crown', + 'crucifix', 'cruise_ship', 'police_cruiser', 'crumb', 'crutch', + 'cub_(animal)', 'cube', 'cucumber', 'cufflink', 'cup', 'trophy_cup', + 'cupboard', 'cupcake', 'hair_curler', 'curling_iron', 'curtain', + 'cushion', 'cylinder', 'cymbal', 'dagger', 'dalmatian', 'dartboard', + 'date_(fruit)', 'deck_chair', 'deer', 'dental_floss', 'desk', + 'detergent', 'diaper', 'diary', 'die', 'dinghy', 'dining_table', + 'tux', 'dish', 'dish_antenna', 'dishrag', 'dishtowel', 'dishwasher', + 'dishwasher_detergent', 'dispenser', 'diving_board', 'Dixie_cup', + 'dog', 'dog_collar', 'doll', 'dollar', 'dollhouse', 'dolphin', + 'domestic_ass', 'doorknob', 'doormat', 'doughnut', 'dove', + 'dragonfly', 'drawer', 'underdrawers', 'dress', 'dress_hat', + 'dress_suit', 'dresser', 'drill', 'drone', 'dropper', + 'drum_(musical_instrument)', 'drumstick', 'duck', 'duckling', + 'duct_tape', 'duffel_bag', 'dumbbell', 'dumpster', 'dustpan', 'eagle', + 'earphone', 'earplug', 'earring', 'easel', 'eclair', 'eel', 'egg', + 'egg_roll', 'egg_yolk', 'eggbeater', 'eggplant', 'electric_chair', + 'refrigerator', 'elephant', 'elk', 'envelope', 'eraser', 'escargot', + 'eyepatch', 'falcon', 'fan', 'faucet', 'fedora', 'ferret', + 'Ferris_wheel', 'ferry', 'fig_(fruit)', 'fighter_jet', 'figurine', + 'file_cabinet', 'file_(tool)', 'fire_alarm', 'fire_engine', + 'fire_extinguisher', 'fire_hose', 'fireplace', 'fireplug', + 'first-aid_kit', 'fish', 'fish_(food)', 'fishbowl', 'fishing_rod', + 'flag', 'flagpole', 'flamingo', 'flannel', 'flap', 'flash', + 'flashlight', 'fleece', 'flip-flop_(sandal)', 'flipper_(footwear)', + 'flower_arrangement', 'flute_glass', 'foal', 'folding_chair', + 'food_processor', 'football_(American)', 'football_helmet', + 'footstool', 'fork', 'forklift', 'freight_car', 'French_toast', + 'freshener', 'frisbee', 'frog', 'fruit_juice', 'frying_pan', 'fudge', + 'funnel', 'futon', 'gag', 'garbage', 'garbage_truck', 'garden_hose', + 'gargle', 'gargoyle', 'garlic', 'gasmask', 'gazelle', 'gelatin', + 'gemstone', 'generator', 'giant_panda', 'gift_wrap', 'ginger', + 'giraffe', 'cincture', 'glass_(drink_container)', 'globe', 'glove', + 'goat', 'goggles', 'goldfish', 'golf_club', 'golfcart', + 'gondola_(boat)', 'goose', 'gorilla', 'gourd', 'grape', 'grater', + 'gravestone', 'gravy_boat', 'green_bean', 'green_onion', 'griddle', + 'grill', 'grits', 'grizzly', 'grocery_bag', 'guitar', 'gull', 'gun', + 'hairbrush', 'hairnet', 'hairpin', 'halter_top', 'ham', 'hamburger', + 'hammer', 'hammock', 'hamper', 'hamster', 'hair_dryer', 'hand_glass', + 'hand_towel', 'handcart', 'handcuff', 'handkerchief', 'handle', + 'handsaw', 'hardback_book', 'harmonium', 'hat', 'hatbox', 'veil', + 'headband', 'headboard', 'headlight', 'headscarf', 'headset', + 'headstall_(for_horses)', 'heart', 'heater', 'helicopter', 'helmet', + 'heron', 'highchair', 'hinge', 'hippopotamus', 'hockey_stick', 'hog', + 'home_plate_(baseball)', 'honey', 'fume_hood', 'hook', 'hookah', + 'hornet', 'horse', 'hose', 'hot-air_balloon', 'hotplate', 'hot_sauce', + 'hourglass', 'houseboat', 'hummingbird', 'hummus', 'polar_bear', + 'icecream', 'popsicle', 'ice_maker', 'ice_pack', 'ice_skate', + 'igniter', 'inhaler', 'iPod', 'iron_(for_clothing)', 'ironing_board', + 'jacket', 'jam', 'jar', 'jean', 'jeep', 'jelly_bean', 'jersey', + 'jet_plane', 'jewel', 'jewelry', 'joystick', 'jumpsuit', 'kayak', + 'keg', 'kennel', 'kettle', 'key', 'keycard', 'kilt', 'kimono', + 'kitchen_sink', 'kitchen_table', 'kite', 'kitten', 'kiwi_fruit', + 'knee_pad', 'knife', 'knitting_needle', 'knob', 'knocker_(on_a_door)', + 'koala', 'lab_coat', 'ladder', 'ladle', 'ladybug', 'lamb_(animal)', + 'lamb-chop', 'lamp', 'lamppost', 'lampshade', 'lantern', 'lanyard', + 'laptop_computer', 'lasagna', 'latch', 'lawn_mower', 'leather', + 'legging_(clothing)', 'Lego', 'legume', 'lemon', 'lemonade', + 'lettuce', 'license_plate', 'life_buoy', 'life_jacket', 'lightbulb', + 'lightning_rod', 'lime', 'limousine', 'lion', 'lip_balm', 'liquor', + 'lizard', 'log', 'lollipop', 'speaker_(stereo_equipment)', 'loveseat', + 'machine_gun', 'magazine', 'magnet', 'mail_slot', 'mailbox_(at_home)', + 'mallard', 'mallet', 'mammoth', 'manatee', 'mandarin_orange', + 'manger', 'manhole', 'map', 'marker', 'martini', 'mascot', + 'mashed_potato', 'masher', 'mask', 'mast', 'mat_(gym_equipment)', + 'matchbox', 'mattress', 'measuring_cup', 'measuring_stick', + 'meatball', 'medicine', 'melon', 'microphone', 'microscope', + 'microwave_oven', 'milestone', 'milk', 'milk_can', 'milkshake', + 'minivan', 'mint_candy', 'mirror', 'mitten', 'mixer_(kitchen_tool)', + 'money', 'monitor_(computer_equipment) computer_monitor', 'monkey', + 'motor', 'motor_scooter', 'motor_vehicle', 'motorcycle', + 'mound_(baseball)', 'mouse_(computer_equipment)', 'mousepad', + 'muffin', 'mug', 'mushroom', 'music_stool', 'musical_instrument', + 'nailfile', 'napkin', 'neckerchief', 'necklace', 'necktie', 'needle', + 'nest', 'newspaper', 'newsstand', 'nightshirt', + 'nosebag_(for_animals)', 'noseband_(for_animals)', 'notebook', + 'notepad', 'nut', 'nutcracker', 'oar', 'octopus_(food)', + 'octopus_(animal)', 'oil_lamp', 'olive_oil', 'omelet', 'onion', + 'orange_(fruit)', 'orange_juice', 'ostrich', 'ottoman', 'oven', + 'overalls_(clothing)', 'owl', 'packet', 'inkpad', 'pad', 'paddle', + 'padlock', 'paintbrush', 'painting', 'pajamas', 'palette', + 'pan_(for_cooking)', 'pan_(metal_container)', 'pancake', 'pantyhose', + 'papaya', 'paper_plate', 'paper_towel', 'paperback_book', + 'paperweight', 'parachute', 'parakeet', 'parasail_(sports)', + 'parasol', 'parchment', 'parka', 'parking_meter', 'parrot', + 'passenger_car_(part_of_a_train)', 'passenger_ship', 'passport', + 'pastry', 'patty_(food)', 'pea_(food)', 'peach', 'peanut_butter', + 'pear', 'peeler_(tool_for_fruit_and_vegetables)', 'wooden_leg', + 'pegboard', 'pelican', 'pen', 'pencil', 'pencil_box', + 'pencil_sharpener', 'pendulum', 'penguin', 'pennant', 'penny_(coin)', + 'pepper', 'pepper_mill', 'perfume', 'persimmon', 'person', 'pet', + 'pew_(church_bench)', 'phonebook', 'phonograph_record', 'piano', + 'pickle', 'pickup_truck', 'pie', 'pigeon', 'piggy_bank', 'pillow', + 'pin_(non_jewelry)', 'pineapple', 'pinecone', 'ping-pong_ball', + 'pinwheel', 'tobacco_pipe', 'pipe', 'pistol', 'pita_(bread)', + 'pitcher_(vessel_for_liquid)', 'pitchfork', 'pizza', 'place_mat', + 'plate', 'platter', 'playpen', 'pliers', 'plow_(farm_equipment)', + 'plume', 'pocket_watch', 'pocketknife', 'poker_(fire_stirring_tool)', + 'pole', 'polo_shirt', 'poncho', 'pony', 'pool_table', 'pop_(soda)', + 'postbox_(public)', 'postcard', 'poster', 'pot', 'flowerpot', + 'potato', 'potholder', 'pottery', 'pouch', 'power_shovel', 'prawn', + 'pretzel', 'printer', 'projectile_(weapon)', 'projector', 'propeller', + 'prune', 'pudding', 'puffer_(fish)', 'puffin', 'pug-dog', 'pumpkin', + 'puncher', 'puppet', 'puppy', 'quesadilla', 'quiche', 'quilt', + 'rabbit', 'race_car', 'racket', 'radar', 'radiator', 'radio_receiver', + 'radish', 'raft', 'rag_doll', 'raincoat', 'ram_(animal)', 'raspberry', + 'rat', 'razorblade', 'reamer_(juicer)', 'rearview_mirror', 'receipt', + 'recliner', 'record_player', 'reflector', 'remote_control', + 'rhinoceros', 'rib_(food)', 'rifle', 'ring', 'river_boat', 'road_map', + 'robe', 'rocking_chair', 'rodent', 'roller_skate', 'Rollerblade', + 'rolling_pin', 'root_beer', 'router_(computer_equipment)', + 'rubber_band', 'runner_(carpet)', 'plastic_bag', + 'saddle_(on_an_animal)', 'saddle_blanket', 'saddlebag', 'safety_pin', + 'sail', 'salad', 'salad_plate', 'salami', 'salmon_(fish)', + 'salmon_(food)', 'salsa', 'saltshaker', 'sandal_(type_of_shoe)', + 'sandwich', 'satchel', 'saucepan', 'saucer', 'sausage', 'sawhorse', + 'saxophone', 'scale_(measuring_instrument)', 'scarecrow', 'scarf', + 'school_bus', 'scissors', 'scoreboard', 'scraper', 'screwdriver', + 'scrubbing_brush', 'sculpture', 'seabird', 'seahorse', 'seaplane', + 'seashell', 'sewing_machine', 'shaker', 'shampoo', 'shark', + 'sharpener', 'Sharpie', 'shaver_(electric)', 'shaving_cream', 'shawl', + 'shears', 'sheep', 'shepherd_dog', 'sherbert', 'shield', 'shirt', + 'shoe', 'shopping_bag', 'shopping_cart', 'short_pants', 'shot_glass', + 'shoulder_bag', 'shovel', 'shower_head', 'shower_cap', + 'shower_curtain', 'shredder_(for_paper)', 'signboard', 'silo', 'sink', + 'skateboard', 'skewer', 'ski', 'ski_boot', 'ski_parka', 'ski_pole', + 'skirt', 'skullcap', 'sled', 'sleeping_bag', 'sling_(bandage)', + 'slipper_(footwear)', 'smoothie', 'snake', 'snowboard', 'snowman', + 'snowmobile', 'soap', 'soccer_ball', 'sock', 'sofa', 'softball', + 'solar_array', 'sombrero', 'soup', 'soup_bowl', 'soupspoon', + 'sour_cream', 'soya_milk', 'space_shuttle', 'sparkler_(fireworks)', + 'spatula', 'spear', 'spectacles', 'spice_rack', 'spider', 'crawfish', + 'sponge', 'spoon', 'sportswear', 'spotlight', 'squid_(food)', + 'squirrel', 'stagecoach', 'stapler_(stapling_machine)', 'starfish', + 'statue_(sculpture)', 'steak_(food)', 'steak_knife', 'steering_wheel', + 'stepladder', 'step_stool', 'stereo_(sound_system)', 'stew', + 'stirrer', 'stirrup', 'stool', 'stop_sign', 'brake_light', 'stove', + 'strainer', 'strap', 'straw_(for_drinking)', 'strawberry', + 'street_sign', 'streetlight', 'string_cheese', 'stylus', 'subwoofer', + 'sugar_bowl', 'sugarcane_(plant)', 'suit_(clothing)', 'sunflower', + 'sunglasses', 'sunhat', 'surfboard', 'sushi', 'mop', 'sweat_pants', + 'sweatband', 'sweater', 'sweatshirt', 'sweet_potato', 'swimsuit', + 'sword', 'syringe', 'Tabasco_sauce', 'table-tennis_table', 'table', + 'table_lamp', 'tablecloth', 'tachometer', 'taco', 'tag', 'taillight', + 'tambourine', 'army_tank', 'tank_(storage_vessel)', + 'tank_top_(clothing)', 'tape_(sticky_cloth_or_paper)', 'tape_measure', + 'tapestry', 'tarp', 'tartan', 'tassel', 'tea_bag', 'teacup', + 'teakettle', 'teapot', 'teddy_bear', 'telephone', 'telephone_booth', + 'telephone_pole', 'telephoto_lens', 'television_camera', + 'television_set', 'tennis_ball', 'tennis_racket', 'tequila', + 'thermometer', 'thermos_bottle', 'thermostat', 'thimble', 'thread', + 'thumbtack', 'tiara', 'tiger', 'tights_(clothing)', 'timer', + 'tinfoil', 'tinsel', 'tissue_paper', 'toast_(food)', 'toaster', + 'toaster_oven', 'toilet', 'toilet_tissue', 'tomato', 'tongs', + 'toolbox', 'toothbrush', 'toothpaste', 'toothpick', 'cover', + 'tortilla', 'tow_truck', 'towel', 'towel_rack', 'toy', + 'tractor_(farm_equipment)', 'traffic_light', 'dirt_bike', + 'trailer_truck', 'train_(railroad_vehicle)', 'trampoline', 'tray', + 'trench_coat', 'triangle_(musical_instrument)', 'tricycle', 'tripod', + 'trousers', 'truck', 'truffle_(chocolate)', 'trunk', 'vat', 'turban', + 'turkey_(food)', 'turnip', 'turtle', 'turtleneck_(clothing)', + 'typewriter', 'umbrella', 'underwear', 'unicycle', 'urinal', 'urn', + 'vacuum_cleaner', 'vase', 'vending_machine', 'vent', 'vest', + 'videotape', 'vinegar', 'violin', 'vodka', 'volleyball', 'vulture', + 'waffle', 'waffle_iron', 'wagon', 'wagon_wheel', 'walking_stick', + 'wall_clock', 'wall_socket', 'wallet', 'walrus', 'wardrobe', + 'washbasin', 'automatic_washer', 'watch', 'water_bottle', + 'water_cooler', 'water_faucet', 'water_heater', 'water_jug', + 'water_gun', 'water_scooter', 'water_ski', 'water_tower', + 'watering_can', 'watermelon', 'weathervane', 'webcam', 'wedding_cake', + 'wedding_ring', 'wet_suit', 'wheel', 'wheelchair', 'whipped_cream', + 'whistle', 'wig', 'wind_chime', 'windmill', 'window_box_(for_plants)', + 'windshield_wiper', 'windsock', 'wine_bottle', 'wine_bucket', + 'wineglass', 'blinder_(for_horses)', 'wok', 'wolf', 'wooden_spoon', + 'wreath', 'wrench', 'wristband', 'wristlet', 'yacht', 'yogurt', + 'yoke_(animal_equipment)', 'zebra', 'zucchini'), + 'palette': + None + } + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + try: + import lvis + if getattr(lvis, '__version__', '0') >= '10.5.3': + warnings.warn( + 'mmlvis is deprecated, please install official lvis-api by "pip install git+https://github.com/lvis-dataset/lvis-api.git"', # noqa: E501 + UserWarning) + from lvis import LVIS + except ImportError: + raise ImportError( + 'Package lvis is not installed. Please run "pip install git+https://github.com/lvis-dataset/lvis-api.git".' # noqa: E501 + ) + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.lvis = LVIS(local_path) + self.cat_ids = self.lvis.get_cat_ids() + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.lvis.cat_img_map) + + img_ids = self.lvis.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.lvis.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + # coco_url is used in LVISv1 instead of file_name + # e.g. http://images.cocodataset.org/train2017/000000391895.jpg + # train/val split in specified in url + raw_img_info['file_name'] = raw_img_info['coco_url'].replace( + 'http://images.cocodataset.org/', '') + ann_ids = self.lvis.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.lvis.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.lvis + + return data_list diff --git a/mmdet_code/SR-TOD/mmdet/datasets/mot_challenge_dataset.py b/mmdet_code/SR-TOD/mmdet/datasets/mot_challenge_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbdc48ebf8d4a4ba11a605c8bc2a479cf2a0c96 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/mot_challenge_dataset.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List, Union + +from mmdet.registry import DATASETS +from .base_video_dataset import BaseVideoDataset + + +@DATASETS.register_module() +class MOTChallengeDataset(BaseVideoDataset): + """Dataset for MOTChallenge. + + Args: + visibility_thr (float, optional): The minimum visibility + for the objects during training. Default to -1. + """ + + METAINFO = { + 'classes': + ('pedestrian', 'person_on_vehicle', 'car', 'bicycle', 'motorbike', + 'non_mot_vehicle', 'static_person', 'distractor', 'occluder', + 'occluder_on_ground', 'occluder_full', 'reflection', 'crowd') + } + + def __init__(self, visibility_thr: float = -1, *args, **kwargs): + self.visibility_thr = visibility_thr + super().__init__(*args, **kwargs) + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. The difference between this + function and the one in ``BaseVideoDataset`` is that the parsing here + adds ``visibility`` and ``mot_conf``. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + data_info = {} + + data_info.update(img_info) + if self.data_prefix.get('img_path', None) is not None: + img_path = osp.join(self.data_prefix['img_path'], + img_info['file_name']) + else: + img_path = img_info['file_name'] + data_info['img_path'] = img_path + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if (not self.test_mode) and (ann['visibility'] < + self.visibility_thr): + continue + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + instance['instance_id'] = ann['instance_id'] + instance['category_id'] = ann['category_id'] + instance['mot_conf'] = ann['mot_conf'] + instance['visibility'] = ann['visibility'] + if len(instance) > 0: + instances.append(instance) + if not self.test_mode: + assert len(instances) > 0, f'No valid instances found in ' \ + f'image {data_info["img_path"]}!' + data_info['instances'] = instances + return data_info diff --git a/mmdet_code/SR-TOD/mmdet/datasets/objects365.py b/mmdet_code/SR-TOD/mmdet/datasets/objects365.py new file mode 100644 index 0000000000000000000000000000000000000000..e99869bfa309635af3c03cbfa77f732db3f50637 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/objects365.py @@ -0,0 +1,284 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .coco import CocoDataset + +# images exist in annotations but not in image folder. +objv2_ignore_list = [ + osp.join('patch16', 'objects365_v2_00908726.jpg'), + osp.join('patch6', 'objects365_v1_00320532.jpg'), + osp.join('patch6', 'objects365_v1_00320534.jpg'), +] + + +@DATASETS.register_module() +class Objects365V1Dataset(CocoDataset): + """Objects365 v1 dataset for detection.""" + + METAINFO = { + 'classes': + ('person', 'sneakers', 'chair', 'hat', 'lamp', 'bottle', + 'cabinet/shelf', 'cup', 'car', 'glasses', 'picture/frame', 'desk', + 'handbag', 'street lights', 'book', 'plate', 'helmet', + 'leather shoes', 'pillow', 'glove', 'potted plant', 'bracelet', + 'flower', 'tv', 'storage box', 'vase', 'bench', 'wine glass', 'boots', + 'bowl', 'dining table', 'umbrella', 'boat', 'flag', 'speaker', + 'trash bin/can', 'stool', 'backpack', 'couch', 'belt', 'carpet', + 'basket', 'towel/napkin', 'slippers', 'barrel/bucket', 'coffee table', + 'suv', 'toy', 'tie', 'bed', 'traffic light', 'pen/pencil', + 'microphone', 'sandals', 'canned', 'necklace', 'mirror', 'faucet', + 'bicycle', 'bread', 'high heels', 'ring', 'van', 'watch', 'sink', + 'horse', 'fish', 'apple', 'camera', 'candle', 'teddy bear', 'cake', + 'motorcycle', 'wild bird', 'laptop', 'knife', 'traffic sign', + 'cell phone', 'paddle', 'truck', 'cow', 'power outlet', 'clock', + 'drum', 'fork', 'bus', 'hanger', 'nightstand', 'pot/pan', 'sheep', + 'guitar', 'traffic cone', 'tea pot', 'keyboard', 'tripod', 'hockey', + 'fan', 'dog', 'spoon', 'blackboard/whiteboard', 'balloon', + 'air conditioner', 'cymbal', 'mouse', 'telephone', 'pickup truck', + 'orange', 'banana', 'airplane', 'luggage', 'skis', 'soccer', + 'trolley', 'oven', 'remote', 'baseball glove', 'paper towel', + 'refrigerator', 'train', 'tomato', 'machinery vehicle', 'tent', + 'shampoo/shower gel', 'head phone', 'lantern', 'donut', + 'cleaning products', 'sailboat', 'tangerine', 'pizza', 'kite', + 'computer box', 'elephant', 'toiletries', 'gas stove', 'broccoli', + 'toilet', 'stroller', 'shovel', 'baseball bat', 'microwave', + 'skateboard', 'surfboard', 'surveillance camera', 'gun', 'life saver', + 'cat', 'lemon', 'liquid soap', 'zebra', 'duck', 'sports car', + 'giraffe', 'pumpkin', 'piano', 'stop sign', 'radiator', 'converter', + 'tissue ', 'carrot', 'washing machine', 'vent', 'cookies', + 'cutting/chopping board', 'tennis racket', 'candy', + 'skating and skiing shoes', 'scissors', 'folder', 'baseball', + 'strawberry', 'bow tie', 'pigeon', 'pepper', 'coffee machine', + 'bathtub', 'snowboard', 'suitcase', 'grapes', 'ladder', 'pear', + 'american football', 'basketball', 'potato', 'paint brush', 'printer', + 'billiards', 'fire hydrant', 'goose', 'projector', 'sausage', + 'fire extinguisher', 'extension cord', 'facial mask', 'tennis ball', + 'chopsticks', 'electronic stove and gas stove', 'pie', 'frisbee', + 'kettle', 'hamburger', 'golf club', 'cucumber', 'clutch', 'blender', + 'tong', 'slide', 'hot dog', 'toothbrush', 'facial cleanser', 'mango', + 'deer', 'egg', 'violin', 'marker', 'ship', 'chicken', 'onion', + 'ice cream', 'tape', 'wheelchair', 'plum', 'bar soap', 'scale', + 'watermelon', 'cabbage', 'router/modem', 'golf ball', 'pine apple', + 'crane', 'fire truck', 'peach', 'cello', 'notepaper', 'tricycle', + 'toaster', 'helicopter', 'green beans', 'brush', 'carriage', 'cigar', + 'earphone', 'penguin', 'hurdle', 'swing', 'radio', 'CD', + 'parking meter', 'swan', 'garlic', 'french fries', 'horn', 'avocado', + 'saxophone', 'trumpet', 'sandwich', 'cue', 'kiwi fruit', 'bear', + 'fishing rod', 'cherry', 'tablet', 'green vegetables', 'nuts', 'corn', + 'key', 'screwdriver', 'globe', 'broom', 'pliers', 'volleyball', + 'hammer', 'eggplant', 'trophy', 'dates', 'board eraser', 'rice', + 'tape measure/ruler', 'dumbbell', 'hamimelon', 'stapler', 'camel', + 'lettuce', 'goldfish', 'meat balls', 'medal', 'toothpaste', + 'antelope', 'shrimp', 'rickshaw', 'trombone', 'pomegranate', + 'coconut', 'jellyfish', 'mushroom', 'calculator', 'treadmill', + 'butterfly', 'egg tart', 'cheese', 'pig', 'pomelo', 'race car', + 'rice cooker', 'tuba', 'crosswalk sign', 'papaya', 'hair drier', + 'green onion', 'chips', 'dolphin', 'sushi', 'urinal', 'donkey', + 'electric drill', 'spring rolls', 'tortoise/turtle', 'parrot', + 'flute', 'measuring cup', 'shark', 'steak', 'poker card', + 'binoculars', 'llama', 'radish', 'noodles', 'yak', 'mop', 'crab', + 'microscope', 'barbell', 'bread/bun', 'baozi', 'lion', 'red cabbage', + 'polar bear', 'lighter', 'seal', 'mangosteen', 'comb', 'eraser', + 'pitaya', 'scallop', 'pencil case', 'saw', 'table tennis paddle', + 'okra', 'starfish', 'eagle', 'monkey', 'durian', 'game board', + 'rabbit', 'french horn', 'ambulance', 'asparagus', 'hoverboard', + 'pasta', 'target', 'hotair balloon', 'chainsaw', 'lobster', 'iron', + 'flashlight'), + 'palette': + None + } + + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + + # 'categories' list in objects365_train.json and objects365_val.json + # is inconsistent, need sort list(or dict) before get cat_ids. + cats = self.coco.cats + sorted_cats = {i: cats[i] for i in sorted(cats)} + self.coco.cats = sorted_cats + categories = self.coco.dataset['categories'] + sorted_categories = sorted(categories, key=lambda i: i['id']) + self.coco.dataset['categories'] = sorted_categories + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + +@DATASETS.register_module() +class Objects365V2Dataset(CocoDataset): + """Objects365 v2 dataset for detection.""" + METAINFO = { + 'classes': + ('Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', + 'Glasses', 'Bottle', 'Desk', 'Cup', 'Street Lights', 'Cabinet/shelf', + 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', + 'Book', 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', + 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag', 'Pillow', 'Boots', + 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', + 'Moniter/TV', 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', + 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle', 'Stool', + 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Bakset', 'Drum', + 'Pen/Pencil', 'Bus', 'Wild Bird', 'High Heels', 'Motorcycle', + 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', + 'Truck', 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', + 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning', 'Bed', + 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', + 'Air Conditioner', 'Knife', 'Hockey Stick', 'Paddle', 'Pickup Truck', + 'Fork', 'Traffic Sign', 'Ballon', 'Tripod', 'Dog', 'Spoon', 'Clock', + 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', + 'Blackboard/Whiteboard', 'Napkin', 'Other Fish', 'Orange/Tangerine', + 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', + 'Fan', 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', + 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard', 'Luggage', + 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', + 'Sports Car', 'Stop Sign', 'Dessert', 'Scooter', 'Stroller', 'Crane', + 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat', + 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', + 'Elephant', 'Skateboard', 'Surfboard', 'Gun', + 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', + 'Toilet', 'Kite', 'Strawberry', 'Other Balls', 'Shovel', 'Pepper', + 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks', + 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', + 'Coffee Table', 'Side Table', 'Scissors', 'Marker', 'Pie', 'Ladder', + 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', + 'Zebra', 'Grape', 'Giraffe', 'Potato', 'Sausage', 'Tricycle', + 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck', + 'Billards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', + 'Briefcase', 'Cucumber', 'Cigar/Cigarette ', 'Paint Brush', 'Pear', + 'Heavy Truck', 'Hamburger', 'Extractor', 'Extention Cord', 'Tong', + 'Tennis Racket', 'Folder', 'American Football', 'earphone', 'Mask', + 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine', 'Slide', + 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', + 'Washing Machine/Drying Machine', 'Chicken', 'Printer', 'Watermelon', + 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hotair ballon', + 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', + 'Blender', 'Peach', 'Rice', 'Wallet/Purse', 'Volleyball', 'Deer', + 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', + 'Golf Ball', 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', + 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin', 'Megaphone', + 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', + 'Sandwich', 'Nuts', 'Speed Limit Sign', 'Induction Cooker', 'Broom', + 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit', + 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', + 'Notepaper', 'Cherry', 'Pliers', 'CD', 'Pasta', 'Hammer', 'Cue', + 'Avocado', 'Hamimelon', 'Flask', 'Mushroon', 'Screwdriver', 'Soap', + 'Recorder', 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', + 'Tape Measur/ Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips', 'Steak', + 'Crosswalk Sign', 'Stapler', 'Campel', 'Formula 1 ', 'Pomegranate', + 'Dishwasher', 'Crab', 'Hoverboard', 'Meat ball', 'Rice Cooker', + 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal', + 'Buttefly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', + 'Electric Drill', 'Hair Dryer', 'Egg tart', 'Jellyfish', 'Treadmill', + 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', + 'Target', 'French', 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', + 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell', 'Scallop', + 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Teniis paddle', + 'Cosmetics Brush/Eyeliner Pencil', 'Chainsaw', 'Eraser', 'Lobster', + 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', + 'Table Tennis '), + 'palette': + None + } + + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + # file_name should be `patchX/xxx.jpg` + file_name = osp.join( + osp.split(osp.split(raw_img_info['file_name'])[0])[-1], + osp.split(raw_img_info['file_name'])[-1]) + + if file_name in objv2_ignore_list: + continue + + raw_img_info['file_name'] = file_name + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list diff --git a/mmdet_code/SR-TOD/mmdet/datasets/openimages.py b/mmdet_code/SR-TOD/mmdet/datasets/openimages.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c6c8ec44fdfe86a653fc6a716009836f7d471c --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/openimages.py @@ -0,0 +1,484 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import csv +import os.path as osp +from collections import defaultdict +from typing import Dict, List, Optional + +import numpy as np +from mmengine.fileio import get_local_path, load +from mmengine.utils import is_abs + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class OpenImagesDataset(BaseDetDataset): + """Open Images dataset for detection. + + Args: + ann_file (str): Annotation file path. + label_file (str): File path of the label description file that + maps the classes names in MID format to their short + descriptions. + meta_file (str): File path to get image metas. + hierarchy_file (str): The file path of the class hierarchy. + image_level_ann_file (str): Human-verified image level annotation, + which is used in evaluation. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + """ + + METAINFO: dict = dict(dataset_type='oid_v6') + + def __init__(self, + label_file: str, + meta_file: str, + hierarchy_file: str, + image_level_ann_file: Optional[str] = None, + **kwargs) -> None: + self.label_file = label_file + self.meta_file = meta_file + self.hierarchy_file = hierarchy_file + self.image_level_ann_file = image_level_ann_file + super().__init__(**kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ + classes_names, label_id_mapping = self._parse_label_file( + self.label_file) + self._metainfo['classes'] = classes_names + self.label_id_mapping = label_id_mapping + + if self.image_level_ann_file is not None: + img_level_anns = self._parse_img_level_ann( + self.image_level_ann_file) + else: + img_level_anns = None + + # OpenImagesMetric can get the relation matrix from the dataset meta + relation_matrix = self._get_relation_matrix(self.hierarchy_file) + self._metainfo['RELATION_MATRIX'] = relation_matrix + + data_list = [] + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + last_img_id = None + instances = [] + for i, line in enumerate(reader): + if i == 0: + continue + img_id = line[0] + if last_img_id is None: + last_img_id = img_id + label_id = line[2] + assert label_id in self.label_id_mapping + label = int(self.label_id_mapping[label_id]) + bbox = [ + float(line[4]), # xmin + float(line[6]), # ymin + float(line[5]), # xmax + float(line[7]) # ymax + ] + is_occluded = True if int(line[8]) == 1 else False + is_truncated = True if int(line[9]) == 1 else False + is_group_of = True if int(line[10]) == 1 else False + is_depiction = True if int(line[11]) == 1 else False + is_inside = True if int(line[12]) == 1 else False + + instance = dict( + bbox=bbox, + bbox_label=label, + ignore_flag=0, + is_occluded=is_occluded, + is_truncated=is_truncated, + is_group_of=is_group_of, + is_depiction=is_depiction, + is_inside=is_inside) + last_img_path = osp.join(self.data_prefix['img'], + f'{last_img_id}.jpg') + if img_id != last_img_id: + # switch to a new image, record previous image's data. + data_info = dict( + img_path=last_img_path, + img_id=last_img_id, + instances=instances, + ) + data_list.append(data_info) + instances = [] + instances.append(instance) + last_img_id = img_id + data_list.append( + dict( + img_path=last_img_path, + img_id=last_img_id, + instances=instances, + )) + + # add image metas to data list + img_metas = load( + self.meta_file, file_format='pkl', backend_args=self.backend_args) + assert len(img_metas) == len(data_list) + for i, meta in enumerate(img_metas): + img_id = data_list[i]['img_id'] + assert f'{img_id}.jpg' == osp.split(meta['filename'])[-1] + h, w = meta['ori_shape'][:2] + data_list[i]['height'] = h + data_list[i]['width'] = w + # denormalize bboxes + for j in range(len(data_list[i]['instances'])): + data_list[i]['instances'][j]['bbox'][0] *= w + data_list[i]['instances'][j]['bbox'][2] *= w + data_list[i]['instances'][j]['bbox'][1] *= h + data_list[i]['instances'][j]['bbox'][3] *= h + # add image-level annotation + if img_level_anns is not None: + img_labels = [] + confidences = [] + img_ann_list = img_level_anns.get(img_id, []) + for ann in img_ann_list: + img_labels.append(int(ann['image_level_label'])) + confidences.append(float(ann['confidence'])) + data_list[i]['image_level_labels'] = np.array( + img_labels, dtype=np.int64) + data_list[i]['confidences'] = np.array( + confidences, dtype=np.float32) + return data_list + + def _parse_label_file(self, label_file: str) -> tuple: + """Get classes name and index mapping from cls-label-description file. + + Args: + label_file (str): File path of the label description file that + maps the classes names in MID format to their short + descriptions. + + Returns: + tuple: Class name of OpenImages. + """ + + index_list = [] + classes_names = [] + with get_local_path( + label_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + for line in reader: + # self.cat2label[line[0]] = line[1] + classes_names.append(line[1]) + index_list.append(line[0]) + index_mapping = {index: i for i, index in enumerate(index_list)} + return classes_names, index_mapping + + def _parse_img_level_ann(self, + img_level_ann_file: str) -> Dict[str, List[dict]]: + """Parse image level annotations from csv style ann_file. + + Args: + img_level_ann_file (str): CSV style image level annotation + file path. + + Returns: + Dict[str, List[dict]]: Annotations where item of the defaultdict + indicates an image, each of which has (n) dicts. + Keys of dicts are: + + - `image_level_label` (int): Label id. + - `confidence` (float): Labels that are human-verified to be + present in an image have confidence = 1 (positive labels). + Labels that are human-verified to be absent from an image + have confidence = 0 (negative labels). Machine-generated + labels have fractional confidences, generally >= 0.5. + The higher the confidence, the smaller the chance for + the label to be a false positive. + """ + + item_lists = defaultdict(list) + with get_local_path( + img_level_ann_file, + backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + for i, line in enumerate(reader): + if i == 0: + continue + img_id = line[0] + item_lists[img_id].append( + dict( + image_level_label=int( + self.label_id_mapping[line[2]]), + confidence=float(line[3]))) + return item_lists + + def _get_relation_matrix(self, hierarchy_file: str) -> np.ndarray: + """Get the matrix of class hierarchy from the hierarchy file. Hierarchy + for 600 classes can be found at https://storage.googleapis.com/openimag + es/2018_04/bbox_labels_600_hierarchy_visualizer/circle.html. + + Args: + hierarchy_file (str): File path to the hierarchy for classes. + + Returns: + np.ndarray: The matrix of the corresponding relationship between + the parent class and the child class, of shape + (class_num, class_num). + """ # noqa + + hierarchy = load( + hierarchy_file, file_format='json', backend_args=self.backend_args) + class_num = len(self._metainfo['classes']) + relation_matrix = np.eye(class_num, class_num) + relation_matrix = self._convert_hierarchy_tree(hierarchy, + relation_matrix) + return relation_matrix + + def _convert_hierarchy_tree(self, + hierarchy_map: dict, + relation_matrix: np.ndarray, + parents: list = [], + get_all_parents: bool = True) -> np.ndarray: + """Get matrix of the corresponding relationship between the parent + class and the child class. + + Args: + hierarchy_map (dict): Including label name and corresponding + subcategory. Keys of dicts are: + + - `LabeName` (str): Name of the label. + - `Subcategory` (dict | list): Corresponding subcategory(ies). + relation_matrix (ndarray): The matrix of the corresponding + relationship between the parent class and the child class, + of shape (class_num, class_num). + parents (list): Corresponding parent class. + get_all_parents (bool): Whether get all parent names. + Default: True + + Returns: + ndarray: The matrix of the corresponding relationship between + the parent class and the child class, of shape + (class_num, class_num). + """ + + if 'Subcategory' in hierarchy_map: + for node in hierarchy_map['Subcategory']: + if 'LabelName' in node: + children_name = node['LabelName'] + children_index = self.label_id_mapping[children_name] + children = [children_index] + else: + continue + if len(parents) > 0: + for parent_index in parents: + if get_all_parents: + children.append(parent_index) + relation_matrix[children_index, parent_index] = 1 + relation_matrix = self._convert_hierarchy_tree( + node, relation_matrix, parents=children) + return relation_matrix + + def _join_prefix(self): + """Join ``self.data_root`` with annotation path.""" + super()._join_prefix() + if not is_abs(self.label_file) and self.label_file: + self.label_file = osp.join(self.data_root, self.label_file) + if not is_abs(self.meta_file) and self.meta_file: + self.meta_file = osp.join(self.data_root, self.meta_file) + if not is_abs(self.hierarchy_file) and self.hierarchy_file: + self.hierarchy_file = osp.join(self.data_root, self.hierarchy_file) + if self.image_level_ann_file and not is_abs(self.image_level_ann_file): + self.image_level_ann_file = osp.join(self.data_root, + self.image_level_ann_file) + + +@DATASETS.register_module() +class OpenImagesChallengeDataset(OpenImagesDataset): + """Open Images Challenge dataset for detection. + + Args: + ann_file (str): Open Images Challenge box annotation in txt format. + """ + + METAINFO: dict = dict(dataset_type='oid_challenge') + + def __init__(self, ann_file: str, **kwargs) -> None: + if not ann_file.endswith('txt'): + raise TypeError('The annotation file of Open Images Challenge ' + 'should be a txt file.') + + super().__init__(ann_file=ann_file, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ + classes_names, label_id_mapping = self._parse_label_file( + self.label_file) + self._metainfo['classes'] = classes_names + self.label_id_mapping = label_id_mapping + + if self.image_level_ann_file is not None: + img_level_anns = self._parse_img_level_ann( + self.image_level_ann_file) + else: + img_level_anns = None + + # OpenImagesMetric can get the relation matrix from the dataset meta + relation_matrix = self._get_relation_matrix(self.hierarchy_file) + self._metainfo['RELATION_MATRIX'] = relation_matrix + + data_list = [] + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + lines = f.readlines() + i = 0 + while i < len(lines): + instances = [] + filename = lines[i].rstrip() + i += 2 + img_gt_size = int(lines[i]) + i += 1 + for j in range(img_gt_size): + sp = lines[i + j].split() + instances.append( + dict( + bbox=[ + float(sp[1]), + float(sp[2]), + float(sp[3]), + float(sp[4]) + ], + bbox_label=int(sp[0]) - 1, # labels begin from 1 + ignore_flag=0, + is_group_ofs=True if int(sp[5]) == 1 else False)) + i += img_gt_size + data_list.append( + dict( + img_path=osp.join(self.data_prefix['img'], filename), + instances=instances, + )) + + # add image metas to data list + img_metas = load( + self.meta_file, file_format='pkl', backend_args=self.backend_args) + assert len(img_metas) == len(data_list) + for i, meta in enumerate(img_metas): + img_id = osp.split(data_list[i]['img_path'])[-1][:-4] + assert img_id == osp.split(meta['filename'])[-1][:-4] + h, w = meta['ori_shape'][:2] + data_list[i]['height'] = h + data_list[i]['width'] = w + data_list[i]['img_id'] = img_id + # denormalize bboxes + for j in range(len(data_list[i]['instances'])): + data_list[i]['instances'][j]['bbox'][0] *= w + data_list[i]['instances'][j]['bbox'][2] *= w + data_list[i]['instances'][j]['bbox'][1] *= h + data_list[i]['instances'][j]['bbox'][3] *= h + # add image-level annotation + if img_level_anns is not None: + img_labels = [] + confidences = [] + img_ann_list = img_level_anns.get(img_id, []) + for ann in img_ann_list: + img_labels.append(int(ann['image_level_label'])) + confidences.append(float(ann['confidence'])) + data_list[i]['image_level_labels'] = np.array( + img_labels, dtype=np.int64) + data_list[i]['confidences'] = np.array( + confidences, dtype=np.float32) + return data_list + + def _parse_label_file(self, label_file: str) -> tuple: + """Get classes name and index mapping from cls-label-description file. + + Args: + label_file (str): File path of the label description file that + maps the classes names in MID format to their short + descriptions. + + Returns: + tuple: Class name of OpenImages. + """ + label_list = [] + id_list = [] + index_mapping = {} + with get_local_path( + label_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + for line in reader: + label_name = line[0] + label_id = int(line[2]) + label_list.append(line[1]) + id_list.append(label_id) + index_mapping[label_name] = label_id - 1 + indexes = np.argsort(id_list) + classes_names = [] + for index in indexes: + classes_names.append(label_list[index]) + return classes_names, index_mapping + + def _parse_img_level_ann(self, image_level_ann_file): + """Parse image level annotations from csv style ann_file. + + Args: + image_level_ann_file (str): CSV style image level annotation + file path. + + Returns: + defaultdict[list[dict]]: Annotations where item of the defaultdict + indicates an image, each of which has (n) dicts. + Keys of dicts are: + + - `image_level_label` (int): of shape 1. + - `confidence` (float): of shape 1. + """ + + item_lists = defaultdict(list) + with get_local_path( + image_level_ann_file, + backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + i = -1 + for line in reader: + i += 1 + if i == 0: + continue + else: + img_id = line[0] + label_id = line[1] + assert label_id in self.label_id_mapping + image_level_label = int( + self.label_id_mapping[label_id]) + confidence = float(line[2]) + item_lists[img_id].append( + dict( + image_level_label=image_level_label, + confidence=confidence)) + return item_lists + + def _get_relation_matrix(self, hierarchy_file: str) -> np.ndarray: + """Get the matrix of class hierarchy from the hierarchy file. + + Args: + hierarchy_file (str): File path to the hierarchy for classes. + + Returns: + np.ndarray: The matrix of the corresponding + relationship between the parent class and the child class, + of shape (class_num, class_num). + """ + with get_local_path( + hierarchy_file, backend_args=self.backend_args) as local_path: + class_label_tree = np.load(local_path, allow_pickle=True) + return class_label_tree[1:, 1:] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/refcoco.py b/mmdet_code/SR-TOD/mmdet/datasets/refcoco.py new file mode 100644 index 0000000000000000000000000000000000000000..0dae75fd547216a5b69033cc821b93a1d9ac6abc --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/refcoco.py @@ -0,0 +1,163 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import collections +import os.path as osp +import random +from typing import Dict, List + +import mmengine +from mmengine.dataset import BaseDataset + +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class RefCocoDataset(BaseDataset): + """RefCOCO dataset. + + The `Refcoco` and `Refcoco+` dataset is based on + `ReferItGame: Referring to Objects in Photographs of Natural Scenes + `_. + + The `Refcocog` dataset is based on + `Generation and Comprehension of Unambiguous Object Descriptions + `_. + + Args: + ann_file (str): Annotation file path. + data_root (str): The root directory for ``data_prefix`` and + ``ann_file``. Defaults to ''. + data_prefix (str): Prefix for training data. + split_file (str): Split file path. + split (str): Split name. Defaults to 'train'. + text_mode (str): Text mode. Defaults to 'random'. + **kwargs: Other keyword arguments in :class:`BaseDataset`. + """ + + def __init__(self, + data_root: str, + ann_file: str, + split_file: str, + data_prefix: Dict, + split: str = 'train', + text_mode: str = 'random', + **kwargs): + self.split_file = split_file + self.split = split + + assert text_mode in ['original', 'random', 'concat', 'select_first'] + self.text_mode = text_mode + super().__init__( + data_root=data_root, + data_prefix=data_prefix, + ann_file=ann_file, + **kwargs, + ) + + def _join_prefix(self): + if not mmengine.is_abs(self.split_file) and self.split_file: + self.split_file = osp.join(self.data_root, self.split_file) + + return super()._join_prefix() + + def _init_refs(self): + """Initialize the refs for RefCOCO.""" + anns, imgs = {}, {} + for ann in self.instances['annotations']: + anns[ann['id']] = ann + for img in self.instances['images']: + imgs[img['id']] = img + + refs, ref_to_ann = {}, {} + for ref in self.splits: + # ids + ref_id = ref['ref_id'] + ann_id = ref['ann_id'] + # add mapping related to ref + refs[ref_id] = ref + ref_to_ann[ref_id] = anns[ann_id] + + self.refs = refs + self.ref_to_ann = ref_to_ann + + def load_data_list(self) -> List[dict]: + """Load data list.""" + self.splits = mmengine.load(self.split_file, file_format='pkl') + self.instances = mmengine.load(self.ann_file, file_format='json') + self._init_refs() + img_prefix = self.data_prefix['img_path'] + + ref_ids = [ + ref['ref_id'] for ref in self.splits if ref['split'] == self.split + ] + full_anno = [] + for ref_id in ref_ids: + ref = self.refs[ref_id] + ann = self.ref_to_ann[ref_id] + ann.update(ref) + full_anno.append(ann) + + image_id_list = [] + final_anno = {} + for anno in full_anno: + image_id_list.append(anno['image_id']) + final_anno[anno['ann_id']] = anno + annotations = [value for key, value in final_anno.items()] + + coco_train_id = [] + image_annot = {} + for i in range(len(self.instances['images'])): + coco_train_id.append(self.instances['images'][i]['id']) + image_annot[self.instances['images'][i] + ['id']] = self.instances['images'][i] + + images = [] + for image_id in list(set(image_id_list)): + images += [image_annot[image_id]] + + data_list = [] + + grounding_dict = collections.defaultdict(list) + for anno in annotations: + image_id = int(anno['image_id']) + grounding_dict[image_id].append(anno) + + join_path = mmengine.fileio.get_file_backend(img_prefix).join_path + for image in images: + img_id = image['id'] + instances = [] + sentences = [] + for grounding_anno in grounding_dict[img_id]: + texts = [x['raw'].lower() for x in grounding_anno['sentences']] + # random select one text + if self.text_mode == 'random': + idx = random.randint(0, len(texts) - 1) + text = [texts[idx]] + # concat all texts + elif self.text_mode == 'concat': + text = [''.join(texts)] + # select the first text + elif self.text_mode == 'select_first': + text = [texts[0]] + # use all texts + elif self.text_mode == 'original': + text = texts + else: + raise ValueError(f'Invalid text mode "{self.text_mode}".') + ins = [{ + 'mask': grounding_anno['segmentation'], + 'ignore_flag': 0 + }] * len(text) + instances.extend(ins) + sentences.extend(text) + data_info = { + 'img_path': join_path(img_prefix, image['file_name']), + 'img_id': img_id, + 'instances': instances, + 'text': sentences + } + data_list.append(data_info) + + if len(data_list) == 0: + raise ValueError(f'No sample in split "{self.split}".') + + return data_list diff --git a/mmdet_code/SR-TOD/mmdet/datasets/reid_dataset.py b/mmdet_code/SR-TOD/mmdet/datasets/reid_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..1eed3ee4f0358edf59d19695c2b28394336dffd3 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/reid_dataset.py @@ -0,0 +1,127 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from collections import defaultdict +from typing import Any, Dict, List + +import numpy as np +from mmengine.dataset import BaseDataset +from mmengine.utils import check_file_exist + +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class ReIDDataset(BaseDataset): + """Dataset for ReID. + + Args: + triplet_sampler (dict, optional): The sampler for hard mining + triplet loss. Defaults to None. + keys: num_ids (int): The number of person ids. + ins_per_id (int): The number of image for each person. + """ + + def __init__(self, triplet_sampler: dict = None, *args, **kwargs): + self.triplet_sampler = triplet_sampler + super().__init__(*args, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ''self.ann_file''. + + Returns: + list[dict]: A list of annotation. + """ + assert isinstance(self.ann_file, str) + check_file_exist(self.ann_file) + data_list = [] + with open(self.ann_file) as f: + samples = [x.strip().split(' ') for x in f.readlines()] + for filename, gt_label in samples: + info = dict(img_prefix=self.data_prefix) + if self.data_prefix['img_path'] is not None: + info['img_path'] = osp.join(self.data_prefix['img_path'], + filename) + else: + info['img_path'] = filename + info['gt_label'] = np.array(gt_label, dtype=np.int64) + data_list.append(info) + self._parse_ann_info(data_list) + return data_list + + def _parse_ann_info(self, data_list: List[dict]): + """Parse person id annotations.""" + index_tmp_dic = defaultdict(list) # pid->[idx1,...,idxN] + self.index_dic = dict() # pid->array([idx1,...,idxN]) + for idx, info in enumerate(data_list): + pid = info['gt_label'] + index_tmp_dic[int(pid)].append(idx) + for pid, idxs in index_tmp_dic.items(): + self.index_dic[pid] = np.asarray(idxs, dtype=np.int64) + self.pids = np.asarray(list(self.index_dic.keys()), dtype=np.int64) + + def prepare_data(self, idx: int) -> Any: + """Get data processed by ''self.pipeline''. + + Args: + idx (int): The index of ''data_info'' + + Returns: + Any: Depends on ''self.pipeline'' + """ + data_info = self.get_data_info(idx) + if self.triplet_sampler is not None: + img_info = self.triplet_sampling(data_info['gt_label'], + **self.triplet_sampler) + data_info = copy.deepcopy(img_info) # triplet -> list + else: + data_info = copy.deepcopy(data_info) # no triplet -> dict + return self.pipeline(data_info) + + def triplet_sampling(self, + pos_pid, + num_ids: int = 8, + ins_per_id: int = 4) -> Dict: + """Triplet sampler for hard mining triplet loss. First, for one + pos_pid, random sample ins_per_id images with same person id. + + Then, random sample num_ids - 1 images for each negative id. + Finally, random sample ins_per_id images for each negative id. + + Args: + pos_pid (ndarray): The person id of the anchor. + num_ids (int): The number of person ids. + ins_per_id (int): The number of images for each person. + + Returns: + Dict: Annotation information of num_ids X ins_per_id images. + """ + assert len(self.pids) >= num_ids, \ + 'The number of person ids in the training set must ' \ + 'be greater than the number of person ids in the sample.' + + pos_idxs = self.index_dic[int( + pos_pid)] # all positive idxs for pos_pid + idxs_list = [] + # select positive samplers + idxs_list.extend(pos_idxs[np.random.choice( + pos_idxs.shape[0], ins_per_id, replace=True)]) + # select negative ids + neg_pids = np.random.choice( + [i for i, _ in enumerate(self.pids) if i != pos_pid], + num_ids - 1, + replace=False) + # select negative samplers for each negative id + for neg_pid in neg_pids: + neg_idxs = self.index_dic[neg_pid] + idxs_list.extend(neg_idxs[np.random.choice( + neg_idxs.shape[0], ins_per_id, replace=True)]) + # return the final triplet batch + triplet_img_infos = [] + for idx in idxs_list: + triplet_img_infos.append(copy.deepcopy(self.get_data_info(idx))) + # Collect data_list scatters (list of dict -> dict of list) + out = dict() + for key in triplet_img_infos[0].keys(): + out[key] = [_info[key] for _info in triplet_img_infos] + return out diff --git a/mmdet_code/SR-TOD/mmdet/datasets/samplers/__init__.py b/mmdet_code/SR-TOD/mmdet/datasets/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..769f38131be83f70e5868f74f17780875b3f652a --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/samplers/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .batch_sampler import (AspectRatioBatchSampler, + TrackAspectRatioBatchSampler) +from .class_aware_sampler import ClassAwareSampler +from .multi_source_sampler import GroupMultiSourceSampler, MultiSourceSampler +from .track_img_sampler import TrackImgSampler + +__all__ = [ + 'ClassAwareSampler', 'AspectRatioBatchSampler', 'MultiSourceSampler', + 'GroupMultiSourceSampler', 'TrackImgSampler', + 'TrackAspectRatioBatchSampler' +] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/samplers/batch_sampler.py b/mmdet_code/SR-TOD/mmdet/datasets/samplers/batch_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..6357713223dcd204e327473f5dae6389597f6786 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/samplers/batch_sampler.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Sequence + +from torch.utils.data import BatchSampler, Sampler + +from mmdet.datasets.samplers.track_img_sampler import TrackImgSampler +from mmdet.registry import DATA_SAMPLERS + + +# TODO: maybe replace with a data_loader wrapper +@DATA_SAMPLERS.register_module() +class AspectRatioBatchSampler(BatchSampler): + """A sampler wrapper for grouping images with similar aspect ratio (< 1 or. + + >= 1) into a same batch. + + Args: + sampler (Sampler): Base sampler. + batch_size (int): Size of mini-batch. + drop_last (bool): If ``True``, the sampler will drop the last batch if + its size would be less than ``batch_size``. + """ + + def __init__(self, + sampler: Sampler, + batch_size: int, + drop_last: bool = False) -> None: + if not isinstance(sampler, Sampler): + raise TypeError('sampler should be an instance of ``Sampler``, ' + f'but got {sampler}') + if not isinstance(batch_size, int) or batch_size <= 0: + raise ValueError('batch_size should be a positive integer value, ' + f'but got batch_size={batch_size}') + self.sampler = sampler + self.batch_size = batch_size + self.drop_last = drop_last + # two groups for w < h and w >= h + self._aspect_ratio_buckets = [[] for _ in range(2)] + + def __iter__(self) -> Sequence[int]: + for idx in self.sampler: + data_info = self.sampler.dataset.get_data_info(idx) + width, height = data_info['width'], data_info['height'] + bucket_id = 0 if width < height else 1 + bucket = self._aspect_ratio_buckets[bucket_id] + bucket.append(idx) + # yield a batch of indices in the same aspect ratio group + if len(bucket) == self.batch_size: + yield bucket[:] + del bucket[:] + + # yield the rest data and reset the bucket + left_data = self._aspect_ratio_buckets[0] + self._aspect_ratio_buckets[ + 1] + self._aspect_ratio_buckets = [[] for _ in range(2)] + while len(left_data) > 0: + if len(left_data) <= self.batch_size: + if not self.drop_last: + yield left_data[:] + left_data = [] + else: + yield left_data[:self.batch_size] + left_data = left_data[self.batch_size:] + + def __len__(self) -> int: + if self.drop_last: + return len(self.sampler) // self.batch_size + else: + return (len(self.sampler) + self.batch_size - 1) // self.batch_size + + +@DATA_SAMPLERS.register_module() +class TrackAspectRatioBatchSampler(AspectRatioBatchSampler): + """A sampler wrapper for grouping images with similar aspect ratio (< 1 or. + + >= 1) into a same batch. + + Args: + sampler (Sampler): Base sampler. + batch_size (int): Size of mini-batch. + drop_last (bool): If ``True``, the sampler will drop the last batch if + its size would be less than ``batch_size``. + """ + + def __iter__(self) -> Sequence[int]: + for idx in self.sampler: + # hard code to solve TrackImgSampler + if isinstance(self.sampler, TrackImgSampler): + video_idx, _ = idx + else: + video_idx = idx + # video_idx + data_info = self.sampler.dataset.get_data_info(video_idx) + # data_info {video_id, images, video_length} + img_data_info = data_info['images'][0] + width, height = img_data_info['width'], img_data_info['height'] + bucket_id = 0 if width < height else 1 + bucket = self._aspect_ratio_buckets[bucket_id] + bucket.append(idx) + # yield a batch of indices in the same aspect ratio group + if len(bucket) == self.batch_size: + yield bucket[:] + del bucket[:] + + # yield the rest data and reset the bucket + left_data = self._aspect_ratio_buckets[0] + self._aspect_ratio_buckets[ + 1] + self._aspect_ratio_buckets = [[] for _ in range(2)] + while len(left_data) > 0: + if len(left_data) <= self.batch_size: + if not self.drop_last: + yield left_data[:] + left_data = [] + else: + yield left_data[:self.batch_size] + left_data = left_data[self.batch_size:] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/samplers/class_aware_sampler.py b/mmdet_code/SR-TOD/mmdet/datasets/samplers/class_aware_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..6ca2f9b3ffb7c780ab25cc3704b67589763259e0 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/samplers/class_aware_sampler.py @@ -0,0 +1,192 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +from typing import Dict, Iterator, Optional, Union + +import numpy as np +import torch +from mmengine.dataset import BaseDataset +from mmengine.dist import get_dist_info, sync_random_seed +from torch.utils.data import Sampler + +from mmdet.registry import DATA_SAMPLERS + + +@DATA_SAMPLERS.register_module() +class ClassAwareSampler(Sampler): + r"""Sampler that restricts data loading to the label of the dataset. + + A class-aware sampling strategy to effectively tackle the + non-uniform class distribution. The length of the training data is + consistent with source data. Simple improvements based on `Relay + Backpropagation for Effective Learning of Deep Convolutional + Neural Networks `_ + + The implementation logic is referred to + https://github.com/Sense-X/TSD/blob/master/mmdet/datasets/samplers/distributed_classaware_sampler.py + + Args: + dataset: Dataset used for sampling. + seed (int, optional): random seed used to shuffle the sampler. + This number should be identical across all + processes in the distributed group. Defaults to None. + num_sample_class (int): The number of samples taken from each + per-label list. Defaults to 1. + """ + + def __init__(self, + dataset: BaseDataset, + seed: Optional[int] = None, + num_sample_class: int = 1) -> None: + rank, world_size = get_dist_info() + self.rank = rank + self.world_size = world_size + + self.dataset = dataset + self.epoch = 0 + # Must be the same across all workers. If None, will use a + # random seed shared among workers + # (require synchronization among all workers) + if seed is None: + seed = sync_random_seed() + self.seed = seed + + # The number of samples taken from each per-label list + assert num_sample_class > 0 and isinstance(num_sample_class, int) + self.num_sample_class = num_sample_class + # Get per-label image list from dataset + self.cat_dict = self.get_cat2imgs() + + self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / world_size)) + self.total_size = self.num_samples * self.world_size + + # get number of images containing each category + self.num_cat_imgs = [len(x) for x in self.cat_dict.values()] + # filter labels without images + self.valid_cat_inds = [ + i for i, length in enumerate(self.num_cat_imgs) if length != 0 + ] + self.num_classes = len(self.valid_cat_inds) + + def get_cat2imgs(self) -> Dict[int, list]: + """Get a dict with class as key and img_ids as values. + + Returns: + dict[int, list]: A dict of per-label image list, + the item of the dict indicates a label index, + corresponds to the image index that contains the label. + """ + classes = self.dataset.metainfo.get('classes', None) + if classes is None: + raise ValueError('dataset metainfo must contain `classes`') + # sort the label index + cat2imgs = {i: [] for i in range(len(classes))} + for i in range(len(self.dataset)): + cat_ids = set(self.dataset.get_cat_ids(i)) + for cat in cat_ids: + cat2imgs[cat].append(i) + return cat2imgs + + def __iter__(self) -> Iterator[int]: + # deterministically shuffle based on epoch + g = torch.Generator() + g.manual_seed(self.epoch + self.seed) + + # initialize label list + label_iter_list = RandomCycleIter(self.valid_cat_inds, generator=g) + # initialize each per-label image list + data_iter_dict = dict() + for i in self.valid_cat_inds: + data_iter_dict[i] = RandomCycleIter(self.cat_dict[i], generator=g) + + def gen_cat_img_inds(cls_list, data_dict, num_sample_cls): + """Traverse the categories and extract `num_sample_cls` image + indexes of the corresponding categories one by one.""" + id_indices = [] + for _ in range(len(cls_list)): + cls_idx = next(cls_list) + for _ in range(num_sample_cls): + id = next(data_dict[cls_idx]) + id_indices.append(id) + return id_indices + + # deterministically shuffle based on epoch + num_bins = int( + math.ceil(self.total_size * 1.0 / self.num_classes / + self.num_sample_class)) + indices = [] + for i in range(num_bins): + indices += gen_cat_img_inds(label_iter_list, data_iter_dict, + self.num_sample_class) + + # fix extra samples to make it evenly divisible + if len(indices) >= self.total_size: + indices = indices[:self.total_size] + else: + indices += indices[:(self.total_size - len(indices))] + assert len(indices) == self.total_size + + # subsample + offset = self.num_samples * self.rank + indices = indices[offset:offset + self.num_samples] + assert len(indices) == self.num_samples + + return iter(indices) + + def __len__(self) -> int: + """The number of samples in this rank.""" + return self.num_samples + + def set_epoch(self, epoch: int) -> None: + """Sets the epoch for this sampler. + + When :attr:`shuffle=True`, this ensures all replicas use a different + random ordering for each epoch. Otherwise, the next iteration of this + sampler will yield the same ordering. + + Args: + epoch (int): Epoch number. + """ + self.epoch = epoch + + +class RandomCycleIter: + """Shuffle the list and do it again after the list have traversed. + + The implementation logic is referred to + https://github.com/wutong16/DistributionBalancedLoss/blob/master/mllt/datasets/loader/sampler.py + + Example: + >>> label_list = [0, 1, 2, 4, 5] + >>> g = torch.Generator() + >>> g.manual_seed(0) + >>> label_iter_list = RandomCycleIter(label_list, generator=g) + >>> index = next(label_iter_list) + Args: + data (list or ndarray): The data that needs to be shuffled. + generator: An torch.Generator object, which is used in setting the seed + for generating random numbers. + """ # noqa: W605 + + def __init__(self, + data: Union[list, np.ndarray], + generator: torch.Generator = None) -> None: + self.data = data + self.length = len(data) + self.index = torch.randperm(self.length, generator=generator).numpy() + self.i = 0 + self.generator = generator + + def __iter__(self) -> Iterator: + return self + + def __len__(self) -> int: + return len(self.data) + + def __next__(self): + if self.i == self.length: + self.index = torch.randperm( + self.length, generator=self.generator).numpy() + self.i = 0 + idx = self.data[self.index[self.i]] + self.i += 1 + return idx diff --git a/mmdet_code/SR-TOD/mmdet/datasets/samplers/multi_source_sampler.py b/mmdet_code/SR-TOD/mmdet/datasets/samplers/multi_source_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..6efcde35e1375547239825a8f78a9e74f7825290 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/samplers/multi_source_sampler.py @@ -0,0 +1,214 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import itertools +from typing import Iterator, List, Optional, Sized, Union + +import numpy as np +import torch +from mmengine.dataset import BaseDataset +from mmengine.dist import get_dist_info, sync_random_seed +from torch.utils.data import Sampler + +from mmdet.registry import DATA_SAMPLERS + + +@DATA_SAMPLERS.register_module() +class MultiSourceSampler(Sampler): + r"""Multi-Source Infinite Sampler. + + According to the sampling ratio, sample data from different + datasets to form batches. + + Args: + dataset (Sized): The dataset. + batch_size (int): Size of mini-batch. + source_ratio (list[int | float]): The sampling ratio of different + source datasets in a mini-batch. + shuffle (bool): Whether shuffle the dataset or not. Defaults to True. + seed (int, optional): Random seed. If None, set a random seed. + Defaults to None. + + Examples: + >>> dataset_type = 'ConcatDataset' + >>> sub_dataset_type = 'CocoDataset' + >>> data_root = 'data/coco/' + >>> sup_ann = '../coco_semi_annos/instances_train2017.1@10.json' + >>> unsup_ann = '../coco_semi_annos/' \ + >>> 'instances_train2017.1@10-unlabeled.json' + >>> dataset = dict(type=dataset_type, + >>> datasets=[ + >>> dict( + >>> type=sub_dataset_type, + >>> data_root=data_root, + >>> ann_file=sup_ann, + >>> data_prefix=dict(img='train2017/'), + >>> filter_cfg=dict(filter_empty_gt=True, min_size=32), + >>> pipeline=sup_pipeline), + >>> dict( + >>> type=sub_dataset_type, + >>> data_root=data_root, + >>> ann_file=unsup_ann, + >>> data_prefix=dict(img='train2017/'), + >>> filter_cfg=dict(filter_empty_gt=True, min_size=32), + >>> pipeline=unsup_pipeline), + >>> ]) + >>> train_dataloader = dict( + >>> batch_size=5, + >>> num_workers=5, + >>> persistent_workers=True, + >>> sampler=dict(type='MultiSourceSampler', + >>> batch_size=5, source_ratio=[1, 4]), + >>> batch_sampler=None, + >>> dataset=dataset) + """ + + def __init__(self, + dataset: Sized, + batch_size: int, + source_ratio: List[Union[int, float]], + shuffle: bool = True, + seed: Optional[int] = None) -> None: + + assert hasattr(dataset, 'cumulative_sizes'),\ + f'The dataset must be ConcatDataset, but get {dataset}' + assert isinstance(batch_size, int) and batch_size > 0, \ + 'batch_size must be a positive integer value, ' \ + f'but got batch_size={batch_size}' + assert isinstance(source_ratio, list), \ + f'source_ratio must be a list, but got source_ratio={source_ratio}' + assert len(source_ratio) == len(dataset.cumulative_sizes), \ + 'The length of source_ratio must be equal to ' \ + f'the number of datasets, but got source_ratio={source_ratio}' + + rank, world_size = get_dist_info() + self.rank = rank + self.world_size = world_size + + self.dataset = dataset + self.cumulative_sizes = [0] + dataset.cumulative_sizes + self.batch_size = batch_size + self.source_ratio = source_ratio + + self.num_per_source = [ + int(batch_size * sr / sum(source_ratio)) for sr in source_ratio + ] + self.num_per_source[0] = batch_size - sum(self.num_per_source[1:]) + + assert sum(self.num_per_source) == batch_size, \ + 'The sum of num_per_source must be equal to ' \ + f'batch_size, but get {self.num_per_source}' + + self.seed = sync_random_seed() if seed is None else seed + self.shuffle = shuffle + self.source2inds = { + source: self._indices_of_rank(len(ds)) + for source, ds in enumerate(dataset.datasets) + } + + def _infinite_indices(self, sample_size: int) -> Iterator[int]: + """Infinitely yield a sequence of indices.""" + g = torch.Generator() + g.manual_seed(self.seed) + while True: + if self.shuffle: + yield from torch.randperm(sample_size, generator=g).tolist() + else: + yield from torch.arange(sample_size).tolist() + + def _indices_of_rank(self, sample_size: int) -> Iterator[int]: + """Slice the infinite indices by rank.""" + yield from itertools.islice( + self._infinite_indices(sample_size), self.rank, None, + self.world_size) + + def __iter__(self) -> Iterator[int]: + batch_buffer = [] + while True: + for source, num in enumerate(self.num_per_source): + batch_buffer_per_source = [] + for idx in self.source2inds[source]: + idx += self.cumulative_sizes[source] + batch_buffer_per_source.append(idx) + if len(batch_buffer_per_source) == num: + batch_buffer += batch_buffer_per_source + break + yield from batch_buffer + batch_buffer = [] + + def __len__(self) -> int: + return len(self.dataset) + + def set_epoch(self, epoch: int) -> None: + """Not supported in `epoch-based runner.""" + pass + + +@DATA_SAMPLERS.register_module() +class GroupMultiSourceSampler(MultiSourceSampler): + r"""Group Multi-Source Infinite Sampler. + + According to the sampling ratio, sample data from different + datasets but the same group to form batches. + + Args: + dataset (Sized): The dataset. + batch_size (int): Size of mini-batch. + source_ratio (list[int | float]): The sampling ratio of different + source datasets in a mini-batch. + shuffle (bool): Whether shuffle the dataset or not. Defaults to True. + seed (int, optional): Random seed. If None, set a random seed. + Defaults to None. + """ + + def __init__(self, + dataset: BaseDataset, + batch_size: int, + source_ratio: List[Union[int, float]], + shuffle: bool = True, + seed: Optional[int] = None) -> None: + super().__init__( + dataset=dataset, + batch_size=batch_size, + source_ratio=source_ratio, + shuffle=shuffle, + seed=seed) + + self._get_source_group_info() + self.group_source2inds = [{ + source: + self._indices_of_rank(self.group2size_per_source[source][group]) + for source in range(len(dataset.datasets)) + } for group in range(len(self.group_ratio))] + + def _get_source_group_info(self) -> None: + self.group2size_per_source = [{0: 0, 1: 0}, {0: 0, 1: 0}] + self.group2inds_per_source = [{0: [], 1: []}, {0: [], 1: []}] + for source, dataset in enumerate(self.dataset.datasets): + for idx in range(len(dataset)): + data_info = dataset.get_data_info(idx) + width, height = data_info['width'], data_info['height'] + group = 0 if width < height else 1 + self.group2size_per_source[source][group] += 1 + self.group2inds_per_source[source][group].append(idx) + + self.group_sizes = np.zeros(2, dtype=np.int64) + for group2size in self.group2size_per_source: + for group, size in group2size.items(): + self.group_sizes[group] += size + self.group_ratio = self.group_sizes / sum(self.group_sizes) + + def __iter__(self) -> Iterator[int]: + batch_buffer = [] + while True: + group = np.random.choice( + list(range(len(self.group_ratio))), p=self.group_ratio) + for source, num in enumerate(self.num_per_source): + batch_buffer_per_source = [] + for idx in self.group_source2inds[group][source]: + idx = self.group2inds_per_source[source][group][ + idx] + self.cumulative_sizes[source] + batch_buffer_per_source.append(idx) + if len(batch_buffer_per_source) == num: + batch_buffer += batch_buffer_per_source + break + yield from batch_buffer + batch_buffer = [] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/samplers/track_img_sampler.py b/mmdet_code/SR-TOD/mmdet/datasets/samplers/track_img_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..d7db629f40f3f24bdf14cd852ccc4472d1d50f1b --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/samplers/track_img_sampler.py @@ -0,0 +1,146 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +import random +from typing import Iterator, Optional, Sized + +import numpy as np +from mmengine.dataset import ClassBalancedDataset, ConcatDataset +from mmengine.dist import get_dist_info, sync_random_seed +from torch.utils.data import Sampler + +from mmdet.registry import DATA_SAMPLERS +from ..base_video_dataset import BaseVideoDataset + + +@DATA_SAMPLERS.register_module() +class TrackImgSampler(Sampler): + """Sampler that providing image-level sampling outputs for video datasets + in tracking tasks. It could be both used in both distributed and + non-distributed environment. + If using the default sampler in pytorch, the subsequent data receiver will + get one video, which is not desired in some cases: + (Take a non-distributed environment as an example) + 1. In test mode, we want only one image is fed into the data pipeline. This + is in consideration of memory usage since feeding the whole video commonly + requires a large amount of memory (>=20G on MOTChallenge17 dataset), which + is not available in some machines. + 2. In training mode, we may want to make sure all the images in one video + are randomly sampled once in one epoch and this can not be guaranteed in + the default sampler in pytorch. + + Args: + dataset (Sized): Dataset used for sampling. + seed (int, optional): random seed used to shuffle the sampler. This + number should be identical across all processes in the distributed + group. Defaults to None. + """ + + def __init__( + self, + dataset: Sized, + seed: Optional[int] = None, + ) -> None: + rank, world_size = get_dist_info() + self.rank = rank + self.world_size = world_size + self.epoch = 0 + if seed is None: + self.seed = sync_random_seed() + else: + self.seed = seed + + self.dataset = dataset + self.indices = [] + # Hard code here to handle different dataset wrapper + if isinstance(self.dataset, ConcatDataset): + cat_datasets = self.dataset.datasets + assert isinstance( + cat_datasets[0], BaseVideoDataset + ), f'expected BaseVideoDataset, but got {type(cat_datasets[0])}' + self.test_mode = cat_datasets[0].test_mode + assert not self.test_mode, "'ConcatDataset' should not exist in " + 'test mode' + for dataset in cat_datasets: + num_videos = len(dataset) + for video_ind in range(num_videos): + self.indices.extend([ + (video_ind, frame_ind) for frame_ind in range( + dataset.get_len_per_video(video_ind)) + ]) + elif isinstance(self.dataset, ClassBalancedDataset): + ori_dataset = self.dataset.dataset + assert isinstance( + ori_dataset, BaseVideoDataset + ), f'expected BaseVideoDataset, but got {type(ori_dataset)}' + self.test_mode = ori_dataset.test_mode + assert not self.test_mode, "'ClassBalancedDataset' should not " + 'exist in test mode' + video_indices = self.dataset.repeat_indices + for index in video_indices: + self.indices.extend([(index, frame_ind) for frame_ind in range( + ori_dataset.get_len_per_video(index))]) + else: + assert isinstance( + self.dataset, BaseVideoDataset + ), 'TrackImgSampler is only supported in BaseVideoDataset or ' + 'dataset wrapper: ClassBalancedDataset and ConcatDataset, but ' + f'got {type(self.dataset)} ' + self.test_mode = self.dataset.test_mode + num_videos = len(self.dataset) + + if self.test_mode: + # in test mode, the images belong to the same video must be put + # on the same device. + if num_videos < self.world_size: + raise ValueError(f'only {num_videos} videos loaded,' + f'but {self.world_size} gpus were given.') + chunks = np.array_split( + list(range(num_videos)), self.world_size) + for videos_inds in chunks: + indices_chunk = [] + for video_ind in videos_inds: + indices_chunk.extend([ + (video_ind, frame_ind) for frame_ind in range( + self.dataset.get_len_per_video(video_ind)) + ]) + self.indices.append(indices_chunk) + else: + for video_ind in range(num_videos): + self.indices.extend([ + (video_ind, frame_ind) for frame_ind in range( + self.dataset.get_len_per_video(video_ind)) + ]) + + if self.test_mode: + self.num_samples = len(self.indices[self.rank]) + self.total_size = sum( + [len(index_list) for index_list in self.indices]) + else: + self.num_samples = int( + math.ceil(len(self.indices) * 1.0 / self.world_size)) + self.total_size = self.num_samples * self.world_size + + def __iter__(self) -> Iterator: + if self.test_mode: + # in test mode, the order of frames can not be shuffled. + indices = self.indices[self.rank] + else: + # deterministically shuffle based on epoch + rng = random.Random(self.epoch + self.seed) + indices = rng.sample(self.indices, len(self.indices)) + + # add extra samples to make it evenly divisible + indices += indices[:(self.total_size - len(indices))] + assert len(indices) == self.total_size + + # subsample + indices = indices[self.rank:self.total_size:self.world_size] + assert len(indices) == self.num_samples + + return iter(indices) + + def __len__(self): + return self.num_samples + + def set_epoch(self, epoch): + self.epoch = epoch diff --git a/mmdet_code/SR-TOD/mmdet/datasets/soda_d.py b/mmdet_code/SR-TOD/mmdet/datasets/soda_d.py new file mode 100644 index 0000000000000000000000000000000000000000..1d04645417b73a435bcceffb354228b18ff83b5f --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/soda_d.py @@ -0,0 +1,190 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class SODA_DDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('people', 'rider', 'bicycle', 'motor', 'vehicle', + 'traffic-sign', 'traffic-light', 'traffic-camera', + 'warning-cone'), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/tinyperson.py b/mmdet_code/SR-TOD/mmdet/datasets/tinyperson.py new file mode 100644 index 0000000000000000000000000000000000000000..010692e0bb5e22baa5a321c389ebdacc89b5a395 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/tinyperson.py @@ -0,0 +1,188 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class TinyPersonDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('person',), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/__init__.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5ab375838283d5f14012494805c9ba117688472 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/__init__.py @@ -0,0 +1,41 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .augment_wrappers import AutoAugment, RandAugment +from .colorspace import (AutoContrast, Brightness, Color, ColorTransform, + Contrast, Equalize, Invert, Posterize, Sharpness, + Solarize, SolarizeAdd) +from .formatting import (ImageToTensor, PackDetInputs, PackReIDInputs, + PackTrackInputs, ToTensor, Transpose) +from .frame_sampling import BaseFrameSample, UniformRefFrameSample +from .geometric import (GeomTransform, Rotate, ShearX, ShearY, TranslateX, + TranslateY) +from .instaboost import InstaBoost +from .loading import (FilterAnnotations, InferencerLoader, LoadAnnotations, + LoadEmptyAnnotations, LoadImageFromNDArray, + LoadMultiChannelImageFromFiles, LoadPanopticAnnotations, + LoadProposals, LoadTrackAnnotations) +from .transforms import (Albu, CachedMixUp, CachedMosaic, CopyPaste, CutOut, + Expand, FixScaleResize, FixShapeResize, + MinIoURandomCrop, MixUp, Mosaic, Pad, + PhotoMetricDistortion, RandomAffine, + RandomCenterCropPad, RandomCrop, RandomErasing, + RandomFlip, RandomShift, Resize, ResizeShortestEdge, + SegRescale, YOLOXHSVRandomAug) +from .wrappers import MultiBranch, ProposalBroadcaster, RandomOrder + +__all__ = [ + 'PackDetInputs', 'ToTensor', 'ImageToTensor', 'Transpose', + 'LoadImageFromNDArray', 'LoadAnnotations', 'LoadPanopticAnnotations', + 'LoadMultiChannelImageFromFiles', 'LoadProposals', 'Resize', 'RandomFlip', + 'RandomCrop', 'SegRescale', 'MinIoURandomCrop', 'Expand', + 'PhotoMetricDistortion', 'Albu', 'InstaBoost', 'RandomCenterCropPad', + 'AutoAugment', 'CutOut', 'ShearX', 'ShearY', 'Rotate', 'Color', 'Equalize', + 'Brightness', 'Contrast', 'TranslateX', 'TranslateY', 'RandomShift', + 'Mosaic', 'MixUp', 'RandomAffine', 'YOLOXHSVRandomAug', 'CopyPaste', + 'FilterAnnotations', 'Pad', 'GeomTransform', 'ColorTransform', + 'RandAugment', 'Sharpness', 'Solarize', 'SolarizeAdd', 'Posterize', + 'AutoContrast', 'Invert', 'MultiBranch', 'RandomErasing', + 'LoadEmptyAnnotations', 'RandomOrder', 'CachedMosaic', 'CachedMixUp', + 'FixShapeResize', 'ProposalBroadcaster', 'InferencerLoader', + 'LoadTrackAnnotations', 'BaseFrameSample', 'UniformRefFrameSample', + 'PackTrackInputs', 'PackReIDInputs', 'FixScaleResize', 'ResizeShortestEdge' +] diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/augment_wrappers.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/augment_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..19fae6efdf66aa4c26bb85a2f2c96a1e079320b8 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/augment_wrappers.py @@ -0,0 +1,264 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional, Union + +import numpy as np +from mmcv.transforms import RandomChoice +from mmcv.transforms.utils import cache_randomness +from mmengine.config import ConfigDict + +from mmdet.registry import TRANSFORMS + +# AutoAugment uses reinforcement learning to search for +# some widely useful data augmentation strategies, +# here we provide AUTOAUG_POLICIES_V0. +# For AUTOAUG_POLICIES_V0, each tuple is an augmentation +# operation of the form (operation, probability, magnitude). +# Each element in policies is a policy that will be applied +# sequentially on the image. + +# RandAugment defines a data augmentation search space, RANDAUG_SPACE, +# sampling 1~3 data augmentations each time, and +# setting the magnitude of each data augmentation randomly, +# which will be applied sequentially on the image. + +_MAX_LEVEL = 10 + +AUTOAUG_POLICIES_V0 = [ + [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], + [('Color', 0.4, 9), ('Equalize', 0.6, 3)], + [('Color', 0.4, 1), ('Rotate', 0.6, 8)], + [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)], + [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)], + [('Color', 0.2, 0), ('Equalize', 0.8, 8)], + [('Equalize', 0.4, 8), ('SolarizeAdd', 0.8, 3)], + [('ShearX', 0.2, 9), ('Rotate', 0.6, 8)], + [('Color', 0.6, 1), ('Equalize', 1.0, 2)], + [('Invert', 0.4, 9), ('Rotate', 0.6, 0)], + [('Equalize', 1.0, 9), ('ShearY', 0.6, 3)], + [('Color', 0.4, 7), ('Equalize', 0.6, 0)], + [('Posterize', 0.4, 6), ('AutoContrast', 0.4, 7)], + [('Solarize', 0.6, 8), ('Color', 0.6, 9)], + [('Solarize', 0.2, 4), ('Rotate', 0.8, 9)], + [('Rotate', 1.0, 7), ('TranslateY', 0.8, 9)], + [('ShearX', 0.0, 0), ('Solarize', 0.8, 4)], + [('ShearY', 0.8, 0), ('Color', 0.6, 4)], + [('Color', 1.0, 0), ('Rotate', 0.6, 2)], + [('Equalize', 0.8, 4), ('Equalize', 0.0, 8)], + [('Equalize', 1.0, 4), ('AutoContrast', 0.6, 2)], + [('ShearY', 0.4, 7), ('SolarizeAdd', 0.6, 7)], + [('Posterize', 0.8, 2), ('Solarize', 0.6, 10)], + [('Solarize', 0.6, 8), ('Equalize', 0.6, 1)], + [('Color', 0.8, 6), ('Rotate', 0.4, 5)], +] + + +def policies_v0(): + """Autoaugment policies that was used in AutoAugment Paper.""" + policies = list() + for policy_args in AUTOAUG_POLICIES_V0: + policy = list() + for args in policy_args: + policy.append(dict(type=args[0], prob=args[1], level=args[2])) + policies.append(policy) + return policies + + +RANDAUG_SPACE = [[dict(type='AutoContrast')], [dict(type='Equalize')], + [dict(type='Invert')], [dict(type='Rotate')], + [dict(type='Posterize')], [dict(type='Solarize')], + [dict(type='SolarizeAdd')], [dict(type='Color')], + [dict(type='Contrast')], [dict(type='Brightness')], + [dict(type='Sharpness')], [dict(type='ShearX')], + [dict(type='ShearY')], [dict(type='TranslateX')], + [dict(type='TranslateY')]] + + +def level_to_mag(level: Optional[int], min_mag: float, + max_mag: float) -> float: + """Map from level to magnitude.""" + if level is None: + return round(np.random.rand() * (max_mag - min_mag) + min_mag, 1) + else: + return round(level / _MAX_LEVEL * (max_mag - min_mag) + min_mag, 1) + + +@TRANSFORMS.register_module() +class AutoAugment(RandomChoice): + """Auto augmentation. + + This data augmentation is proposed in `AutoAugment: Learning + Augmentation Policies from Data `_ + and in `Learning Data Augmentation Strategies for Object Detection + `_. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_bboxes_labels + - gt_masks + - gt_ignore_flags + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + policies (List[List[Union[dict, ConfigDict]]]): + The policies of auto augmentation.Each policy in ``policies`` + is a specific augmentation policy, and is composed by several + augmentations. When AutoAugment is called, a random policy in + ``policies`` will be selected to augment images. + Defaults to policy_v0(). + prob (list[float], optional): The probabilities associated + with each policy. The length should be equal to the policy + number and the sum should be 1. If not given, a uniform + distribution will be assumed. Defaults to None. + + Examples: + >>> policies = [ + >>> [ + >>> dict(type='Sharpness', prob=0.0, level=8), + >>> dict(type='ShearX', prob=0.4, level=0,) + >>> ], + >>> [ + >>> dict(type='Rotate', prob=0.6, level=10), + >>> dict(type='Color', prob=1.0, level=6) + >>> ] + >>> ] + >>> augmentation = AutoAugment(policies) + >>> img = np.ones(100, 100, 3) + >>> gt_bboxes = np.ones(10, 4) + >>> results = dict(img=img, gt_bboxes=gt_bboxes) + >>> results = augmentation(results) + """ + + def __init__(self, + policies: List[List[Union[dict, ConfigDict]]] = policies_v0(), + prob: Optional[List[float]] = None) -> None: + assert isinstance(policies, list) and len(policies) > 0, \ + 'Policies must be a non-empty list.' + for policy in policies: + assert isinstance(policy, list) and len(policy) > 0, \ + 'Each policy in policies must be a non-empty list.' + for augment in policy: + assert isinstance(augment, dict) and 'type' in augment, \ + 'Each specific augmentation must be a dict with key' \ + ' "type".' + super().__init__(transforms=policies, prob=prob) + self.policies = policies + + def __repr__(self) -> str: + return f'{self.__class__.__name__}(policies={self.policies}, ' \ + f'prob={self.prob})' + + +@TRANSFORMS.register_module() +class RandAugment(RandomChoice): + """Rand augmentation. + + This data augmentation is proposed in `RandAugment: + Practical automated data augmentation with a reduced + search space `_. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_bboxes_labels + - gt_masks + - gt_ignore_flags + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + aug_space (List[List[Union[dict, ConfigDict]]]): The augmentation space + of rand augmentation. Each augmentation transform in ``aug_space`` + is a specific transform, and is composed by several augmentations. + When RandAugment is called, a random transform in ``aug_space`` + will be selected to augment images. Defaults to aug_space. + aug_num (int): Number of augmentation to apply equentially. + Defaults to 2. + prob (list[float], optional): The probabilities associated with + each augmentation. The length should be equal to the + augmentation space and the sum should be 1. If not given, + a uniform distribution will be assumed. Defaults to None. + + Examples: + >>> aug_space = [ + >>> dict(type='Sharpness'), + >>> dict(type='ShearX'), + >>> dict(type='Color'), + >>> ], + >>> augmentation = RandAugment(aug_space) + >>> img = np.ones(100, 100, 3) + >>> gt_bboxes = np.ones(10, 4) + >>> results = dict(img=img, gt_bboxes=gt_bboxes) + >>> results = augmentation(results) + """ + + def __init__(self, + aug_space: List[Union[dict, ConfigDict]] = RANDAUG_SPACE, + aug_num: int = 2, + prob: Optional[List[float]] = None) -> None: + assert isinstance(aug_space, list) and len(aug_space) > 0, \ + 'Augmentation space must be a non-empty list.' + for aug in aug_space: + assert isinstance(aug, list) and len(aug) == 1, \ + 'Each augmentation in aug_space must be a list.' + for transform in aug: + assert isinstance(transform, dict) and 'type' in transform, \ + 'Each specific transform must be a dict with key' \ + ' "type".' + super().__init__(transforms=aug_space, prob=prob) + self.aug_space = aug_space + self.aug_num = aug_num + + @cache_randomness + def random_pipeline_index(self): + indices = np.arange(len(self.transforms)) + return np.random.choice( + indices, self.aug_num, p=self.prob, replace=False) + + def transform(self, results: dict) -> dict: + """Transform function to use RandAugment. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with RandAugment. + """ + for idx in self.random_pipeline_index(): + results = self.transforms[idx](results) + return results + + def __repr__(self) -> str: + return f'{self.__class__.__name__}(' \ + f'aug_space={self.aug_space}, '\ + f'aug_num={self.aug_num}, ' \ + f'prob={self.prob})' diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/colorspace.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/colorspace.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ba2e97c7eedf65df5ab8942ee461f48a785f39 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/colorspace.py @@ -0,0 +1,493 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +from typing import Optional + +import mmcv +import numpy as np +from mmcv.transforms import BaseTransform +from mmcv.transforms.utils import cache_randomness + +from mmdet.registry import TRANSFORMS +from .augment_wrappers import _MAX_LEVEL, level_to_mag + + +@TRANSFORMS.register_module() +class ColorTransform(BaseTransform): + """Base class for color transformations. All color transformations need to + inherit from this base class. ``ColorTransform`` unifies the class + attributes and class functions of color transformations (Color, Brightness, + Contrast, Sharpness, Solarize, SolarizeAdd, Equalize, AutoContrast, Invert, + and Posterize), and only distort color channels, without impacting the + locations of the instances. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing the geometric + transformation and should be in range [0, 1]. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for color transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for color transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0 <= prob <= 1.0, f'The probability of the transformation ' \ + f'should be in range [0,1], got {prob}.' + assert level is None or isinstance(level, int), \ + f'The level should be None or type int, got {type(level)}.' + assert level is None or 0 <= level <= _MAX_LEVEL, \ + f'The level should be in range [0,{_MAX_LEVEL}], got {level}.' + assert isinstance(min_mag, float), \ + f'min_mag should be type float, got {type(min_mag)}.' + assert isinstance(max_mag, float), \ + f'max_mag should be type float, got {type(max_mag)}.' + assert min_mag <= max_mag, \ + f'min_mag should smaller than max_mag, ' \ + f'got min_mag={min_mag} and max_mag={max_mag}' + self.prob = prob + self.level = level + self.min_mag = min_mag + self.max_mag = max_mag + + def _transform_img(self, results: dict, mag: float) -> None: + """Transform the image.""" + pass + + @cache_randomness + def _random_disable(self): + """Randomly disable the transform.""" + return np.random.rand() > self.prob + + @cache_randomness + def _get_mag(self): + """Get the magnitude of the transform.""" + return level_to_mag(self.level, self.min_mag, self.max_mag) + + def transform(self, results: dict) -> dict: + """Transform function for images. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Transformed results. + """ + + if self._random_disable(): + return results + mag = self._get_mag() + self._transform_img(results, mag) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'level={self.level}, ' + repr_str += f'min_mag={self.min_mag}, ' + repr_str += f'max_mag={self.max_mag})' + return repr_str + + +@TRANSFORMS.register_module() +class Color(ColorTransform): + """Adjust the color balance of the image, in a manner similar to the + controls on a colour TV set. A magnitude=0 gives a black & white image, + whereas magnitude=1 gives the original image. The bboxes, masks and + segmentations are not modified. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Color transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Color transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for Color transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0. <= min_mag <= 2.0, \ + f'min_mag for Color should be in range [0,2], got {min_mag}.' + assert 0. <= max_mag <= 2.0, \ + f'max_mag for Color should be in range [0,2], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Apply Color transformation to image.""" + # NOTE defaultly the image should be BGR format + img = results['img'] + results['img'] = mmcv.adjust_color(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Brightness(ColorTransform): + """Adjust the brightness of the image. A magnitude=0 gives a black image, + whereas magnitude=1 gives the original image. The bboxes, masks and + segmentations are not modified. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Brightness transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Brightness transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for Brightness transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0. <= min_mag <= 2.0, \ + f'min_mag for Brightness should be in range [0,2], got {min_mag}.' + assert 0. <= max_mag <= 2.0, \ + f'max_mag for Brightness should be in range [0,2], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Adjust the brightness of image.""" + img = results['img'] + results['img'] = mmcv.adjust_brightness(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Contrast(ColorTransform): + """Control the contrast of the image. A magnitude=0 gives a gray image, + whereas magnitude=1 gives the original imageThe bboxes, masks and + segmentations are not modified. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Contrast transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Contrast transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for Contrast transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0. <= min_mag <= 2.0, \ + f'min_mag for Contrast should be in range [0,2], got {min_mag}.' + assert 0. <= max_mag <= 2.0, \ + f'max_mag for Contrast should be in range [0,2], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Adjust the image contrast.""" + img = results['img'] + results['img'] = mmcv.adjust_contrast(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Sharpness(ColorTransform): + """Adjust images sharpness. A positive magnitude would enhance the + sharpness and a negative magnitude would make the image blurry. A + magnitude=0 gives the origin img. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Sharpness transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Sharpness transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for Sharpness transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0. <= min_mag <= 2.0, \ + f'min_mag for Sharpness should be in range [0,2], got {min_mag}.' + assert 0. <= max_mag <= 2.0, \ + f'max_mag for Sharpness should be in range [0,2], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Adjust the image sharpness.""" + img = results['img'] + results['img'] = mmcv.adjust_sharpness(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Solarize(ColorTransform): + """Solarize images (Invert all pixels above a threshold value of + magnitude.). + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Solarize transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Solarize transformation. + Defaults to 0.0. + max_mag (float): The maximum magnitude for Solarize transformation. + Defaults to 256.0. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 256.0) -> None: + assert 0. <= min_mag <= 256.0, f'min_mag for Solarize should be ' \ + f'in range [0, 256], got {min_mag}.' + assert 0. <= max_mag <= 256.0, f'max_mag for Solarize should be ' \ + f'in range [0, 256], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Invert all pixel values above magnitude.""" + img = results['img'] + results['img'] = mmcv.solarize(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class SolarizeAdd(ColorTransform): + """SolarizeAdd images. For each pixel in the image that is less than 128, + add an additional amount to it decided by the magnitude. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing SolarizeAdd + transformation. Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for SolarizeAdd transformation. + Defaults to 0.0. + max_mag (float): The maximum magnitude for SolarizeAdd transformation. + Defaults to 110.0. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 110.0) -> None: + assert 0. <= min_mag <= 110.0, f'min_mag for SolarizeAdd should be ' \ + f'in range [0, 110], got {min_mag}.' + assert 0. <= max_mag <= 110.0, f'max_mag for SolarizeAdd should be ' \ + f'in range [0, 110], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """SolarizeAdd the image.""" + img = results['img'] + img_solarized = np.where(img < 128, np.minimum(img + mag, 255), img) + results['img'] = img_solarized.astype(img.dtype) + + +@TRANSFORMS.register_module() +class Posterize(ColorTransform): + """Posterize images (reduce the number of bits for each color channel). + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Posterize + transformation. Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Posterize transformation. + Defaults to 0.0. + max_mag (float): The maximum magnitude for Posterize transformation. + Defaults to 4.0. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 4.0) -> None: + assert 0. <= min_mag <= 8.0, f'min_mag for Posterize should be ' \ + f'in range [0, 8], got {min_mag}.' + assert 0. <= max_mag <= 8.0, f'max_mag for Posterize should be ' \ + f'in range [0, 8], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Posterize the image.""" + img = results['img'] + results['img'] = mmcv.posterize(img, math.ceil(mag)).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Equalize(ColorTransform): + """Equalize the image histogram. The bboxes, masks and segmentations are + not modified. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Equalize transformation. + Defaults to 1.0. + level (int, optional): No use for Equalize transformation. + Defaults to None. + min_mag (float): No use for Equalize transformation. Defaults to 0.1. + max_mag (float): No use for Equalize transformation. Defaults to 1.9. + """ + + def _transform_img(self, results: dict, mag: float) -> None: + """Equalizes the histogram of one image.""" + img = results['img'] + results['img'] = mmcv.imequalize(img).astype(img.dtype) + + +@TRANSFORMS.register_module() +class AutoContrast(ColorTransform): + """Auto adjust image contrast. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing AutoContrast should + be in range [0, 1]. Defaults to 1.0. + level (int, optional): No use for AutoContrast transformation. + Defaults to None. + min_mag (float): No use for AutoContrast transformation. + Defaults to 0.1. + max_mag (float): No use for AutoContrast transformation. + Defaults to 1.9. + """ + + def _transform_img(self, results: dict, mag: float) -> None: + """Auto adjust image contrast.""" + img = results['img'] + results['img'] = mmcv.auto_contrast(img).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Invert(ColorTransform): + """Invert images. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing invert therefore should + be in range [0, 1]. Defaults to 1.0. + level (int, optional): No use for Invert transformation. + Defaults to None. + min_mag (float): No use for Invert transformation. Defaults to 0.1. + max_mag (float): No use for Invert transformation. Defaults to 1.9. + """ + + def _transform_img(self, results: dict, mag: float) -> None: + """Invert the image.""" + img = results['img'] + results['img'] = mmcv.iminvert(img).astype(img.dtype) diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/formatting.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..83fada30b1f9018eccae5054c396d71de3b78a07 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/formatting.py @@ -0,0 +1,514 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional, Sequence + +import numpy as np +from mmcv.transforms import to_tensor +from mmcv.transforms.base import BaseTransform +from mmengine.structures import InstanceData, PixelData + +from mmdet.registry import TRANSFORMS +from mmdet.structures import DetDataSample, ReIDDataSample, TrackDataSample +from mmdet.structures.bbox import BaseBoxes + + +@TRANSFORMS.register_module() +class PackDetInputs(BaseTransform): + """Pack the inputs data for the detection / semantic segmentation / + panoptic segmentation. + + The ``img_meta`` item is always populated. The contents of the + ``img_meta`` dictionary depends on ``meta_keys``. By default this includes: + + - ``img_id``: id of the image + + - ``img_path``: path to the image file + + - ``ori_shape``: original shape of the image as a tuple (h, w) + + - ``img_shape``: shape of the image input to the network as a tuple \ + (h, w). Note that images may be zero padded on the \ + bottom/right if the batch tensor is larger than this shape. + + - ``scale_factor``: a float indicating the preprocessing scale + + - ``flip``: a boolean indicating if image flip transform was used + + - ``flip_direction``: the flipping direction + + Args: + meta_keys (Sequence[str], optional): Meta keys to be converted to + ``mmcv.DataContainer`` and collected in ``data[img_metas]``. + Default: ``('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction')`` + """ + mapping_table = { + 'gt_bboxes': 'bboxes', + 'gt_bboxes_labels': 'labels', + 'gt_masks': 'masks' + } + + def __init__(self, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction')): + self.meta_keys = meta_keys + + def transform(self, results: dict) -> dict: + """Method to pack the input data. + + Args: + results (dict): Result dict from the data pipeline. + + Returns: + dict: + + - 'inputs' (obj:`torch.Tensor`): The forward data of models. + - 'data_sample' (obj:`DetDataSample`): The annotation info of the + sample. + """ + packed_results = dict() + if 'img' in results: + img = results['img'] + if len(img.shape) < 3: + img = np.expand_dims(img, -1) + # To improve the computational speed by by 3-5 times, apply: + # If image is not contiguous, use + # `numpy.transpose()` followed by `numpy.ascontiguousarray()` + # If image is already contiguous, use + # `torch.permute()` followed by `torch.contiguous()` + # Refer to https://github.com/open-mmlab/mmdetection/pull/9533 + # for more details + if not img.flags.c_contiguous: + img = np.ascontiguousarray(img.transpose(2, 0, 1)) + img = to_tensor(img) + else: + img = to_tensor(img).permute(2, 0, 1).contiguous() + + packed_results['inputs'] = img + + if 'gt_ignore_flags' in results: + valid_idx = np.where(results['gt_ignore_flags'] == 0)[0] + ignore_idx = np.where(results['gt_ignore_flags'] == 1)[0] + + data_sample = DetDataSample() + instance_data = InstanceData() + ignore_instance_data = InstanceData() + + for key in self.mapping_table.keys(): + if key not in results: + continue + if key == 'gt_masks' or isinstance(results[key], BaseBoxes): + if 'gt_ignore_flags' in results: + instance_data[ + self.mapping_table[key]] = results[key][valid_idx] + ignore_instance_data[ + self.mapping_table[key]] = results[key][ignore_idx] + else: + instance_data[self.mapping_table[key]] = results[key] + else: + if 'gt_ignore_flags' in results: + instance_data[self.mapping_table[key]] = to_tensor( + results[key][valid_idx]) + ignore_instance_data[self.mapping_table[key]] = to_tensor( + results[key][ignore_idx]) + else: + instance_data[self.mapping_table[key]] = to_tensor( + results[key]) + data_sample.gt_instances = instance_data + data_sample.ignored_instances = ignore_instance_data + + if 'proposals' in results: + proposals = InstanceData( + bboxes=to_tensor(results['proposals']), + scores=to_tensor(results['proposals_scores'])) + data_sample.proposals = proposals + + if 'gt_seg_map' in results: + gt_sem_seg_data = dict( + sem_seg=to_tensor(results['gt_seg_map'][None, ...].copy())) + gt_sem_seg_data = PixelData(**gt_sem_seg_data) + if 'ignore_index' in results: + metainfo = dict(ignore_index=results['ignore_index']) + gt_sem_seg_data.set_metainfo(metainfo) + data_sample.gt_sem_seg = gt_sem_seg_data + + img_meta = {} + for key in self.meta_keys: + assert key in results, f'`{key}` is not found in `results`, ' \ + f'the valid keys are {list(results)}.' + img_meta[key] = results[key] + + data_sample.set_metainfo(img_meta) + packed_results['data_samples'] = data_sample + + return packed_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(meta_keys={self.meta_keys})' + return repr_str + + +@TRANSFORMS.register_module() +class ToTensor: + """Convert some results to :obj:`torch.Tensor` by given keys. + + Args: + keys (Sequence[str]): Keys that need to be converted to Tensor. + """ + + def __init__(self, keys): + self.keys = keys + + def __call__(self, results): + """Call function to convert data in results to :obj:`torch.Tensor`. + + Args: + results (dict): Result dict contains the data to convert. + + Returns: + dict: The result dict contains the data converted + to :obj:`torch.Tensor`. + """ + for key in self.keys: + results[key] = to_tensor(results[key]) + return results + + def __repr__(self): + return self.__class__.__name__ + f'(keys={self.keys})' + + +@TRANSFORMS.register_module() +class ImageToTensor: + """Convert image to :obj:`torch.Tensor` by given keys. + + The dimension order of input image is (H, W, C). The pipeline will convert + it to (C, H, W). If only 2 dimension (H, W) is given, the output would be + (1, H, W). + + Args: + keys (Sequence[str]): Key of images to be converted to Tensor. + """ + + def __init__(self, keys): + self.keys = keys + + def __call__(self, results): + """Call function to convert image in results to :obj:`torch.Tensor` and + transpose the channel order. + + Args: + results (dict): Result dict contains the image data to convert. + + Returns: + dict: The result dict contains the image converted + to :obj:`torch.Tensor` and permuted to (C, H, W) order. + """ + for key in self.keys: + img = results[key] + if len(img.shape) < 3: + img = np.expand_dims(img, -1) + results[key] = to_tensor(img).permute(2, 0, 1).contiguous() + + return results + + def __repr__(self): + return self.__class__.__name__ + f'(keys={self.keys})' + + +@TRANSFORMS.register_module() +class Transpose: + """Transpose some results by given keys. + + Args: + keys (Sequence[str]): Keys of results to be transposed. + order (Sequence[int]): Order of transpose. + """ + + def __init__(self, keys, order): + self.keys = keys + self.order = order + + def __call__(self, results): + """Call function to transpose the channel order of data in results. + + Args: + results (dict): Result dict contains the data to transpose. + + Returns: + dict: The result dict contains the data transposed to \ + ``self.order``. + """ + for key in self.keys: + results[key] = results[key].transpose(self.order) + return results + + def __repr__(self): + return self.__class__.__name__ + \ + f'(keys={self.keys}, order={self.order})' + + +@TRANSFORMS.register_module() +class WrapFieldsToLists: + """Wrap fields of the data dictionary into lists for evaluation. + + This class can be used as a last step of a test or validation + pipeline for single image evaluation or inference. + + Example: + >>> test_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> 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']), + >>> dict(type='WrapFieldsToLists') + >>> ] + """ + + def __call__(self, results): + """Call function to wrap fields into lists. + + Args: + results (dict): Result dict contains the data to wrap. + + Returns: + dict: The result dict where value of ``self.keys`` are wrapped \ + into list. + """ + + # Wrap dict fields into lists + for key, val in results.items(): + results[key] = [val] + return results + + def __repr__(self): + return f'{self.__class__.__name__}()' + + +@TRANSFORMS.register_module() +class PackTrackInputs(BaseTransform): + """Pack the inputs data for the multi object tracking and video instance + segmentation. All the information of images are packed to ``inputs``. All + the information except images are packed to ``data_samples``. In order to + get the original annotaiton and meta info, we add `instances` key into meta + keys. + + Args: + meta_keys (Sequence[str]): Meta keys to be collected in + ``data_sample.metainfo``. Defaults to None. + default_meta_keys (tuple): Default meta keys. Defaults to ('img_id', + 'img_path', 'ori_shape', 'img_shape', 'scale_factor', + 'flip', 'flip_direction', 'frame_id', 'is_video_data', + 'video_id', 'video_length', 'instances'). + """ + mapping_table = { + 'gt_bboxes': 'bboxes', + 'gt_bboxes_labels': 'labels', + 'gt_masks': 'masks', + 'gt_instances_ids': 'instances_ids' + } + + def __init__(self, + meta_keys: Optional[dict] = None, + default_meta_keys: tuple = ('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', + 'flip', 'flip_direction', + 'frame_id', 'video_id', + 'video_length', + 'ori_video_length', 'instances')): + self.meta_keys = default_meta_keys + if meta_keys is not None: + if isinstance(meta_keys, str): + meta_keys = (meta_keys, ) + else: + assert isinstance(meta_keys, tuple), \ + 'meta_keys must be str or tuple' + self.meta_keys += meta_keys + + def transform(self, results: dict) -> dict: + """Method to pack the input data. + Args: + results (dict): Result dict from the data pipeline. + Returns: + dict: + - 'inputs' (dict[Tensor]): The forward data of models. + - 'data_samples' (obj:`TrackDataSample`): The annotation info of + the samples. + """ + packed_results = dict() + packed_results['inputs'] = dict() + + # 1. Pack images + if 'img' in results: + imgs = results['img'] + imgs = np.stack(imgs, axis=0) + imgs = imgs.transpose(0, 3, 1, 2) + packed_results['inputs'] = to_tensor(imgs) + + # 2. Pack InstanceData + if 'gt_ignore_flags' in results: + gt_ignore_flags_list = results['gt_ignore_flags'] + valid_idx_list, ignore_idx_list = [], [] + for gt_ignore_flags in gt_ignore_flags_list: + valid_idx = np.where(gt_ignore_flags == 0)[0] + ignore_idx = np.where(gt_ignore_flags == 1)[0] + valid_idx_list.append(valid_idx) + ignore_idx_list.append(ignore_idx) + + assert 'img_id' in results, "'img_id' must contained in the results " + 'for counting the number of images' + + num_imgs = len(results['img_id']) + instance_data_list = [InstanceData() for _ in range(num_imgs)] + ignore_instance_data_list = [InstanceData() for _ in range(num_imgs)] + + for key in self.mapping_table.keys(): + if key not in results: + continue + if key == 'gt_masks': + mapped_key = self.mapping_table[key] + gt_masks_list = results[key] + if 'gt_ignore_flags' in results: + for i, gt_mask in enumerate(gt_masks_list): + valid_idx, ignore_idx = valid_idx_list[ + i], ignore_idx_list[i] + instance_data_list[i][mapped_key] = gt_mask[valid_idx] + ignore_instance_data_list[i][mapped_key] = gt_mask[ + ignore_idx] + + else: + for i, gt_mask in enumerate(gt_masks_list): + instance_data_list[i][mapped_key] = gt_mask + + else: + anns_list = results[key] + if 'gt_ignore_flags' in results: + for i, ann in enumerate(anns_list): + valid_idx, ignore_idx = valid_idx_list[ + i], ignore_idx_list[i] + instance_data_list[i][ + self.mapping_table[key]] = to_tensor( + ann[valid_idx]) + ignore_instance_data_list[i][ + self.mapping_table[key]] = to_tensor( + ann[ignore_idx]) + else: + for i, ann in enumerate(anns_list): + instance_data_list[i][ + self.mapping_table[key]] = to_tensor(ann) + + det_data_samples_list = [] + for i in range(num_imgs): + det_data_sample = DetDataSample() + det_data_sample.gt_instances = instance_data_list[i] + det_data_sample.ignored_instances = ignore_instance_data_list[i] + det_data_samples_list.append(det_data_sample) + + # 3. Pack metainfo + for key in self.meta_keys: + if key not in results: + continue + img_metas_list = results[key] + for i, img_meta in enumerate(img_metas_list): + det_data_samples_list[i].set_metainfo({f'{key}': img_meta}) + + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = det_data_samples_list + if 'key_frame_flags' in results: + key_frame_flags = np.asarray(results['key_frame_flags']) + key_frames_inds = np.where(key_frame_flags)[0].tolist() + ref_frames_inds = np.where(~key_frame_flags)[0].tolist() + track_data_sample.set_metainfo( + dict(key_frames_inds=key_frames_inds)) + track_data_sample.set_metainfo( + dict(ref_frames_inds=ref_frames_inds)) + + packed_results['data_samples'] = track_data_sample + return packed_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'meta_keys={self.meta_keys}, ' + repr_str += f'default_meta_keys={self.default_meta_keys})' + return repr_str + + +@TRANSFORMS.register_module() +class PackReIDInputs(BaseTransform): + """Pack the inputs data for the ReID. The ``meta_info`` item is always + populated. The contents of the ``meta_info`` dictionary depends on + ``meta_keys``. By default this includes: + + - ``img_path``: path to the image file. + - ``ori_shape``: original shape of the image as a tuple (H, W). + - ``img_shape``: shape of the image input to the network as a tuple + (H, W). Note that images may be zero padded on the bottom/right + if the batch tensor is larger than this shape. + - ``scale``: scale of the image as a tuple (W, H). + - ``scale_factor``: a float indicating the pre-processing scale. + - ``flip``: a boolean indicating if image flip transform was used. + - ``flip_direction``: the flipping direction. + Args: + meta_keys (Sequence[str], optional): The meta keys to saved in the + ``metainfo`` of the packed ``data_sample``. + """ + default_meta_keys = ('img_path', 'ori_shape', 'img_shape', 'scale', + 'scale_factor') + + def __init__(self, meta_keys: Sequence[str] = ()) -> None: + self.meta_keys = self.default_meta_keys + if meta_keys is not None: + if isinstance(meta_keys, str): + meta_keys = (meta_keys, ) + else: + assert isinstance(meta_keys, tuple), \ + 'meta_keys must be str or tuple.' + self.meta_keys += meta_keys + + def transform(self, results: dict) -> dict: + """Method to pack the input data. + Args: + results (dict): Result dict from the data pipeline. + Returns: + dict: + - 'inputs' (dict[Tensor]): The forward data of models. + - 'data_samples' (obj:`ReIDDataSample`): The meta info of the + sample. + """ + packed_results = dict(inputs=dict(), data_samples=None) + assert 'img' in results, 'Missing the key ``img``.' + _type = type(results['img']) + label = results['gt_label'] + + if _type == list: + img = results['img'] + label = np.stack(label, axis=0) # (N,) + assert all([type(v) == _type for v in results.values()]), \ + 'All items in the results must have the same type.' + else: + img = [results['img']] + + img = np.stack(img, axis=3) # (H, W, C, N) + img = img.transpose(3, 2, 0, 1) # (N, C, H, W) + img = np.ascontiguousarray(img) + + packed_results['inputs'] = to_tensor(img) + + data_sample = ReIDDataSample() + data_sample.set_gt_label(label) + + meta_info = dict() + for key in self.meta_keys: + meta_info[key] = results[key] + data_sample.set_metainfo(meta_info) + packed_results['data_samples'] = data_sample + + return packed_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(meta_keys={self.meta_keys})' + return repr_str diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/frame_sampling.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/frame_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..a91f1e7880f8f061f183dc30a01758d97b7d03da --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/frame_sampling.py @@ -0,0 +1,177 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import random +from collections import defaultdict +from typing import Dict, List, Optional, Union + +from mmcv.transforms import BaseTransform + +from mmdet.registry import TRANSFORMS + + +@TRANSFORMS.register_module() +class BaseFrameSample(BaseTransform): + """Directly get the key frame, no reference frames. + + Args: + collect_video_keys (list[str]): The keys of video info to be + collected. + """ + + def __init__(self, + collect_video_keys: List[str] = ['video_id', 'video_length']): + self.collect_video_keys = collect_video_keys + + def prepare_data(self, video_infos: dict, + sampled_inds: List[int]) -> Dict[str, List]: + """Prepare data for the subsequent pipeline. + + Args: + video_infos (dict): The whole video information. + sampled_inds (list[int]): The sampled frame indices. + + Returns: + dict: The processed data information. + """ + frames_anns = video_infos['images'] + final_data_info = defaultdict(list) + # for data in frames_anns: + for index in sampled_inds: + data = frames_anns[index] + # copy the info in video-level into img-level + for key in self.collect_video_keys: + if key == 'video_length': + data['ori_video_length'] = video_infos[key] + data['video_length'] = len(sampled_inds) + else: + data[key] = video_infos[key] + # Collate data_list (list of dict to dict of list) + for key, value in data.items(): + final_data_info[key].append(value) + + return final_data_info + + def transform(self, video_infos: dict) -> Optional[Dict[str, List]]: + """Transform the video information. + + Args: + video_infos (dict): The whole video information. + + Returns: + dict: The data information of the key frames. + """ + if 'key_frame_id' in video_infos: + key_frame_id = video_infos['key_frame_id'] + assert isinstance(video_infos['key_frame_id'], int) + else: + key_frame_id = random.sample( + list(range(video_infos['video_length'])), 1)[0] + results = self.prepare_data(video_infos, [key_frame_id]) + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(collect_video_keys={self.collect_video_keys})' + return repr_str + + +@TRANSFORMS.register_module() +class UniformRefFrameSample(BaseFrameSample): + """Uniformly sample reference frames. + + Args: + num_ref_imgs (int): Number of reference frames to be sampled. + frame_range (int | list[int]): Range of frames to be sampled around + key frame. If int, the range is [-frame_range, frame_range]. + Defaults to 10. + filter_key_img (bool): Whether to filter the key frame when + sampling reference frames. Defaults to True. + collect_video_keys (list[str]): The keys of video info to be + collected. + """ + + def __init__(self, + num_ref_imgs: int = 1, + frame_range: Union[int, List[int]] = 10, + filter_key_img: bool = True, + collect_video_keys: List[str] = ['video_id', 'video_length']): + self.num_ref_imgs = num_ref_imgs + self.filter_key_img = filter_key_img + if isinstance(frame_range, int): + assert frame_range >= 0, 'frame_range can not be a negative value.' + frame_range = [-frame_range, frame_range] + elif isinstance(frame_range, list): + assert len(frame_range) == 2, 'The length must be 2.' + assert frame_range[0] <= 0 and frame_range[1] >= 0 + for i in frame_range: + assert isinstance(i, int), 'Each element must be int.' + else: + raise TypeError('The type of frame_range must be int or list.') + self.frame_range = frame_range + super().__init__(collect_video_keys=collect_video_keys) + + def sampling_frames(self, video_length: int, key_frame_id: int): + """Sampling frames. + + Args: + video_length (int): The length of the video. + key_frame_id (int): The key frame id. + + Returns: + list[int]: The sampled frame indices. + """ + if video_length > 1: + left = max(0, key_frame_id + self.frame_range[0]) + right = min(key_frame_id + self.frame_range[1], video_length - 1) + frame_ids = list(range(0, video_length)) + + valid_ids = frame_ids[left:right + 1] + if self.filter_key_img and key_frame_id in valid_ids: + valid_ids.remove(key_frame_id) + assert len( + valid_ids + ) > 0, 'After filtering key frame, there are no valid frames' + if len(valid_ids) < self.num_ref_imgs: + valid_ids = valid_ids * self.num_ref_imgs + ref_frame_ids = random.sample(valid_ids, self.num_ref_imgs) + else: + ref_frame_ids = [key_frame_id] * self.num_ref_imgs + + sampled_frames_ids = [key_frame_id] + ref_frame_ids + sampled_frames_ids = sorted(sampled_frames_ids) + + key_frames_ind = sampled_frames_ids.index(key_frame_id) + key_frame_flags = [False] * len(sampled_frames_ids) + key_frame_flags[key_frames_ind] = True + return sampled_frames_ids, key_frame_flags + + def transform(self, video_infos: dict) -> Optional[Dict[str, List]]: + """Transform the video information. + + Args: + video_infos (dict): The whole video information. + + Returns: + dict: The data information of the sampled frames. + """ + if 'key_frame_id' in video_infos: + key_frame_id = video_infos['key_frame_id'] + assert isinstance(video_infos['key_frame_id'], int) + else: + key_frame_id = random.sample( + list(range(video_infos['video_length'])), 1)[0] + + (sampled_frames_ids, key_frame_flags) = self.sampling_frames( + video_infos['video_length'], key_frame_id=key_frame_id) + results = self.prepare_data(video_infos, sampled_frames_ids) + results['key_frame_flags'] = key_frame_flags + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(num_ref_imgs={self.num_ref_imgs}, ' + repr_str += f'frame_range={self.frame_range}, ' + repr_str += f'filter_key_img={self.filter_key_img}, ' + repr_str += f'collect_video_keys={self.collect_video_keys})' + return repr_str diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/geometric.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/geometric.py new file mode 100644 index 0000000000000000000000000000000000000000..d2cd6be258f73a69aa2c2b36fef64c6c4e46a2a4 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/geometric.py @@ -0,0 +1,754 @@ +# Copyright (c) OpenMMLab. All rights reserved. + +from typing import Optional, Union + +import cv2 +import mmcv +import numpy as np +from mmcv.transforms import BaseTransform +from mmcv.transforms.utils import cache_randomness + +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import autocast_box_type +from .augment_wrappers import _MAX_LEVEL, level_to_mag + + +@TRANSFORMS.register_module() +class GeomTransform(BaseTransform): + """Base class for geometric transformations. All geometric transformations + need to inherit from this base class. ``GeomTransform`` unifies the class + attributes and class functions of geometric transformations (ShearX, + ShearY, Rotate, TranslateX, and TranslateY), and records the homography + matrix. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for performing the geometric + transformation and should be in range [0, 1]. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for geometric transformation. + Defaults to 0.0. + max_mag (float): The maximum magnitude for geometric transformation. + Defaults to 1.0. + reversal_prob (float): The probability that reverses the geometric + transformation magnitude. Should be in range [0,1]. + Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 1.0, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0 <= prob <= 1.0, f'The probability of the transformation ' \ + f'should be in range [0,1], got {prob}.' + assert level is None or isinstance(level, int), \ + f'The level should be None or type int, got {type(level)}.' + assert level is None or 0 <= level <= _MAX_LEVEL, \ + f'The level should be in range [0,{_MAX_LEVEL}], got {level}.' + assert isinstance(min_mag, float), \ + f'min_mag should be type float, got {type(min_mag)}.' + assert isinstance(max_mag, float), \ + f'max_mag should be type float, got {type(max_mag)}.' + assert min_mag <= max_mag, \ + f'min_mag should smaller than max_mag, ' \ + f'got min_mag={min_mag} and max_mag={max_mag}' + assert isinstance(reversal_prob, float), \ + f'reversal_prob should be type float, got {type(max_mag)}.' + assert 0 <= reversal_prob <= 1.0, \ + f'The reversal probability of the transformation magnitude ' \ + f'should be type float, got {type(reversal_prob)}.' + if isinstance(img_border_value, (float, int)): + img_border_value = tuple([float(img_border_value)] * 3) + elif isinstance(img_border_value, tuple): + assert len(img_border_value) == 3, \ + f'img_border_value as tuple must have 3 elements, ' \ + f'got {len(img_border_value)}.' + img_border_value = tuple([float(val) for val in img_border_value]) + else: + raise ValueError( + 'img_border_value must be float or tuple with 3 elements.') + assert np.all([0 <= val <= 255 for val in img_border_value]), 'all ' \ + 'elements of img_border_value should between range [0,255].' \ + f'got {img_border_value}.' + self.prob = prob + self.level = level + self.min_mag = min_mag + self.max_mag = max_mag + self.reversal_prob = reversal_prob + self.img_border_value = img_border_value + self.mask_border_value = mask_border_value + self.seg_ignore_label = seg_ignore_label + self.interpolation = interpolation + + def _transform_img(self, results: dict, mag: float) -> None: + """Transform the image.""" + pass + + def _transform_masks(self, results: dict, mag: float) -> None: + """Transform the masks.""" + pass + + def _transform_seg(self, results: dict, mag: float) -> None: + """Transform the segmentation map.""" + pass + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for the geometric transformation.""" + return np.eye(3, dtype=np.float32) + + def _transform_bboxes(self, results: dict, mag: float) -> None: + """Transform the bboxes.""" + results['gt_bboxes'].project_(self.homography_matrix) + results['gt_bboxes'].clip_(results['img_shape']) + + def _record_homography_matrix(self, results: dict) -> None: + """Record the homography matrix for the geometric transformation.""" + if results.get('homography_matrix', None) is None: + results['homography_matrix'] = self.homography_matrix + else: + results['homography_matrix'] = self.homography_matrix @ results[ + 'homography_matrix'] + + @cache_randomness + def _random_disable(self): + """Randomly disable the transform.""" + return np.random.rand() > self.prob + + @cache_randomness + def _get_mag(self): + """Get the magnitude of the transform.""" + mag = level_to_mag(self.level, self.min_mag, self.max_mag) + return -mag if np.random.rand() > self.reversal_prob else mag + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function for images, bounding boxes, masks and semantic + segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Transformed results. + """ + + if self._random_disable(): + return results + mag = self._get_mag() + self.homography_matrix = self._get_homography_matrix(results, mag) + self._record_homography_matrix(results) + self._transform_img(results, mag) + if results.get('gt_bboxes', None) is not None: + self._transform_bboxes(results, mag) + if results.get('gt_masks', None) is not None: + self._transform_masks(results, mag) + if results.get('gt_seg_map', None) is not None: + self._transform_seg(results, mag) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'level={self.level}, ' + repr_str += f'min_mag={self.min_mag}, ' + repr_str += f'max_mag={self.max_mag}, ' + repr_str += f'reversal_prob={self.reversal_prob}, ' + repr_str += f'img_border_value={self.img_border_value}, ' + repr_str += f'mask_border_value={self.mask_border_value}, ' + repr_str += f'seg_ignore_label={self.seg_ignore_label}, ' + repr_str += f'interpolation={self.interpolation})' + return repr_str + + +@TRANSFORMS.register_module() +class ShearX(GeomTransform): + """Shear the images, bboxes, masks and segmentation map horizontally. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for performing Shear and should be in + range [0, 1]. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum angle for the horizontal shear. + Defaults to 0.0. + max_mag (float): The maximum angle for the horizontal shear. + Defaults to 30.0. + reversal_prob (float): The probability that reverses the horizontal + shear magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 30.0, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 90., \ + f'min_mag angle for ShearX should be ' \ + f'in range [0, 90], got {min_mag}.' + assert 0. <= max_mag <= 90., \ + f'max_mag angle for ShearX should be ' \ + f'in range [0, 90], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + @cache_randomness + def _get_mag(self): + """Get the magnitude of the transform.""" + mag = level_to_mag(self.level, self.min_mag, self.max_mag) + mag = np.tan(mag * np.pi / 180) + return -mag if np.random.rand() > self.reversal_prob else mag + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for ShearX.""" + return np.array([[1, mag, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Shear the image horizontally.""" + results['img'] = mmcv.imshear( + results['img'], + mag, + direction='horizontal', + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Shear the masks horizontally.""" + results['gt_masks'] = results['gt_masks'].shear( + results['img_shape'], + mag, + direction='horizontal', + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Shear the segmentation map horizontally.""" + results['gt_seg_map'] = mmcv.imshear( + results['gt_seg_map'], + mag, + direction='horizontal', + border_value=self.seg_ignore_label, + interpolation='nearest') + + +@TRANSFORMS.register_module() +class ShearY(GeomTransform): + """Shear the images, bboxes, masks and segmentation map vertically. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for performing ShearY and should be in + range [0, 1]. Defaults to 1.0. + level (int, optional): The level should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum angle for the vertical shear. + Defaults to 0.0. + max_mag (float): The maximum angle for the vertical shear. + Defaults to 30.0. + reversal_prob (float): The probability that reverses the vertical + shear magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 30., + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 90., \ + f'min_mag angle for ShearY should be ' \ + f'in range [0, 90], got {min_mag}.' + assert 0. <= max_mag <= 90., \ + f'max_mag angle for ShearY should be ' \ + f'in range [0, 90], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + @cache_randomness + def _get_mag(self): + """Get the magnitude of the transform.""" + mag = level_to_mag(self.level, self.min_mag, self.max_mag) + mag = np.tan(mag * np.pi / 180) + return -mag if np.random.rand() > self.reversal_prob else mag + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for ShearY.""" + return np.array([[1, 0, 0], [mag, 1, 0], [0, 0, 1]], dtype=np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Shear the image vertically.""" + results['img'] = mmcv.imshear( + results['img'], + mag, + direction='vertical', + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Shear the masks vertically.""" + results['gt_masks'] = results['gt_masks'].shear( + results['img_shape'], + mag, + direction='vertical', + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Shear the segmentation map vertically.""" + results['gt_seg_map'] = mmcv.imshear( + results['gt_seg_map'], + mag, + direction='vertical', + border_value=self.seg_ignore_label, + interpolation='nearest') + + +@TRANSFORMS.register_module() +class Rotate(GeomTransform): + """Rotate the images, bboxes, masks and segmentation map. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for perform transformation and + should be in range 0 to 1. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The maximum angle for rotation. + Defaults to 0.0. + max_mag (float): The maximum angle for rotation. + Defaults to 30.0. + reversal_prob (float): The probability that reverses the rotation + magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 30.0, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 180., \ + f'min_mag for Rotate should be in range [0,180], got {min_mag}.' + assert 0. <= max_mag <= 180., \ + f'max_mag for Rotate should be in range [0,180], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for Rotate.""" + img_shape = results['img_shape'] + center = ((img_shape[1] - 1) * 0.5, (img_shape[0] - 1) * 0.5) + cv2_rotation_matrix = cv2.getRotationMatrix2D(center, -mag, 1.0) + return np.concatenate( + [cv2_rotation_matrix, + np.array([0, 0, 1]).reshape((1, 3))]).astype(np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Rotate the image.""" + results['img'] = mmcv.imrotate( + results['img'], + mag, + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Rotate the masks.""" + results['gt_masks'] = results['gt_masks'].rotate( + results['img_shape'], + mag, + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Rotate the segmentation map.""" + results['gt_seg_map'] = mmcv.imrotate( + results['gt_seg_map'], + mag, + border_value=self.seg_ignore_label, + interpolation='nearest') + + +@TRANSFORMS.register_module() +class TranslateX(GeomTransform): + """Translate the images, bboxes, masks and segmentation map horizontally. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for perform transformation and + should be in range 0 to 1. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum pixel's offset ratio for horizontal + translation. Defaults to 0.0. + max_mag (float): The maximum pixel's offset ratio for horizontal + translation. Defaults to 0.1. + reversal_prob (float): The probability that reverses the horizontal + translation magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 0.1, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 1., \ + f'min_mag ratio for TranslateX should be ' \ + f'in range [0, 1], got {min_mag}.' + assert 0. <= max_mag <= 1., \ + f'max_mag ratio for TranslateX should be ' \ + f'in range [0, 1], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for TranslateX.""" + mag = int(results['img_shape'][1] * mag) + return np.array([[1, 0, mag], [0, 1, 0], [0, 0, 1]], dtype=np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Translate the image horizontally.""" + mag = int(results['img_shape'][1] * mag) + results['img'] = mmcv.imtranslate( + results['img'], + mag, + direction='horizontal', + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Translate the masks horizontally.""" + mag = int(results['img_shape'][1] * mag) + results['gt_masks'] = results['gt_masks'].translate( + results['img_shape'], + mag, + direction='horizontal', + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Translate the segmentation map horizontally.""" + mag = int(results['img_shape'][1] * mag) + results['gt_seg_map'] = mmcv.imtranslate( + results['gt_seg_map'], + mag, + direction='horizontal', + border_value=self.seg_ignore_label, + interpolation='nearest') + + +@TRANSFORMS.register_module() +class TranslateY(GeomTransform): + """Translate the images, bboxes, masks and segmentation map vertically. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for perform transformation and + should be in range 0 to 1. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum pixel's offset ratio for vertical + translation. Defaults to 0.0. + max_mag (float): The maximum pixel's offset ratio for vertical + translation. Defaults to 0.1. + reversal_prob (float): The probability that reverses the vertical + translation magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 0.1, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 1., \ + f'min_mag ratio for TranslateY should be ' \ + f'in range [0,1], got {min_mag}.' + assert 0. <= max_mag <= 1., \ + f'max_mag ratio for TranslateY should be ' \ + f'in range [0,1], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for TranslateY.""" + mag = int(results['img_shape'][0] * mag) + return np.array([[1, 0, 0], [0, 1, mag], [0, 0, 1]], dtype=np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Translate the image vertically.""" + mag = int(results['img_shape'][0] * mag) + results['img'] = mmcv.imtranslate( + results['img'], + mag, + direction='vertical', + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Translate masks vertically.""" + mag = int(results['img_shape'][0] * mag) + results['gt_masks'] = results['gt_masks'].translate( + results['img_shape'], + mag, + direction='vertical', + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Translate segmentation map vertically.""" + mag = int(results['img_shape'][0] * mag) + results['gt_seg_map'] = mmcv.imtranslate( + results['gt_seg_map'], + mag, + direction='vertical', + border_value=self.seg_ignore_label, + interpolation='nearest') diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/instaboost.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/instaboost.py new file mode 100644 index 0000000000000000000000000000000000000000..30dc1603643ec8d398bfade95f5ec1c9b8f89c8d --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/instaboost.py @@ -0,0 +1,150 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Tuple + +import numpy as np +from mmcv.transforms import BaseTransform + +from mmdet.registry import TRANSFORMS + + +@TRANSFORMS.register_module() +class InstaBoost(BaseTransform): + r"""Data augmentation method in `InstaBoost: Boosting Instance + Segmentation Via Probability Map Guided Copy-Pasting + `_. + + Refer to https://github.com/GothicAi/Instaboost for implementation details. + + + Required Keys: + + - img (np.uint8) + - instances + + Modified Keys: + + - img (np.uint8) + - instances + + Args: + action_candidate (tuple): Action candidates. "normal", "horizontal", \ + "vertical", "skip" are supported. Defaults to ('normal', \ + 'horizontal', 'skip'). + action_prob (tuple): Corresponding action probabilities. Should be \ + the same length as action_candidate. Defaults to (1, 0, 0). + scale (tuple): (min scale, max scale). Defaults to (0.8, 1.2). + dx (int): The maximum x-axis shift will be (instance width) / dx. + Defaults to 15. + dy (int): The maximum y-axis shift will be (instance height) / dy. + Defaults to 15. + theta (tuple): (min rotation degree, max rotation degree). \ + Defaults to (-1, 1). + color_prob (float): Probability of images for color augmentation. + Defaults to 0.5. + hflag (bool): Whether to use heatmap guided. Defaults to False. + aug_ratio (float): Probability of applying this transformation. \ + Defaults to 0.5. + """ + + def __init__(self, + action_candidate: tuple = ('normal', 'horizontal', 'skip'), + action_prob: tuple = (1, 0, 0), + scale: tuple = (0.8, 1.2), + dx: int = 15, + dy: int = 15, + theta: tuple = (-1, 1), + color_prob: float = 0.5, + hflag: bool = False, + aug_ratio: float = 0.5) -> None: + + import matplotlib + import matplotlib.pyplot as plt + default_backend = plt.get_backend() + + try: + import instaboostfast as instaboost + except ImportError: + raise ImportError( + 'Please run "pip install instaboostfast" ' + 'to install instaboostfast first for instaboost augmentation.') + + # instaboost will modify the default backend + # and cause visualization to fail. + matplotlib.use(default_backend) + + self.cfg = instaboost.InstaBoostConfig(action_candidate, action_prob, + scale, dx, dy, theta, + color_prob, hflag) + self.aug_ratio = aug_ratio + + def _load_anns(self, results: dict) -> Tuple[list, list]: + """Convert raw anns to instaboost expected input format.""" + anns = [] + ignore_anns = [] + for instance in results['instances']: + label = instance['bbox_label'] + bbox = instance['bbox'] + mask = instance['mask'] + x1, y1, x2, y2 = bbox + # assert (x2 - x1) >= 1 and (y2 - y1) >= 1 + bbox = [x1, y1, x2 - x1, y2 - y1] + + if instance['ignore_flag'] == 0: + anns.append({ + 'category_id': label, + 'segmentation': mask, + 'bbox': bbox + }) + else: + # Ignore instances without data augmentation + ignore_anns.append(instance) + return anns, ignore_anns + + def _parse_anns(self, results: dict, anns: list, ignore_anns: list, + img: np.ndarray) -> dict: + """Restore the result of instaboost processing to the original anns + format.""" + instances = [] + for ann in anns: + x1, y1, w, h = ann['bbox'] + # TODO: more essential bug need to be fixed in instaboost + if w <= 0 or h <= 0: + continue + bbox = [x1, y1, x1 + w, y1 + h] + instances.append( + dict( + bbox=bbox, + bbox_label=ann['category_id'], + mask=ann['segmentation'], + ignore_flag=0)) + + instances.extend(ignore_anns) + results['img'] = img + results['instances'] = instances + return results + + def transform(self, results) -> dict: + """The transform function.""" + img = results['img'] + ori_type = img.dtype + if 'instances' not in results or len(results['instances']) == 0: + return results + + anns, ignore_anns = self._load_anns(results) + if np.random.choice([0, 1], p=[1 - self.aug_ratio, self.aug_ratio]): + try: + import instaboostfast as instaboost + except ImportError: + raise ImportError('Please run "pip install instaboostfast" ' + 'to install instaboostfast first.') + anns, img = instaboost.get_new_data( + anns, img.astype(np.uint8), self.cfg, background=None) + + results = self._parse_anns(results, anns, ignore_anns, + img.astype(ori_type)) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(aug_ratio={self.aug_ratio})' + return repr_str diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/loading.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/loading.py new file mode 100644 index 0000000000000000000000000000000000000000..95945a82d88054a1453e5b54f3a02898efdae257 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/loading.py @@ -0,0 +1,1074 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional, Tuple, Union + +import mmcv +import numpy as np +import pycocotools.mask as maskUtils +import torch +from mmcv.transforms import BaseTransform +from mmcv.transforms import LoadAnnotations as MMCV_LoadAnnotations +from mmcv.transforms import LoadImageFromFile +from mmengine.fileio import get +from mmengine.structures import BaseDataElement + +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import get_box_type +from mmdet.structures.bbox.box_type import autocast_box_type +from mmdet.structures.mask import BitmapMasks, PolygonMasks + + +@TRANSFORMS.register_module() +class LoadImageFromNDArray(LoadImageFromFile): + """Load an image from ``results['img']``. + + Similar with :obj:`LoadImageFromFile`, but the image has been loaded as + :obj:`np.ndarray` in ``results['img']``. Can be used when loading image + from webcam. + + Required Keys: + + - img + + Modified Keys: + + - img + - img_path + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + """ + + def transform(self, results: dict) -> dict: + """Transform function to add image meta information. + + Args: + results (dict): Result dict with Webcam read image in + ``results['img']``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + + img = results['img'] + if self.to_float32: + img = img.astype(np.float32) + + results['img_path'] = None + results['img'] = img + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + return results + + +@TRANSFORMS.register_module() +class LoadMultiChannelImageFromFiles(BaseTransform): + """Load multi-channel images from a list of separate channel files. + + Required Keys: + + - img_path + + Modified Keys: + + - img + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + color_type (str): The flag argument for :func:``mmcv.imfrombytes``. + Defaults to 'unchanged'. + imdecode_backend (str): The image decoding backend type. The backend + argument for :func:``mmcv.imfrombytes``. + See :func:``mmcv.imfrombytes`` for details. + Defaults to 'cv2'. + file_client_args (dict): Arguments to instantiate the + corresponding backend in mmdet <= 3.0.0rc6. Defaults to None. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend in mmdet >= 3.0.0rc7. Defaults to None. + """ + + def __init__( + self, + to_float32: bool = False, + color_type: str = 'unchanged', + imdecode_backend: str = 'cv2', + file_client_args: dict = None, + backend_args: dict = None, + ) -> None: + self.to_float32 = to_float32 + self.color_type = color_type + self.imdecode_backend = imdecode_backend + self.backend_args = backend_args + if file_client_args is not None: + raise RuntimeError( + 'The `file_client_args` is deprecated, ' + 'please use `backend_args` instead, please refer to' + 'https://github.com/open-mmlab/mmdetection/blob/main/configs/_base_/datasets/coco_detection.py' # noqa: E501 + ) + + def transform(self, results: dict) -> dict: + """Transform functions to load multiple images and get images meta + information. + + Args: + results (dict): Result dict from :obj:`mmdet.CustomDataset`. + + Returns: + dict: The dict contains loaded images and meta information. + """ + + assert isinstance(results['img_path'], list) + img = [] + for name in results['img_path']: + img_bytes = get(name, backend_args=self.backend_args) + img.append( + mmcv.imfrombytes( + img_bytes, + flag=self.color_type, + backend=self.imdecode_backend)) + img = np.stack(img, axis=-1) + if self.to_float32: + img = img.astype(np.float32) + + results['img'] = img + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + return results + + def __repr__(self): + repr_str = (f'{self.__class__.__name__}(' + f'to_float32={self.to_float32}, ' + f"color_type='{self.color_type}', " + f"imdecode_backend='{self.imdecode_backend}', " + f'backend_args={self.backend_args})') + return repr_str + + +@TRANSFORMS.register_module() +class LoadAnnotations(MMCV_LoadAnnotations): + """Load and process the ``instances`` and ``seg_map`` annotation provided + by dataset. + + The annotation format is as the following: + + .. code-block:: python + + { + 'instances': + [ + { + # List of 4 numbers representing the bounding box of the + # instance, in (x1, y1, x2, y2) order. + 'bbox': [x1, y1, x2, y2], + + # Label of image classification. + 'bbox_label': 1, + + # Used in instance/panoptic segmentation. The segmentation mask + # of the instance or the information of segments. + # 1. If list[list[float]], it represents a list of polygons, + # one for each connected component of the object. Each + # list[float] is one simple polygon in the format of + # [x1, y1, ..., xn, yn] (n≥3). The Xs and Ys are absolute + # coordinates in unit of pixels. + # 2. If dict, it represents the per-pixel segmentation mask in + # COCO’s compressed RLE format. The dict should have keys + # “size” and “counts”. Can be loaded by pycocotools + 'mask': list[list[float]] or dict, + + } + ] + # Filename of semantic or panoptic segmentation ground truth file. + 'seg_map_path': 'a/b/c' + } + + After this module, the annotation has been changed to the format below: + + .. code-block:: python + + { + # In (x1, y1, x2, y2) order, float type. N is the number of bboxes + # in an image + 'gt_bboxes': BaseBoxes(N, 4) + # In int type. + 'gt_bboxes_labels': np.ndarray(N, ) + # In built-in class + 'gt_masks': PolygonMasks (H, W) or BitmapMasks (H, W) + # In uint8 type. + 'gt_seg_map': np.ndarray (H, W) + # in (x, y, v) order, float type. + } + + Required Keys: + + - height + - width + - instances + + - bbox (optional) + - bbox_label + - mask (optional) + - ignore_flag + + - seg_map_path (optional) + + Added Keys: + + - gt_bboxes (BaseBoxes[torch.float32]) + - gt_bboxes_labels (np.int64) + - gt_masks (BitmapMasks | PolygonMasks) + - gt_seg_map (np.uint8) + - gt_ignore_flags (bool) + + Args: + with_bbox (bool): Whether to parse and load the bbox annotation. + Defaults to True. + with_label (bool): Whether to parse and load the label annotation. + Defaults to True. + with_mask (bool): Whether to parse and load the mask annotation. + Default: False. + with_seg (bool): Whether to parse and load the semantic segmentation + annotation. Defaults to False. + poly2mask (bool): Whether to convert mask to bitmap. Default: True. + box_type (str): The box type used to wrap the bboxes. If ``box_type`` + is None, gt_bboxes will keep being np.ndarray. Defaults to 'hbox'. + reduce_zero_label (bool): Whether reduce all label value + by 1. Usually used for datasets where 0 is background label. + Defaults to False. + ignore_index (int): The label index to be ignored. + Valid only if reduce_zero_label is true. Defaults is 255. + imdecode_backend (str): The image decoding backend type. The backend + argument for :func:``mmcv.imfrombytes``. + See :fun:``mmcv.imfrombytes`` for details. + Defaults to 'cv2'. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + """ + + def __init__( + self, + with_mask: bool = False, + poly2mask: bool = True, + box_type: str = 'hbox', + # use for semseg + reduce_zero_label: bool = False, + ignore_index: int = 255, + **kwargs) -> None: + super(LoadAnnotations, self).__init__(**kwargs) + self.with_mask = with_mask + self.poly2mask = poly2mask + self.box_type = box_type + self.reduce_zero_label = reduce_zero_label + self.ignore_index = ignore_index + + def _load_bboxes(self, results: dict) -> None: + """Private function to load bounding box annotations. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + Returns: + dict: The dict contains loaded bounding box annotations. + """ + gt_bboxes = [] + gt_ignore_flags = [] + for instance in results.get('instances', []): + gt_bboxes.append(instance['bbox']) + gt_ignore_flags.append(instance['ignore_flag']) + if self.box_type is None: + results['gt_bboxes'] = np.array( + gt_bboxes, dtype=np.float32).reshape((-1, 4)) + else: + _, box_type_cls = get_box_type(self.box_type) + results['gt_bboxes'] = box_type_cls(gt_bboxes, dtype=torch.float32) + results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool) + + def _load_labels(self, results: dict) -> None: + """Private function to load label annotations. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + + Returns: + dict: The dict contains loaded label annotations. + """ + gt_bboxes_labels = [] + for instance in results.get('instances', []): + gt_bboxes_labels.append(instance['bbox_label']) + # TODO: Inconsistent with mmcv, consider how to deal with it later. + results['gt_bboxes_labels'] = np.array( + gt_bboxes_labels, dtype=np.int64) + + def _poly2mask(self, mask_ann: Union[list, dict], img_h: int, + img_w: int) -> np.ndarray: + """Private function to convert masks represented with polygon to + bitmaps. + + Args: + mask_ann (list | dict): Polygon mask annotation input. + img_h (int): The height of output mask. + img_w (int): The width of output mask. + + Returns: + np.ndarray: The decode bitmap mask of shape (img_h, img_w). + """ + + if isinstance(mask_ann, list): + # polygon -- a single object might consist of multiple parts + # we merge all parts into one mask rle code + rles = maskUtils.frPyObjects(mask_ann, img_h, img_w) + rle = maskUtils.merge(rles) + elif isinstance(mask_ann['counts'], list): + # uncompressed RLE + rle = maskUtils.frPyObjects(mask_ann, img_h, img_w) + else: + # rle + rle = mask_ann + mask = maskUtils.decode(rle) + return mask + + def _process_masks(self, results: dict) -> list: + """Process gt_masks and filter invalid polygons. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + + Returns: + list: Processed gt_masks. + """ + gt_masks = [] + gt_ignore_flags = [] + for instance in results.get('instances', []): + gt_mask = instance['mask'] + # If the annotation of segmentation mask is invalid, + # ignore the whole instance. + if isinstance(gt_mask, list): + gt_mask = [ + np.array(polygon) for polygon in gt_mask + if len(polygon) % 2 == 0 and len(polygon) >= 6 + ] + if len(gt_mask) == 0: + # ignore this instance and set gt_mask to a fake mask + instance['ignore_flag'] = 1 + gt_mask = [np.zeros(6)] + elif not self.poly2mask: + # `PolygonMasks` requires a ploygon of format List[np.array], + # other formats are invalid. + instance['ignore_flag'] = 1 + gt_mask = [np.zeros(6)] + elif isinstance(gt_mask, dict) and \ + not (gt_mask.get('counts') is not None and + gt_mask.get('size') is not None and + isinstance(gt_mask['counts'], (list, str))): + # if gt_mask is a dict, it should include `counts` and `size`, + # so that `BitmapMasks` can uncompressed RLE + instance['ignore_flag'] = 1 + gt_mask = [np.zeros(6)] + gt_masks.append(gt_mask) + # re-process gt_ignore_flags + gt_ignore_flags.append(instance['ignore_flag']) + results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool) + return gt_masks + + def _load_masks(self, results: dict) -> None: + """Private function to load mask annotations. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + """ + h, w = results['ori_shape'] + gt_masks = self._process_masks(results) + if self.poly2mask: + gt_masks = BitmapMasks( + [self._poly2mask(mask, h, w) for mask in gt_masks], h, w) + else: + # fake polygon masks will be ignored in `PackDetInputs` + gt_masks = PolygonMasks([mask for mask in gt_masks], h, w) + results['gt_masks'] = gt_masks + + def _load_seg_map(self, results: dict) -> None: + """Private function to load semantic segmentation annotations. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded semantic segmentation annotations. + """ + if results.get('seg_map_path', None) is None: + return + + img_bytes = get( + results['seg_map_path'], backend_args=self.backend_args) + gt_semantic_seg = mmcv.imfrombytes( + img_bytes, flag='unchanged', + backend=self.imdecode_backend).squeeze() + + if self.reduce_zero_label: + # avoid using underflow conversion + gt_semantic_seg[gt_semantic_seg == 0] = self.ignore_index + gt_semantic_seg = gt_semantic_seg - 1 + gt_semantic_seg[gt_semantic_seg == self.ignore_index - + 1] = self.ignore_index + + # modify if custom classes + if results.get('label_map', None) is not None: + # Add deep copy to solve bug of repeatedly + # replace `gt_semantic_seg`, which is reported in + # https://github.com/open-mmlab/mmsegmentation/pull/1445/ + gt_semantic_seg_copy = gt_semantic_seg.copy() + for old_id, new_id in results['label_map'].items(): + gt_semantic_seg[gt_semantic_seg_copy == old_id] = new_id + results['gt_seg_map'] = gt_semantic_seg + results['ignore_index'] = self.ignore_index + + def transform(self, results: dict) -> dict: + """Function to load multiple types annotations. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + + Returns: + dict: The dict contains loaded bounding box, label and + semantic segmentation. + """ + + if self.with_bbox: + self._load_bboxes(results) + if self.with_label: + self._load_labels(results) + if self.with_mask: + self._load_masks(results) + if self.with_seg: + self._load_seg_map(results) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(with_bbox={self.with_bbox}, ' + repr_str += f'with_label={self.with_label}, ' + repr_str += f'with_mask={self.with_mask}, ' + repr_str += f'with_seg={self.with_seg}, ' + repr_str += f'poly2mask={self.poly2mask}, ' + repr_str += f"imdecode_backend='{self.imdecode_backend}', " + repr_str += f'backend_args={self.backend_args})' + return repr_str + + +@TRANSFORMS.register_module() +class LoadPanopticAnnotations(LoadAnnotations): + """Load multiple types of panoptic annotations. + + The annotation format is as the following: + + .. code-block:: python + + { + 'instances': + [ + { + # List of 4 numbers representing the bounding box of the + # instance, in (x1, y1, x2, y2) order. + 'bbox': [x1, y1, x2, y2], + + # Label of image classification. + 'bbox_label': 1, + }, + ... + ] + 'segments_info': + [ + { + # id = cls_id + instance_id * INSTANCE_OFFSET + 'id': int, + + # Contiguous category id defined in dataset. + 'category': int + + # Thing flag. + 'is_thing': bool + }, + ... + ] + + # Filename of semantic or panoptic segmentation ground truth file. + 'seg_map_path': 'a/b/c' + } + + After this module, the annotation has been changed to the format below: + + .. code-block:: python + + { + # In (x1, y1, x2, y2) order, float type. N is the number of bboxes + # in an image + 'gt_bboxes': BaseBoxes(N, 4) + # In int type. + 'gt_bboxes_labels': np.ndarray(N, ) + # In built-in class + 'gt_masks': PolygonMasks (H, W) or BitmapMasks (H, W) + # In uint8 type. + 'gt_seg_map': np.ndarray (H, W) + # in (x, y, v) order, float type. + } + + Required Keys: + + - height + - width + - instances + - bbox + - bbox_label + - ignore_flag + - segments_info + - id + - category + - is_thing + - seg_map_path + + Added Keys: + + - gt_bboxes (BaseBoxes[torch.float32]) + - gt_bboxes_labels (np.int64) + - gt_masks (BitmapMasks | PolygonMasks) + - gt_seg_map (np.uint8) + - gt_ignore_flags (bool) + + Args: + with_bbox (bool): Whether to parse and load the bbox annotation. + Defaults to True. + with_label (bool): Whether to parse and load the label annotation. + Defaults to True. + with_mask (bool): Whether to parse and load the mask annotation. + Defaults to True. + with_seg (bool): Whether to parse and load the semantic segmentation + annotation. Defaults to False. + box_type (str): The box mode used to wrap the bboxes. + imdecode_backend (str): The image decoding backend type. The backend + argument for :func:``mmcv.imfrombytes``. + See :fun:``mmcv.imfrombytes`` for details. + Defaults to 'cv2'. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend in mmdet >= 3.0.0rc7. Defaults to None. + """ + + def __init__(self, + with_bbox: bool = True, + with_label: bool = True, + with_mask: bool = True, + with_seg: bool = True, + box_type: str = 'hbox', + imdecode_backend: str = 'cv2', + backend_args: dict = None) -> None: + try: + from panopticapi import utils + except ImportError: + raise ImportError( + 'panopticapi is not installed, please install it by: ' + 'pip install git+https://github.com/cocodataset/' + 'panopticapi.git.') + self.rgb2id = utils.rgb2id + + super(LoadPanopticAnnotations, self).__init__( + with_bbox=with_bbox, + with_label=with_label, + with_mask=with_mask, + with_seg=with_seg, + with_keypoints=False, + box_type=box_type, + imdecode_backend=imdecode_backend, + backend_args=backend_args) + + def _load_masks_and_semantic_segs(self, results: dict) -> None: + """Private function to load mask and semantic segmentation annotations. + + In gt_semantic_seg, the foreground label is from ``0`` to + ``num_things - 1``, the background label is from ``num_things`` to + ``num_things + num_stuff - 1``, 255 means the ignored label (``VOID``). + + Args: + results (dict): Result dict from :obj:``mmdet.CustomDataset``. + """ + # seg_map_path is None, when inference on the dataset without gts. + if results.get('seg_map_path', None) is None: + return + + img_bytes = get( + results['seg_map_path'], backend_args=self.backend_args) + pan_png = mmcv.imfrombytes( + img_bytes, flag='color', channel_order='rgb').squeeze() + pan_png = self.rgb2id(pan_png) + + gt_masks = [] + gt_seg = np.zeros_like(pan_png) + 255 # 255 as ignore + + for segment_info in results['segments_info']: + mask = (pan_png == segment_info['id']) + gt_seg = np.where(mask, segment_info['category'], gt_seg) + + # The legal thing masks + if segment_info.get('is_thing'): + gt_masks.append(mask.astype(np.uint8)) + + if self.with_mask: + h, w = results['ori_shape'] + gt_masks = BitmapMasks(gt_masks, h, w) + results['gt_masks'] = gt_masks + + if self.with_seg: + results['gt_seg_map'] = gt_seg + + def transform(self, results: dict) -> dict: + """Function to load multiple types panoptic annotations. + + Args: + results (dict): Result dict from :obj:``mmdet.CustomDataset``. + + Returns: + dict: The dict contains loaded bounding box, label, mask and + semantic segmentation annotations. + """ + + if self.with_bbox: + self._load_bboxes(results) + if self.with_label: + self._load_labels(results) + if self.with_mask or self.with_seg: + # The tasks completed by '_load_masks' and '_load_semantic_segs' + # in LoadAnnotations are merged to one function. + self._load_masks_and_semantic_segs(results) + + return results + + +@TRANSFORMS.register_module() +class LoadProposals(BaseTransform): + """Load proposal pipeline. + + Required Keys: + + - proposals + + Modified Keys: + + - proposals + + Args: + num_max_proposals (int, optional): Maximum number of proposals to load. + If not specified, all proposals will be loaded. + """ + + def __init__(self, num_max_proposals: Optional[int] = None) -> None: + self.num_max_proposals = num_max_proposals + + def transform(self, results: dict) -> dict: + """Transform function to load proposals from file. + + Args: + results (dict): Result dict from :obj:`mmdet.CustomDataset`. + + Returns: + dict: The dict contains loaded proposal annotations. + """ + + proposals = results['proposals'] + # the type of proposals should be `dict` or `InstanceData` + assert isinstance(proposals, dict) \ + or isinstance(proposals, BaseDataElement) + bboxes = proposals['bboxes'].astype(np.float32) + assert bboxes.shape[1] == 4, \ + f'Proposals should have shapes (n, 4), but found {bboxes.shape}' + + if 'scores' in proposals: + scores = proposals['scores'].astype(np.float32) + assert bboxes.shape[0] == scores.shape[0] + else: + scores = np.zeros(bboxes.shape[0], dtype=np.float32) + + if self.num_max_proposals is not None: + # proposals should sort by scores during dumping the proposals + bboxes = bboxes[:self.num_max_proposals] + scores = scores[:self.num_max_proposals] + + if len(bboxes) == 0: + bboxes = np.zeros((0, 4), dtype=np.float32) + scores = np.zeros(0, dtype=np.float32) + + results['proposals'] = bboxes + results['proposals_scores'] = scores + return results + + def __repr__(self): + return self.__class__.__name__ + \ + f'(num_max_proposals={self.num_max_proposals})' + + +@TRANSFORMS.register_module() +class FilterAnnotations(BaseTransform): + """Filter invalid annotations. + + Required Keys: + + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_masks (optional) + - gt_ignore_flags (optional) + + Args: + min_gt_bbox_wh (tuple[float]): Minimum width and height of ground truth + boxes. Default: (1., 1.) + min_gt_mask_area (int): Minimum foreground area of ground truth masks. + Default: 1 + by_box (bool): Filter instances with bounding boxes not meeting the + min_gt_bbox_wh threshold. Default: True + by_mask (bool): Filter instances with masks not meeting + min_gt_mask_area threshold. Default: False + keep_empty (bool): Whether to return None when it + becomes an empty bbox after filtering. Defaults to True. + """ + + def __init__(self, + min_gt_bbox_wh: Tuple[int, int] = (1, 1), + min_gt_mask_area: int = 1, + by_box: bool = True, + by_mask: bool = False, + keep_empty: bool = True) -> None: + # TODO: add more filter options + assert by_box or by_mask + self.min_gt_bbox_wh = min_gt_bbox_wh + self.min_gt_mask_area = min_gt_mask_area + self.by_box = by_box + self.by_mask = by_mask + self.keep_empty = keep_empty + + @autocast_box_type() + def transform(self, results: dict) -> Union[dict, None]: + """Transform function to filter annotations. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + assert 'gt_bboxes' in results + gt_bboxes = results['gt_bboxes'] + if gt_bboxes.shape[0] == 0: + return results + + tests = [] + if self.by_box: + tests.append( + ((gt_bboxes.widths > self.min_gt_bbox_wh[0]) & + (gt_bboxes.heights > self.min_gt_bbox_wh[1])).numpy()) + if self.by_mask: + assert 'gt_masks' in results + gt_masks = results['gt_masks'] + tests.append(gt_masks.areas >= self.min_gt_mask_area) + + keep = tests[0] + for t in tests[1:]: + keep = keep & t + + if not keep.any(): + if self.keep_empty: + return None + + keys = ('gt_bboxes', 'gt_bboxes_labels', 'gt_masks', 'gt_ignore_flags') + for key in keys: + if key in results: + results[key] = results[key][keep] + + return results + + def __repr__(self): + return self.__class__.__name__ + \ + f'(min_gt_bbox_wh={self.min_gt_bbox_wh}, ' \ + f'keep_empty={self.keep_empty})' + + +@TRANSFORMS.register_module() +class LoadEmptyAnnotations(BaseTransform): + """Load Empty Annotations for unlabeled images. + + Added Keys: + - gt_bboxes (np.float32) + - gt_bboxes_labels (np.int64) + - gt_masks (BitmapMasks | PolygonMasks) + - gt_seg_map (np.uint8) + - gt_ignore_flags (bool) + + Args: + with_bbox (bool): Whether to load the pseudo bbox annotation. + Defaults to True. + with_label (bool): Whether to load the pseudo label annotation. + Defaults to True. + with_mask (bool): Whether to load the pseudo mask annotation. + Default: False. + with_seg (bool): Whether to load the pseudo semantic segmentation + annotation. Defaults to False. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + """ + + def __init__(self, + with_bbox: bool = True, + with_label: bool = True, + with_mask: bool = False, + with_seg: bool = False, + seg_ignore_label: int = 255) -> None: + self.with_bbox = with_bbox + self.with_label = with_label + self.with_mask = with_mask + self.with_seg = with_seg + self.seg_ignore_label = seg_ignore_label + + def transform(self, results: dict) -> dict: + """Transform function to load empty annotations. + + Args: + results (dict): Result dict. + Returns: + dict: Updated result dict. + """ + if self.with_bbox: + results['gt_bboxes'] = np.zeros((0, 4), dtype=np.float32) + results['gt_ignore_flags'] = np.zeros((0, ), dtype=bool) + if self.with_label: + results['gt_bboxes_labels'] = np.zeros((0, ), dtype=np.int64) + if self.with_mask: + # TODO: support PolygonMasks + h, w = results['img_shape'] + gt_masks = np.zeros((0, h, w), dtype=np.uint8) + results['gt_masks'] = BitmapMasks(gt_masks, h, w) + if self.with_seg: + h, w = results['img_shape'] + results['gt_seg_map'] = self.seg_ignore_label * np.ones( + (h, w), dtype=np.uint8) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(with_bbox={self.with_bbox}, ' + repr_str += f'with_label={self.with_label}, ' + repr_str += f'with_mask={self.with_mask}, ' + repr_str += f'with_seg={self.with_seg}, ' + repr_str += f'seg_ignore_label={self.seg_ignore_label})' + return repr_str + + +@TRANSFORMS.register_module() +class InferencerLoader(BaseTransform): + """Load an image from ``results['img']``. + + Similar with :obj:`LoadImageFromFile`, but the image has been loaded as + :obj:`np.ndarray` in ``results['img']``. Can be used when loading image + from webcam. + + Required Keys: + + - img + + Modified Keys: + + - img + - img_path + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + """ + + def __init__(self, **kwargs) -> None: + super().__init__() + self.from_file = TRANSFORMS.build( + dict(type='LoadImageFromFile', **kwargs)) + self.from_ndarray = TRANSFORMS.build( + dict(type='mmdet.LoadImageFromNDArray', **kwargs)) + + def transform(self, results: Union[str, np.ndarray, dict]) -> dict: + """Transform function to add image meta information. + + Args: + results (str, np.ndarray or dict): The result. + + Returns: + dict: The dict contains loaded image and meta information. + """ + if isinstance(results, str): + inputs = dict(img_path=results) + elif isinstance(results, np.ndarray): + inputs = dict(img=results) + elif isinstance(results, dict): + inputs = results + else: + raise NotImplementedError + + if 'img' in inputs: + return self.from_ndarray(inputs) + return self.from_file(inputs) + + +@TRANSFORMS.register_module() +class LoadTrackAnnotations(LoadAnnotations): + """Load and process the ``instances`` and ``seg_map`` annotation provided + by dataset. It must load ``instances_ids`` which is only used in the + tracking tasks. The annotation format is as the following: + + .. code-block:: python + { + 'instances': + [ + { + # List of 4 numbers representing the bounding box of the + # instance, in (x1, y1, x2, y2) order. + 'bbox': [x1, y1, x2, y2], + # Label of image classification. + 'bbox_label': 1, + # Used in tracking. + # Id of instances. + 'instance_id': 100, + # Used in instance/panoptic segmentation. The segmentation mask + # of the instance or the information of segments. + # 1. If list[list[float]], it represents a list of polygons, + # one for each connected component of the object. Each + # list[float] is one simple polygon in the format of + # [x1, y1, ..., xn, yn] (n≥3). The Xs and Ys are absolute + # coordinates in unit of pixels. + # 2. If dict, it represents the per-pixel segmentation mask in + # COCO's compressed RLE format. The dict should have keys + # “size” and “counts”. Can be loaded by pycocotools + 'mask': list[list[float]] or dict, + } + ] + # Filename of semantic or panoptic segmentation ground truth file. + 'seg_map_path': 'a/b/c' + } + + After this module, the annotation has been changed to the format below: + .. code-block:: python + { + # In (x1, y1, x2, y2) order, float type. N is the number of bboxes + # in an image + 'gt_bboxes': np.ndarray(N, 4) + # In int type. + 'gt_bboxes_labels': np.ndarray(N, ) + # In built-in class + 'gt_masks': PolygonMasks (H, W) or BitmapMasks (H, W) + # In uint8 type. + 'gt_seg_map': np.ndarray (H, W) + # in (x, y, v) order, float type. + } + + Required Keys: + + - height (optional) + - width (optional) + - instances + - bbox (optional) + - bbox_label + - instance_id (optional) + - mask (optional) + - ignore_flag (optional) + - seg_map_path (optional) + + Added Keys: + + - gt_bboxes (np.float32) + - gt_bboxes_labels (np.int32) + - gt_instances_ids (np.int32) + - gt_masks (BitmapMasks | PolygonMasks) + - gt_seg_map (np.uint8) + - gt_ignore_flags (np.bool) + """ + + def __init__(self, **kwargs) -> None: + super().__init__(**kwargs) + + def _load_bboxes(self, results: dict) -> None: + """Private function to load bounding box annotations. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded bounding box annotations. + """ + gt_bboxes = [] + gt_ignore_flags = [] + # TODO: use bbox_type + for instance in results['instances']: + # The datasets which are only format in evaluation don't have + # groundtruth boxes. + if 'bbox' in instance: + gt_bboxes.append(instance['bbox']) + if 'ignore_flag' in instance: + gt_ignore_flags.append(instance['ignore_flag']) + + # TODO: check this case + if len(gt_bboxes) != len(gt_ignore_flags): + # There may be no ``gt_ignore_flags`` in some cases, we treat them + # as all False in order to keep the length of ``gt_bboxes`` and + # ``gt_ignore_flags`` the same + gt_ignore_flags = [False] * len(gt_bboxes) + + results['gt_bboxes'] = np.array( + gt_bboxes, dtype=np.float32).reshape(-1, 4) + results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool) + + def _load_instances_ids(self, results: dict) -> None: + """Private function to load instances id annotations. + + Args: + results (dict): Result dict from :obj :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict containing instances id annotations. + """ + gt_instances_ids = [] + for instance in results['instances']: + gt_instances_ids.append(instance['instance_id']) + results['gt_instances_ids'] = np.array( + gt_instances_ids, dtype=np.int32) + + def transform(self, results: dict) -> dict: + """Function to load multiple types annotations. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded bounding box, label, instances id + and semantic segmentation and keypoints annotations. + """ + results = super().transform(results) + self._load_instances_ids(results) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(with_bbox={self.with_bbox}, ' + repr_str += f'with_label={self.with_label}, ' + repr_str += f'with_mask={self.with_mask}, ' + repr_str += f'with_seg={self.with_seg}, ' + repr_str += f'poly2mask={self.poly2mask}, ' + repr_str += f"imdecode_backend='{self.imdecode_backend}', " + repr_str += f'file_client_args={self.file_client_args})' + return repr_str diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/transforms.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..9d1c1ed71ab25821d45a323425ae5e7c3954a50c --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/transforms.py @@ -0,0 +1,3855 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import inspect +import math +import warnings +from typing import List, Optional, Sequence, Tuple, Union + +import cv2 +import mmcv +import numpy +import numpy as np +from mmcv.image import imresize +from mmcv.image.geometric import _scale_size +from mmcv.transforms import BaseTransform +from mmcv.transforms import Pad as MMCV_Pad +from mmcv.transforms import RandomFlip as MMCV_RandomFlip +from mmcv.transforms import Resize as MMCV_Resize +from mmcv.transforms.utils import avoid_cache_randomness, cache_randomness +from mmengine.dataset import BaseDataset +from mmengine.utils import is_str +from numpy import random + +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import HorizontalBoxes, autocast_box_type +from mmdet.structures.mask import BitmapMasks, PolygonMasks +from mmdet.utils import log_img_scale + +try: + from imagecorruptions import corrupt +except ImportError: + corrupt = None + +try: + import albumentations + from albumentations import Compose +except ImportError: + albumentations = None + Compose = None + +Number = Union[int, float] + + +def _fixed_scale_size( + size: Tuple[int, int], + scale: Union[float, int, tuple], +) -> Tuple[int, int]: + """Rescale a size by a ratio. + + Args: + size (tuple[int]): (w, h). + scale (float | tuple(float)): Scaling factor. + + Returns: + tuple[int]: scaled size. + """ + if isinstance(scale, (float, int)): + scale = (scale, scale) + w, h = size + # don’t need o.5 offset + return int(w * float(scale[0])), int(h * float(scale[1])) + + +def rescale_size(old_size: tuple, + scale: Union[float, int, tuple], + return_scale: bool = False) -> tuple: + """Calculate the new size to be rescaled to. + + Args: + old_size (tuple[int]): The old size (w, h) of image. + scale (float | tuple[int]): The scaling factor or maximum size. + If it is a float number, then the image will be rescaled by this + factor, else if it is a tuple of 2 integers, then the image will + be rescaled as large as possible within the scale. + return_scale (bool): Whether to return the scaling factor besides the + rescaled image size. + + Returns: + tuple[int]: The new rescaled image size. + """ + w, h = old_size + if isinstance(scale, (float, int)): + if scale <= 0: + raise ValueError(f'Invalid scale {scale}, must be positive.') + scale_factor = scale + elif isinstance(scale, tuple): + max_long_edge = max(scale) + max_short_edge = min(scale) + scale_factor = min(max_long_edge / max(h, w), + max_short_edge / min(h, w)) + else: + raise TypeError( + f'Scale must be a number or tuple of int, but got {type(scale)}') + # only change this + new_size = _fixed_scale_size((w, h), scale_factor) + + if return_scale: + return new_size, scale_factor + else: + return new_size + + +def imrescale( + img: np.ndarray, + scale: Union[float, Tuple[int, int]], + return_scale: bool = False, + interpolation: str = 'bilinear', + backend: Optional[str] = None +) -> Union[np.ndarray, Tuple[np.ndarray, float]]: + """Resize image while keeping the aspect ratio. + + Args: + img (ndarray): The input image. + scale (float | tuple[int]): The scaling factor or maximum size. + If it is a float number, then the image will be rescaled by this + factor, else if it is a tuple of 2 integers, then the image will + be rescaled as large as possible within the scale. + return_scale (bool): Whether to return the scaling factor besides the + rescaled image. + interpolation (str): Same as :func:`resize`. + backend (str | None): Same as :func:`resize`. + + Returns: + ndarray: The rescaled image. + """ + h, w = img.shape[:2] + new_size, scale_factor = rescale_size((w, h), scale, return_scale=True) + rescaled_img = imresize( + img, new_size, interpolation=interpolation, backend=backend) + if return_scale: + return rescaled_img, scale_factor + else: + return rescaled_img + + +@TRANSFORMS.register_module() +class Resize(MMCV_Resize): + """Resize images & bbox & seg. + + This transform resizes the input image according to ``scale`` or + ``scale_factor``. Bboxes, masks, and seg map are then resized + with the same scale factor. + if ``scale`` and ``scale_factor`` are both set, it will use ``scale`` to + resize. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_masks + - gt_seg_map + + + Added Keys: + + - scale + - scale_factor + - keep_ratio + - homography_matrix + + Args: + scale (int or tuple): Images scales for resizing. Defaults to None + scale_factor (float or tuple[float]): Scale factors for resizing. + Defaults to None. + keep_ratio (bool): Whether to keep the aspect ratio when resizing the + image. Defaults to False. + clip_object_border (bool): Whether to clip the objects + outside the border of the image. In some dataset like MOT17, the gt + bboxes are allowed to cross the border of images. Therefore, we + don't need to clip the gt bboxes in these cases. Defaults to True. + backend (str): Image resize backend, choices are 'cv2' and 'pillow'. + These two backends generates slightly different results. Defaults + to 'cv2'. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def _resize_masks(self, results: dict) -> None: + """Resize masks with ``results['scale']``""" + if results.get('gt_masks', None) is not None: + if self.keep_ratio: + results['gt_masks'] = results['gt_masks'].rescale( + results['scale']) + else: + results['gt_masks'] = results['gt_masks'].resize( + results['img_shape']) + + def _resize_bboxes(self, results: dict) -> None: + """Resize bounding boxes with ``results['scale_factor']``.""" + if results.get('gt_bboxes', None) is not None: + results['gt_bboxes'].rescale_(results['scale_factor']) + if self.clip_object_border: + results['gt_bboxes'].clip_(results['img_shape']) + + def _record_homography_matrix(self, results: dict) -> None: + """Record the homography matrix for the Resize.""" + w_scale, h_scale = results['scale_factor'] + homography_matrix = np.array( + [[w_scale, 0, 0], [0, h_scale, 0], [0, 0, 1]], dtype=np.float32) + if results.get('homography_matrix', None) is None: + results['homography_matrix'] = homography_matrix + else: + results['homography_matrix'] = homography_matrix @ results[ + 'homography_matrix'] + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to resize images, bounding boxes and semantic + segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + Returns: + dict: Resized results, 'img', 'gt_bboxes', 'gt_seg_map', + 'scale', 'scale_factor', 'height', 'width', and 'keep_ratio' keys + are updated in result dict. + """ + if self.scale: + results['scale'] = self.scale + else: + img_shape = results['img'].shape[:2] + results['scale'] = _scale_size(img_shape[::-1], self.scale_factor) + self._resize_img(results) + self._resize_bboxes(results) + self._resize_masks(results) + self._resize_seg(results) + self._record_homography_matrix(results) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(scale={self.scale}, ' + repr_str += f'scale_factor={self.scale_factor}, ' + repr_str += f'keep_ratio={self.keep_ratio}, ' + repr_str += f'clip_object_border={self.clip_object_border}), ' + repr_str += f'backend={self.backend}), ' + repr_str += f'interpolation={self.interpolation})' + return repr_str + + +@TRANSFORMS.register_module() +class FixScaleResize(Resize): + """Compared to Resize, FixScaleResize fixes the scaling issue when + `keep_ratio=true`.""" + + def _resize_img(self, results): + """Resize images with ``results['scale']``.""" + if results.get('img', None) is not None: + if self.keep_ratio: + img, scale_factor = imrescale( + results['img'], + results['scale'], + interpolation=self.interpolation, + return_scale=True, + backend=self.backend) + new_h, new_w = img.shape[:2] + h, w = results['img'].shape[:2] + w_scale = new_w / w + h_scale = new_h / h + else: + img, w_scale, h_scale = mmcv.imresize( + results['img'], + results['scale'], + interpolation=self.interpolation, + return_scale=True, + backend=self.backend) + results['img'] = img + results['img_shape'] = img.shape[:2] + results['scale_factor'] = (w_scale, h_scale) + results['keep_ratio'] = self.keep_ratio + + +@TRANSFORMS.register_module() +class ResizeShortestEdge(BaseTransform): + """Resize the image and mask while keeping the aspect ratio unchanged. + + Modified from https://github.com/facebookresearch/detectron2/blob/main/detectron2/data/transforms/augmentation_impl.py#L130 # noqa:E501 + + This transform attempts to scale the shorter edge to the given + `scale`, as long as the longer edge does not exceed `max_size`. + If `max_size` is reached, then downscale so that the longer + edge does not exceed `max_size`. + + Required Keys: + - img + - gt_seg_map (optional) + Modified Keys: + - img + - img_shape + - gt_seg_map (optional)) + Added Keys: + - scale + - scale_factor + - keep_ratio + + Args: + scale (Union[int, Tuple[int, int]]): The target short edge length. + If it's tuple, will select the min value as the short edge length. + max_size (int): The maximum allowed longest edge length. + """ + + def __init__(self, + scale: Union[int, Tuple[int, int]], + max_size: Optional[int] = None, + resize_type: str = 'Resize', + **resize_kwargs) -> None: + super().__init__() + self.scale = scale + self.max_size = max_size + + self.resize_cfg = dict(type=resize_type, **resize_kwargs) + self.resize = TRANSFORMS.build({'scale': 0, **self.resize_cfg}) + + def _get_output_shape( + self, img: np.ndarray, + short_edge_length: Union[int, Tuple[int, int]]) -> Tuple[int, int]: + """Compute the target image shape with the given `short_edge_length`. + + Args: + img (np.ndarray): The input image. + short_edge_length (Union[int, Tuple[int, int]]): The target short + edge length. If it's tuple, will select the min value as the + short edge length. + """ + h, w = img.shape[:2] + if isinstance(short_edge_length, int): + size = short_edge_length * 1.0 + elif isinstance(short_edge_length, tuple): + size = min(short_edge_length) * 1.0 + scale = size / min(h, w) + if h < w: + new_h, new_w = size, scale * w + else: + new_h, new_w = scale * h, size + + if self.max_size and max(new_h, new_w) > self.max_size: + scale = self.max_size * 1.0 / max(new_h, new_w) + new_h *= scale + new_w *= scale + + new_h = int(new_h + 0.5) + new_w = int(new_w + 0.5) + return new_w, new_h + + def transform(self, results: dict) -> dict: + self.resize.scale = self._get_output_shape(results['img'], self.scale) + return self.resize(results) + + +@TRANSFORMS.register_module() +class FixShapeResize(Resize): + """Resize images & bbox & seg to the specified size. + + This transform resizes the input image according to ``width`` and + ``height``. Bboxes, masks, and seg map are then resized + with the same parameters. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_masks + - gt_seg_map + + + Added Keys: + + - scale + - scale_factor + - keep_ratio + - homography_matrix + + Args: + width (int): width for resizing. + height (int): height for resizing. + Defaults to None. + pad_val (Number | dict[str, Number], optional): Padding value for if + the pad_mode is "constant". If it is a single number, the value + to pad the image is the number and to pad the semantic + segmentation map is 255. If it is a dict, it should have the + following keys: + + - img: The value to pad the image. + - seg: The value to pad the semantic segmentation map. + Defaults to dict(img=0, seg=255). + keep_ratio (bool): Whether to keep the aspect ratio when resizing the + image. Defaults to False. + clip_object_border (bool): Whether to clip the objects + outside the border of the image. In some dataset like MOT17, the gt + bboxes are allowed to cross the border of images. Therefore, we + don't need to clip the gt bboxes in these cases. Defaults to True. + backend (str): Image resize backend, choices are 'cv2' and 'pillow'. + These two backends generates slightly different results. Defaults + to 'cv2'. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + width: int, + height: int, + pad_val: Union[Number, dict] = dict(img=0, seg=255), + keep_ratio: bool = False, + clip_object_border: bool = True, + backend: str = 'cv2', + interpolation: str = 'bilinear') -> None: + assert width is not None and height is not None, ( + '`width` and' + '`height` can not be `None`') + + self.width = width + self.height = height + self.scale = (width, height) + + self.backend = backend + self.interpolation = interpolation + self.keep_ratio = keep_ratio + self.clip_object_border = clip_object_border + + if keep_ratio is True: + # padding to the fixed size when keep_ratio=True + self.pad_transform = Pad(size=self.scale, pad_val=pad_val) + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to resize images, bounding boxes and semantic + segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + Returns: + dict: Resized results, 'img', 'gt_bboxes', 'gt_seg_map', + 'scale', 'scale_factor', 'height', 'width', and 'keep_ratio' keys + are updated in result dict. + """ + img = results['img'] + h, w = img.shape[:2] + if self.keep_ratio: + scale_factor = min(self.width / w, self.height / h) + results['scale_factor'] = (scale_factor, scale_factor) + real_w, real_h = int(w * float(scale_factor) + + 0.5), int(h * float(scale_factor) + 0.5) + img, scale_factor = mmcv.imrescale( + results['img'], (real_w, real_h), + interpolation=self.interpolation, + return_scale=True, + backend=self.backend) + # the w_scale and h_scale has minor difference + # a real fix should be done in the mmcv.imrescale in the future + results['img'] = img + results['img_shape'] = img.shape[:2] + results['keep_ratio'] = self.keep_ratio + results['scale'] = (real_w, real_h) + else: + results['scale'] = (self.width, self.height) + results['scale_factor'] = (self.width / w, self.height / h) + super()._resize_img(results) + + self._resize_bboxes(results) + self._resize_masks(results) + self._resize_seg(results) + self._record_homography_matrix(results) + if self.keep_ratio: + self.pad_transform(results) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(width={self.width}, height={self.height}, ' + repr_str += f'keep_ratio={self.keep_ratio}, ' + repr_str += f'clip_object_border={self.clip_object_border}), ' + repr_str += f'backend={self.backend}), ' + repr_str += f'interpolation={self.interpolation})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomFlip(MMCV_RandomFlip): + """Flip the image & bbox & mask & segmentation map. Added or Updated keys: + flip, flip_direction, img, gt_bboxes, and gt_seg_map. There are 3 flip + modes: + + - ``prob`` is float, ``direction`` is string: the image will be + ``direction``ly flipped with probability of ``prob`` . + E.g., ``prob=0.5``, ``direction='horizontal'``, + then image will be horizontally flipped with probability of 0.5. + - ``prob`` is float, ``direction`` is list of string: the image will + be ``direction[i]``ly flipped with probability of + ``prob/len(direction)``. + E.g., ``prob=0.5``, ``direction=['horizontal', 'vertical']``, + then image will be horizontally flipped with probability of 0.25, + vertically with probability of 0.25. + - ``prob`` is list of float, ``direction`` is list of string: + given ``len(prob) == len(direction)``, the image will + be ``direction[i]``ly flipped with probability of ``prob[i]``. + E.g., ``prob=[0.3, 0.5]``, ``direction=['horizontal', + 'vertical']``, then image will be horizontally flipped with + probability of 0.3, vertically with probability of 0.5. + + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - flip + - flip_direction + - homography_matrix + + + Args: + prob (float | list[float], optional): The flipping probability. + Defaults to None. + direction(str | list[str]): The flipping direction. Options + If input is a list, the length must equal ``prob``. Each + element in ``prob`` indicates the flip probability of + corresponding direction. Defaults to 'horizontal'. + """ + + def _record_homography_matrix(self, results: dict) -> None: + """Record the homography matrix for the RandomFlip.""" + cur_dir = results['flip_direction'] + h, w = results['img'].shape[:2] + + if cur_dir == 'horizontal': + homography_matrix = np.array([[-1, 0, w], [0, 1, 0], [0, 0, 1]], + dtype=np.float32) + elif cur_dir == 'vertical': + homography_matrix = np.array([[1, 0, 0], [0, -1, h], [0, 0, 1]], + dtype=np.float32) + elif cur_dir == 'diagonal': + homography_matrix = np.array([[-1, 0, w], [0, -1, h], [0, 0, 1]], + dtype=np.float32) + else: + homography_matrix = np.eye(3, dtype=np.float32) + + if results.get('homography_matrix', None) is None: + results['homography_matrix'] = homography_matrix + else: + results['homography_matrix'] = homography_matrix @ results[ + 'homography_matrix'] + + @autocast_box_type() + def _flip(self, results: dict) -> None: + """Flip images, bounding boxes, and semantic segmentation map.""" + # flip image + results['img'] = mmcv.imflip( + results['img'], direction=results['flip_direction']) + + img_shape = results['img'].shape[:2] + + # flip bboxes + if results.get('gt_bboxes', None) is not None: + results['gt_bboxes'].flip_(img_shape, results['flip_direction']) + + # flip masks + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'].flip( + results['flip_direction']) + + # flip segs + if results.get('gt_seg_map', None) is not None: + results['gt_seg_map'] = mmcv.imflip( + results['gt_seg_map'], direction=results['flip_direction']) + + # record homography matrix for flip + self._record_homography_matrix(results) + + +@TRANSFORMS.register_module() +class RandomShift(BaseTransform): + """Shift the image and box given shift pixels and probability. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) + - gt_bboxes_labels (np.int64) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_bboxes_labels + - gt_ignore_flags (bool) (optional) + + Args: + prob (float): Probability of shifts. Defaults to 0.5. + max_shift_px (int): The max pixels for shifting. Defaults to 32. + filter_thr_px (int): The width and height threshold for filtering. + The bbox and the rest of the targets below the width and + height threshold will be filtered. Defaults to 1. + """ + + def __init__(self, + prob: float = 0.5, + max_shift_px: int = 32, + filter_thr_px: int = 1) -> None: + assert 0 <= prob <= 1 + assert max_shift_px >= 0 + self.prob = prob + self.max_shift_px = max_shift_px + self.filter_thr_px = int(filter_thr_px) + + @cache_randomness + def _random_prob(self) -> float: + return random.uniform(0, 1) + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to random shift images, bounding boxes. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Shift results. + """ + if self._random_prob() < self.prob: + img_shape = results['img'].shape[:2] + + random_shift_x = random.randint(-self.max_shift_px, + self.max_shift_px) + random_shift_y = random.randint(-self.max_shift_px, + self.max_shift_px) + new_x = max(0, random_shift_x) + ori_x = max(0, -random_shift_x) + new_y = max(0, random_shift_y) + ori_y = max(0, -random_shift_y) + + # TODO: support mask and semantic segmentation maps. + bboxes = results['gt_bboxes'].clone() + bboxes.translate_([random_shift_x, random_shift_y]) + + # clip border + bboxes.clip_(img_shape) + + # remove invalid bboxes + valid_inds = (bboxes.widths > self.filter_thr_px).numpy() & ( + bboxes.heights > self.filter_thr_px).numpy() + # If the shift does not contain any gt-bbox area, skip this + # image. + if not valid_inds.any(): + return results + bboxes = bboxes[valid_inds] + results['gt_bboxes'] = bboxes + results['gt_bboxes_labels'] = results['gt_bboxes_labels'][ + valid_inds] + + if results.get('gt_ignore_flags', None) is not None: + results['gt_ignore_flags'] = \ + results['gt_ignore_flags'][valid_inds] + + # shift img + img = results['img'] + new_img = np.zeros_like(img) + img_h, img_w = img.shape[:2] + new_h = img_h - np.abs(random_shift_y) + new_w = img_w - np.abs(random_shift_x) + new_img[new_y:new_y + new_h, new_x:new_x + new_w] \ + = img[ori_y:ori_y + new_h, ori_x:ori_x + new_w] + results['img'] = new_img + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'max_shift_px={self.max_shift_px}, ' + repr_str += f'filter_thr_px={self.filter_thr_px})' + return repr_str + + +@TRANSFORMS.register_module() +class Pad(MMCV_Pad): + """Pad the image & segmentation map. + + There are three padding modes: (1) pad to a fixed size and (2) pad to the + minimum size that is divisible by some number. and (3)pad to square. Also, + pad to square and pad to the minimum size can be used as the same time. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_masks + - gt_seg_map + + Added Keys: + + - pad_shape + - pad_fixed_size + - pad_size_divisor + + Args: + size (tuple, optional): Fixed padding size. + Expected padding shape (width, height). Defaults to None. + size_divisor (int, optional): The divisor of padded size. Defaults to + None. + pad_to_square (bool): Whether to pad the image into a square. + Currently only used for YOLOX. Defaults to False. + pad_val (Number | dict[str, Number], optional) - Padding value for if + the pad_mode is "constant". If it is a single number, the value + to pad the image is the number and to pad the semantic + segmentation map is 255. If it is a dict, it should have the + following keys: + + - img: The value to pad the image. + - seg: The value to pad the semantic segmentation map. + Defaults to dict(img=0, seg=255). + padding_mode (str): Type of padding. Should be: constant, edge, + reflect or symmetric. Defaults to 'constant'. + + - constant: pads with a constant value, this value is specified + with pad_val. + - edge: pads with the last value at the edge of the image. + - reflect: pads with reflection of image without repeating the last + value on the edge. For example, padding [1, 2, 3, 4] with 2 + elements on both sides in reflect mode will result in + [3, 2, 1, 2, 3, 4, 3, 2]. + - symmetric: pads with reflection of image repeating the last value + on the edge. For example, padding [1, 2, 3, 4] with 2 elements on + both sides in symmetric mode will result in + [2, 1, 1, 2, 3, 4, 4, 3] + """ + + def _pad_masks(self, results: dict) -> None: + """Pad masks according to ``results['pad_shape']``.""" + if results.get('gt_masks', None) is not None: + pad_val = self.pad_val.get('masks', 0) + pad_shape = results['pad_shape'][:2] + results['gt_masks'] = results['gt_masks'].pad( + pad_shape, pad_val=pad_val) + + def transform(self, results: dict) -> dict: + """Call function to pad images, masks, semantic segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Updated result dict. + """ + self._pad_img(results) + self._pad_seg(results) + self._pad_masks(results) + return results + + +@TRANSFORMS.register_module() +class RandomCrop(BaseTransform): + """Random crop the image & bboxes & masks. + + The absolute ``crop_size`` is sampled based on ``crop_type`` and + ``image_size``, then the cropped results are generated. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_masks (optional) + - gt_ignore_flags (optional) + - gt_seg_map (optional) + - gt_instances_ids (options, only used in MOT/VIS) + + Added Keys: + + - homography_matrix + + Args: + crop_size (tuple): The relative ratio or absolute pixels of + (width, height). + crop_type (str, optional): One of "relative_range", "relative", + "absolute", "absolute_range". "relative" randomly crops + (h * crop_size[0], w * crop_size[1]) part from an input of size + (h, w). "relative_range" uniformly samples relative crop size from + range [crop_size[0], 1] and [crop_size[1], 1] for height and width + respectively. "absolute" crops from an input with absolute size + (crop_size[0], crop_size[1]). "absolute_range" uniformly samples + crop_h in range [crop_size[0], min(h, crop_size[1])] and crop_w + in range [crop_size[0], min(w, crop_size[1])]. + Defaults to "absolute". + allow_negative_crop (bool, optional): Whether to allow a crop that does + not contain any bbox area. Defaults to False. + recompute_bbox (bool, optional): Whether to re-compute the boxes based + on cropped instance masks. Defaults to False. + bbox_clip_border (bool, optional): Whether clip the objects outside + the border of the image. Defaults to True. + + Note: + - If the image is smaller than the absolute crop size, return the + original image. + - The keys for bboxes, labels and masks must be aligned. That is, + ``gt_bboxes`` corresponds to ``gt_labels`` and ``gt_masks``, and + ``gt_bboxes_ignore`` corresponds to ``gt_labels_ignore`` and + ``gt_masks_ignore``. + - If the crop does not contain any gt-bbox region and + ``allow_negative_crop`` is set to False, skip this image. + """ + + def __init__(self, + crop_size: tuple, + crop_type: str = 'absolute', + allow_negative_crop: bool = False, + recompute_bbox: bool = False, + bbox_clip_border: bool = True) -> None: + if crop_type not in [ + 'relative_range', 'relative', 'absolute', 'absolute_range' + ]: + raise ValueError(f'Invalid crop_type {crop_type}.') + if crop_type in ['absolute', 'absolute_range']: + assert crop_size[0] > 0 and crop_size[1] > 0 + assert isinstance(crop_size[0], int) and isinstance( + crop_size[1], int) + if crop_type == 'absolute_range': + assert crop_size[0] <= crop_size[1] + else: + assert 0 < crop_size[0] <= 1 and 0 < crop_size[1] <= 1 + self.crop_size = crop_size + self.crop_type = crop_type + self.allow_negative_crop = allow_negative_crop + self.bbox_clip_border = bbox_clip_border + self.recompute_bbox = recompute_bbox + + def _crop_data(self, results: dict, crop_size: Tuple[int, int], + allow_negative_crop: bool) -> Union[dict, None]: + """Function to randomly crop images, bounding boxes, masks, semantic + segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + crop_size (Tuple[int, int]): Expected absolute size after + cropping, (h, w). + allow_negative_crop (bool): Whether to allow a crop that does not + contain any bbox area. + + Returns: + results (Union[dict, None]): Randomly cropped results, 'img_shape' + key in result dict is updated according to crop size. None will + be returned when there is no valid bbox after cropping. + """ + assert crop_size[0] > 0 and crop_size[1] > 0 + img = results['img'] + margin_h = max(img.shape[0] - crop_size[0], 0) + margin_w = max(img.shape[1] - crop_size[1], 0) + offset_h, offset_w = self._rand_offset((margin_h, margin_w)) + crop_y1, crop_y2 = offset_h, offset_h + crop_size[0] + crop_x1, crop_x2 = offset_w, offset_w + crop_size[1] + + # Record the homography matrix for the RandomCrop + homography_matrix = np.array( + [[1, 0, -offset_w], [0, 1, -offset_h], [0, 0, 1]], + dtype=np.float32) + if results.get('homography_matrix', None) is None: + results['homography_matrix'] = homography_matrix + else: + results['homography_matrix'] = homography_matrix @ results[ + 'homography_matrix'] + + # crop the image + img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...] + img_shape = img.shape + results['img'] = img + results['img_shape'] = img_shape[:2] + + # crop bboxes accordingly and clip to the image boundary + if results.get('gt_bboxes', None) is not None: + bboxes = results['gt_bboxes'] + bboxes.translate_([-offset_w, -offset_h]) + if self.bbox_clip_border: + bboxes.clip_(img_shape[:2]) + valid_inds = bboxes.is_inside(img_shape[:2]).numpy() + # If the crop does not contain any gt-bbox area and + # allow_negative_crop is False, skip this image. + if (not valid_inds.any() and not allow_negative_crop): + return None + + results['gt_bboxes'] = bboxes[valid_inds] + + if results.get('gt_ignore_flags', None) is not None: + results['gt_ignore_flags'] = \ + results['gt_ignore_flags'][valid_inds] + + if results.get('gt_bboxes_labels', None) is not None: + results['gt_bboxes_labels'] = \ + results['gt_bboxes_labels'][valid_inds] + + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'][ + valid_inds.nonzero()[0]].crop( + np.asarray([crop_x1, crop_y1, crop_x2, crop_y2])) + if self.recompute_bbox: + results['gt_bboxes'] = results['gt_masks'].get_bboxes( + type(results['gt_bboxes'])) + + # We should remove the instance ids corresponding to invalid boxes. + if results.get('gt_instances_ids', None) is not None: + results['gt_instances_ids'] = \ + results['gt_instances_ids'][valid_inds] + + # crop semantic seg + if results.get('gt_seg_map', None) is not None: + results['gt_seg_map'] = results['gt_seg_map'][crop_y1:crop_y2, + crop_x1:crop_x2] + + return results + + @cache_randomness + def _rand_offset(self, margin: Tuple[int, int]) -> Tuple[int, int]: + """Randomly generate crop offset. + + Args: + margin (Tuple[int, int]): The upper bound for the offset generated + randomly. + + Returns: + Tuple[int, int]: The random offset for the crop. + """ + margin_h, margin_w = margin + offset_h = np.random.randint(0, margin_h + 1) + offset_w = np.random.randint(0, margin_w + 1) + + return offset_h, offset_w + + @cache_randomness + def _get_crop_size(self, image_size: Tuple[int, int]) -> Tuple[int, int]: + """Randomly generates the absolute crop size based on `crop_type` and + `image_size`. + + Args: + image_size (Tuple[int, int]): (h, w). + + Returns: + crop_size (Tuple[int, int]): (crop_h, crop_w) in absolute pixels. + """ + h, w = image_size + if self.crop_type == 'absolute': + return min(self.crop_size[1], h), min(self.crop_size[0], w) + elif self.crop_type == 'absolute_range': + crop_h = np.random.randint( + min(h, self.crop_size[0]), + min(h, self.crop_size[1]) + 1) + crop_w = np.random.randint( + min(w, self.crop_size[0]), + min(w, self.crop_size[1]) + 1) + return crop_h, crop_w + elif self.crop_type == 'relative': + crop_w, crop_h = self.crop_size + return int(h * crop_h + 0.5), int(w * crop_w + 0.5) + else: + # 'relative_range' + crop_size = np.asarray(self.crop_size, dtype=np.float32) + crop_h, crop_w = crop_size + np.random.rand(2) * (1 - crop_size) + return int(h * crop_h + 0.5), int(w * crop_w + 0.5) + + @autocast_box_type() + def transform(self, results: dict) -> Union[dict, None]: + """Transform function to randomly crop images, bounding boxes, masks, + semantic segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + results (Union[dict, None]): Randomly cropped results, 'img_shape' + key in result dict is updated according to crop size. None will + be returned when there is no valid bbox after cropping. + """ + image_size = results['img'].shape[:2] + crop_size = self._get_crop_size(image_size) + results = self._crop_data(results, crop_size, self.allow_negative_crop) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(crop_size={self.crop_size}, ' + repr_str += f'crop_type={self.crop_type}, ' + repr_str += f'allow_negative_crop={self.allow_negative_crop}, ' + repr_str += f'recompute_bbox={self.recompute_bbox}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + +@TRANSFORMS.register_module() +class SegRescale(BaseTransform): + """Rescale semantic segmentation maps. + + This transform rescale the ``gt_seg_map`` according to ``scale_factor``. + + Required Keys: + + - gt_seg_map + + Modified Keys: + + - gt_seg_map + + Args: + scale_factor (float): The scale factor of the final output. Defaults + to 1. + backend (str): Image rescale backend, choices are 'cv2' and 'pillow'. + These two backends generates slightly different results. Defaults + to 'cv2'. + """ + + def __init__(self, scale_factor: float = 1, backend: str = 'cv2') -> None: + self.scale_factor = scale_factor + self.backend = backend + + def transform(self, results: dict) -> dict: + """Transform function to scale the semantic segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with semantic segmentation map scaled. + """ + if self.scale_factor != 1: + results['gt_seg_map'] = mmcv.imrescale( + results['gt_seg_map'], + self.scale_factor, + interpolation='nearest', + backend=self.backend) + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(scale_factor={self.scale_factor}, ' + repr_str += f'backend={self.backend})' + return repr_str + + +@TRANSFORMS.register_module() +class PhotoMetricDistortion(BaseTransform): + """Apply photometric distortion to image sequentially, every transformation + is applied with a probability of 0.5. The position of random contrast is in + second or second to last. + + 1. random brightness + 2. random contrast (mode 0) + 3. convert color from BGR to HSV + 4. random saturation + 5. random hue + 6. convert color from HSV to BGR + 7. random contrast (mode 1) + 8. randomly swap channels + + Required Keys: + + - img (np.uint8) + + Modified Keys: + + - img (np.float32) + + Args: + brightness_delta (int): delta of brightness. + contrast_range (sequence): range of contrast. + saturation_range (sequence): range of saturation. + hue_delta (int): delta of hue. + """ + + def __init__(self, + brightness_delta: int = 32, + contrast_range: Sequence[Number] = (0.5, 1.5), + saturation_range: Sequence[Number] = (0.5, 1.5), + hue_delta: int = 18) -> None: + self.brightness_delta = brightness_delta + self.contrast_lower, self.contrast_upper = contrast_range + self.saturation_lower, self.saturation_upper = saturation_range + self.hue_delta = hue_delta + + @cache_randomness + def _random_flags(self) -> Sequence[Number]: + mode = random.randint(2) + brightness_flag = random.randint(2) + contrast_flag = random.randint(2) + saturation_flag = random.randint(2) + hue_flag = random.randint(2) + swap_flag = random.randint(2) + delta_value = random.uniform(-self.brightness_delta, + self.brightness_delta) + alpha_value = random.uniform(self.contrast_lower, self.contrast_upper) + saturation_value = random.uniform(self.saturation_lower, + self.saturation_upper) + hue_value = random.uniform(-self.hue_delta, self.hue_delta) + swap_value = random.permutation(3) + + return (mode, brightness_flag, contrast_flag, saturation_flag, + hue_flag, swap_flag, delta_value, alpha_value, + saturation_value, hue_value, swap_value) + + def transform(self, results: dict) -> dict: + """Transform function to perform photometric distortion on images. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images distorted. + """ + assert 'img' in results, '`img` is not found in results' + img = results['img'] + img = img.astype(np.float32) + + (mode, brightness_flag, contrast_flag, saturation_flag, hue_flag, + swap_flag, delta_value, alpha_value, saturation_value, hue_value, + swap_value) = self._random_flags() + + # random brightness + if brightness_flag: + img += delta_value + + # mode == 0 --> do random contrast first + # mode == 1 --> do random contrast last + if mode == 1: + if contrast_flag: + img *= alpha_value + + # convert color from BGR to HSV + img = mmcv.bgr2hsv(img) + + # random saturation + if saturation_flag: + img[..., 1] *= saturation_value + # For image(type=float32), after convert bgr to hsv by opencv, + # valid saturation value range is [0, 1] + if saturation_value > 1: + img[..., 1] = img[..., 1].clip(0, 1) + + # random hue + if hue_flag: + img[..., 0] += hue_value + img[..., 0][img[..., 0] > 360] -= 360 + img[..., 0][img[..., 0] < 0] += 360 + + # convert color from HSV to BGR + img = mmcv.hsv2bgr(img) + + # random contrast + if mode == 0: + if contrast_flag: + img *= alpha_value + + # randomly swap channels + if swap_flag: + img = img[..., swap_value] + + results['img'] = img + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(brightness_delta={self.brightness_delta}, ' + repr_str += 'contrast_range=' + repr_str += f'{(self.contrast_lower, self.contrast_upper)}, ' + repr_str += 'saturation_range=' + repr_str += f'{(self.saturation_lower, self.saturation_upper)}, ' + repr_str += f'hue_delta={self.hue_delta})' + return repr_str + + +@TRANSFORMS.register_module() +class Expand(BaseTransform): + """Random expand the image & bboxes & masks & segmentation map. + + Randomly place the original image on a canvas of ``ratio`` x original image + size filled with mean values. The ratio is in the range of ratio_range. + + Required Keys: + + - img + - img_shape + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_masks + - gt_seg_map + + + Args: + mean (sequence): mean value of dataset. + to_rgb (bool): if need to convert the order of mean to align with RGB. + ratio_range (sequence)): range of expand ratio. + seg_ignore_label (int): label of ignore segmentation map. + prob (float): probability of applying this transformation + """ + + def __init__(self, + mean: Sequence[Number] = (0, 0, 0), + to_rgb: bool = True, + ratio_range: Sequence[Number] = (1, 4), + seg_ignore_label: int = None, + prob: float = 0.5) -> None: + self.to_rgb = to_rgb + self.ratio_range = ratio_range + if to_rgb: + self.mean = mean[::-1] + else: + self.mean = mean + self.min_ratio, self.max_ratio = ratio_range + self.seg_ignore_label = seg_ignore_label + self.prob = prob + + @cache_randomness + def _random_prob(self) -> float: + return random.uniform(0, 1) + + @cache_randomness + def _random_ratio(self) -> float: + return random.uniform(self.min_ratio, self.max_ratio) + + @cache_randomness + def _random_left_top(self, ratio: float, h: int, + w: int) -> Tuple[int, int]: + left = int(random.uniform(0, w * ratio - w)) + top = int(random.uniform(0, h * ratio - h)) + return left, top + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to expand images, bounding boxes, masks, + segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images, bounding boxes, masks, segmentation + map expanded. + """ + if self._random_prob() > self.prob: + return results + assert 'img' in results, '`img` is not found in results' + img = results['img'] + h, w, c = img.shape + ratio = self._random_ratio() + # speedup expand when meets large image + if np.all(self.mean == self.mean[0]): + expand_img = np.empty((int(h * ratio), int(w * ratio), c), + img.dtype) + expand_img.fill(self.mean[0]) + else: + expand_img = np.full((int(h * ratio), int(w * ratio), c), + self.mean, + dtype=img.dtype) + left, top = self._random_left_top(ratio, h, w) + expand_img[top:top + h, left:left + w] = img + results['img'] = expand_img + results['img_shape'] = expand_img.shape[:2] + + # expand bboxes + if results.get('gt_bboxes', None) is not None: + results['gt_bboxes'].translate_([left, top]) + + # expand masks + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'].expand( + int(h * ratio), int(w * ratio), top, left) + + # expand segmentation map + if results.get('gt_seg_map', None) is not None: + gt_seg = results['gt_seg_map'] + expand_gt_seg = np.full((int(h * ratio), int(w * ratio)), + self.seg_ignore_label, + dtype=gt_seg.dtype) + expand_gt_seg[top:top + h, left:left + w] = gt_seg + results['gt_seg_map'] = expand_gt_seg + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(mean={self.mean}, to_rgb={self.to_rgb}, ' + repr_str += f'ratio_range={self.ratio_range}, ' + repr_str += f'seg_ignore_label={self.seg_ignore_label}, ' + repr_str += f'prob={self.prob})' + return repr_str + + +@TRANSFORMS.register_module() +class MinIoURandomCrop(BaseTransform): + """Random crop the image & bboxes & masks & segmentation map, the cropped + patches have minimum IoU requirement with original image & bboxes & masks. + + & segmentation map, the IoU threshold is randomly selected from min_ious. + + + Required Keys: + + - img + - img_shape + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_bboxes_labels + - gt_masks + - gt_ignore_flags + - gt_seg_map + + + Args: + min_ious (Sequence[float]): minimum IoU threshold for all intersections + with bounding boxes. + min_crop_size (float): minimum crop's size (i.e. h,w := a*h, a*w, + where a >= min_crop_size). + bbox_clip_border (bool, optional): Whether clip the objects outside + the border of the image. Defaults to True. + """ + + def __init__(self, + min_ious: Sequence[float] = (0.1, 0.3, 0.5, 0.7, 0.9), + min_crop_size: float = 0.3, + bbox_clip_border: bool = True) -> None: + + self.min_ious = min_ious + self.sample_mode = (1, *min_ious, 0) + self.min_crop_size = min_crop_size + self.bbox_clip_border = bbox_clip_border + + @cache_randomness + def _random_mode(self) -> Number: + return random.choice(self.sample_mode) + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to crop images and bounding boxes with minimum + IoU constraint. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images and bounding boxes cropped, \ + 'img_shape' key is updated. + """ + assert 'img' in results, '`img` is not found in results' + assert 'gt_bboxes' in results, '`gt_bboxes` is not found in results' + img = results['img'] + boxes = results['gt_bboxes'] + h, w, c = img.shape + while True: + mode = self._random_mode() + self.mode = mode + if mode == 1: + return results + + min_iou = self.mode + for i in range(50): + new_w = random.uniform(self.min_crop_size * w, w) + new_h = random.uniform(self.min_crop_size * h, h) + + # h / w in [0.5, 2] + if new_h / new_w < 0.5 or new_h / new_w > 2: + continue + + left = random.uniform(w - new_w) + top = random.uniform(h - new_h) + + patch = np.array( + (int(left), int(top), int(left + new_w), int(top + new_h))) + # Line or point crop is not allowed + if patch[2] == patch[0] or patch[3] == patch[1]: + continue + overlaps = boxes.overlaps( + HorizontalBoxes(patch.reshape(-1, 4).astype(np.float32)), + boxes).numpy().reshape(-1) + if len(overlaps) > 0 and overlaps.min() < min_iou: + continue + + # center of boxes should inside the crop img + # only adjust boxes and instance masks when the gt is not empty + if len(overlaps) > 0: + # adjust boxes + def is_center_of_bboxes_in_patch(boxes, patch): + centers = boxes.centers.numpy() + mask = ((centers[:, 0] > patch[0]) * + (centers[:, 1] > patch[1]) * + (centers[:, 0] < patch[2]) * + (centers[:, 1] < patch[3])) + return mask + + mask = is_center_of_bboxes_in_patch(boxes, patch) + if not mask.any(): + continue + if results.get('gt_bboxes', None) is not None: + boxes = results['gt_bboxes'] + mask = is_center_of_bboxes_in_patch(boxes, patch) + boxes = boxes[mask] + boxes.translate_([-patch[0], -patch[1]]) + if self.bbox_clip_border: + boxes.clip_( + [patch[3] - patch[1], patch[2] - patch[0]]) + results['gt_bboxes'] = boxes + + # ignore_flags + if results.get('gt_ignore_flags', None) is not None: + results['gt_ignore_flags'] = \ + results['gt_ignore_flags'][mask] + + # labels + if results.get('gt_bboxes_labels', None) is not None: + results['gt_bboxes_labels'] = results[ + 'gt_bboxes_labels'][mask] + + # mask fields + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'][ + mask.nonzero()[0]].crop(patch) + # adjust the img no matter whether the gt is empty before crop + img = img[patch[1]:patch[3], patch[0]:patch[2]] + results['img'] = img + results['img_shape'] = img.shape[:2] + + # seg fields + if results.get('gt_seg_map', None) is not None: + results['gt_seg_map'] = results['gt_seg_map'][ + patch[1]:patch[3], patch[0]:patch[2]] + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(min_ious={self.min_ious}, ' + repr_str += f'min_crop_size={self.min_crop_size}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + +@TRANSFORMS.register_module() +class Corrupt(BaseTransform): + """Corruption augmentation. + + Corruption transforms implemented based on + `imagecorruptions `_. + + Required Keys: + + - img (np.uint8) + + + Modified Keys: + + - img (np.uint8) + + + Args: + corruption (str): Corruption name. + severity (int): The severity of corruption. Defaults to 1. + """ + + def __init__(self, corruption: str, severity: int = 1) -> None: + self.corruption = corruption + self.severity = severity + + def transform(self, results: dict) -> dict: + """Call function to corrupt image. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images corrupted. + """ + + if corrupt is None: + raise RuntimeError('imagecorruptions is not installed') + results['img'] = corrupt( + results['img'].astype(np.uint8), + corruption_name=self.corruption, + severity=self.severity) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(corruption={self.corruption}, ' + repr_str += f'severity={self.severity})' + return repr_str + + +@TRANSFORMS.register_module() +@avoid_cache_randomness +class Albu(BaseTransform): + """Albumentation augmentation. + + Adds custom transformations from Albumentations library. + Please, visit `https://albumentations.readthedocs.io` + to get more information. + + Required Keys: + + - img (np.uint8) + - gt_bboxes (HorizontalBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + + Modified Keys: + + - img (np.uint8) + - gt_bboxes (HorizontalBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - img_shape (tuple) + + An example of ``transforms`` is as followed: + + .. code-block:: + + [ + dict( + type='ShiftScaleRotate', + shift_limit=0.0625, + scale_limit=0.0, + rotate_limit=0, + interpolation=1, + p=0.5), + dict( + type='RandomBrightnessContrast', + brightness_limit=[0.1, 0.3], + contrast_limit=[0.1, 0.3], + p=0.2), + dict(type='ChannelShuffle', p=0.1), + dict( + type='OneOf', + transforms=[ + dict(type='Blur', blur_limit=3, p=1.0), + dict(type='MedianBlur', blur_limit=3, p=1.0) + ], + p=0.1), + ] + + Args: + transforms (list[dict]): A list of albu transformations + bbox_params (dict, optional): Bbox_params for albumentation `Compose` + keymap (dict, optional): Contains + {'input key':'albumentation-style key'} + skip_img_without_anno (bool): Whether to skip the image if no ann left + after aug. Defaults to False. + """ + + def __init__(self, + transforms: List[dict], + bbox_params: Optional[dict] = None, + keymap: Optional[dict] = None, + skip_img_without_anno: bool = False) -> None: + if Compose is None: + raise RuntimeError('albumentations is not installed') + + # Args will be modified later, copying it will be safer + transforms = copy.deepcopy(transforms) + if bbox_params is not None: + bbox_params = copy.deepcopy(bbox_params) + if keymap is not None: + keymap = copy.deepcopy(keymap) + self.transforms = transforms + self.filter_lost_elements = False + self.skip_img_without_anno = skip_img_without_anno + + # A simple workaround to remove masks without boxes + if (isinstance(bbox_params, dict) and 'label_fields' in bbox_params + and 'filter_lost_elements' in bbox_params): + self.filter_lost_elements = True + self.origin_label_fields = bbox_params['label_fields'] + bbox_params['label_fields'] = ['idx_mapper'] + del bbox_params['filter_lost_elements'] + + self.bbox_params = ( + self.albu_builder(bbox_params) if bbox_params else None) + self.aug = Compose([self.albu_builder(t) for t in self.transforms], + bbox_params=self.bbox_params) + + if not keymap: + self.keymap_to_albu = { + 'img': 'image', + 'gt_masks': 'masks', + 'gt_bboxes': 'bboxes' + } + else: + self.keymap_to_albu = keymap + self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()} + + def albu_builder(self, cfg: dict) -> albumentations: + """Import a module from albumentations. + + It inherits some of :func:`build_from_cfg` logic. + + Args: + cfg (dict): Config dict. It should at least contain the key "type". + + Returns: + obj: The constructed object. + """ + + assert isinstance(cfg, dict) and 'type' in cfg + args = cfg.copy() + obj_type = args.pop('type') + if is_str(obj_type): + if albumentations is None: + raise RuntimeError('albumentations is not installed') + obj_cls = getattr(albumentations, obj_type) + elif inspect.isclass(obj_type): + obj_cls = obj_type + else: + raise TypeError( + f'type must be a str or valid type, but got {type(obj_type)}') + + if 'transforms' in args: + args['transforms'] = [ + self.albu_builder(transform) + for transform in args['transforms'] + ] + + return obj_cls(**args) + + @staticmethod + def mapper(d: dict, keymap: dict) -> dict: + """Dictionary mapper. Renames keys according to keymap provided. + + Args: + d (dict): old dict + keymap (dict): {'old_key':'new_key'} + Returns: + dict: new dict. + """ + updated_dict = {} + for k, v in zip(d.keys(), d.values()): + new_k = keymap.get(k, k) + updated_dict[new_k] = d[k] + return updated_dict + + @autocast_box_type() + def transform(self, results: dict) -> Union[dict, None]: + """Transform function of Albu.""" + # TODO: gt_seg_map is not currently supported + # dict to albumentations format + results = self.mapper(results, self.keymap_to_albu) + results, ori_masks = self._preprocess_results(results) + results = self.aug(**results) + results = self._postprocess_results(results, ori_masks) + if results is None: + return None + # back to the original format + results = self.mapper(results, self.keymap_back) + results['img_shape'] = results['img'].shape[:2] + return results + + def _preprocess_results(self, results: dict) -> tuple: + """Pre-processing results to facilitate the use of Albu.""" + if 'bboxes' in results: + # to list of boxes + if not isinstance(results['bboxes'], HorizontalBoxes): + raise NotImplementedError( + 'Albu only supports horizontal boxes now') + bboxes = results['bboxes'].numpy() + results['bboxes'] = [x for x in bboxes] + # add pseudo-field for filtration + if self.filter_lost_elements: + results['idx_mapper'] = np.arange(len(results['bboxes'])) + + # TODO: Support mask structure in albu + ori_masks = None + if 'masks' in results: + if isinstance(results['masks'], PolygonMasks): + raise NotImplementedError( + 'Albu only supports BitMap masks now') + ori_masks = results['masks'] + if albumentations.__version__ < '0.5': + results['masks'] = results['masks'].masks + else: + results['masks'] = [mask for mask in results['masks'].masks] + + return results, ori_masks + + def _postprocess_results( + self, + results: dict, + ori_masks: Optional[Union[BitmapMasks, + PolygonMasks]] = None) -> dict: + """Post-processing Albu output.""" + # albumentations may return np.array or list on different versions + if 'gt_bboxes_labels' in results and isinstance( + results['gt_bboxes_labels'], list): + results['gt_bboxes_labels'] = np.array( + results['gt_bboxes_labels'], dtype=np.int64) + if 'gt_ignore_flags' in results and isinstance( + results['gt_ignore_flags'], list): + results['gt_ignore_flags'] = np.array( + results['gt_ignore_flags'], dtype=bool) + + if 'bboxes' in results: + if isinstance(results['bboxes'], list): + results['bboxes'] = np.array( + results['bboxes'], dtype=np.float32) + results['bboxes'] = results['bboxes'].reshape(-1, 4) + results['bboxes'] = HorizontalBoxes(results['bboxes']) + + # filter label_fields + if self.filter_lost_elements: + + for label in self.origin_label_fields: + results[label] = np.array( + [results[label][i] for i in results['idx_mapper']]) + if 'masks' in results: + assert ori_masks is not None + results['masks'] = np.array( + [results['masks'][i] for i in results['idx_mapper']]) + results['masks'] = ori_masks.__class__( + results['masks'], ori_masks.height, ori_masks.width) + + if (not len(results['idx_mapper']) + and self.skip_img_without_anno): + return None + elif 'masks' in results: + results['masks'] = ori_masks.__class__(results['masks'], + ori_masks.height, + ori_masks.width) + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + f'(transforms={self.transforms})' + return repr_str + + +@TRANSFORMS.register_module() +@avoid_cache_randomness +class RandomCenterCropPad(BaseTransform): + """Random center crop and random around padding for CornerNet. + + This operation generates randomly cropped image from the original image and + pads it simultaneously. Different from :class:`RandomCrop`, the output + shape may not equal to ``crop_size`` strictly. We choose a random value + from ``ratios`` and the output shape could be larger or smaller than + ``crop_size``. The padding operation is also different from :class:`Pad`, + here we use around padding instead of right-bottom padding. + + The relation between output image (padding image) and original image: + + .. code:: text + + output image + + +----------------------------+ + | padded area | + +------|----------------------------|----------+ + | | cropped area | | + | | +---------------+ | | + | | | . center | | | original image + | | | range | | | + | | +---------------+ | | + +------|----------------------------|----------+ + | padded area | + +----------------------------+ + + There are 5 main areas in the figure: + + - output image: output image of this operation, also called padding + image in following instruction. + - original image: input image of this operation. + - padded area: non-intersect area of output image and original image. + - cropped area: the overlap of output image and original image. + - center range: a smaller area where random center chosen from. + center range is computed by ``border`` and original image's shape + to avoid our random center is too close to original image's border. + + Also this operation act differently in train and test mode, the summary + pipeline is listed below. + + Train pipeline: + + 1. Choose a ``random_ratio`` from ``ratios``, the shape of padding image + will be ``random_ratio * crop_size``. + 2. Choose a ``random_center`` in center range. + 3. Generate padding image with center matches the ``random_center``. + 4. Initialize the padding image with pixel value equals to ``mean``. + 5. Copy the cropped area to padding image. + 6. Refine annotations. + + Test pipeline: + + 1. Compute output shape according to ``test_pad_mode``. + 2. Generate padding image with center matches the original image + center. + 3. Initialize the padding image with pixel value equals to ``mean``. + 4. Copy the ``cropped area`` to padding image. + + Required Keys: + + - img (np.float32) + - img_shape (tuple) + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - img (np.float32) + - img_shape (tuple) + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + + Args: + crop_size (tuple, optional): expected size after crop, final size will + computed according to ratio. Requires (width, height) + in train mode, and None in test mode. + ratios (tuple, optional): random select a ratio from tuple and crop + image to (crop_size[0] * ratio) * (crop_size[1] * ratio). + Only available in train mode. Defaults to (0.9, 1.0, 1.1). + border (int, optional): max distance from center select area to image + border. Only available in train mode. Defaults to 128. + mean (sequence, optional): Mean values of 3 channels. + std (sequence, optional): Std values of 3 channels. + to_rgb (bool, optional): Whether to convert the image from BGR to RGB. + test_mode (bool): whether involve random variables in transform. + In train mode, crop_size is fixed, center coords and ratio is + random selected from predefined lists. In test mode, crop_size + is image's original shape, center coords and ratio is fixed. + Defaults to False. + test_pad_mode (tuple, optional): padding method and padding shape + value, only available in test mode. Default is using + 'logical_or' with 127 as padding shape value. + + - 'logical_or': final_shape = input_shape | padding_shape_value + - 'size_divisor': final_shape = int( + ceil(input_shape / padding_shape_value) * padding_shape_value) + + Defaults to ('logical_or', 127). + test_pad_add_pix (int): Extra padding pixel in test mode. + Defaults to 0. + bbox_clip_border (bool): Whether clip the objects outside + the border of the image. Defaults to True. + """ + + def __init__(self, + crop_size: Optional[tuple] = None, + ratios: Optional[tuple] = (0.9, 1.0, 1.1), + border: Optional[int] = 128, + mean: Optional[Sequence] = None, + std: Optional[Sequence] = None, + to_rgb: Optional[bool] = None, + test_mode: bool = False, + test_pad_mode: Optional[tuple] = ('logical_or', 127), + test_pad_add_pix: int = 0, + bbox_clip_border: bool = True) -> None: + if test_mode: + assert crop_size is None, 'crop_size must be None in test mode' + assert ratios is None, 'ratios must be None in test mode' + assert border is None, 'border must be None in test mode' + assert isinstance(test_pad_mode, (list, tuple)) + assert test_pad_mode[0] in ['logical_or', 'size_divisor'] + else: + assert isinstance(crop_size, (list, tuple)) + assert crop_size[0] > 0 and crop_size[1] > 0, ( + 'crop_size must > 0 in train mode') + assert isinstance(ratios, (list, tuple)) + assert test_pad_mode is None, ( + 'test_pad_mode must be None in train mode') + + self.crop_size = crop_size + self.ratios = ratios + self.border = border + # We do not set default value to mean, std and to_rgb because these + # hyper-parameters are easy to forget but could affect the performance. + # Please use the same setting as Normalize for performance assurance. + assert mean is not None and std is not None and to_rgb is not None + self.to_rgb = to_rgb + self.input_mean = mean + self.input_std = std + if to_rgb: + self.mean = mean[::-1] + self.std = std[::-1] + else: + self.mean = mean + self.std = std + self.test_mode = test_mode + self.test_pad_mode = test_pad_mode + self.test_pad_add_pix = test_pad_add_pix + self.bbox_clip_border = bbox_clip_border + + def _get_border(self, border, size): + """Get final border for the target size. + + This function generates a ``final_border`` according to image's shape. + The area between ``final_border`` and ``size - final_border`` is the + ``center range``. We randomly choose center from the ``center range`` + to avoid our random center is too close to original image's border. + Also ``center range`` should be larger than 0. + + Args: + border (int): The initial border, default is 128. + size (int): The width or height of original image. + Returns: + int: The final border. + """ + k = 2 * border / size + i = pow(2, np.ceil(np.log2(np.ceil(k))) + (k == int(k))) + return border // i + + def _filter_boxes(self, patch, boxes): + """Check whether the center of each box is in the patch. + + Args: + patch (list[int]): The cropped area, [left, top, right, bottom]. + boxes (numpy array, (N x 4)): Ground truth boxes. + + Returns: + mask (numpy array, (N,)): Each box is inside or outside the patch. + """ + center = boxes.centers.numpy() + mask = (center[:, 0] > patch[0]) * (center[:, 1] > patch[1]) * ( + center[:, 0] < patch[2]) * ( + center[:, 1] < patch[3]) + return mask + + def _crop_image_and_paste(self, image, center, size): + """Crop image with a given center and size, then paste the cropped + image to a blank image with two centers align. + + This function is equivalent to generating a blank image with ``size`` + as its shape. Then cover it on the original image with two centers ( + the center of blank image and the random center of original image) + aligned. The overlap area is paste from the original image and the + outside area is filled with ``mean pixel``. + + Args: + image (np array, H x W x C): Original image. + center (list[int]): Target crop center coord. + size (list[int]): Target crop size. [target_h, target_w] + + Returns: + cropped_img (np array, target_h x target_w x C): Cropped image. + border (np array, 4): The distance of four border of + ``cropped_img`` to the original image area, [top, bottom, + left, right] + patch (list[int]): The cropped area, [left, top, right, bottom]. + """ + center_y, center_x = center + target_h, target_w = size + img_h, img_w, img_c = image.shape + + x0 = max(0, center_x - target_w // 2) + x1 = min(center_x + target_w // 2, img_w) + y0 = max(0, center_y - target_h // 2) + y1 = min(center_y + target_h // 2, img_h) + patch = np.array((int(x0), int(y0), int(x1), int(y1))) + + left, right = center_x - x0, x1 - center_x + top, bottom = center_y - y0, y1 - center_y + + cropped_center_y, cropped_center_x = target_h // 2, target_w // 2 + cropped_img = np.zeros((target_h, target_w, img_c), dtype=image.dtype) + for i in range(img_c): + cropped_img[:, :, i] += self.mean[i] + y_slice = slice(cropped_center_y - top, cropped_center_y + bottom) + x_slice = slice(cropped_center_x - left, cropped_center_x + right) + cropped_img[y_slice, x_slice, :] = image[y0:y1, x0:x1, :] + + border = np.array([ + cropped_center_y - top, cropped_center_y + bottom, + cropped_center_x - left, cropped_center_x + right + ], + dtype=np.float32) + + return cropped_img, border, patch + + def _train_aug(self, results): + """Random crop and around padding the original image. + + Args: + results (dict): Image infomations in the augment pipeline. + + Returns: + results (dict): The updated dict. + """ + img = results['img'] + h, w, c = img.shape + gt_bboxes = results['gt_bboxes'] + while True: + scale = random.choice(self.ratios) + new_h = int(self.crop_size[1] * scale) + new_w = int(self.crop_size[0] * scale) + h_border = self._get_border(self.border, h) + w_border = self._get_border(self.border, w) + + for i in range(50): + center_x = random.randint(low=w_border, high=w - w_border) + center_y = random.randint(low=h_border, high=h - h_border) + + cropped_img, border, patch = self._crop_image_and_paste( + img, [center_y, center_x], [new_h, new_w]) + + if len(gt_bboxes) == 0: + results['img'] = cropped_img + results['img_shape'] = cropped_img.shape[:2] + return results + + # if image do not have valid bbox, any crop patch is valid. + mask = self._filter_boxes(patch, gt_bboxes) + if not mask.any(): + continue + + results['img'] = cropped_img + results['img_shape'] = cropped_img.shape[:2] + + x0, y0, x1, y1 = patch + + left_w, top_h = center_x - x0, center_y - y0 + cropped_center_x, cropped_center_y = new_w // 2, new_h // 2 + + # crop bboxes accordingly and clip to the image boundary + gt_bboxes = gt_bboxes[mask] + gt_bboxes.translate_([ + cropped_center_x - left_w - x0, + cropped_center_y - top_h - y0 + ]) + if self.bbox_clip_border: + gt_bboxes.clip_([new_h, new_w]) + keep = gt_bboxes.is_inside([new_h, new_w]).numpy() + gt_bboxes = gt_bboxes[keep] + + results['gt_bboxes'] = gt_bboxes + + # ignore_flags + if results.get('gt_ignore_flags', None) is not None: + gt_ignore_flags = results['gt_ignore_flags'][mask] + results['gt_ignore_flags'] = \ + gt_ignore_flags[keep] + + # labels + if results.get('gt_bboxes_labels', None) is not None: + gt_labels = results['gt_bboxes_labels'][mask] + results['gt_bboxes_labels'] = gt_labels[keep] + + if 'gt_masks' in results or 'gt_seg_map' in results: + raise NotImplementedError( + 'RandomCenterCropPad only supports bbox.') + + return results + + def _test_aug(self, results): + """Around padding the original image without cropping. + + The padding mode and value are from ``test_pad_mode``. + + Args: + results (dict): Image infomations in the augment pipeline. + + Returns: + results (dict): The updated dict. + """ + img = results['img'] + h, w, c = img.shape + if self.test_pad_mode[0] in ['logical_or']: + # self.test_pad_add_pix is only used for centernet + target_h = (h | self.test_pad_mode[1]) + self.test_pad_add_pix + target_w = (w | self.test_pad_mode[1]) + self.test_pad_add_pix + elif self.test_pad_mode[0] in ['size_divisor']: + divisor = self.test_pad_mode[1] + target_h = int(np.ceil(h / divisor)) * divisor + target_w = int(np.ceil(w / divisor)) * divisor + else: + raise NotImplementedError( + 'RandomCenterCropPad only support two testing pad mode:' + 'logical-or and size_divisor.') + + cropped_img, border, _ = self._crop_image_and_paste( + img, [h // 2, w // 2], [target_h, target_w]) + results['img'] = cropped_img + results['img_shape'] = cropped_img.shape[:2] + results['border'] = border + return results + + @autocast_box_type() + def transform(self, results: dict) -> dict: + img = results['img'] + assert img.dtype == np.float32, ( + 'RandomCenterCropPad needs the input image of dtype np.float32,' + ' please set "to_float32=True" in "LoadImageFromFile" pipeline') + h, w, c = img.shape + assert c == len(self.mean) + if self.test_mode: + return self._test_aug(results) + else: + return self._train_aug(results) + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(crop_size={self.crop_size}, ' + repr_str += f'ratios={self.ratios}, ' + repr_str += f'border={self.border}, ' + repr_str += f'mean={self.input_mean}, ' + repr_str += f'std={self.input_std}, ' + repr_str += f'to_rgb={self.to_rgb}, ' + repr_str += f'test_mode={self.test_mode}, ' + repr_str += f'test_pad_mode={self.test_pad_mode}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + +@TRANSFORMS.register_module() +class CutOut(BaseTransform): + """CutOut operation. + + Randomly drop some regions of image used in + `Cutout `_. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + n_holes (int or tuple[int, int]): Number of regions to be dropped. + If it is given as a list, number of holes will be randomly + selected from the closed interval [``n_holes[0]``, ``n_holes[1]``]. + cutout_shape (tuple[int, int] or list[tuple[int, int]], optional): + The candidate shape of dropped regions. It can be + ``tuple[int, int]`` to use a fixed cutout shape, or + ``list[tuple[int, int]]`` to randomly choose shape + from the list. Defaults to None. + cutout_ratio (tuple[float, float] or list[tuple[float, float]], + optional): The candidate ratio of dropped regions. It can be + ``tuple[float, float]`` to use a fixed ratio or + ``list[tuple[float, float]]`` to randomly choose ratio + from the list. Please note that ``cutout_shape`` and + ``cutout_ratio`` cannot be both given at the same time. + Defaults to None. + fill_in (tuple[float, float, float] or tuple[int, int, int]): The value + of pixel to fill in the dropped regions. Defaults to (0, 0, 0). + """ + + def __init__( + self, + n_holes: Union[int, Tuple[int, int]], + cutout_shape: Optional[Union[Tuple[int, int], + List[Tuple[int, int]]]] = None, + cutout_ratio: Optional[Union[Tuple[float, float], + List[Tuple[float, float]]]] = None, + fill_in: Union[Tuple[float, float, float], Tuple[int, int, + int]] = (0, 0, 0) + ) -> None: + + assert (cutout_shape is None) ^ (cutout_ratio is None), \ + 'Either cutout_shape or cutout_ratio should be specified.' + assert (isinstance(cutout_shape, (list, tuple)) + or isinstance(cutout_ratio, (list, tuple))) + if isinstance(n_holes, tuple): + assert len(n_holes) == 2 and 0 <= n_holes[0] < n_holes[1] + else: + n_holes = (n_holes, n_holes) + self.n_holes = n_holes + self.fill_in = fill_in + self.with_ratio = cutout_ratio is not None + self.candidates = cutout_ratio if self.with_ratio else cutout_shape + if not isinstance(self.candidates, list): + self.candidates = [self.candidates] + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Call function to drop some regions of image.""" + h, w, c = results['img'].shape + n_holes = np.random.randint(self.n_holes[0], self.n_holes[1] + 1) + for _ in range(n_holes): + x1 = np.random.randint(0, w) + y1 = np.random.randint(0, h) + index = np.random.randint(0, len(self.candidates)) + if not self.with_ratio: + cutout_w, cutout_h = self.candidates[index] + else: + cutout_w = int(self.candidates[index][0] * w) + cutout_h = int(self.candidates[index][1] * h) + + x2 = np.clip(x1 + cutout_w, 0, w) + y2 = np.clip(y1 + cutout_h, 0, h) + results['img'][y1:y2, x1:x2, :] = self.fill_in + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(n_holes={self.n_holes}, ' + repr_str += (f'cutout_ratio={self.candidates}, ' if self.with_ratio + else f'cutout_shape={self.candidates}, ') + repr_str += f'fill_in={self.fill_in})' + return repr_str + + +@TRANSFORMS.register_module() +class Mosaic(BaseTransform): + """Mosaic augmentation. + + Given 4 images, mosaic transform combines them into + one output image. The output image is composed of the parts from each sub- + image. + + .. code:: text + + mosaic transform + center_x + +------------------------------+ + | pad | pad | + | +-----------+ | + | | | | + | | image1 |--------+ | + | | | | | + | | | image2 | | + center_y |----+-------------+-----------| + | | cropped | | + |pad | image3 | image4 | + | | | | + +----|-------------+-----------+ + | | + +-------------+ + + The mosaic transform steps are as follows: + + 1. Choose the mosaic center as the intersections of 4 images + 2. Get the left top image according to the index, and randomly + sample another 3 images from the custom dataset. + 3. Sub image will be cropped if image is larger than mosaic patch + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - mix_results (List[dict]) + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + Args: + img_scale (Sequence[int]): Image size before mosaic pipeline of single + image. The shape order should be (width, height). + Defaults to (640, 640). + center_ratio_range (Sequence[float]): Center ratio range of mosaic + output. Defaults to (0.5, 1.5). + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + pad_val (int): Pad value. Defaults to 114. + prob (float): Probability of applying this transformation. + Defaults to 1.0. + """ + + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + center_ratio_range: Tuple[float, float] = (0.5, 1.5), + bbox_clip_border: bool = True, + pad_val: float = 114.0, + prob: float = 1.0) -> None: + assert isinstance(img_scale, tuple) + assert 0 <= prob <= 1.0, 'The probability should be in range [0,1]. ' \ + f'got {prob}.' + + log_img_scale(img_scale, skip_square=True, shape_order='wh') + self.img_scale = img_scale + self.center_ratio_range = center_ratio_range + self.bbox_clip_border = bbox_clip_border + self.pad_val = pad_val + self.prob = prob + + @cache_randomness + def get_indexes(self, dataset: BaseDataset) -> int: + """Call function to collect indexes. + + Args: + dataset (:obj:`MultiImageMixDataset`): The dataset. + + Returns: + list: indexes. + """ + + indexes = [random.randint(0, len(dataset)) for _ in range(3)] + return indexes + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Mosaic transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + if random.uniform(0, 1) > self.prob: + return results + + assert 'mix_results' in results + mosaic_bboxes = [] + mosaic_bboxes_labels = [] + mosaic_ignore_flags = [] + if len(results['img'].shape) == 3: + mosaic_img = np.full( + (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2), 3), + self.pad_val, + dtype=results['img'].dtype) + else: + mosaic_img = np.full( + (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2)), + self.pad_val, + dtype=results['img'].dtype) + + # mosaic center x, y + center_x = int( + random.uniform(*self.center_ratio_range) * self.img_scale[0]) + center_y = int( + random.uniform(*self.center_ratio_range) * self.img_scale[1]) + center_position = (center_x, center_y) + + loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') + for i, loc in enumerate(loc_strs): + if loc == 'top_left': + results_patch = copy.deepcopy(results) + else: + results_patch = copy.deepcopy(results['mix_results'][i - 1]) + + img_i = results_patch['img'] + h_i, w_i = img_i.shape[:2] + # keep_ratio resize + scale_ratio_i = min(self.img_scale[1] / h_i, + self.img_scale[0] / w_i) + img_i = mmcv.imresize( + img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i))) + + # compute the combine parameters + paste_coord, crop_coord = self._mosaic_combine( + loc, center_position, img_i.shape[:2][::-1]) + x1_p, y1_p, x2_p, y2_p = paste_coord + x1_c, y1_c, x2_c, y2_c = crop_coord + + # crop and paste image + mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c] + + # adjust coordinate + gt_bboxes_i = results_patch['gt_bboxes'] + gt_bboxes_labels_i = results_patch['gt_bboxes_labels'] + gt_ignore_flags_i = results_patch['gt_ignore_flags'] + + padw = x1_p - x1_c + padh = y1_p - y1_c + gt_bboxes_i.rescale_([scale_ratio_i, scale_ratio_i]) + gt_bboxes_i.translate_([padw, padh]) + mosaic_bboxes.append(gt_bboxes_i) + mosaic_bboxes_labels.append(gt_bboxes_labels_i) + mosaic_ignore_flags.append(gt_ignore_flags_i) + + mosaic_bboxes = mosaic_bboxes[0].cat(mosaic_bboxes, 0) + mosaic_bboxes_labels = np.concatenate(mosaic_bboxes_labels, 0) + mosaic_ignore_flags = np.concatenate(mosaic_ignore_flags, 0) + + if self.bbox_clip_border: + mosaic_bboxes.clip_([2 * self.img_scale[1], 2 * self.img_scale[0]]) + # remove outside bboxes + inside_inds = mosaic_bboxes.is_inside( + [2 * self.img_scale[1], 2 * self.img_scale[0]]).numpy() + mosaic_bboxes = mosaic_bboxes[inside_inds] + mosaic_bboxes_labels = mosaic_bboxes_labels[inside_inds] + mosaic_ignore_flags = mosaic_ignore_flags[inside_inds] + + results['img'] = mosaic_img + results['img_shape'] = mosaic_img.shape[:2] + results['gt_bboxes'] = mosaic_bboxes + results['gt_bboxes_labels'] = mosaic_bboxes_labels + results['gt_ignore_flags'] = mosaic_ignore_flags + return results + + def _mosaic_combine( + self, loc: str, center_position_xy: Sequence[float], + img_shape_wh: Sequence[int]) -> Tuple[Tuple[int], Tuple[int]]: + """Calculate global coordinate of mosaic image and local coordinate of + cropped sub-image. + + Args: + loc (str): Index for the sub-image, loc in ('top_left', + 'top_right', 'bottom_left', 'bottom_right'). + center_position_xy (Sequence[float]): Mixing center for 4 images, + (x, y). + img_shape_wh (Sequence[int]): Width and height of sub-image + + Returns: + tuple[tuple[float]]: Corresponding coordinate of pasting and + cropping + - paste_coord (tuple): paste corner coordinate in mosaic image. + - crop_coord (tuple): crop corner coordinate in mosaic image. + """ + assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right') + if loc == 'top_left': + # index0 to top left part of image + x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ + max(center_position_xy[1] - img_shape_wh[1], 0), \ + center_position_xy[0], \ + center_position_xy[1] + crop_coord = img_shape_wh[0] - (x2 - x1), img_shape_wh[1] - ( + y2 - y1), img_shape_wh[0], img_shape_wh[1] + + elif loc == 'top_right': + # index1 to top right part of image + x1, y1, x2, y2 = center_position_xy[0], \ + max(center_position_xy[1] - img_shape_wh[1], 0), \ + min(center_position_xy[0] + img_shape_wh[0], + self.img_scale[0] * 2), \ + center_position_xy[1] + crop_coord = 0, img_shape_wh[1] - (y2 - y1), min( + img_shape_wh[0], x2 - x1), img_shape_wh[1] + + elif loc == 'bottom_left': + # index2 to bottom left part of image + x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ + center_position_xy[1], \ + center_position_xy[0], \ + min(self.img_scale[1] * 2, center_position_xy[1] + + img_shape_wh[1]) + crop_coord = img_shape_wh[0] - (x2 - x1), 0, img_shape_wh[0], min( + y2 - y1, img_shape_wh[1]) + + else: + # index3 to bottom right part of image + x1, y1, x2, y2 = center_position_xy[0], \ + center_position_xy[1], \ + min(center_position_xy[0] + img_shape_wh[0], + self.img_scale[0] * 2), \ + min(self.img_scale[1] * 2, center_position_xy[1] + + img_shape_wh[1]) + crop_coord = 0, 0, min(img_shape_wh[0], + x2 - x1), min(y2 - y1, img_shape_wh[1]) + + paste_coord = x1, y1, x2, y2 + return paste_coord, crop_coord + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(img_scale={self.img_scale}, ' + repr_str += f'center_ratio_range={self.center_ratio_range}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'prob={self.prob})' + return repr_str + + +@TRANSFORMS.register_module() +class MixUp(BaseTransform): + """MixUp data augmentation. + + .. code:: text + + mixup transform + +------------------------------+ + | mixup image | | + | +--------|--------+ | + | | | | | + |---------------+ | | + | | | | + | | image | | + | | | | + | | | | + | |-----------------+ | + | pad | + +------------------------------+ + + The mixup transform steps are as follows: + + 1. Another random image is picked by dataset and embedded in + the top left patch(after padding and resizing) + 2. The target of mixup transform is the weighted average of mixup + image and origin image. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - mix_results (List[dict]) + + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + + Args: + img_scale (Sequence[int]): Image output size after mixup pipeline. + The shape order should be (width, height). Defaults to (640, 640). + ratio_range (Sequence[float]): Scale ratio of mixup image. + Defaults to (0.5, 1.5). + flip_ratio (float): Horizontal flip ratio of mixup image. + Defaults to 0.5. + pad_val (int): Pad value. Defaults to 114. + max_iters (int): The maximum number of iterations. If the number of + iterations is greater than `max_iters`, but gt_bbox is still + empty, then the iteration is terminated. Defaults to 15. + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + """ + + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + ratio_range: Tuple[float, float] = (0.5, 1.5), + flip_ratio: float = 0.5, + pad_val: float = 114.0, + max_iters: int = 15, + bbox_clip_border: bool = True) -> None: + assert isinstance(img_scale, tuple) + log_img_scale(img_scale, skip_square=True, shape_order='wh') + self.dynamic_scale = img_scale + self.ratio_range = ratio_range + self.flip_ratio = flip_ratio + self.pad_val = pad_val + self.max_iters = max_iters + self.bbox_clip_border = bbox_clip_border + + @cache_randomness + def get_indexes(self, dataset: BaseDataset) -> int: + """Call function to collect indexes. + + Args: + dataset (:obj:`MultiImageMixDataset`): The dataset. + + Returns: + list: indexes. + """ + + for i in range(self.max_iters): + index = random.randint(0, len(dataset)) + gt_bboxes_i = dataset[index]['gt_bboxes'] + if len(gt_bboxes_i) != 0: + break + + return index + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """MixUp transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + + assert 'mix_results' in results + assert len( + results['mix_results']) == 1, 'MixUp only support 2 images now !' + + if results['mix_results'][0]['gt_bboxes'].shape[0] == 0: + # empty bbox + return results + + retrieve_results = results['mix_results'][0] + retrieve_img = retrieve_results['img'] + + jit_factor = random.uniform(*self.ratio_range) + is_filp = random.uniform(0, 1) > self.flip_ratio + + if len(retrieve_img.shape) == 3: + out_img = np.ones( + (self.dynamic_scale[1], self.dynamic_scale[0], 3), + dtype=retrieve_img.dtype) * self.pad_val + else: + out_img = np.ones( + self.dynamic_scale[::-1], + dtype=retrieve_img.dtype) * self.pad_val + + # 1. keep_ratio resize + scale_ratio = min(self.dynamic_scale[1] / retrieve_img.shape[0], + self.dynamic_scale[0] / retrieve_img.shape[1]) + retrieve_img = mmcv.imresize( + retrieve_img, (int(retrieve_img.shape[1] * scale_ratio), + int(retrieve_img.shape[0] * scale_ratio))) + + # 2. paste + out_img[:retrieve_img.shape[0], :retrieve_img.shape[1]] = retrieve_img + + # 3. scale jit + scale_ratio *= jit_factor + out_img = mmcv.imresize(out_img, (int(out_img.shape[1] * jit_factor), + int(out_img.shape[0] * jit_factor))) + + # 4. flip + if is_filp: + out_img = out_img[:, ::-1, :] + + # 5. random crop + ori_img = results['img'] + origin_h, origin_w = out_img.shape[:2] + target_h, target_w = ori_img.shape[:2] + padded_img = np.ones((max(origin_h, target_h), max( + origin_w, target_w), 3)) * self.pad_val + padded_img = padded_img.astype(np.uint8) + padded_img[:origin_h, :origin_w] = out_img + + x_offset, y_offset = 0, 0 + if padded_img.shape[0] > target_h: + y_offset = random.randint(0, padded_img.shape[0] - target_h) + if padded_img.shape[1] > target_w: + x_offset = random.randint(0, padded_img.shape[1] - target_w) + padded_cropped_img = padded_img[y_offset:y_offset + target_h, + x_offset:x_offset + target_w] + + # 6. adjust bbox + retrieve_gt_bboxes = retrieve_results['gt_bboxes'] + retrieve_gt_bboxes.rescale_([scale_ratio, scale_ratio]) + if self.bbox_clip_border: + retrieve_gt_bboxes.clip_([origin_h, origin_w]) + + if is_filp: + retrieve_gt_bboxes.flip_([origin_h, origin_w], + direction='horizontal') + + # 7. filter + cp_retrieve_gt_bboxes = retrieve_gt_bboxes.clone() + cp_retrieve_gt_bboxes.translate_([-x_offset, -y_offset]) + if self.bbox_clip_border: + cp_retrieve_gt_bboxes.clip_([target_h, target_w]) + + # 8. mix up + ori_img = ori_img.astype(np.float32) + mixup_img = 0.5 * ori_img + 0.5 * padded_cropped_img.astype(np.float32) + + retrieve_gt_bboxes_labels = retrieve_results['gt_bboxes_labels'] + retrieve_gt_ignore_flags = retrieve_results['gt_ignore_flags'] + + mixup_gt_bboxes = cp_retrieve_gt_bboxes.cat( + (results['gt_bboxes'], cp_retrieve_gt_bboxes), dim=0) + mixup_gt_bboxes_labels = np.concatenate( + (results['gt_bboxes_labels'], retrieve_gt_bboxes_labels), axis=0) + mixup_gt_ignore_flags = np.concatenate( + (results['gt_ignore_flags'], retrieve_gt_ignore_flags), axis=0) + + # remove outside bbox + inside_inds = mixup_gt_bboxes.is_inside([target_h, target_w]).numpy() + mixup_gt_bboxes = mixup_gt_bboxes[inside_inds] + mixup_gt_bboxes_labels = mixup_gt_bboxes_labels[inside_inds] + mixup_gt_ignore_flags = mixup_gt_ignore_flags[inside_inds] + + results['img'] = mixup_img.astype(np.uint8) + results['img_shape'] = mixup_img.shape[:2] + results['gt_bboxes'] = mixup_gt_bboxes + results['gt_bboxes_labels'] = mixup_gt_bboxes_labels + results['gt_ignore_flags'] = mixup_gt_ignore_flags + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(dynamic_scale={self.dynamic_scale}, ' + repr_str += f'ratio_range={self.ratio_range}, ' + repr_str += f'flip_ratio={self.flip_ratio}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'max_iters={self.max_iters}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomAffine(BaseTransform): + """Random affine transform data augmentation. + + This operation randomly generates affine transform matrix which including + rotation, translation, shear and scaling transforms. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + Args: + max_rotate_degree (float): Maximum degrees of rotation transform. + Defaults to 10. + max_translate_ratio (float): Maximum ratio of translation. + Defaults to 0.1. + scaling_ratio_range (tuple[float]): Min and max ratio of + scaling transform. Defaults to (0.5, 1.5). + max_shear_degree (float): Maximum degrees of shear + transform. Defaults to 2. + border (tuple[int]): Distance from width and height sides of input + image to adjust output shape. Only used in mosaic dataset. + Defaults to (0, 0). + border_val (tuple[int]): Border padding values of 3 channels. + Defaults to (114, 114, 114). + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + """ + + def __init__(self, + max_rotate_degree: float = 10.0, + max_translate_ratio: float = 0.1, + scaling_ratio_range: Tuple[float, float] = (0.5, 1.5), + max_shear_degree: float = 2.0, + border: Tuple[int, int] = (0, 0), + border_val: Tuple[int, int, int] = (114, 114, 114), + bbox_clip_border: bool = True) -> None: + assert 0 <= max_translate_ratio <= 1 + assert scaling_ratio_range[0] <= scaling_ratio_range[1] + assert scaling_ratio_range[0] > 0 + self.max_rotate_degree = max_rotate_degree + self.max_translate_ratio = max_translate_ratio + self.scaling_ratio_range = scaling_ratio_range + self.max_shear_degree = max_shear_degree + self.border = border + self.border_val = border_val + self.bbox_clip_border = bbox_clip_border + + @cache_randomness + def _get_random_homography_matrix(self, height, width): + # Rotation + rotation_degree = random.uniform(-self.max_rotate_degree, + self.max_rotate_degree) + rotation_matrix = self._get_rotation_matrix(rotation_degree) + + # Scaling + scaling_ratio = random.uniform(self.scaling_ratio_range[0], + self.scaling_ratio_range[1]) + scaling_matrix = self._get_scaling_matrix(scaling_ratio) + + # Shear + x_degree = random.uniform(-self.max_shear_degree, + self.max_shear_degree) + y_degree = random.uniform(-self.max_shear_degree, + self.max_shear_degree) + shear_matrix = self._get_shear_matrix(x_degree, y_degree) + + # Translation + trans_x = random.uniform(-self.max_translate_ratio, + self.max_translate_ratio) * width + trans_y = random.uniform(-self.max_translate_ratio, + self.max_translate_ratio) * height + translate_matrix = self._get_translation_matrix(trans_x, trans_y) + + warp_matrix = ( + translate_matrix @ shear_matrix @ rotation_matrix @ scaling_matrix) + return warp_matrix + + @autocast_box_type() + def transform(self, results: dict) -> dict: + img = results['img'] + height = img.shape[0] + self.border[1] * 2 + width = img.shape[1] + self.border[0] * 2 + + warp_matrix = self._get_random_homography_matrix(height, width) + + img = cv2.warpPerspective( + img, + warp_matrix, + dsize=(width, height), + borderValue=self.border_val) + results['img'] = img + results['img_shape'] = img.shape[:2] + + bboxes = results['gt_bboxes'] + num_bboxes = len(bboxes) + if num_bboxes: + bboxes.project_(warp_matrix) + if self.bbox_clip_border: + bboxes.clip_([height, width]) + # remove outside bbox + valid_index = bboxes.is_inside([height, width]).numpy() + results['gt_bboxes'] = bboxes[valid_index] + results['gt_bboxes_labels'] = results['gt_bboxes_labels'][ + valid_index] + results['gt_ignore_flags'] = results['gt_ignore_flags'][ + valid_index] + + if 'gt_masks' in results: + raise NotImplementedError('RandomAffine only supports bbox.') + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(max_rotate_degree={self.max_rotate_degree}, ' + repr_str += f'max_translate_ratio={self.max_translate_ratio}, ' + repr_str += f'scaling_ratio_range={self.scaling_ratio_range}, ' + repr_str += f'max_shear_degree={self.max_shear_degree}, ' + repr_str += f'border={self.border}, ' + repr_str += f'border_val={self.border_val}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + @staticmethod + def _get_rotation_matrix(rotate_degrees: float) -> np.ndarray: + radian = math.radians(rotate_degrees) + rotation_matrix = np.array( + [[np.cos(radian), -np.sin(radian), 0.], + [np.sin(radian), np.cos(radian), 0.], [0., 0., 1.]], + dtype=np.float32) + return rotation_matrix + + @staticmethod + def _get_scaling_matrix(scale_ratio: float) -> np.ndarray: + scaling_matrix = np.array( + [[scale_ratio, 0., 0.], [0., scale_ratio, 0.], [0., 0., 1.]], + dtype=np.float32) + return scaling_matrix + + @staticmethod + def _get_shear_matrix(x_shear_degrees: float, + y_shear_degrees: float) -> np.ndarray: + x_radian = math.radians(x_shear_degrees) + y_radian = math.radians(y_shear_degrees) + shear_matrix = np.array([[1, np.tan(x_radian), 0.], + [np.tan(y_radian), 1, 0.], [0., 0., 1.]], + dtype=np.float32) + return shear_matrix + + @staticmethod + def _get_translation_matrix(x: float, y: float) -> np.ndarray: + translation_matrix = np.array([[1, 0., x], [0., 1, y], [0., 0., 1.]], + dtype=np.float32) + return translation_matrix + + +@TRANSFORMS.register_module() +class YOLOXHSVRandomAug(BaseTransform): + """Apply HSV augmentation to image sequentially. It is referenced from + https://github.com/Megvii- + BaseDetection/YOLOX/blob/main/yolox/data/data_augment.py#L21. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + hue_delta (int): delta of hue. Defaults to 5. + saturation_delta (int): delta of saturation. Defaults to 30. + value_delta (int): delat of value. Defaults to 30. + """ + + def __init__(self, + hue_delta: int = 5, + saturation_delta: int = 30, + value_delta: int = 30) -> None: + self.hue_delta = hue_delta + self.saturation_delta = saturation_delta + self.value_delta = value_delta + + @cache_randomness + def _get_hsv_gains(self): + hsv_gains = np.random.uniform(-1, 1, 3) * [ + self.hue_delta, self.saturation_delta, self.value_delta + ] + # random selection of h, s, v + hsv_gains *= np.random.randint(0, 2, 3) + # prevent overflow + hsv_gains = hsv_gains.astype(np.int16) + return hsv_gains + + def transform(self, results: dict) -> dict: + img = results['img'] + hsv_gains = self._get_hsv_gains() + img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype(np.int16) + + img_hsv[..., 0] = (img_hsv[..., 0] + hsv_gains[0]) % 180 + img_hsv[..., 1] = np.clip(img_hsv[..., 1] + hsv_gains[1], 0, 255) + img_hsv[..., 2] = np.clip(img_hsv[..., 2] + hsv_gains[2], 0, 255) + cv2.cvtColor(img_hsv.astype(img.dtype), cv2.COLOR_HSV2BGR, dst=img) + + results['img'] = img + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(hue_delta={self.hue_delta}, ' + repr_str += f'saturation_delta={self.saturation_delta}, ' + repr_str += f'value_delta={self.value_delta})' + return repr_str + + +@TRANSFORMS.register_module() +class CopyPaste(BaseTransform): + """Simple Copy-Paste is a Strong Data Augmentation Method for Instance + Segmentation The simple copy-paste transform steps are as follows: + + 1. The destination image is already resized with aspect ratio kept, + cropped and padded. + 2. Randomly select a source image, which is also already resized + with aspect ratio kept, cropped and padded in a similar way + as the destination image. + 3. Randomly select some objects from the source image. + 4. Paste these source objects to the destination image directly, + due to the source and destination image have the same size. + 5. Update object masks of the destination image, for some origin objects + may be occluded. + 6. Generate bboxes from the updated destination masks and + filter some objects which are totally occluded, and adjust bboxes + which are partly occluded. + 7. Append selected source bboxes, masks, and labels. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - gt_masks (BitmapMasks) (optional) + + Modified Keys: + + - img + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + - gt_masks (optional) + + Args: + max_num_pasted (int): The maximum number of pasted objects. + Defaults to 100. + bbox_occluded_thr (int): The threshold of occluded bbox. + Defaults to 10. + mask_occluded_thr (int): The threshold of occluded mask. + Defaults to 300. + selected (bool): Whether select objects or not. If select is False, + all objects of the source image will be pasted to the + destination image. + Defaults to True. + paste_by_box (bool): Whether use boxes as masks when masks are not + available. + Defaults to False. + """ + + def __init__( + self, + max_num_pasted: int = 100, + bbox_occluded_thr: int = 10, + mask_occluded_thr: int = 300, + selected: bool = True, + paste_by_box: bool = False, + ) -> None: + self.max_num_pasted = max_num_pasted + self.bbox_occluded_thr = bbox_occluded_thr + self.mask_occluded_thr = mask_occluded_thr + self.selected = selected + self.paste_by_box = paste_by_box + + @cache_randomness + def get_indexes(self, dataset: BaseDataset) -> int: + """Call function to collect indexes.s. + + Args: + dataset (:obj:`MultiImageMixDataset`): The dataset. + Returns: + list: Indexes. + """ + return random.randint(0, len(dataset)) + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to make a copy-paste of image. + + Args: + results (dict): Result dict. + Returns: + dict: Result dict with copy-paste transformed. + """ + + assert 'mix_results' in results + num_images = len(results['mix_results']) + assert num_images == 1, \ + f'CopyPaste only supports processing 2 images, got {num_images}' + if self.selected: + selected_results = self._select_object(results['mix_results'][0]) + else: + selected_results = results['mix_results'][0] + return self._copy_paste(results, selected_results) + + @cache_randomness + def _get_selected_inds(self, num_bboxes: int) -> np.ndarray: + max_num_pasted = min(num_bboxes + 1, self.max_num_pasted) + num_pasted = np.random.randint(0, max_num_pasted) + return np.random.choice(num_bboxes, size=num_pasted, replace=False) + + def get_gt_masks(self, results: dict) -> BitmapMasks: + """Get gt_masks originally or generated based on bboxes. + + If gt_masks is not contained in results, + it will be generated based on gt_bboxes. + Args: + results (dict): Result dict. + Returns: + BitmapMasks: gt_masks, originally or generated based on bboxes. + """ + if results.get('gt_masks', None) is not None: + if self.paste_by_box: + warnings.warn('gt_masks is already contained in results, ' + 'so paste_by_box is disabled.') + return results['gt_masks'] + else: + if not self.paste_by_box: + raise RuntimeError('results does not contain masks.') + return results['gt_bboxes'].create_masks(results['img'].shape[:2]) + + def _select_object(self, results: dict) -> dict: + """Select some objects from the source results.""" + bboxes = results['gt_bboxes'] + labels = results['gt_bboxes_labels'] + masks = self.get_gt_masks(results) + ignore_flags = results['gt_ignore_flags'] + + selected_inds = self._get_selected_inds(bboxes.shape[0]) + + selected_bboxes = bboxes[selected_inds] + selected_labels = labels[selected_inds] + selected_masks = masks[selected_inds] + selected_ignore_flags = ignore_flags[selected_inds] + + results['gt_bboxes'] = selected_bboxes + results['gt_bboxes_labels'] = selected_labels + results['gt_masks'] = selected_masks + results['gt_ignore_flags'] = selected_ignore_flags + return results + + def _copy_paste(self, dst_results: dict, src_results: dict) -> dict: + """CopyPaste transform function. + + Args: + dst_results (dict): Result dict of the destination image. + src_results (dict): Result dict of the source image. + Returns: + dict: Updated result dict. + """ + dst_img = dst_results['img'] + dst_bboxes = dst_results['gt_bboxes'] + dst_labels = dst_results['gt_bboxes_labels'] + dst_masks = self.get_gt_masks(dst_results) + dst_ignore_flags = dst_results['gt_ignore_flags'] + + src_img = src_results['img'] + src_bboxes = src_results['gt_bboxes'] + src_labels = src_results['gt_bboxes_labels'] + src_masks = src_results['gt_masks'] + src_ignore_flags = src_results['gt_ignore_flags'] + + if len(src_bboxes) == 0: + return dst_results + + # update masks and generate bboxes from updated masks + composed_mask = np.where(np.any(src_masks.masks, axis=0), 1, 0) + updated_dst_masks = self._get_updated_masks(dst_masks, composed_mask) + updated_dst_bboxes = updated_dst_masks.get_bboxes(type(dst_bboxes)) + assert len(updated_dst_bboxes) == len(updated_dst_masks) + + # filter totally occluded objects + l1_distance = (updated_dst_bboxes.tensor - dst_bboxes.tensor).abs() + bboxes_inds = (l1_distance <= self.bbox_occluded_thr).all( + dim=-1).numpy() + masks_inds = updated_dst_masks.masks.sum( + axis=(1, 2)) > self.mask_occluded_thr + valid_inds = bboxes_inds | masks_inds + + # Paste source objects to destination image directly + img = dst_img * (1 - composed_mask[..., np.newaxis] + ) + src_img * composed_mask[..., np.newaxis] + bboxes = src_bboxes.cat([updated_dst_bboxes[valid_inds], src_bboxes]) + labels = np.concatenate([dst_labels[valid_inds], src_labels]) + masks = np.concatenate( + [updated_dst_masks.masks[valid_inds], src_masks.masks]) + ignore_flags = np.concatenate( + [dst_ignore_flags[valid_inds], src_ignore_flags]) + + dst_results['img'] = img + dst_results['gt_bboxes'] = bboxes + dst_results['gt_bboxes_labels'] = labels + dst_results['gt_masks'] = BitmapMasks(masks, masks.shape[1], + masks.shape[2]) + dst_results['gt_ignore_flags'] = ignore_flags + + return dst_results + + def _get_updated_masks(self, masks: BitmapMasks, + composed_mask: np.ndarray) -> BitmapMasks: + """Update masks with composed mask.""" + assert masks.masks.shape[-2:] == composed_mask.shape[-2:], \ + 'Cannot compare two arrays of different size' + masks.masks = np.where(composed_mask, 0, masks.masks) + return masks + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(max_num_pasted={self.max_num_pasted}, ' + repr_str += f'bbox_occluded_thr={self.bbox_occluded_thr}, ' + repr_str += f'mask_occluded_thr={self.mask_occluded_thr}, ' + repr_str += f'selected={self.selected}), ' + repr_str += f'paste_by_box={self.paste_by_box})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomErasing(BaseTransform): + """RandomErasing operation. + + Random Erasing randomly selects a rectangle region + in an image and erases its pixels with random values. + `RandomErasing `_. + + Required Keys: + + - img + - gt_bboxes (HorizontalBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - gt_masks (BitmapMasks) (optional) + + Modified Keys: + - img + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + - gt_masks (optional) + + Args: + n_patches (int or tuple[int, int]): Number of regions to be dropped. + If it is given as a tuple, number of patches will be randomly + selected from the closed interval [``n_patches[0]``, + ``n_patches[1]``]. + ratio (float or tuple[float, float]): The ratio of erased regions. + It can be ``float`` to use a fixed ratio or ``tuple[float, float]`` + to randomly choose ratio from the interval. + squared (bool): Whether to erase square region. Defaults to True. + bbox_erased_thr (float): The threshold for the maximum area proportion + of the bbox to be erased. When the proportion of the area where the + bbox is erased is greater than the threshold, the bbox will be + removed. Defaults to 0.9. + img_border_value (int or float or tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + """ + + def __init__( + self, + n_patches: Union[int, Tuple[int, int]], + ratio: Union[float, Tuple[float, float]], + squared: bool = True, + bbox_erased_thr: float = 0.9, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + ) -> None: + if isinstance(n_patches, tuple): + assert len(n_patches) == 2 and 0 <= n_patches[0] < n_patches[1] + else: + n_patches = (n_patches, n_patches) + if isinstance(ratio, tuple): + assert len(ratio) == 2 and 0 <= ratio[0] < ratio[1] <= 1 + else: + ratio = (ratio, ratio) + + self.n_patches = n_patches + self.ratio = ratio + self.squared = squared + self.bbox_erased_thr = bbox_erased_thr + self.img_border_value = img_border_value + self.mask_border_value = mask_border_value + self.seg_ignore_label = seg_ignore_label + + @cache_randomness + def _get_patches(self, img_shape: Tuple[int, int]) -> List[list]: + """Get patches for random erasing.""" + patches = [] + n_patches = np.random.randint(self.n_patches[0], self.n_patches[1] + 1) + for _ in range(n_patches): + if self.squared: + ratio = np.random.random() * (self.ratio[1] - + self.ratio[0]) + self.ratio[0] + ratio = (ratio, ratio) + else: + ratio = (np.random.random() * (self.ratio[1] - self.ratio[0]) + + self.ratio[0], np.random.random() * + (self.ratio[1] - self.ratio[0]) + self.ratio[0]) + ph, pw = int(img_shape[0] * ratio[0]), int(img_shape[1] * ratio[1]) + px1, py1 = np.random.randint(0, + img_shape[1] - pw), np.random.randint( + 0, img_shape[0] - ph) + px2, py2 = px1 + pw, py1 + ph + patches.append([px1, py1, px2, py2]) + return np.array(patches) + + def _transform_img(self, results: dict, patches: List[list]) -> None: + """Random erasing the image.""" + for patch in patches: + px1, py1, px2, py2 = patch + results['img'][py1:py2, px1:px2, :] = self.img_border_value + + def _transform_bboxes(self, results: dict, patches: List[list]) -> None: + """Random erasing the bboxes.""" + bboxes = results['gt_bboxes'] + # TODO: unify the logic by using operators in BaseBoxes. + assert isinstance(bboxes, HorizontalBoxes) + bboxes = bboxes.numpy() + left_top = np.maximum(bboxes[:, None, :2], patches[:, :2]) + right_bottom = np.minimum(bboxes[:, None, 2:], patches[:, 2:]) + wh = np.maximum(right_bottom - left_top, 0) + inter_areas = wh[:, :, 0] * wh[:, :, 1] + bbox_areas = (bboxes[:, 2] - bboxes[:, 0]) * ( + bboxes[:, 3] - bboxes[:, 1]) + bboxes_erased_ratio = inter_areas.sum(-1) / (bbox_areas + 1e-7) + valid_inds = bboxes_erased_ratio < self.bbox_erased_thr + results['gt_bboxes'] = HorizontalBoxes(bboxes[valid_inds]) + results['gt_bboxes_labels'] = results['gt_bboxes_labels'][valid_inds] + results['gt_ignore_flags'] = results['gt_ignore_flags'][valid_inds] + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'][valid_inds] + + def _transform_masks(self, results: dict, patches: List[list]) -> None: + """Random erasing the masks.""" + for patch in patches: + px1, py1, px2, py2 = patch + results['gt_masks'].masks[:, py1:py2, + px1:px2] = self.mask_border_value + + def _transform_seg(self, results: dict, patches: List[list]) -> None: + """Random erasing the segmentation map.""" + for patch in patches: + px1, py1, px2, py2 = patch + results['gt_seg_map'][py1:py2, px1:px2] = self.seg_ignore_label + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to erase some regions of image.""" + patches = self._get_patches(results['img_shape']) + self._transform_img(results, patches) + if results.get('gt_bboxes', None) is not None: + self._transform_bboxes(results, patches) + if results.get('gt_masks', None) is not None: + self._transform_masks(results, patches) + if results.get('gt_seg_map', None) is not None: + self._transform_seg(results, patches) + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(n_patches={self.n_patches}, ' + repr_str += f'ratio={self.ratio}, ' + repr_str += f'squared={self.squared}, ' + repr_str += f'bbox_erased_thr={self.bbox_erased_thr}, ' + repr_str += f'img_border_value={self.img_border_value}, ' + repr_str += f'mask_border_value={self.mask_border_value}, ' + repr_str += f'seg_ignore_label={self.seg_ignore_label})' + return repr_str + + +@TRANSFORMS.register_module() +class CachedMosaic(Mosaic): + """Cached mosaic augmentation. + + Cached mosaic transform will random select images from the cache + and combine them into one output image. + + .. code:: text + + mosaic transform + center_x + +------------------------------+ + | pad | pad | + | +-----------+ | + | | | | + | | image1 |--------+ | + | | | | | + | | | image2 | | + center_y |----+-------------+-----------| + | | cropped | | + |pad | image3 | image4 | + | | | | + +----|-------------+-----------+ + | | + +-------------+ + + The cached mosaic transform steps are as follows: + + 1. Append the results from the last transform into the cache. + 2. Choose the mosaic center as the intersections of 4 images + 3. Get the left top image according to the index, and randomly + sample another 3 images from the result cache. + 4. Sub image will be cropped if image is larger than mosaic patch + + Required Keys: + + - img + - gt_bboxes (np.float32) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + Args: + img_scale (Sequence[int]): Image size before mosaic pipeline of single + image. The shape order should be (width, height). + Defaults to (640, 640). + center_ratio_range (Sequence[float]): Center ratio range of mosaic + output. Defaults to (0.5, 1.5). + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + pad_val (int): Pad value. Defaults to 114. + prob (float): Probability of applying this transformation. + Defaults to 1.0. + max_cached_images (int): The maximum length of the cache. The larger + the cache, the stronger the randomness of this transform. As a + rule of thumb, providing 10 caches for each image suffices for + randomness. Defaults to 40. + random_pop (bool): Whether to randomly pop a result from the cache + when the cache is full. If set to False, use FIFO popping method. + Defaults to True. + """ + + def __init__(self, + *args, + max_cached_images: int = 40, + random_pop: bool = True, + **kwargs) -> None: + super().__init__(*args, **kwargs) + self.results_cache = [] + self.random_pop = random_pop + assert max_cached_images >= 4, 'The length of cache must >= 4, ' \ + f'but got {max_cached_images}.' + self.max_cached_images = max_cached_images + + @cache_randomness + def get_indexes(self, cache: list) -> list: + """Call function to collect indexes. + + Args: + cache (list): The results cache. + + Returns: + list: indexes. + """ + + indexes = [random.randint(0, len(cache) - 1) for _ in range(3)] + return indexes + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Mosaic transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + # cache and pop images + self.results_cache.append(copy.deepcopy(results)) + if len(self.results_cache) > self.max_cached_images: + if self.random_pop: + index = random.randint(0, len(self.results_cache) - 1) + else: + index = 0 + self.results_cache.pop(index) + + if len(self.results_cache) <= 4: + return results + + if random.uniform(0, 1) > self.prob: + return results + indices = self.get_indexes(self.results_cache) + mix_results = [copy.deepcopy(self.results_cache[i]) for i in indices] + + # TODO: refactor mosaic to reuse these code. + mosaic_bboxes = [] + mosaic_bboxes_labels = [] + mosaic_ignore_flags = [] + mosaic_masks = [] + with_mask = True if 'gt_masks' in results else False + + if len(results['img'].shape) == 3: + mosaic_img = np.full( + (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2), 3), + self.pad_val, + dtype=results['img'].dtype) + else: + mosaic_img = np.full( + (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2)), + self.pad_val, + dtype=results['img'].dtype) + + # mosaic center x, y + center_x = int( + random.uniform(*self.center_ratio_range) * self.img_scale[0]) + center_y = int( + random.uniform(*self.center_ratio_range) * self.img_scale[1]) + center_position = (center_x, center_y) + + loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') + for i, loc in enumerate(loc_strs): + if loc == 'top_left': + results_patch = copy.deepcopy(results) + else: + results_patch = copy.deepcopy(mix_results[i - 1]) + + img_i = results_patch['img'] + h_i, w_i = img_i.shape[:2] + # keep_ratio resize + scale_ratio_i = min(self.img_scale[1] / h_i, + self.img_scale[0] / w_i) + img_i = mmcv.imresize( + img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i))) + + # compute the combine parameters + paste_coord, crop_coord = self._mosaic_combine( + loc, center_position, img_i.shape[:2][::-1]) + x1_p, y1_p, x2_p, y2_p = paste_coord + x1_c, y1_c, x2_c, y2_c = crop_coord + + # crop and paste image + mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c] + + # adjust coordinate + gt_bboxes_i = results_patch['gt_bboxes'] + gt_bboxes_labels_i = results_patch['gt_bboxes_labels'] + gt_ignore_flags_i = results_patch['gt_ignore_flags'] + + padw = x1_p - x1_c + padh = y1_p - y1_c + gt_bboxes_i.rescale_([scale_ratio_i, scale_ratio_i]) + gt_bboxes_i.translate_([padw, padh]) + mosaic_bboxes.append(gt_bboxes_i) + mosaic_bboxes_labels.append(gt_bboxes_labels_i) + mosaic_ignore_flags.append(gt_ignore_flags_i) + if with_mask and results_patch.get('gt_masks', None) is not None: + gt_masks_i = results_patch['gt_masks'] + gt_masks_i = gt_masks_i.rescale(float(scale_ratio_i)) + gt_masks_i = gt_masks_i.translate( + out_shape=(int(self.img_scale[0] * 2), + int(self.img_scale[1] * 2)), + offset=padw, + direction='horizontal') + gt_masks_i = gt_masks_i.translate( + out_shape=(int(self.img_scale[0] * 2), + int(self.img_scale[1] * 2)), + offset=padh, + direction='vertical') + mosaic_masks.append(gt_masks_i) + + mosaic_bboxes = mosaic_bboxes[0].cat(mosaic_bboxes, 0) + mosaic_bboxes_labels = np.concatenate(mosaic_bboxes_labels, 0) + mosaic_ignore_flags = np.concatenate(mosaic_ignore_flags, 0) + + if self.bbox_clip_border: + mosaic_bboxes.clip_([2 * self.img_scale[1], 2 * self.img_scale[0]]) + # remove outside bboxes + inside_inds = mosaic_bboxes.is_inside( + [2 * self.img_scale[1], 2 * self.img_scale[0]]).numpy() + mosaic_bboxes = mosaic_bboxes[inside_inds] + mosaic_bboxes_labels = mosaic_bboxes_labels[inside_inds] + mosaic_ignore_flags = mosaic_ignore_flags[inside_inds] + + results['img'] = mosaic_img + results['img_shape'] = mosaic_img.shape[:2] + results['gt_bboxes'] = mosaic_bboxes + results['gt_bboxes_labels'] = mosaic_bboxes_labels + results['gt_ignore_flags'] = mosaic_ignore_flags + + if with_mask: + mosaic_masks = mosaic_masks[0].cat(mosaic_masks) + results['gt_masks'] = mosaic_masks[inside_inds] + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(img_scale={self.img_scale}, ' + repr_str += f'center_ratio_range={self.center_ratio_range}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'prob={self.prob}, ' + repr_str += f'max_cached_images={self.max_cached_images}, ' + repr_str += f'random_pop={self.random_pop})' + return repr_str + + +@TRANSFORMS.register_module() +class CachedMixUp(BaseTransform): + """Cached mixup data augmentation. + + .. code:: text + + mixup transform + +------------------------------+ + | mixup image | | + | +--------|--------+ | + | | | | | + |---------------+ | | + | | | | + | | image | | + | | | | + | | | | + | |-----------------+ | + | pad | + +------------------------------+ + + The cached mixup transform steps are as follows: + + 1. Append the results from the last transform into the cache. + 2. Another random image is picked from the cache and embedded in + the top left patch(after padding and resizing) + 3. The target of mixup transform is the weighted average of mixup + image and origin image. + + Required Keys: + + - img + - gt_bboxes (np.float32) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - mix_results (List[dict]) + + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + + Args: + img_scale (Sequence[int]): Image output size after mixup pipeline. + The shape order should be (width, height). Defaults to (640, 640). + ratio_range (Sequence[float]): Scale ratio of mixup image. + Defaults to (0.5, 1.5). + flip_ratio (float): Horizontal flip ratio of mixup image. + Defaults to 0.5. + pad_val (int): Pad value. Defaults to 114. + max_iters (int): The maximum number of iterations. If the number of + iterations is greater than `max_iters`, but gt_bbox is still + empty, then the iteration is terminated. Defaults to 15. + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + max_cached_images (int): The maximum length of the cache. The larger + the cache, the stronger the randomness of this transform. As a + rule of thumb, providing 10 caches for each image suffices for + randomness. Defaults to 20. + random_pop (bool): Whether to randomly pop a result from the cache + when the cache is full. If set to False, use FIFO popping method. + Defaults to True. + prob (float): Probability of applying this transformation. + Defaults to 1.0. + """ + + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + ratio_range: Tuple[float, float] = (0.5, 1.5), + flip_ratio: float = 0.5, + pad_val: float = 114.0, + max_iters: int = 15, + bbox_clip_border: bool = True, + max_cached_images: int = 20, + random_pop: bool = True, + prob: float = 1.0) -> None: + assert isinstance(img_scale, tuple) + assert max_cached_images >= 2, 'The length of cache must >= 2, ' \ + f'but got {max_cached_images}.' + assert 0 <= prob <= 1.0, 'The probability should be in range [0,1]. ' \ + f'got {prob}.' + self.dynamic_scale = img_scale + self.ratio_range = ratio_range + self.flip_ratio = flip_ratio + self.pad_val = pad_val + self.max_iters = max_iters + self.bbox_clip_border = bbox_clip_border + self.results_cache = [] + + self.max_cached_images = max_cached_images + self.random_pop = random_pop + self.prob = prob + + @cache_randomness + def get_indexes(self, cache: list) -> int: + """Call function to collect indexes. + + Args: + cache (list): The result cache. + + Returns: + int: index. + """ + + for i in range(self.max_iters): + index = random.randint(0, len(cache) - 1) + gt_bboxes_i = cache[index]['gt_bboxes'] + if len(gt_bboxes_i) != 0: + break + return index + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """MixUp transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + # cache and pop images + self.results_cache.append(copy.deepcopy(results)) + if len(self.results_cache) > self.max_cached_images: + if self.random_pop: + index = random.randint(0, len(self.results_cache) - 1) + else: + index = 0 + self.results_cache.pop(index) + + if len(self.results_cache) <= 1: + return results + + if random.uniform(0, 1) > self.prob: + return results + + index = self.get_indexes(self.results_cache) + retrieve_results = copy.deepcopy(self.results_cache[index]) + + # TODO: refactor mixup to reuse these code. + if retrieve_results['gt_bboxes'].shape[0] == 0: + # empty bbox + return results + + retrieve_img = retrieve_results['img'] + with_mask = True if 'gt_masks' in results else False + + jit_factor = random.uniform(*self.ratio_range) + is_filp = random.uniform(0, 1) > self.flip_ratio + + if len(retrieve_img.shape) == 3: + out_img = np.ones( + (self.dynamic_scale[1], self.dynamic_scale[0], 3), + dtype=retrieve_img.dtype) * self.pad_val + else: + out_img = np.ones( + self.dynamic_scale[::-1], + dtype=retrieve_img.dtype) * self.pad_val + + # 1. keep_ratio resize + scale_ratio = min(self.dynamic_scale[1] / retrieve_img.shape[0], + self.dynamic_scale[0] / retrieve_img.shape[1]) + retrieve_img = mmcv.imresize( + retrieve_img, (int(retrieve_img.shape[1] * scale_ratio), + int(retrieve_img.shape[0] * scale_ratio))) + + # 2. paste + out_img[:retrieve_img.shape[0], :retrieve_img.shape[1]] = retrieve_img + + # 3. scale jit + scale_ratio *= jit_factor + out_img = mmcv.imresize(out_img, (int(out_img.shape[1] * jit_factor), + int(out_img.shape[0] * jit_factor))) + + # 4. flip + if is_filp: + out_img = out_img[:, ::-1, :] + + # 5. random crop + ori_img = results['img'] + origin_h, origin_w = out_img.shape[:2] + target_h, target_w = ori_img.shape[:2] + padded_img = np.ones((max(origin_h, target_h), max( + origin_w, target_w), 3)) * self.pad_val + padded_img = padded_img.astype(np.uint8) + padded_img[:origin_h, :origin_w] = out_img + + x_offset, y_offset = 0, 0 + if padded_img.shape[0] > target_h: + y_offset = random.randint(0, padded_img.shape[0] - target_h) + if padded_img.shape[1] > target_w: + x_offset = random.randint(0, padded_img.shape[1] - target_w) + padded_cropped_img = padded_img[y_offset:y_offset + target_h, + x_offset:x_offset + target_w] + + # 6. adjust bbox + retrieve_gt_bboxes = retrieve_results['gt_bboxes'] + retrieve_gt_bboxes.rescale_([scale_ratio, scale_ratio]) + if with_mask: + retrieve_gt_masks = retrieve_results['gt_masks'].rescale( + scale_ratio) + + if self.bbox_clip_border: + retrieve_gt_bboxes.clip_([origin_h, origin_w]) + + if is_filp: + retrieve_gt_bboxes.flip_([origin_h, origin_w], + direction='horizontal') + if with_mask: + retrieve_gt_masks = retrieve_gt_masks.flip() + + # 7. filter + cp_retrieve_gt_bboxes = retrieve_gt_bboxes.clone() + cp_retrieve_gt_bboxes.translate_([-x_offset, -y_offset]) + if with_mask: + retrieve_gt_masks = retrieve_gt_masks.translate( + out_shape=(target_h, target_w), + offset=-x_offset, + direction='horizontal') + retrieve_gt_masks = retrieve_gt_masks.translate( + out_shape=(target_h, target_w), + offset=-y_offset, + direction='vertical') + + if self.bbox_clip_border: + cp_retrieve_gt_bboxes.clip_([target_h, target_w]) + + # 8. mix up + ori_img = ori_img.astype(np.float32) + mixup_img = 0.5 * ori_img + 0.5 * padded_cropped_img.astype(np.float32) + + retrieve_gt_bboxes_labels = retrieve_results['gt_bboxes_labels'] + retrieve_gt_ignore_flags = retrieve_results['gt_ignore_flags'] + + mixup_gt_bboxes = cp_retrieve_gt_bboxes.cat( + (results['gt_bboxes'], cp_retrieve_gt_bboxes), dim=0) + mixup_gt_bboxes_labels = np.concatenate( + (results['gt_bboxes_labels'], retrieve_gt_bboxes_labels), axis=0) + mixup_gt_ignore_flags = np.concatenate( + (results['gt_ignore_flags'], retrieve_gt_ignore_flags), axis=0) + if with_mask: + mixup_gt_masks = retrieve_gt_masks.cat( + [results['gt_masks'], retrieve_gt_masks]) + + # remove outside bbox + inside_inds = mixup_gt_bboxes.is_inside([target_h, target_w]).numpy() + mixup_gt_bboxes = mixup_gt_bboxes[inside_inds] + mixup_gt_bboxes_labels = mixup_gt_bboxes_labels[inside_inds] + mixup_gt_ignore_flags = mixup_gt_ignore_flags[inside_inds] + if with_mask: + mixup_gt_masks = mixup_gt_masks[inside_inds] + + results['img'] = mixup_img.astype(np.uint8) + results['img_shape'] = mixup_img.shape[:2] + results['gt_bboxes'] = mixup_gt_bboxes + results['gt_bboxes_labels'] = mixup_gt_bboxes_labels + results['gt_ignore_flags'] = mixup_gt_ignore_flags + if with_mask: + results['gt_masks'] = mixup_gt_masks + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(dynamic_scale={self.dynamic_scale}, ' + repr_str += f'ratio_range={self.ratio_range}, ' + repr_str += f'flip_ratio={self.flip_ratio}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'max_iters={self.max_iters}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border}, ' + repr_str += f'max_cached_images={self.max_cached_images}, ' + repr_str += f'random_pop={self.random_pop}, ' + repr_str += f'prob={self.prob})' + return repr_str diff --git a/mmdet_code/SR-TOD/mmdet/datasets/transforms/wrappers.py b/mmdet_code/SR-TOD/mmdet/datasets/transforms/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..3a17711c06bfbd4dc0038dce9ea7796d1476c37e --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/transforms/wrappers.py @@ -0,0 +1,277 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +from typing import Callable, Dict, List, Optional, Union + +import numpy as np +from mmcv.transforms import BaseTransform, Compose +from mmcv.transforms.utils import cache_random_params, cache_randomness + +from mmdet.registry import TRANSFORMS + + +@TRANSFORMS.register_module() +class MultiBranch(BaseTransform): + r"""Multiple branch pipeline wrapper. + + Generate multiple data-augmented versions of the same image. + `MultiBranch` needs to specify the branch names of all + pipelines of the dataset, perform corresponding data augmentation + for the current branch, and return None for other branches, + which ensures the consistency of return format across + different samples. + + Args: + branch_field (list): List of branch names. + branch_pipelines (dict): Dict of different pipeline configs + to be composed. + + Examples: + >>> branch_field = ['sup', 'unsup_teacher', 'unsup_student'] + >>> sup_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadAnnotations', with_bbox=True), + >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True), + >>> dict(type='RandomFlip', prob=0.5), + >>> dict( + >>> type='MultiBranch', + >>> branch_field=branch_field, + >>> sup=dict(type='PackDetInputs')) + >>> ] + >>> weak_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadAnnotations', with_bbox=True), + >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True), + >>> dict(type='RandomFlip', prob=0.0), + >>> dict( + >>> type='MultiBranch', + >>> branch_field=branch_field, + >>> sup=dict(type='PackDetInputs')) + >>> ] + >>> strong_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadAnnotations', with_bbox=True), + >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True), + >>> dict(type='RandomFlip', prob=1.0), + >>> dict( + >>> type='MultiBranch', + >>> branch_field=branch_field, + >>> sup=dict(type='PackDetInputs')) + >>> ] + >>> unsup_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadEmptyAnnotations'), + >>> dict( + >>> type='MultiBranch', + >>> branch_field=branch_field, + >>> unsup_teacher=weak_pipeline, + >>> unsup_student=strong_pipeline) + >>> ] + >>> from mmcv.transforms import Compose + >>> sup_branch = Compose(sup_pipeline) + >>> unsup_branch = Compose(unsup_pipeline) + >>> print(sup_branch) + >>> Compose( + >>> LoadImageFromFile(ignore_empty=False, to_float32=False, color_type='color', imdecode_backend='cv2') # noqa + >>> LoadAnnotations(with_bbox=True, with_label=True, with_mask=False, with_seg=False, poly2mask=True, imdecode_backend='cv2') # noqa + >>> Resize(scale=(1333, 800), scale_factor=None, keep_ratio=True, clip_object_border=True), backend=cv2), interpolation=bilinear) # noqa + >>> RandomFlip(prob=0.5, direction=horizontal) + >>> MultiBranch(branch_pipelines=['sup']) + >>> ) + >>> print(unsup_branch) + >>> Compose( + >>> LoadImageFromFile(ignore_empty=False, to_float32=False, color_type='color', imdecode_backend='cv2') # noqa + >>> LoadEmptyAnnotations(with_bbox=True, with_label=True, with_mask=False, with_seg=False, seg_ignore_label=255) # noqa + >>> MultiBranch(branch_pipelines=['unsup_teacher', 'unsup_student']) + >>> ) + """ + + def __init__(self, branch_field: List[str], + **branch_pipelines: dict) -> None: + self.branch_field = branch_field + self.branch_pipelines = { + branch: Compose(pipeline) + for branch, pipeline in branch_pipelines.items() + } + + def transform(self, results: dict) -> dict: + """Transform function to apply transforms sequentially. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: + + - 'inputs' (Dict[str, obj:`torch.Tensor`]): The forward data of + models from different branches. + - 'data_sample' (Dict[str,obj:`DetDataSample`]): The annotation + info of the sample from different branches. + """ + + multi_results = {} + for branch in self.branch_field: + multi_results[branch] = {'inputs': None, 'data_samples': None} + for branch, pipeline in self.branch_pipelines.items(): + branch_results = pipeline(copy.deepcopy(results)) + # If one branch pipeline returns None, + # it will sample another data from dataset. + if branch_results is None: + return None + multi_results[branch] = branch_results + + format_results = {} + for branch, results in multi_results.items(): + for key in results.keys(): + if format_results.get(key, None) is None: + format_results[key] = {branch: results[key]} + else: + format_results[key][branch] = results[key] + return format_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(branch_pipelines={list(self.branch_pipelines.keys())})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomOrder(Compose): + """Shuffle the transform Sequence.""" + + @cache_randomness + def _random_permutation(self): + return np.random.permutation(len(self.transforms)) + + def transform(self, results: Dict) -> Optional[Dict]: + """Transform function to apply transforms in random order. + + Args: + results (dict): A result dict contains the results to transform. + + Returns: + dict or None: Transformed results. + """ + inds = self._random_permutation() + for idx in inds: + t = self.transforms[idx] + results = t(results) + if results is None: + return None + return results + + def __repr__(self): + """Compute the string representation.""" + format_string = self.__class__.__name__ + '(' + for t in self.transforms: + format_string += f'{t.__class__.__name__}, ' + format_string += ')' + return format_string + + +@TRANSFORMS.register_module() +class ProposalBroadcaster(BaseTransform): + """A transform wrapper to apply the wrapped transforms to process both + `gt_bboxes` and `proposals` without adding any codes. It will do the + following steps: + + 1. Scatter the broadcasting targets to a list of inputs of the wrapped + transforms. The type of the list should be list[dict, dict], which + the first is the original inputs, the second is the processing + results that `gt_bboxes` being rewritten by the `proposals`. + 2. Apply ``self.transforms``, with same random parameters, which is + sharing with a context manager. The type of the outputs is a + list[dict, dict]. + 3. Gather the outputs, update the `proposals` in the first item of + the outputs with the `gt_bboxes` in the second . + + Args: + transforms (list, optional): Sequence of transform + object or config dict to be wrapped. Defaults to []. + + Note: The `TransformBroadcaster` in MMCV can achieve the same operation as + `ProposalBroadcaster`, but need to set more complex parameters. + + Examples: + >>> pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadProposals', num_max_proposals=2000), + >>> dict(type='LoadAnnotations', with_bbox=True), + >>> dict( + >>> type='ProposalBroadcaster', + >>> transforms=[ + >>> dict(type='Resize', scale=(1333, 800), + >>> keep_ratio=True), + >>> dict(type='RandomFlip', prob=0.5), + >>> ]), + >>> dict(type='PackDetInputs')] + """ + + def __init__(self, transforms: List[Union[dict, Callable]] = []) -> None: + self.transforms = Compose(transforms) + + def transform(self, results: dict) -> dict: + """Apply wrapped transform functions to process both `gt_bboxes` and + `proposals`. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Updated result dict. + """ + assert results.get('proposals', None) is not None, \ + '`proposals` should be in the results, please delete ' \ + '`ProposalBroadcaster` in your configs, or check whether ' \ + 'you have load proposals successfully.' + + inputs = self._process_input(results) + outputs = self._apply_transforms(inputs) + outputs = self._process_output(outputs) + return outputs + + def _process_input(self, data: dict) -> list: + """Scatter the broadcasting targets to a list of inputs of the wrapped + transforms. + + Args: + data (dict): The original input data. + + Returns: + list[dict]: A list of input data. + """ + cp_data = copy.deepcopy(data) + cp_data['gt_bboxes'] = cp_data['proposals'] + scatters = [data, cp_data] + return scatters + + def _apply_transforms(self, inputs: list) -> list: + """Apply ``self.transforms``. + + Args: + inputs (list[dict, dict]): list of input data. + + Returns: + list[dict]: The output of the wrapped pipeline. + """ + assert len(inputs) == 2 + ctx = cache_random_params + with ctx(self.transforms): + output_scatters = [self.transforms(_input) for _input in inputs] + return output_scatters + + def _process_output(self, output_scatters: list) -> dict: + """Gathering and renaming data items. + + Args: + output_scatters (list[dict, dict]): The output of the wrapped + pipeline. + + Returns: + dict: Updated result dict. + """ + assert isinstance(output_scatters, list) and \ + isinstance(output_scatters[0], dict) and \ + len(output_scatters) == 2 + outputs = output_scatters[0] + outputs['proposals'] = output_scatters[1]['gt_bboxes'] + return outputs diff --git a/mmdet_code/SR-TOD/mmdet/datasets/utils.py b/mmdet_code/SR-TOD/mmdet/datasets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a281fb0b99e111fd5c4e12c6639efc38f33c3224 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/utils.py @@ -0,0 +1,48 @@ +# Copyright (c) OpenMMLab. All rights reserved. + +from mmcv.transforms import LoadImageFromFile + +from mmdet.datasets.transforms import LoadAnnotations, LoadPanopticAnnotations +from mmdet.registry import TRANSFORMS + + +def get_loading_pipeline(pipeline): + """Only keep loading image and annotations related configuration. + + Args: + pipeline (list[dict]): Data pipeline configs. + + Returns: + list[dict]: The new pipeline list with only keep + loading image and annotations related configuration. + + Examples: + >>> pipelines = [ + ... dict(type='LoadImageFromFile'), + ... dict(type='LoadAnnotations', with_bbox=True), + ... dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), + ... dict(type='RandomFlip', flip_ratio=0.5), + ... dict(type='Normalize', **img_norm_cfg), + ... dict(type='Pad', size_divisor=32), + ... dict(type='DefaultFormatBundle'), + ... dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) + ... ] + >>> expected_pipelines = [ + ... dict(type='LoadImageFromFile'), + ... dict(type='LoadAnnotations', with_bbox=True) + ... ] + >>> assert expected_pipelines ==\ + ... get_loading_pipeline(pipelines) + """ + loading_pipeline_cfg = [] + for cfg in pipeline: + obj_cls = TRANSFORMS.get(cfg['type']) + # TODO:use more elegant way to distinguish loading modules + if obj_cls is not None and obj_cls in (LoadImageFromFile, + LoadAnnotations, + LoadPanopticAnnotations): + loading_pipeline_cfg.append(cfg) + assert len(loading_pipeline_cfg) == 2, \ + 'The data pipeline in your config file must include ' \ + 'loading image and annotations related pipeline.' + return loading_pipeline_cfg diff --git a/mmdet_code/SR-TOD/mmdet/datasets/visdrone.py b/mmdet_code/SR-TOD/mmdet/datasets/visdrone.py new file mode 100644 index 0000000000000000000000000000000000000000..1a09f65f80adb58c370e407851033e283f793ea5 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/visdrone.py @@ -0,0 +1,189 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class VisDroneDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('pedestrian','people','bicycle','car','van', + 'truck','tricycle','awning-tricycle','bus','motor'), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/voc.py b/mmdet_code/SR-TOD/mmdet/datasets/voc.py new file mode 100644 index 0000000000000000000000000000000000000000..65e73f2f0bd4f2b16d5237cd3b5f342e44cf0438 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/voc.py @@ -0,0 +1,31 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .xml_style import XMLDataset + + +@DATASETS.register_module() +class VOCDataset(XMLDataset): + """Dataset for PASCAL VOC.""" + + METAINFO = { + 'classes': + ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', + 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', + 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'), + # palette is a list of color tuples, which is used for visualization. + 'palette': [(106, 0, 228), (119, 11, 32), (165, 42, 42), (0, 0, 192), + (197, 226, 255), (0, 60, 100), (0, 0, 142), (255, 77, 255), + (153, 69, 1), (120, 166, 157), (0, 182, 199), + (0, 226, 252), (182, 182, 255), (0, 0, 230), (220, 20, 60), + (163, 255, 0), (0, 82, 0), (3, 95, 161), (0, 80, 100), + (183, 130, 88)] + } + + def __init__(self, **kwargs): + super().__init__(**kwargs) + if 'VOC2007' in self.sub_data_root: + self._metainfo['dataset_type'] = 'VOC2007' + elif 'VOC2012' in self.sub_data_root: + self._metainfo['dataset_type'] = 'VOC2012' + else: + self._metainfo['dataset_type'] = None diff --git a/mmdet_code/SR-TOD/mmdet/datasets/wider_face.py b/mmdet_code/SR-TOD/mmdet/datasets/wider_face.py new file mode 100644 index 0000000000000000000000000000000000000000..62c7fff869ab970b6f96908a998ba6feb25ea205 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/wider_face.py @@ -0,0 +1,90 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import xml.etree.ElementTree as ET + +from mmengine.dist import is_main_process +from mmengine.fileio import get_local_path, list_from_file +from mmengine.utils import ProgressBar + +from mmdet.registry import DATASETS +from mmdet.utils.typing_utils import List, Union +from .xml_style import XMLDataset + + +@DATASETS.register_module() +class WIDERFaceDataset(XMLDataset): + """Reader for the WIDER Face dataset in PASCAL VOC format. + + Conversion scripts can be found in + https://github.com/sovrasov/wider-face-pascal-voc-annotations + """ + METAINFO = {'classes': ('face', ), 'palette': [(0, 255, 0)]} + + def load_data_list(self) -> List[dict]: + """Load annotation from XML style ann_file. + + Returns: + list[dict]: Annotation info from XML file. + """ + assert self._metainfo.get('classes', None) is not None, \ + 'classes in `XMLDataset` can not be None.' + self.cat2label = { + cat: i + for i, cat in enumerate(self._metainfo['classes']) + } + + data_list = [] + img_ids = list_from_file(self.ann_file, backend_args=self.backend_args) + + # loading process takes around 10 mins + if is_main_process(): + prog_bar = ProgressBar(len(img_ids)) + + for img_id in img_ids: + raw_img_info = {} + raw_img_info['img_id'] = img_id + raw_img_info['file_name'] = f'{img_id}.jpg' + parsed_data_info = self.parse_data_info(raw_img_info) + data_list.append(parsed_data_info) + + if is_main_process(): + prog_bar.update() + return data_list + + def parse_data_info(self, img_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + img_info (dict): Raw image information, usually it includes + `img_id`, `file_name`, and `xml_path`. + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + data_info = {} + img_id = img_info['img_id'] + xml_path = osp.join(self.data_prefix['img'], 'Annotations', + f'{img_id}.xml') + data_info['img_id'] = img_id + data_info['xml_path'] = xml_path + + # deal with xml file + with get_local_path( + xml_path, backend_args=self.backend_args) as local_path: + raw_ann_info = ET.parse(local_path) + root = raw_ann_info.getroot() + size = root.find('size') + width = int(size.find('width').text) + height = int(size.find('height').text) + folder = root.find('folder').text + img_path = osp.join(self.data_prefix['img'], folder, + img_info['file_name']) + data_info['img_path'] = img_path + + data_info['height'] = height + data_info['width'] = width + + # Coordinates are in range [0, width - 1 or height - 1] + data_info['instances'] = self._parse_instance_info( + raw_ann_info, minus_one=False) + return data_info diff --git a/mmdet_code/SR-TOD/mmdet/datasets/xml_style.py b/mmdet_code/SR-TOD/mmdet/datasets/xml_style.py new file mode 100644 index 0000000000000000000000000000000000000000..06045ea0092238abdac9622511b336586858f8f5 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/xml_style.py @@ -0,0 +1,186 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import xml.etree.ElementTree as ET +from typing import List, Optional, Union + +import mmcv +from mmengine.fileio import get, get_local_path, list_from_file + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class XMLDataset(BaseDetDataset): + """XML dataset for detection. + + Args: + img_subdir (str): Subdir where images are stored. Default: JPEGImages. + ann_subdir (str): Subdir where annotations are. Default: Annotations. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + """ + + def __init__(self, + img_subdir: str = 'JPEGImages', + ann_subdir: str = 'Annotations', + **kwargs) -> None: + self.img_subdir = img_subdir + self.ann_subdir = ann_subdir + super().__init__(**kwargs) + + @property + def sub_data_root(self) -> str: + """Return the sub data root.""" + return self.data_prefix.get('sub_data_root', '') + + def load_data_list(self) -> List[dict]: + """Load annotation from XML style ann_file. + + Returns: + list[dict]: Annotation info from XML file. + """ + assert self._metainfo.get('classes', None) is not None, \ + '`classes` in `XMLDataset` can not be None.' + self.cat2label = { + cat: i + for i, cat in enumerate(self._metainfo['classes']) + } + + data_list = [] + img_ids = list_from_file(self.ann_file, backend_args=self.backend_args) + for img_id in img_ids: + file_name = osp.join(self.img_subdir, f'{img_id}.jpg') + xml_path = osp.join(self.sub_data_root, self.ann_subdir, + f'{img_id}.xml') + + raw_img_info = {} + raw_img_info['img_id'] = img_id + raw_img_info['file_name'] = file_name + raw_img_info['xml_path'] = xml_path + + parsed_data_info = self.parse_data_info(raw_img_info) + data_list.append(parsed_data_info) + return data_list + + @property + def bbox_min_size(self) -> Optional[int]: + """Return the minimum size of bounding boxes in the images.""" + if self.filter_cfg is not None: + return self.filter_cfg.get('bbox_min_size', None) + else: + return None + + def parse_data_info(self, img_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + img_info (dict): Raw image information, usually it includes + `img_id`, `file_name`, and `xml_path`. + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + data_info = {} + img_path = osp.join(self.sub_data_root, img_info['file_name']) + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['xml_path'] = img_info['xml_path'] + + # deal with xml file + with get_local_path( + img_info['xml_path'], + backend_args=self.backend_args) as local_path: + raw_ann_info = ET.parse(local_path) + root = raw_ann_info.getroot() + size = root.find('size') + if size is not None: + width = int(size.find('width').text) + height = int(size.find('height').text) + else: + img_bytes = get(img_path, backend_args=self.backend_args) + img = mmcv.imfrombytes(img_bytes, backend='cv2') + height, width = img.shape[:2] + del img, img_bytes + + data_info['height'] = height + data_info['width'] = width + + data_info['instances'] = self._parse_instance_info( + raw_ann_info, minus_one=True) + + return data_info + + def _parse_instance_info(self, + raw_ann_info: ET, + minus_one: bool = True) -> List[dict]: + """parse instance information. + + Args: + raw_ann_info (ElementTree): ElementTree object. + minus_one (bool): Whether to subtract 1 from the coordinates. + Defaults to True. + + Returns: + List[dict]: List of instances. + """ + instances = [] + for obj in raw_ann_info.findall('object'): + instance = {} + name = obj.find('name').text + if name not in self._metainfo['classes']: + continue + difficult = obj.find('difficult') + difficult = 0 if difficult is None else int(difficult.text) + bnd_box = obj.find('bndbox') + bbox = [ + int(float(bnd_box.find('xmin').text)), + int(float(bnd_box.find('ymin').text)), + int(float(bnd_box.find('xmax').text)), + int(float(bnd_box.find('ymax').text)) + ] + + # VOC needs to subtract 1 from the coordinates + if minus_one: + bbox = [x - 1 for x in bbox] + + ignore = False + if self.bbox_min_size is not None: + assert not self.test_mode + w = bbox[2] - bbox[0] + h = bbox[3] - bbox[1] + if w < self.bbox_min_size or h < self.bbox_min_size: + ignore = True + if difficult or ignore: + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[name] + instances.append(instance) + return instances + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) \ + if self.filter_cfg is not None else False + min_size = self.filter_cfg.get('min_size', 0) \ + if self.filter_cfg is not None else 0 + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and len(data_info['instances']) == 0: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/SR-TOD/mmdet/datasets/youtube_vis_dataset.py b/mmdet_code/SR-TOD/mmdet/datasets/youtube_vis_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..38c3d3909f1b8fd795c181546094056c54c9c4b2 --- /dev/null +++ b/mmdet_code/SR-TOD/mmdet/datasets/youtube_vis_dataset.py @@ -0,0 +1,52 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .base_video_dataset import BaseVideoDataset + + +@DATASETS.register_module() +class YouTubeVISDataset(BaseVideoDataset): + """YouTube VIS dataset for video instance segmentation. + + Args: + dataset_version (str): Select dataset year version. + """ + + def __init__(self, dataset_version: str, *args, **kwargs): + self.set_dataset_classes(dataset_version) + super().__init__(*args, **kwargs) + + @classmethod + def set_dataset_classes(cls, dataset_version: str) -> None: + """Pass the category of the corresponding year to metainfo. + + Args: + dataset_version (str): Select dataset year version. + """ + classes_2019_version = ('person', 'giant_panda', 'lizard', 'parrot', + 'skateboard', 'sedan', 'ape', 'dog', 'snake', + 'monkey', 'hand', 'rabbit', 'duck', 'cat', + 'cow', 'fish', 'train', 'horse', 'turtle', + 'bear', 'motorbike', 'giraffe', 'leopard', + 'fox', 'deer', 'owl', 'surfboard', 'airplane', + 'truck', 'zebra', 'tiger', 'elephant', + 'snowboard', 'boat', 'shark', 'mouse', 'frog', + 'eagle', 'earless_seal', 'tennis_racket') + + classes_2021_version = ('airplane', 'bear', 'bird', 'boat', 'car', + 'cat', 'cow', 'deer', 'dog', 'duck', + 'earless_seal', 'elephant', 'fish', + 'flying_disc', 'fox', 'frog', 'giant_panda', + 'giraffe', 'horse', 'leopard', 'lizard', + 'monkey', 'motorbike', 'mouse', 'parrot', + 'person', 'rabbit', 'shark', 'skateboard', + 'snake', 'snowboard', 'squirrel', 'surfboard', + 'tennis_racket', 'tiger', 'train', 'truck', + 'turtle', 'whale', 'zebra') + + if dataset_version == '2019': + cls.METAINFO = dict(classes=classes_2019_version) + elif dataset_version == '2021': + cls.METAINFO = dict(classes=classes_2021_version) + else: + raise NotImplementedError('Not supported YouTubeVIS dataset' + f'version: {dataset_version}') diff --git a/mmdet_code/SR-TOD/tests/test_apis/test_det_inferencer.py b/mmdet_code/SR-TOD/tests/test_apis/test_det_inferencer.py new file mode 100644 index 0000000000000000000000000000000000000000..78cc8a2cf61597ac14efc6287624570cc3cfa5f8 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_apis/test_det_inferencer.py @@ -0,0 +1,165 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile +from unittest import TestCase, mock +from unittest.mock import Mock, patch + +import mmcv +import mmengine +import numpy as np +import torch +from mmengine.structures import InstanceData +from mmengine.utils import is_list_of +from parameterized import parameterized + +from mmdet.apis import DetInferencer +from mmdet.evaluation.functional import get_classes +from mmdet.structures import DetDataSample + + +class TestDetInferencer(TestCase): + + @mock.patch('mmengine.infer.infer._load_checkpoint', return_value=None) + def test_init(self, mock): + # init from metafile + DetInferencer('rtmdet-t') + # init from cfg + DetInferencer('configs/yolox/yolox_tiny_8xb8-300e_coco.py') + + def assert_predictions_equal(self, preds1, preds2): + for pred1, pred2 in zip(preds1, preds2): + if 'bboxes' in pred1: + self.assertTrue( + np.allclose(pred1['bboxes'], pred2['bboxes'], 0.1)) + if 'scores' in pred1: + self.assertTrue( + np.allclose(pred1['scores'], pred2['scores'], 0.1)) + if 'labels' in pred1: + self.assertTrue(np.allclose(pred1['labels'], pred2['labels'])) + if 'panoptic_seg_path' in pred1: + self.assertTrue( + pred1['panoptic_seg_path'] == pred2['panoptic_seg_path']) + + @parameterized.expand([ + 'rtmdet-t', 'mask-rcnn_r50_fpn_1x_coco', 'panoptic_fpn_r50_fpn_1x_coco' + ]) + def test_call(self, model): + # single img + img_path = 'tests/data/color.jpg' + + mock_load = Mock(return_value=None) + with patch('mmengine.infer.infer._load_checkpoint', mock_load): + inferencer = DetInferencer(model) + + # In the case of not loading the pretrained weight, the category + # defaults to COCO 80, so it needs to be replaced. + if model == 'panoptic_fpn_r50_fpn_1x_coco': + inferencer.visualizer.dataset_meta = { + 'classes': get_classes('coco_panoptic'), + 'palette': 'random' + } + + res_path = inferencer(img_path, return_vis=True) + # ndarray + img = mmcv.imread(img_path) + res_ndarray = inferencer(img, return_vis=True) + self.assert_predictions_equal(res_path['predictions'], + res_ndarray['predictions']) + self.assertIn('visualization', res_path) + self.assertIn('visualization', res_ndarray) + + # multiple images + img_paths = ['tests/data/color.jpg', 'tests/data/gray.jpg'] + res_path = inferencer(img_paths, return_vis=True) + # list of ndarray + imgs = [mmcv.imread(p) for p in img_paths] + res_ndarray = inferencer(imgs, return_vis=True) + self.assert_predictions_equal(res_path['predictions'], + res_ndarray['predictions']) + self.assertIn('visualization', res_path) + self.assertIn('visualization', res_ndarray) + + # img dir, test different batch sizes + img_dir = 'tests/data/VOCdevkit/VOC2007/JPEGImages/' + res_bs1 = inferencer(img_dir, batch_size=1, return_vis=True) + res_bs3 = inferencer(img_dir, batch_size=3, return_vis=True) + self.assert_predictions_equal(res_bs1['predictions'], + res_bs3['predictions']) + + # There is a jitter operation when the mask is drawn, + # so it cannot be asserted. + if model == 'rtmdet-t': + for res_bs1_vis, res_bs3_vis in zip(res_bs1['visualization'], + res_bs3['visualization']): + self.assertTrue(np.allclose(res_bs1_vis, res_bs3_vis)) + + @parameterized.expand([ + 'rtmdet-t', 'mask-rcnn_r50_fpn_1x_coco', 'panoptic_fpn_r50_fpn_1x_coco' + ]) + def test_visualize(self, model): + img_paths = ['tests/data/color.jpg', 'tests/data/gray.jpg'] + + mock_load = Mock(return_value=None) + with patch('mmengine.infer.infer._load_checkpoint', mock_load): + inferencer = DetInferencer(model) + + # In the case of not loading the pretrained weight, the category + # defaults to COCO 80, so it needs to be replaced. + if model == 'panoptic_fpn_r50_fpn_1x_coco': + inferencer.visualizer.dataset_meta = { + 'classes': get_classes('coco_panoptic'), + 'palette': 'random' + } + + with tempfile.TemporaryDirectory() as tmp_dir: + inferencer(img_paths, out_dir=tmp_dir) + for img_dir in ['color.jpg', 'gray.jpg']: + self.assertTrue(osp.exists(osp.join(tmp_dir, 'vis', img_dir))) + + @parameterized.expand([ + 'rtmdet-t', 'mask-rcnn_r50_fpn_1x_coco', 'panoptic_fpn_r50_fpn_1x_coco' + ]) + def test_postprocess(self, model): + # return_datasample + img_path = 'tests/data/color.jpg' + + mock_load = Mock(return_value=None) + with patch('mmengine.infer.infer._load_checkpoint', mock_load): + inferencer = DetInferencer(model) + + # In the case of not loading the pretrained weight, the category + # defaults to COCO 80, so it needs to be replaced. + if model == 'panoptic_fpn_r50_fpn_1x_coco': + inferencer.visualizer.dataset_meta = { + 'classes': get_classes('coco_panoptic'), + 'palette': 'random' + } + + res = inferencer(img_path, return_datasample=True) + self.assertTrue(is_list_of(res['predictions'], DetDataSample)) + + with tempfile.TemporaryDirectory() as tmp_dir: + res = inferencer(img_path, out_dir=tmp_dir, no_save_pred=False) + dumped_res = mmengine.load( + osp.join(tmp_dir, 'preds', 'color.json')) + self.assertEqual(res['predictions'][0], dumped_res) + + @mock.patch('mmengine.infer.infer._load_checkpoint', return_value=None) + def test_pred2dict(self, mock): + data_sample = DetDataSample() + data_sample.pred_instances = InstanceData() + + data_sample.pred_instances.bboxes = np.array([[0, 0, 1, 1]]) + data_sample.pred_instances.labels = np.array([0]) + data_sample.pred_instances.scores = torch.FloatTensor([0.9]) + res = DetInferencer('rtmdet-t').pred2dict(data_sample) + self.assertListAlmostEqual(res['bboxes'], [[0, 0, 1, 1]]) + self.assertListAlmostEqual(res['labels'], [0]) + self.assertListAlmostEqual(res['scores'], [0.9]) + + def assertListAlmostEqual(self, list1, list2, places=7): + for i in range(len(list1)): + if isinstance(list1[i], list): + self.assertListAlmostEqual(list1[i], list2[i], places=places) + else: + self.assertAlmostEqual(list1[i], list2[i], places=places) diff --git a/mmdet_code/SR-TOD/tests/test_apis/test_inference.py b/mmdet_code/SR-TOD/tests/test_apis/test_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e42f86c64e89b4778ec38f14f93bbabf414eb844 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_apis/test_inference.py @@ -0,0 +1,76 @@ +import os +from pathlib import Path + +import numpy as np +import pytest +import torch + +from mmdet.apis import inference_detector, init_detector +from mmdet.structures import DetDataSample +from mmdet.utils import register_all_modules + +# TODO: Waiting to fix multiple call error bug +register_all_modules() + + +@pytest.mark.parametrize('config,devices', + [('configs/retinanet/retinanet_r18_fpn_1x_coco.py', + ('cpu', 'cuda'))]) +def test_init_detector(config, devices): + assert all([device in ['cpu', 'cuda'] for device in devices]) + + project_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + project_dir = os.path.join(project_dir, '..') + + config_file = os.path.join(project_dir, config) + + # test init_detector with config_file: str and cfg_options + cfg_options = dict( + model=dict( + backbone=dict( + depth=18, + init_cfg=dict( + type='Pretrained', checkpoint='torchvision://resnet18')))) + + for device in devices: + if device == 'cuda' and not torch.cuda.is_available(): + pytest.skip('test requires GPU and torch+cuda') + + model = init_detector( + config_file, device=device, cfg_options=cfg_options) + + # test init_detector with :obj:`Path` + config_path_object = Path(config_file) + model = init_detector(config_path_object, device=device) + + # test init_detector with undesirable type + with pytest.raises(TypeError): + config_list = [config_file] + model = init_detector(config_list) # noqa: F841 + + +@pytest.mark.parametrize('config,devices', + [('configs/retinanet/retinanet_r18_fpn_1x_coco.py', + ('cpu', 'cuda'))]) +def test_inference_detector(config, devices): + assert all([device in ['cpu', 'cuda'] for device in devices]) + + project_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + project_dir = os.path.join(project_dir, '..') + + config_file = os.path.join(project_dir, config) + + # test init_detector with config_file: str and cfg_options + rng = np.random.RandomState(0) + img1 = rng.randint(0, 255, (32, 32, 3), dtype=np.uint8) + img2 = rng.randint(0, 255, (32, 32, 3), dtype=np.uint8) + + for device in devices: + if device == 'cuda' and not torch.cuda.is_available(): + pytest.skip('test requires GPU and torch+cuda') + + model = init_detector(config_file, device=device) + result = inference_detector(model, img1) + assert isinstance(result, DetDataSample) + result = inference_detector(model, [img1, img2]) + assert isinstance(result, list) and len(result) == 2 diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_cityscapes.py b/mmdet_code/SR-TOD/tests/test_datasets/test_cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..71a7f9ec170335bfee31b304bfd4a66a9dbe1f38 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_cityscapes.py @@ -0,0 +1,206 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import unittest + +from mmengine.fileio import dump + +from mmdet.datasets import CityscapesDataset + + +class TestCityscapesDataset(unittest.TestCase): + + def setUp(self) -> None: + image1 = { + 'file_name': 'munster/munster_000102_000019_leftImg8bit.png', + 'height': 1024, + 'width': 2048, + 'segm_file': 'munster/munster_000102_000019_gtFine_labelIds.png', + 'id': 0 + } + image2 = { + 'file_name': 'munster/munster_000157_000019_leftImg8bit.png', + 'height': 1024, + 'width': 2048, + 'segm_file': 'munster/munster_000157_000019_gtFine_labelIds.png', + 'id': 1 + } + image3 = { + 'file_name': 'munster/munster_000139_000019_leftImg8bit.png', + 'height': 1024, + 'width': 2048, + 'segm_file': 'munster/munster_000139_000019_gtFine_labelIds.png', + 'id': 2 + } + image4 = { + 'file_name': 'munster/munster_000034_000019_leftImg8bit.png', + 'height': 31, + 'width': 15, + 'segm_file': 'munster/munster_000034_000019_gtFine_labelIds.png', + 'id': 3 + } + + images = [image1, image2, image3, image4] + + categories = [{ + 'id': 24, + 'name': 'person' + }, { + 'id': 25, + 'name': 'rider' + }, { + 'id': 26, + 'name': 'car' + }] + + annotations = [ + { + 'iscrowd': 0, + 'category_id': 24, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 0 + }, + { + 'iscrowd': 0, + 'category_id': 25, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': -1, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 1 + }, + { + 'iscrowd': 0, + 'category_id': 26, + 'bbox': [379.0, 435.0, -1, 124.0], + 'area': 2, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 2 + }, + { + 'iscrowd': 0, + 'category_id': 24, + 'bbox': [379.0, 435.0, 52.0, -1], + 'area': 2, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 3 + }, + { + 'iscrowd': 0, + 'category_id': 1, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 4 + }, + { + 'iscrowd': 1, + 'category_id': 26, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 1, + 'id': 5 + }, + { + 'iscrowd': 0, + 'category_id': 26, + 'bbox': [379.0, 435.0, 10, 2], + 'area': 2595, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 3, + 'id': 6 + }, + ] + fake_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories + } + self.json_name = 'cityscapes.json' + dump(fake_json, self.json_name) + + self.metainfo = dict(classes=('person', 'rider', 'car')) + + def tearDown(self): + os.remove(self.json_name) + + def test_cityscapes_dataset(self): + dataset = CityscapesDataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 1) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = CityscapesDataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + def test_cityscapes_dataset_without_filter_cfg(self): + dataset = CityscapesDataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=None, + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = CityscapesDataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=None, + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_coco.py b/mmdet_code/SR-TOD/tests/test_datasets/test_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..97fb2c95eaad6204e10be2e2d04b3e81dca91d37 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_coco.py @@ -0,0 +1,48 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import CocoDataset + + +class TestCocoDataset(unittest.TestCase): + + def test_coco_dataset(self): + # test CocoDataset + metainfo = dict(classes=('bus', 'car'), task_name='new_task') + dataset = CocoDataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('bus', 'car')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + self.assertListEqual(dataset.get_cat_ids(0), [0, 1]) + + def test_coco_dataset_without_filter_cfg(self): + # test CocoDataset without filter_cfg + dataset = CocoDataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + pipeline=[]) + self.assertEqual(len(dataset), 4) + + # test with test_mode = True + dataset = CocoDataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + test_mode=True, + pipeline=[]) + self.assertEqual(len(dataset), 4) + + def test_coco_annotation_ids_unique(self): + # test annotation ids not unique error + metainfo = dict(classes=('car', ), task_name='new_task') + with self.assertRaisesRegex(AssertionError, 'are not unique!'): + CocoDataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_wrong_format_sample.json', + metainfo=metainfo, + pipeline=[]) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_coco_api_wrapper.py b/mmdet_code/SR-TOD/tests/test_datasets/test_coco_api_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..c3df8ac22cd5c3c0bd4b3c708634624f1b94e297 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_coco_api_wrapper.py @@ -0,0 +1,67 @@ +import os.path as osp +import tempfile +import unittest + +from mmengine.fileio import dump + +from mmdet.datasets.api_wrappers import COCOPanoptic + + +class TestCOCOPanoptic(unittest.TestCase): + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_create_index(self): + ann_json = {'test': ['test', 'createIndex']} + annotation_file = osp.join(self.tmp_dir.name, 'createIndex.json') + dump(ann_json, annotation_file) + COCOPanoptic(annotation_file) + + def test_load_anns(self): + categories = [{ + 'id': 0, + 'name': 'person', + 'supercategory': 'person', + 'isthing': 1 + }] + + images = [{ + 'id': 0, + 'width': 80, + 'height': 60, + 'file_name': 'fake_name1.jpg', + }] + + annotations = [{ + 'segments_info': [ + { + 'id': 1, + 'category_id': 0, + 'area': 400, + 'bbox': [10, 10, 10, 40], + 'iscrowd': 0 + }, + ], + 'file_name': + 'fake_name1.png', + 'image_id': + 0 + }] + + ann_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories, + } + + annotation_file = osp.join(self.tmp_dir.name, 'load_anns.json') + dump(ann_json, annotation_file) + + api = COCOPanoptic(annotation_file) + api.load_anns(1) + + self.assertIsNone(api.load_anns(0.1)) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_coco_panoptic.py b/mmdet_code/SR-TOD/tests/test_datasets/test_coco_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..20d585dcaa4fae9d51b1ec68d8c139d528ada39b --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_coco_panoptic.py @@ -0,0 +1,249 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import unittest + +from mmengine.fileio import dump + +from mmdet.datasets import CocoPanopticDataset + + +class TestCocoPanopticDataset(unittest.TestCase): + + def setUp(self): + image1 = { + 'id': 0, + 'width': 640, + 'height': 640, + 'file_name': 'fake_name1.jpg', + } + + image2 = { + 'id': 1, + 'width': 640, + 'height': 800, + 'file_name': 'fake_name2.jpg', + } + + image3 = { + 'id': 2, + 'width': 31, + 'height': 40, + 'file_name': 'fake_name3.jpg', + } + + image4 = { + 'id': 3, + 'width': 400, + 'height': 400, + 'file_name': 'fake_name4.jpg', + } + images = [image1, image2, image3, image4] + + annotations = [ + { + 'segments_info': [{ + 'id': 1, + 'category_id': 0, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'iscrowd': 0 + }, { + 'id': 2, + 'category_id': 1, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'iscrowd': 0 + }, { + 'id': 3, + 'category_id': 2, + 'iscrowd': 0, + 'bbox': [1, 189, 612, 285], + 'area': 70036 + }], + 'file_name': + 'fake_name1.jpg', + 'image_id': + 0 + }, + { + 'segments_info': [ + { + # Different to instance style json, there + # are duplicate ids in panoptic style json + 'id': 1, + 'category_id': 0, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'iscrowd': 0 + }, + { + 'id': 4, + 'category_id': 1, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'iscrowd': 1 + }, + { + 'id': 5, + 'category_id': 2, + 'iscrowd': 0, + 'bbox': [100, 200, 200, 300], + 'area': 66666 + }, + { + 'id': 6, + 'category_id': 0, + 'iscrowd': 0, + 'bbox': [1, 189, -10, 285], + 'area': -2 + }, + { + 'id': 10, + 'category_id': 0, + 'iscrowd': 0, + 'bbox': [1, 189, 10, -285], + 'area': 100 + } + ], + 'file_name': + 'fake_name2.jpg', + 'image_id': + 1 + }, + { + 'segments_info': [{ + 'id': 7, + 'category_id': 0, + 'area': 25, + 'bbox': [0, 0, 5, 5], + 'iscrowd': 0 + }], + 'file_name': + 'fake_name3.jpg', + 'image_id': + 2 + }, + { + 'segments_info': [{ + 'id': 8, + 'category_id': 0, + 'area': 25, + 'bbox': [0, 0, 400, 400], + 'iscrowd': 1 + }], + 'file_name': + 'fake_name4.jpg', + 'image_id': + 3 + } + ] + + categories = [{ + 'id': 0, + 'name': 'car', + 'supercategory': 'car', + 'isthing': 1 + }, { + 'id': 1, + 'name': 'person', + 'supercategory': 'person', + 'isthing': 1 + }, { + 'id': 2, + 'name': 'wall', + 'supercategory': 'wall', + 'isthing': 0 + }] + + fake_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories + } + self.json_name = 'coco_panoptic.json' + dump(fake_json, self.json_name) + + self.metainfo = dict( + classes=('person', 'car', 'wall'), + thing_classes=('person', 'car'), + stuff_classes=('wall', )) + + def tearDown(self): + os.remove(self.json_name) + + def test_coco_panoptic_dataset(self): + dataset = CocoPanopticDataset( + data_root='./', + ann_file=self.json_name, + data_prefix=dict(img='imgs', seg='seg'), + metainfo=self.metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + self.assertEqual(dataset.metainfo['thing_classes'], + self.metainfo['thing_classes']) + self.assertEqual(dataset.metainfo['stuff_classes'], + self.metainfo['stuff_classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 2) + self.assertEqual(len(dataset.load_data_list()), 4) + # test mode + dataset = CocoPanopticDataset( + data_root='./', + ann_file=self.json_name, + data_prefix=dict(img='imgs', seg='seg'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + self.assertEqual(dataset.metainfo['thing_classes'], + self.metainfo['thing_classes']) + self.assertEqual(dataset.metainfo['stuff_classes'], + self.metainfo['stuff_classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + def test_coco_panoptic_dataset_without_filter_cfg(self): + dataset = CocoPanopticDataset( + data_root='./', + ann_file=self.json_name, + data_prefix=dict(img='imgs', seg='seg'), + metainfo=self.metainfo, + filter_cfg=None, + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + self.assertEqual(dataset.metainfo['thing_classes'], + self.metainfo['thing_classes']) + self.assertEqual(dataset.metainfo['stuff_classes'], + self.metainfo['stuff_classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + # test mode + dataset = CocoPanopticDataset( + data_root='./', + ann_file=self.json_name, + data_prefix=dict(img='imgs', seg='seg'), + metainfo=self.metainfo, + filter_cfg=None, + test_mode=True, + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + self.assertEqual(dataset.metainfo['thing_classes'], + self.metainfo['thing_classes']) + self.assertEqual(dataset.metainfo['stuff_classes'], + self.metainfo['stuff_classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_crowdhuman.py b/mmdet_code/SR-TOD/tests/test_datasets/test_crowdhuman.py new file mode 100644 index 0000000000000000000000000000000000000000..1ccacf3a291403a74ef3b39a8e661e18bf37d2d2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_crowdhuman.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import CrowdHumanDataset + + +class TestCrowdHumanDataset(unittest.TestCase): + + def test_crowdhuman_init(self): + dataset = CrowdHumanDataset( + data_root='tests/data/crowdhuman_dataset/', + ann_file='test_annotation_train.odgt', + data_prefix=dict(img='Images/'), + pipeline=[]) + self.assertEqual(len(dataset), 1) + self.assertEqual(dataset.metainfo['classes'], ('person', )) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_dsdldet.py b/mmdet_code/SR-TOD/tests/test_datasets/test_dsdldet.py new file mode 100644 index 0000000000000000000000000000000000000000..b92bfe4fc03068a4482604287de5ab1d05fa93ae --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_dsdldet.py @@ -0,0 +1,25 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import DSDLDetDataset + +try: + from dsdl.dataset import DSDLDataset +except ImportError: + DSDLDataset = None + + +class TestDSDLDetDataset(unittest.TestCase): + + def test_dsdldet_init(self): + if DSDLDataset is not None: + dataset = DSDLDetDataset( + data_root='tests/data/dsdl_det', + ann_file='set-train/train.yaml') + dataset.full_init() + + self.assertEqual(len(dataset), 2) + self.assertEqual(len(dataset[0]['instances']), 4) + self.assertEqual(dataset.get_cat_ids(0), [3, 0, 0, 1]) + else: + ImportWarning('Package `dsdl` is not installed.') diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_lvis.py b/mmdet_code/SR-TOD/tests/test_datasets/test_lvis.py new file mode 100644 index 0000000000000000000000000000000000000000..e1d908f078d0c097cac85a80400d95a447c6562a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_lvis.py @@ -0,0 +1,231 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import unittest + +from mmengine.fileio import dump + +from mmdet.datasets import LVISV1Dataset, LVISV05Dataset + +try: + import lvis +except ImportError: + lvis = None + + +class TestLVISDataset(unittest.TestCase): + + def setUp(self) -> None: + + image1 = { + # ``coco_url`` for v1 only. + 'coco_url': 'http://images.cocodataset.org/train2017/0.jpg', + # ``file_name`` for v0.5 only. + 'file_name': '0.jpg', + 'height': 1024, + 'width': 2048, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'id': 0 + } + image2 = { + 'coco_url': 'http://images.cocodataset.org/train2017/1.jpg', + 'file_name': '1.jpg', + 'height': 1024, + 'width': 2048, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'id': 1 + } + image3 = { + 'coco_url': 'http://images.cocodataset.org/train2017/2.jpg', + 'file_name': '2.jpg', + 'height': 1024, + 'width': 2048, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'id': 2 + } + image4 = { + 'coco_url': 'http://images.cocodataset.org/train2017/3.jpg', + 'file_name': '3.jpg', + 'height': 31, + 'width': 15, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'id': 3 + } + + images = [image1, image2, image3, image4] + + categories = [{ + 'id': 1, + 'name': 'aerosol_can', + 'frequency': 'c', + 'image_count': 64 + }, { + 'id': 2, + 'name': 'air_conditioner', + 'frequency': 'f', + 'image_count': 364 + }, { + 'id': 3, + 'name': 'airplane', + 'frequency': 'f', + 'image_count': 1911 + }] + + annotations = [ + { + 'category_id': 1, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 0 + }, + { + 'category_id': 2, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': -1, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 1 + }, + { + 'category_id': 3, + 'bbox': [379.0, 435.0, -1, 124.0], + 'area': 2, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 2 + }, + { + 'category_id': 1, + 'bbox': [379.0, 435.0, 52.0, -1], + 'area': 2, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 3 + }, + { + 'category_id': 1, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 4 + }, + { + 'category_id': 3, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': [[0.0, 0.0]], + 'image_id': 1, + 'id': 5 + }, + { + 'category_id': 3, + 'bbox': [379.0, 435.0, 10, 2], + 'area': 2595, + 'segmentation': [[0.0, 0.0]], + 'image_id': 3, + 'id': 6 + }, + ] + fake_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories + } + self.json_name = 'lvis.json' + dump(fake_json, self.json_name) + + self.metainfo = dict( + classes=('aerosol_can', 'air_conditioner', 'airplane')) + + def tearDown(self): + os.remove(self.json_name) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_lvis05_dataset(self): + dataset = LVISV05Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 2) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = LVISV05Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_lvis1_dataset(self): + dataset = LVISV1Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 2) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = LVISV1Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_lvis1_dataset_without_filter_cfg(self): + dataset = LVISV1Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=None, + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = LVISV1Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=None, + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_mot_challenge_dataset.py b/mmdet_code/SR-TOD/tests/test_datasets/test_mot_challenge_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9f61b40906ec61390b0e6de2a89ec3925536e4 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_mot_challenge_dataset.py @@ -0,0 +1,37 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import MOTChallengeDataset + + +class TestMOTChallengeDataset(unittest.TestCase): + + def test_mot_challenge_dataset(self): + # test CocoDataset + metainfo = dict(classes=('pedestrian'), task_name='new_task') + dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('pedestrian')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + self.assertListEqual(dataset.get_cat_ids((0, 1)), [0, 0]) + self.assertListEqual(dataset.get_cat_ids(0), [0, 0, 0, 0, 0, 0]) + self.assertEqual(len(dataset), 2) + self.assertEqual(dataset.num_all_imgs, 5) + self.assertEqual(len(dataset[0]['images'][2]['instances']), 2) + + def test_mot_challenge_dataset_with_visibility(self): + dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + visibility_thr=0.5, + pipeline=[]) + self.assertEqual(dataset.num_all_imgs, 5) + self.assertEqual(len(dataset[0]['images'][2]['instances']), 1) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_objects365.py b/mmdet_code/SR-TOD/tests/test_datasets/test_objects365.py new file mode 100644 index 0000000000000000000000000000000000000000..1e01bf27c03d09d1e66df8e6569b89c7d26f90c9 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_objects365.py @@ -0,0 +1,79 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import Objects365V1Dataset, Objects365V2Dataset + + +class TestObjects365V1Dataset(unittest.TestCase): + + def test_obj365v1_dataset(self): + # test Objects365V1Dataset + metainfo = dict(classes=('bus', 'car'), task_name='new_task') + dataset = Objects365V1Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('bus', 'car')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + self.assertListEqual(dataset.get_cat_ids(0), [0, 1]) + self.assertEqual(dataset.cat_ids, [1, 2]) + + def test_obj365v1_with_unsorted_annotation(self): + # test Objects365V1Dataset with unsorted annotations + metainfo = dict(classes=('bus', 'car'), task_name='new_task') + dataset = Objects365V1Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/Objects365/unsorted_obj365_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('bus', 'car')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + # sort the unsorted annotations + self.assertListEqual(dataset.get_cat_ids(0), [0, 1]) + self.assertEqual(dataset.cat_ids, [1, 2]) + + def test_obj365v1_annotation_ids_unique(self): + # test annotation ids not unique error + metainfo = dict(classes=('car', ), task_name='new_task') + with self.assertRaisesRegex(AssertionError, 'are not unique!'): + Objects365V1Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_wrong_format_sample.json', + metainfo=metainfo, + pipeline=[]) + + +class TestObjects365V2Dataset(unittest.TestCase): + + def test_obj365v2_dataset(self): + # test Objects365V2Dataset + metainfo = dict(classes=('bus', 'car'), task_name='new_task') + dataset = Objects365V2Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('bus', 'car')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + self.assertListEqual(dataset.get_cat_ids(0), [0, 1]) + self.assertEqual(dataset.cat_ids, [1, 2]) + + def test_obj365v1_annotation_ids_unique(self): + # test annotation ids not unique error + metainfo = dict(classes=('car', ), task_name='new_task') + with self.assertRaisesRegex(AssertionError, 'are not unique!'): + Objects365V2Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_wrong_format_sample.json', + metainfo=metainfo, + pipeline=[]) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_openimages.py b/mmdet_code/SR-TOD/tests/test_datasets/test_openimages.py new file mode 100644 index 0000000000000000000000000000000000000000..dcd751ec46c8c9dcb77b555e23a38a8a024774fc --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_openimages.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import OpenImagesChallengeDataset, OpenImagesDataset + + +class TestOpenImagesDataset(unittest.TestCase): + + def test_init(self): + dataset = OpenImagesDataset( + data_root='tests/data/OpenImages/', + ann_file='annotations/oidv6-train-annotations-bbox.csv', + data_prefix=dict(img='OpenImages/train/'), + label_file='annotations/class-descriptions-boxable.csv', + hierarchy_file='annotations/bbox_labels_600_hierarchy.json', + meta_file='annotations/image-metas.pkl', + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + self.assertEqual(dataset.metainfo['classes'], ['Airplane']) + + +class TestOpenImagesChallengeDataset(unittest.TestCase): + + def test_init(self): + dataset = OpenImagesChallengeDataset( + data_root='tests/data/OpenImages/', + ann_file='challenge2019/challenge-2019-train-detection-bbox.txt', + data_prefix=dict(img='OpenImages/train/'), + label_file='challenge2019/cls-label-description.csv', + hierarchy_file='challenge2019/class_label_tree.np', + meta_file='annotations/image-metas.pkl', + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + self.assertEqual(dataset.metainfo['classes'], ['Airplane']) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_pascal_voc.py b/mmdet_code/SR-TOD/tests/test_datasets/test_pascal_voc.py new file mode 100644 index 0000000000000000000000000000000000000000..7188d41e976725f6df2db10707b25148ffb430eb --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_pascal_voc.py @@ -0,0 +1,38 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import VOCDataset + + +class TestVOCDataset(unittest.TestCase): + + def test_voc2007_init(self): + dataset = VOCDataset( + data_root='tests/data/VOCdevkit/', + ann_file='VOC2007/ImageSets/Main/trainval.txt', + data_prefix=dict(sub_data_root='VOC2007/'), + filter_cfg=dict( + filter_empty_gt=True, min_size=32, bbox_min_size=32), + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + + data_list = dataset.load_data_list() + self.assertEqual(len(data_list), 1) + self.assertEqual(len(data_list[0]['instances']), 2) + self.assertEqual(dataset.get_cat_ids(0), [11, 14]) + + def test_voc2012_init(self): + dataset = VOCDataset( + data_root='tests/data/VOCdevkit/', + ann_file='VOC2012/ImageSets/Main/trainval.txt', + data_prefix=dict(sub_data_root='VOC2012/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + + data_list = dataset.load_data_list() + self.assertEqual(len(data_list), 1) + self.assertEqual(len(data_list[0]['instances']), 1) + self.assertEqual(dataset.get_cat_ids(0), [18]) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_reid_dataset.py b/mmdet_code/SR-TOD/tests/test_datasets/test_reid_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..c4083612c47026bbaae9df743f19cb977868221f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_reid_dataset.py @@ -0,0 +1,64 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from unittest import TestCase + +from mmdet.datasets import ReIDDataset + +PREFIX = osp.join(osp.dirname(__file__), '../data') +# This is a demo annotation file for ReIDDataset. +REID_ANN_FILE = f'{PREFIX}/demo_reid_data/mot17_reid/ann.txt' + + +class TestReIDDataset(TestCase): + + @classmethod + def setUpClass(cls): + cls.num_ids = 8 + cls.ins_per_id = 4 + cls.dataset = ReIDDataset( + pipeline=[], ann_file=REID_ANN_FILE, data_prefix=dict(img_path='')) + cls.dataset_triplet = ReIDDataset( + pipeline=[], + triplet_sampler=dict( + num_ids=cls.num_ids, ins_per_id=cls.ins_per_id), + ann_file=REID_ANN_FILE, + data_prefix=dict(img_path='')) + + def test_get_data_info(self): + # id 0 has 21 objects + img_id = 0 + data_list = [ + self.dataset.get_data_info(i) for i in range(len(self.dataset)) + ] + assert len([ + data_info for data_info in data_list + if data_info['gt_label'] == img_id + ]) == 21 + # id 11 doesn't have objects + img_id = 11 + assert len([ + data_info for data_info in data_list + if data_info['gt_label'] == img_id + ]) == 0 + + def test_len(self): + assert len(self.dataset) == 704 + assert len(self.dataset_triplet) == 704 + + def test_getitem(self): + for i in range(len(self.dataset)): + results = self.dataset[i] + assert isinstance(results, dict) # no triplet -> dict + assert 'img_path' in results + assert 'gt_label' in results + for i in range(len(self.dataset_triplet)): + num = self.num_ids * self.ins_per_id + results = self.dataset_triplet[i] + assert isinstance(results, dict) # triplet -> dict + assert len(results['img_path']) == num + assert 'img_path' in results + assert 'gt_label' in results + for idx in range(num - 1): + if (idx + 1) % self.ins_per_id != 0: + assert results['gt_label'][idx] == \ + results['gt_label'][idx + 1] diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_batch_sampler.py b/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_batch_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..e4cb2ee09b8b05de2327fe2a90fc1d04d4b3f377 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_batch_sampler.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. + +from unittest import TestCase +from unittest.mock import patch + +import numpy as np +from mmengine.dataset import DefaultSampler +from torch.utils.data import Dataset + +from mmdet.datasets.samplers import AspectRatioBatchSampler + + +class DummyDataset(Dataset): + + def __init__(self, length): + self.length = length + self.shapes = np.random.random((length, 2)) + + def __len__(self): + return self.length + + def __getitem__(self, idx): + return self.shapes[idx] + + def get_data_info(self, idx): + return dict(width=self.shapes[idx][0], height=self.shapes[idx][1]) + + +class TestAspectRatioBatchSampler(TestCase): + + @patch('mmengine.dist.get_dist_info', return_value=(0, 1)) + def setUp(self, mock): + self.length = 100 + self.dataset = DummyDataset(self.length) + self.sampler = DefaultSampler(self.dataset, shuffle=False) + + def test_invalid_inputs(self): + with self.assertRaisesRegex( + ValueError, 'batch_size should be a positive integer value'): + AspectRatioBatchSampler(self.sampler, batch_size=-1) + + with self.assertRaisesRegex( + TypeError, 'sampler should be an instance of ``Sampler``'): + AspectRatioBatchSampler(None, batch_size=1) + + def test_divisible_batch(self): + batch_size = 5 + batch_sampler = AspectRatioBatchSampler( + self.sampler, batch_size=batch_size, drop_last=True) + self.assertEqual(len(batch_sampler), self.length // batch_size) + for batch_idxs in batch_sampler: + self.assertEqual(len(batch_idxs), batch_size) + batch = [self.dataset[idx] for idx in batch_idxs] + flag = batch[0][0] < batch[0][1] + for i in range(1, batch_size): + self.assertEqual(batch[i][0] < batch[i][1], flag) + + def test_indivisible_batch(self): + batch_size = 7 + batch_sampler = AspectRatioBatchSampler( + self.sampler, batch_size=batch_size, drop_last=False) + all_batch_idxs = list(batch_sampler) + self.assertEqual( + len(batch_sampler), (self.length + batch_size - 1) // batch_size) + self.assertEqual( + len(all_batch_idxs), (self.length + batch_size - 1) // batch_size) + + batch_sampler = AspectRatioBatchSampler( + self.sampler, batch_size=batch_size, drop_last=True) + all_batch_idxs = list(batch_sampler) + self.assertEqual(len(batch_sampler), self.length // batch_size) + self.assertEqual(len(all_batch_idxs), self.length // batch_size) + + # the last batch may not have the same aspect ratio + for batch_idxs in all_batch_idxs[:-1]: + self.assertEqual(len(batch_idxs), batch_size) + batch = [self.dataset[idx] for idx in batch_idxs] + flag = batch[0][0] < batch[0][1] + for i in range(1, batch_size): + self.assertEqual(batch[i][0] < batch[i][1], flag) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_multi_source_sampler.py b/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_multi_source_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..19609d5f2fdb9cb7704b3faf96d099911add9ef1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_multi_source_sampler.py @@ -0,0 +1,107 @@ +# Copyright (c) OpenMMLab. All rights reserved. + +import bisect +from unittest import TestCase +from unittest.mock import patch + +import numpy as np +from torch.utils.data import ConcatDataset, Dataset + +from mmdet.datasets.samplers import GroupMultiSourceSampler, MultiSourceSampler + + +class DummyDataset(Dataset): + + def __init__(self, length, flag): + self.length = length + self.flag = flag + self.shapes = np.random.random((length, 2)) + + def __len__(self): + return self.length + + def __getitem__(self, idx): + return self.shapes[idx] + + def get_data_info(self, idx): + return dict( + width=self.shapes[idx][0], + height=self.shapes[idx][1], + flag=self.flag) + + +class DummyConcatDataset(ConcatDataset): + + def _get_ori_dataset_idx(self, idx): + dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) + sample_idx = idx if dataset_idx == 0 else idx - self.cumulative_sizes[ + dataset_idx - 1] + return dataset_idx, sample_idx + + def get_data_info(self, idx: int): + dataset_idx, sample_idx = self._get_ori_dataset_idx(idx) + return self.datasets[dataset_idx].get_data_info(sample_idx) + + +class TestMultiSourceSampler(TestCase): + + @patch('mmengine.dist.get_dist_info', return_value=(7, 8)) + def setUp(self, mock): + self.length_a = 100 + self.dataset_a = DummyDataset(self.length_a, flag='a') + self.length_b = 1000 + self.dataset_b = DummyDataset(self.length_b, flag='b') + self.dataset = DummyConcatDataset([self.dataset_a, self.dataset_b]) + + def test_multi_source_sampler(self): + # test dataset is not ConcatDataset + with self.assertRaises(AssertionError): + MultiSourceSampler( + self.dataset_a, batch_size=5, source_ratio=[1, 4]) + # test invalid batch_size + with self.assertRaises(AssertionError): + MultiSourceSampler( + self.dataset_a, batch_size=-5, source_ratio=[1, 4]) + # test source_ratio longer then dataset + with self.assertRaises(AssertionError): + MultiSourceSampler( + self.dataset, batch_size=5, source_ratio=[1, 2, 4]) + sampler = MultiSourceSampler( + self.dataset, batch_size=5, source_ratio=[1, 4]) + sampler = iter(sampler) + flags = [] + for i in range(100): + idx = next(sampler) + flags.append(self.dataset.get_data_info(idx)['flag']) + flags_gt = ['a', 'b', 'b', 'b', 'b'] * 20 + self.assertEqual(flags, flags_gt) + + +class TestGroupMultiSourceSampler(TestCase): + + @patch('mmengine.dist.get_dist_info', return_value=(7, 8)) + def setUp(self, mock): + self.length_a = 100 + self.dataset_a = DummyDataset(self.length_a, flag='a') + self.length_b = 1000 + self.dataset_b = DummyDataset(self.length_b, flag='b') + self.dataset = DummyConcatDataset([self.dataset_a, self.dataset_b]) + + def test_group_multi_source_sampler(self): + sampler = GroupMultiSourceSampler( + self.dataset, batch_size=5, source_ratio=[1, 4]) + sampler = iter(sampler) + flags = [] + groups = [] + for i in range(100): + idx = next(sampler) + data_info = self.dataset.get_data_info(idx) + flags.append(data_info['flag']) + group = 0 if data_info['width'] < data_info['height'] else 1 + groups.append(group) + flags_gt = ['a', 'b', 'b', 'b', 'b'] * 20 + self.assertEqual(flags, flags_gt) + groups = set( + [sum(x) for x in (groups[k:k + 5] for k in range(0, 100, 5))]) + groups_gt = set([0, 5]) + self.assertEqual(groups, groups_gt) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_track_img_sampler.py b/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_track_img_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..0273aa08fbbd4493042a9f3b707a6dff002e727a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_samplers/test_track_img_sampler.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from collections.abc import Iterable +from copy import deepcopy +from unittest import TestCase + +from mmengine.dataset import ClassBalancedDataset, ConcatDataset + +from mmdet.datasets import MOTChallengeDataset, TrackImgSampler + + +class TestTrackImgSampler(TestCase): + + def test_iter_base_video_dataset(self): + # train mode + dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + test_mode=False, + pipeline=[]) + video_sampler = TrackImgSampler(dataset) + assert len(video_sampler) == 5 + iterator = iter(video_sampler) + assert isinstance(iterator, Iterable) + for index in iterator: + assert isinstance(index, tuple) + video_index, frame_index = index + assert video_index < 2 + if video_index == 0: + assert frame_index >= 0 and frame_index < 3 + else: + assert frame_index >= 0 and frame_index < 2 + + # test mode + dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + test_mode=True, + pipeline=[]) + video_sampler = TrackImgSampler(dataset) + assert len(video_sampler) == 5 + assert len(video_sampler.indices) == 1 + + def test_iter_concat_dataset(self): + single_dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + test_mode=False, + pipeline=[]) + + dataset = ConcatDataset([single_dataset, deepcopy(single_dataset)]) + video_sampler = TrackImgSampler(dataset) + assert len(video_sampler) == 10 + iterator = iter(video_sampler) + assert isinstance(iterator, Iterable) + for index in iterator: + assert isinstance(index, tuple) + video_index, frame_index = index + assert video_index < 4 + if video_index == 0: + assert frame_index >= 0 and frame_index < 3 + elif video_index == 3: + assert frame_index >= 0 and frame_index < 2 + + def test_iter_class_balanced_dataset(self): + single_dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian', 'person_on_vehicle')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + visibility_thr=0.1, + test_mode=False, + pipeline=[]) + + dataset = ClassBalancedDataset(single_dataset, oversample_thr=0.6) + video_sampler = TrackImgSampler(dataset) + assert len(video_sampler) == 8 + iterator = iter(video_sampler) + assert isinstance(iterator, Iterable) + for index in iterator: + assert isinstance(index, tuple) + video_index, frame_index = index + assert video_index < 3 + if video_index == 0 or video_index == 2: + assert frame_index >= 0 and frame_index < 3 + else: + assert frame_index >= 0 and frame_index < 2 diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/__init__.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1daf8fce080d3dbbe1e2f2794168f6e39e65a7f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .utils import construct_toy_data, create_full_masks, create_random_bboxes + +__all__ = ['create_random_bboxes', 'create_full_masks', 'construct_toy_data'] diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_augment_wrappers.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_augment_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..4e0f75346e49224652e559db9d948fdbd0cc17c7 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_augment_wrappers.py @@ -0,0 +1,249 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import unittest + +from mmdet.datasets.transforms import (AutoAugment, AutoContrast, Brightness, + Color, Contrast, Equalize, Invert, + Posterize, RandAugment, Rotate, + Sharpness, ShearX, ShearY, Solarize, + SolarizeAdd, TranslateX, TranslateY) +from mmdet.utils import register_all_modules +from .utils import check_result_same, construct_toy_data + +register_all_modules() + + +class TestAutoAugment(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map', + 'homography_matrix') + self.results_mask = construct_toy_data(poly2mask=True) + self.img_fill_val = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_autoaugment(self): + # test AutoAugment equipped with Shear + policies = [[ + dict(type='ShearX', prob=1.0, level=3, reversal_prob=0.0), + dict(type='ShearY', prob=1.0, level=7, reversal_prob=1.0) + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_shearx = ShearX(prob=1.0, level=3, reversal_prob=0.0) + transform_sheary = ShearY(prob=1.0, level=7, reversal_prob=1.0) + results_sheared = transform_sheary( + transform_shearx(copy.deepcopy(self.results_mask))) + check_result_same(results_sheared, results_auto, self.check_keys) + + # test AutoAugment equipped with Rotate + policies = [[ + dict(type='Rotate', prob=1.0, level=10, reversal_prob=0.0), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_rotate = Rotate(prob=1.0, level=10, reversal_prob=0.0) + results_rotated = transform_rotate(copy.deepcopy(self.results_mask)) + check_result_same(results_rotated, results_auto, self.check_keys) + + # test AutoAugment equipped with Translate + policies = [[ + dict( + type='TranslateX', + prob=1.0, + level=10, + max_mag=1.0, + reversal_prob=0.0), + dict( + type='TranslateY', + prob=1.0, + level=10, + max_mag=1.0, + reversal_prob=1.0) + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_translatex = TranslateX( + prob=1.0, level=10, max_mag=1.0, reversal_prob=0.0) + transform_translatey = TranslateY( + prob=1.0, level=10, max_mag=1.0, reversal_prob=1.0) + results_translated = transform_translatey( + transform_translatex(copy.deepcopy(self.results_mask))) + check_result_same(results_translated, results_auto, self.check_keys) + + # test AutoAugment equipped with Brightness + policies = [[ + dict(type='Brightness', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_brightness = Brightness(prob=1.0, level=3) + results_brightness = transform_brightness( + copy.deepcopy(self.results_mask)) + check_result_same(results_brightness, results_auto, self.check_keys) + + # test AutoAugment equipped with Color + policies = [[ + dict(type='Color', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_color = Color(prob=1.0, level=3) + results_colored = transform_color(copy.deepcopy(self.results_mask)) + check_result_same(results_colored, results_auto, self.check_keys) + + # test AutoAugment equipped with Contrast + policies = [[ + dict(type='Contrast', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_contrast = Contrast(prob=1.0, level=3) + results_contrasted = transform_contrast( + copy.deepcopy(self.results_mask)) + check_result_same(results_contrasted, results_auto, self.check_keys) + + # test AutoAugment equipped with Sharpness + policies = [[ + dict(type='Sharpness', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_sharpness = Sharpness(prob=1.0, level=3) + results_sharpness = transform_sharpness( + copy.deepcopy(self.results_mask)) + check_result_same(results_sharpness, results_auto, self.check_keys) + + # test AutoAugment equipped with Solarize + policies = [[ + dict(type='Solarize', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_solarize = Solarize(prob=1.0, level=3) + results_solarized = transform_solarize( + copy.deepcopy(self.results_mask)) + check_result_same(results_solarized, results_auto, self.check_keys) + + # test AutoAugment equipped with SolarizeAdd + policies = [[ + dict(type='SolarizeAdd', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_solarizeadd = SolarizeAdd(prob=1.0, level=3) + results_solarizeadded = transform_solarizeadd( + copy.deepcopy(self.results_mask)) + check_result_same(results_solarizeadded, results_auto, self.check_keys) + + # test AutoAugment equipped with Posterize + policies = [[ + dict(type='Posterize', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_posterize = Posterize(prob=1.0, level=3) + results_posterized = transform_posterize( + copy.deepcopy(self.results_mask)) + check_result_same(results_posterized, results_auto, self.check_keys) + + # test AutoAugment equipped with Equalize + policies = [[ + dict(type='Equalize', prob=1.0), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_equalize = Equalize(prob=1.0) + results_equalized = transform_equalize( + copy.deepcopy(self.results_mask)) + check_result_same(results_equalized, results_auto, self.check_keys) + + # test AutoAugment equipped with AutoContrast + policies = [[ + dict(type='AutoContrast', prob=1.0), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_autocontrast = AutoContrast(prob=1.0) + results_autocontrast = transform_autocontrast( + copy.deepcopy(self.results_mask)) + check_result_same(results_autocontrast, results_auto, self.check_keys) + + # test AutoAugment equipped with Invert + policies = [[ + dict(type='Invert', prob=1.0), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_invert = Invert(prob=1.0) + results_inverted = transform_invert(copy.deepcopy(self.results_mask)) + check_result_same(results_inverted, results_auto, self.check_keys) + + # test AutoAugment equipped with default policies + transform_auto = AutoAugment() + transform_auto(copy.deepcopy(self.results_mask)) + + def test_repr(self): + policies = [[ + dict(type='Rotate', prob=1.0, level=10, reversal_prob=0.0), + dict(type='Invert', prob=1.0), + ]] + transform = AutoAugment(policies=policies) + self.assertEqual( + repr(transform), ('AutoAugment(' + 'policies=[[' + "{'type': 'Rotate', 'prob': 1.0, " + "'level': 10, 'reversal_prob': 0.0}, " + "{'type': 'Invert', 'prob': 1.0}]], " + 'prob=None)')) + + +class TestRandAugment(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map', + 'homography_matrix') + self.results_mask = construct_toy_data(poly2mask=True) + self.img_fill_val = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_randaugment(self): + # test RandAugment equipped with Rotate + aug_space = [[ + dict(type='Rotate', prob=1.0, level=10, reversal_prob=0.0) + ]] + transform_rand = RandAugment(aug_space=aug_space, aug_num=1) + results_rand = transform_rand(copy.deepcopy(self.results_mask)) + transform_rotate = Rotate(prob=1.0, level=10, reversal_prob=0.0) + results_rotated = transform_rotate(copy.deepcopy(self.results_mask)) + check_result_same(results_rotated, results_rand, self.check_keys) + + # test RandAugment equipped with default augmentation space + transform_rand = RandAugment() + transform_rand(copy.deepcopy(self.results_mask)) + + def test_repr(self): + aug_space = [ + [dict(type='Rotate')], + [dict(type='Invert')], + ] + transform = RandAugment(aug_space=aug_space) + self.assertEqual( + repr(transform), ('RandAugment(' + 'aug_space=[' + "[{'type': 'Rotate'}], " + "[{'type': 'Invert'}]], " + 'aug_num=2, ' + 'prob=None)')) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_colorspace.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_colorspace.py new file mode 100644 index 0000000000000000000000000000000000000000..468461b41799f27b29342091185294b7b2a98896 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_colorspace.py @@ -0,0 +1,365 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import unittest + +from mmdet.datasets.transforms import (AutoContrast, Brightness, Color, + ColorTransform, Contrast, Equalize, + Invert, Posterize, Sharpness, Solarize, + SolarizeAdd) +from .utils import check_result_same, construct_toy_data + + +class TestColorTransform(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_colortransform(self): + # test assertion for invalid value of level + with self.assertRaises(AssertionError): + transform = ColorTransform(level=-1) + + # test assertion for invalid prob + with self.assertRaises(AssertionError): + transform = ColorTransform(level=1, prob=-0.5) + + # test case when no translation is called (prob=0) + transform = ColorTransform(prob=0.0, level=10) + results_wo_color = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_color, self.check_keys) + + def test_repr(self): + transform = ColorTransform(level=10, prob=1.) + self.assertEqual( + repr(transform), ('ColorTransform(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestColor(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_color(self): + # test case when level=5 (without color aug) + transform = Color(prob=1.0, level=5) + results_wo_color = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_color, self.check_keys) + # test case when level=0 + transform = Color(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + # test case when level=10 + transform = Color(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Color(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Color(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestBrightness(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_brightness(self): + # test case when level=5 (without Brightness aug) + transform = Brightness(level=5, prob=1.0) + results_wo_brightness = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_brightness, + self.check_keys) + # test case when level=0 + transform = Brightness(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + # test case when level=10 + transform = Brightness(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Brightness(prob=1.0, level=10) + self.assertEqual( + repr(transform), ('Brightness(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestContrast(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_contrast(self): + # test case when level=5 (without Contrast aug) + transform = Contrast(prob=1.0, level=5) + results_wo_contrast = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_contrast, + self.check_keys) + # test case when level=0 + transform = Contrast(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + # test case when level=10 + transform = Contrast(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Contrast(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Contrast(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestSharpness(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_sharpness(self): + # test case when level=5 (without Sharpness aug) + transform = Sharpness(prob=1.0, level=5) + results_wo_sharpness = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_sharpness, + self.check_keys) + # test case when level=0 + transform = Sharpness(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + # test case when level=10 + transform = Sharpness(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Sharpness(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Sharpness(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestSolarize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_solarize(self): + # test case when level=10 (without Solarize aug) + transform = Solarize(prob=1.0, level=10) + results_wo_solarize = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_solarize, + self.check_keys) + # test case when level=0 + transform = Solarize(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Solarize(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Solarize(prob=1.0, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=256.0)')) + + +class TestSolarizeAdd(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_solarize(self): + # test case when level=0 (without Solarize aug) + transform = SolarizeAdd(prob=1.0, level=0) + results_wo_solarizeadd = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_solarizeadd, + self.check_keys) + # test case when level=10 + transform = SolarizeAdd(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = SolarizeAdd(level=10, prob=1.) + self.assertEqual( + repr(transform), ('SolarizeAdd(prob=1.0, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=110.0)')) + + +class TestPosterize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_posterize(self): + # test case when level=10 (without Posterize aug) + transform = Posterize(prob=1.0, level=10, max_mag=8.0) + results_wo_posterize = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_posterize, + self.check_keys) + # test case when level=0 + transform = Posterize(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Posterize(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Posterize(prob=1.0, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=4.0)')) + + +class TestEqualize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_equalize(self): + # test case when no translation is called (prob=0) + transform = Equalize(prob=0.0) + results_wo_equalize = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_equalize, + self.check_keys) + # test case when translation is called + transform = Equalize(prob=1.0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Equalize(prob=1.0) + self.assertEqual( + repr(transform), ('Equalize(prob=1.0, ' + 'level=None, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestAutoContrast(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_autocontrast(self): + # test case when no translation is called (prob=0) + transform = AutoContrast(prob=0.0) + results_wo_autocontrast = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_autocontrast, + self.check_keys) + # test case when translation is called + transform = AutoContrast(prob=1.0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = AutoContrast(prob=1.0) + self.assertEqual( + repr(transform), ('AutoContrast(prob=1.0, ' + 'level=None, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestInvert(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_invert(self): + # test case when no translation is called (prob=0) + transform = Invert(prob=0.0) + results_wo_invert = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_invert, + self.check_keys) + # test case when translation is called + transform = Invert(prob=1.0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Invert(prob=1.0) + self.assertEqual( + repr(transform), ('Invert(prob=1.0, ' + 'level=None, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_formatting.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..63719fc4b85341de489fc0f73be82addf743807c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_formatting.py @@ -0,0 +1,246 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +import unittest + +import numpy as np +import torch +from mmengine.structures import InstanceData, LabelData, PixelData + +from mmdet.datasets.transforms import (PackDetInputs, PackReIDInputs, + PackTrackInputs) +from mmdet.structures import DetDataSample, ReIDDataSample +from mmdet.structures.mask import BitmapMasks + + +class TestPackDetInputs(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + data_prefix = osp.join(osp.dirname(__file__), '../../data') + img_path = osp.join(data_prefix, 'color.jpg') + rng = np.random.RandomState(0) + self.results1 = { + 'img_id': 1, + 'img_path': img_path, + 'ori_shape': (300, 400), + 'img_shape': (600, 800), + 'scale_factor': 2.0, + 'flip': False, + 'img': rng.rand(300, 400), + 'gt_seg_map': rng.rand(300, 400), + 'gt_masks': + BitmapMasks(rng.rand(3, 300, 400), height=300, width=400), + 'gt_bboxes_labels': rng.rand(3, ), + 'gt_ignore_flags': np.array([0, 0, 1], dtype=bool), + 'proposals': rng.rand(2, 4), + 'proposals_scores': rng.rand(2, ) + } + self.results2 = { + 'img_id': 1, + 'img_path': img_path, + 'ori_shape': (300, 400), + 'img_shape': (600, 800), + 'scale_factor': 2.0, + 'flip': False, + 'img': rng.rand(300, 400), + 'gt_seg_map': rng.rand(300, 400), + 'gt_masks': + BitmapMasks(rng.rand(3, 300, 400), height=300, width=400), + 'gt_bboxes_labels': rng.rand(3, ), + 'proposals': rng.rand(2, 4), + 'proposals_scores': rng.rand(2, ) + } + self.meta_keys = ('img_id', 'img_path', 'ori_shape', 'scale_factor', + 'flip') + + def test_transform(self): + transform = PackDetInputs(meta_keys=self.meta_keys) + results = transform(copy.deepcopy(self.results1)) + self.assertIn('data_samples', results) + self.assertIsInstance(results['data_samples'], DetDataSample) + self.assertIsInstance(results['data_samples'].gt_instances, + InstanceData) + self.assertIsInstance(results['data_samples'].ignored_instances, + InstanceData) + self.assertEqual(len(results['data_samples'].gt_instances), 2) + self.assertEqual(len(results['data_samples'].ignored_instances), 1) + self.assertIsInstance(results['data_samples'].gt_sem_seg, PixelData) + self.assertIsInstance(results['data_samples'].proposals, InstanceData) + self.assertEqual(len(results['data_samples'].proposals), 2) + self.assertIsInstance(results['data_samples'].proposals.bboxes, + torch.Tensor) + self.assertIsInstance(results['data_samples'].proposals.scores, + torch.Tensor) + + def test_transform_without_ignore(self): + transform = PackDetInputs(meta_keys=self.meta_keys) + results = transform(copy.deepcopy(self.results2)) + self.assertIn('data_samples', results) + self.assertIsInstance(results['data_samples'], DetDataSample) + self.assertIsInstance(results['data_samples'].gt_instances, + InstanceData) + self.assertIsInstance(results['data_samples'].ignored_instances, + InstanceData) + self.assertEqual(len(results['data_samples'].gt_instances), 3) + self.assertEqual(len(results['data_samples'].ignored_instances), 0) + self.assertIsInstance(results['data_samples'].gt_sem_seg, PixelData) + self.assertIsInstance(results['data_samples'].proposals, InstanceData) + self.assertEqual(len(results['data_samples'].proposals), 2) + self.assertIsInstance(results['data_samples'].proposals.bboxes, + torch.Tensor) + self.assertIsInstance(results['data_samples'].proposals.scores, + torch.Tensor) + + def test_repr(self): + transform = PackDetInputs(meta_keys=self.meta_keys) + self.assertEqual( + repr(transform), f'PackDetInputs(meta_keys={self.meta_keys})') + + +class TestPackTrackInputs(unittest.TestCase): + + def setUp(self): + self.H, self.W = 5, 10 + self.img = np.zeros((self.H, self.W, 3)) + self.gt_bboxes = np.zeros((2, 4)) + self.gt_masks = BitmapMasks( + np.random.rand(2, self.H, self.W), height=self.H, width=self.W) + self.gt_bboxes_labels = [ + np.zeros((2, )), + np.zeros((2, )) + 1, + np.zeros((2, )) - 1 + ] + self.gt_instances_ids = [ + np.ones((2, ), dtype=np.int32), + np.ones((2, ), dtype=np.int32) - 1, + np.ones((2, ), dtype=np.int32) + 1 + ] + self.frame_id = [0, 1, 2] + self.scale_factor = [1.0, 1.5, 2.0] + self.flip = [False] * 3 + self.ori_shape = [(self.H, self.W)] * 3 + self.img_id = [0, 1, 2] + self.results_1 = dict( + img=[self.img.copy(), + self.img.copy(), + self.img.copy()], + gt_bboxes=[ + self.gt_bboxes.copy(), + self.gt_bboxes.copy(), + self.gt_bboxes.copy() + ], + gt_bboxes_labels=copy.deepcopy(self.gt_bboxes_labels), + gt_instances_ids=copy.deepcopy(self.gt_instances_ids), + gt_masks=[ + copy.deepcopy(self.gt_masks), + copy.deepcopy(self.gt_masks), + copy.deepcopy(self.gt_masks) + ], + frame_id=self.frame_id, + ori_shape=self.ori_shape, + scale_factor=self.scale_factor, + flip=self.flip, + img_id=self.img_id, + key_frame_flags=[False, True, False]) + + self.results_2 = copy.deepcopy(self.results_1) + self.gt_ignore_flags = [ + np.array([0, 1], dtype=np.bool), + np.array([1, 0], dtype=np.bool), + np.array([0, 0], dtype=np.bool) + ] + self.results_2.update( + dict(gt_ignore_flags=copy.deepcopy(self.gt_ignore_flags))) + + self.meta_keys = ('frame_id', 'ori_shape', 'scale_factor', 'flip') + self.pack_track_inputs = PackTrackInputs(meta_keys=self.meta_keys) + + def test_transform_without_ignore(self): + track_results = self.pack_track_inputs(self.results_1) + assert isinstance(track_results, dict) + + inputs = track_results['inputs'] + assert isinstance(inputs, torch.Tensor) + assert inputs.shape == (3, 3, self.H, self.W) + + track_data_sample = track_results['data_samples'] + assert len(track_data_sample) == 3 + assert 'key_frames_inds' in track_data_sample.metainfo and \ + track_data_sample.key_frames_inds == [1] + assert 'ref_frames_inds' in track_data_sample.metainfo and \ + track_data_sample.ref_frames_inds == [0, 2] + for i, data_sample in enumerate(track_data_sample): + assert data_sample.gt_instances.bboxes.shape == (2, 4) + assert len(data_sample.gt_instances.masks) == 2 + assert (data_sample.gt_instances.labels.numpy() == + self.gt_bboxes_labels[i]).all() + assert (data_sample.gt_instances.instances_ids.numpy() == + self.gt_instances_ids[i]).all() + for key in self.meta_keys: + assert data_sample.metainfo[key] == getattr(self, key)[i] + + def test_transform_with_ignore(self): + track_results = self.pack_track_inputs(self.results_2) + assert isinstance(track_results, dict) + + inputs = track_results['inputs'] + assert isinstance(inputs, torch.Tensor) + assert inputs.shape == (3, 3, self.H, self.W) + + track_data_sample = track_results['data_samples'] + assert len(track_data_sample) == 3 + for i, data_sample in enumerate(track_data_sample): + valid_mask = ~self.gt_ignore_flags[i] + valid_len = valid_mask.sum().item() + assert data_sample.gt_instances.bboxes.shape == (valid_len, 4) + assert len(data_sample.gt_instances.masks) == valid_len + assert (data_sample.gt_instances.labels.numpy() == + self.gt_bboxes_labels[i][valid_mask]).all() + assert (data_sample.gt_instances.instances_ids.numpy() == + self.gt_instances_ids[i][valid_mask]).all() + for key in self.meta_keys: + assert data_sample.metainfo[key] == getattr(self, key)[i] + + +class TestPackReIDInputs(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.results = dict( + img=np.random.randn(256, 128, 3), + gt_label=0, + img_path='', + ori_shape=(128, 128), + img_shape=(256, 128), + scale=(128, 256), + scale_factor=(1., 2.), + flip=False, + flip_direction=None) + cls.pack_reid_inputs = PackReIDInputs( + meta_keys=('flip', 'flip_direction')) + + def test_transform(self): + results = self.pack_reid_inputs(self.results) + self.assertIn('inputs', results) + self.assertIsInstance(results['inputs'], torch.Tensor) + self.assertIn('data_samples', results) + data_sample = results['data_samples'] + self.assertIsInstance(data_sample, ReIDDataSample) + self.assertIsInstance(data_sample.gt_label, LabelData) + self.assertEqual(data_sample.img_path, '') + self.assertEqual(data_sample.ori_shape, (128, 128)) + self.assertEqual(data_sample.img_shape, (256, 128)) + self.assertEqual(data_sample.scale, (128, 256)) + self.assertEqual(data_sample.scale_factor, (1., 2.)) + self.assertEqual(data_sample.flip, False) + self.assertIsNone(data_sample.flip_direction) + + def test_repr(self): + self.assertEqual( + repr(self.pack_reid_inputs), + f'PackReIDInputs(meta_keys={self.pack_reid_inputs.meta_keys})') diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_frame_sampling.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_frame_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..fa995e3c769b7d0d74fa0ad97950abf65331cd4e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_frame_sampling.py @@ -0,0 +1,119 @@ +import unittest + +import numpy as np + +from mmdet.datasets.transforms import BaseFrameSample, UniformRefFrameSample + + +class TestFrameSample(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() + -> tearDown() -> cleanUp() + """ + self.H, self.W = 5, 8 + self.img = np.zeros((self.H, self.W, 3)) + self.gt_bboxes = np.zeros((2, 4)) + self.gt_bboxes_labels = [ + np.zeros((2, )), + np.zeros((2, )) + 1, + np.zeros((2, )) - 1 + ] + self.gt_instances_id = [ + np.ones((2, ), dtype=np.int32), + np.ones((2, ), dtype=np.int32) - 1, + np.ones((2, ), dtype=np.int32) + 1 + ] + self.frame_id = [0, 1, 2] + self.scale_factor = [1.0, 1.5, 2.0] + self.flip = [False] * 3 + self.ori_shape = [(self.H, self.W)] * 3 + self.img_id = [0, 1, 2] + + self.video_infos = dict(video_id=0, video_length=10, key_frame_id=4) + self.video_infos['images'] = [] + self.info_keys = [ + 'video_id', 'video_length', 'img', 'gt_bboxes', 'gt_bboxes_labels', + 'gt_instances_id', 'img_id', 'frame_id' + ] + for i in range(10): + frame_info = dict( + img=np.zeros((self.H, self.W, 3)) + i, + gt_bboxes=np.zeros((2, 4)) + i, + gt_bboxes_labels=np.zeros((2, )) + i, + gt_instances_id=np.zeros((2, ), dtype=np.int32) + i, + ori_shape=(self.H + i, self.W + i), + frame_id=i, + img_id=i) + self.video_infos['images'].append(frame_info) + + def test_base_frame_sample(self): + sampler = BaseFrameSample() + results = sampler(self.video_infos) + assert isinstance(results, dict) + for key in self.info_keys: + assert key in results + assert len(results[key]) == 1 + if key == 'frame_id': + assert results[key] == [4] + + key_frame_id = self.video_infos['key_frame_id'] + assert (results['img'][0] == np.zeros( + (self.H, self.W, 3)) + key_frame_id).all() + assert (results['gt_bboxes'][0] == np.zeros( + (2, 4)) + key_frame_id).all() + assert (results['gt_bboxes_labels'][0] == np.zeros( + (2, )) + key_frame_id).all() + assert (results['gt_instances_id'][0] == np.zeros( + (2, )) + key_frame_id).all() + assert results['ori_shape'][0] == (self.H + key_frame_id, + self.W + key_frame_id) + assert results['img_id'][0] == key_frame_id + + def test_uniform_ref_frame_sample(self): + sampler = UniformRefFrameSample( + num_ref_imgs=2, frame_range=[-1, 1], filter_key_img=True) + results = sampler(self.video_infos) + assert isinstance(results, dict) + for key in self.info_keys: + assert key in results + assert len(results[key]) == 3 + if key == 'frame_id': + assert results[key] == [3, 4, 5] + + key_frame_id = self.video_infos['key_frame_id'] + assert (results['img'][1] == np.zeros( + (self.H, self.W, 3)) + key_frame_id).all() + assert (results['gt_bboxes'][1] == np.zeros( + (2, 4)) + key_frame_id).all() + assert (results['gt_bboxes_labels'][1] == np.zeros( + (2, )) + key_frame_id).all() + assert (results['gt_instances_id'][1] == np.zeros( + (2, )) + key_frame_id).all() + assert results['ori_shape'][1] == (self.H + key_frame_id, + self.W + key_frame_id) + assert results['img_id'][1] == key_frame_id + + # test the filter_key_img and the correctness of returned frame index + sampler = UniformRefFrameSample( + num_ref_imgs=2, frame_range=[0, 1], filter_key_img=False) + results = sampler(self.video_infos) + assert 4 in results['img_id'] and results['img_id'].count(4) == 2 + assert 5 in results['img_id'] and results['img_id'].count(5) == 1 + assert results['key_frame_flags'] == [True, False, False] + + def test_repr(self): + transform = BaseFrameSample() + self.assertEqual( + repr(transform), + "BaseFrameSample(collect_video_keys=['video_id', 'video_length'])") + + transform = UniformRefFrameSample( + num_ref_imgs=2, frame_range=10, filter_key_img=True) + self.assertEqual( + repr(transform), + ('UniformRefFrameSample(num_ref_imgs=2, ' + 'frame_range=[-10, 10], filter_key_img=True, ' + "collect_video_keys=['video_id', 'video_length'])")) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_geometric.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_geometric.py new file mode 100644 index 0000000000000000000000000000000000000000..e13b13d75aa1502966195076dc29c57039d04ce7 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_geometric.py @@ -0,0 +1,752 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import unittest + +import numpy as np + +from mmdet.datasets.transforms import (GeomTransform, Rotate, ShearX, ShearY, + TranslateX, TranslateY) +from mmdet.structures.bbox import HorizontalBoxes +from mmdet.structures.mask import BitmapMasks, PolygonMasks +from .utils import check_result_same, construct_toy_data + + +class TestGeomTransform(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_geomtransform(self): + # test assertion for invalid prob + with self.assertRaises(AssertionError): + transform = GeomTransform( + prob=-0.5, level=1, min_mag=0.0, max_mag=1.0) + + # test assertion for invalid value of level + with self.assertRaises(AssertionError): + transform = GeomTransform( + prob=0.5, level=-1, min_mag=0.0, max_mag=1.0) + + # test assertion for invalid value of min_mag and max_mag + with self.assertRaises(AssertionError): + transform = ShearX(prob=0.5, level=2, min_mag=1.0, max_mag=0.0) + + # test assertion for the num of elements in tuple img_border_value + with self.assertRaises(AssertionError): + transform = GeomTransform( + prob=0.5, + level=1, + min_mag=0.0, + max_mag=1.0, + img_border_value=(128, 128, 128, 128)) + + # test ValueError for invalid type of img_border_value + with self.assertRaises(ValueError): + transform = GeomTransform( + prob=0.5, + level=1, + min_mag=0.0, + max_mag=1.0, + img_border_value=[128, 128, 128]) + + # test assertion for invalid value of img_border_value + with self.assertRaises(AssertionError): + transform = GeomTransform( + prob=0.5, + level=1, + min_mag=0.0, + max_mag=1.0, + img_border_value=(128, -1, 256)) + + # test case when no aug (prob=0) + transform = GeomTransform( + prob=0., + level=10, + min_mag=0.0, + max_mag=1.0, + img_border_value=self.img_border_value) + results_wo_aug = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_aug, self.check_keys) + + def test_repr(self): + transform = GeomTransform( + prob=0.5, + level=5, + min_mag=0.0, + max_mag=1.0, + ) + self.assertEqual( + repr(transform), ('GeomTransform(prob=0.5, ' + 'level=5, ' + 'min_mag=0.0, ' + 'max_mag=1.0, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestShearX(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_shearx(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = ShearX(prob=0.5, level=2, min_mag=-30.) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = ShearX(prob=0.5, level=2, max_mag=100.) + + # test case when no shear horizontally (level=0) + transform = ShearX( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_shearx = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_shearx, + self.check_keys) + + # test shear horizontally, magnitude=-1 + transform = ShearX( + prob=1.0, + level=10, + max_mag=45., + reversal_prob=1.0, + img_border_value=self.img_border_value) + results_sheared = transform(copy.deepcopy(self.results_mask)) + results_gt = copy.deepcopy(self.results_mask) + img_gt = np.array([[1, 2, 3, 4], [0, 5, 6, 7], [0, 0, 9, 10]], + dtype=np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + img_gt[1, 0, :] = np.array(self.img_border_value) + img_gt[2, 0, :] = np.array(self.img_border_value) + img_gt[2, 1, :] = np.array(self.img_border_value) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[1, 0, 4, 2]], dtype=np.float32) + results_gt['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + gt_masks = np.array([[0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 255, 13, 13], [255, 255, 255, 13]], + dtype=self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_sheared, self.check_keys) + + # test PolygonMasks with shear horizontally, magnitude=1 + results_sheared = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([3, 2, 1, 0, 3, 1], dtype=np.float32)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_sheared, self.check_keys) + + def test_shearx_use_box_type(self): + # test case when no shear horizontally (level=0) + transform = ShearX( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_shearx = transform(copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_shearx, + self.check_keys) + + # test shear horizontally, magnitude=-1 + transform = ShearX( + prob=1.0, + level=10, + max_mag=45., + reversal_prob=1.0, + img_border_value=self.img_border_value) + results_sheared = transform(copy.deepcopy(self.results_mask_boxtype)) + results_gt = copy.deepcopy(self.results_mask_boxtype) + img_gt = np.array([[1, 2, 3, 4], [0, 5, 6, 7], [0, 0, 9, 10]], + dtype=np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + img_gt[1, 0, :] = np.array(self.img_border_value) + img_gt[2, 0, :] = np.array(self.img_border_value) + img_gt[2, 1, :] = np.array(self.img_border_value) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[1, 0, 4, 2]], dtype=np.float32)) + results_gt['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + gt_masks = np.array([[0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 255, 13, 13], [255, 255, 255, 13]], + dtype=self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_sheared, self.check_keys) + + def test_repr(self): + transform = ShearX(prob=0.5, level=10) + self.assertEqual( + repr(transform), ('ShearX(prob=0.5, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=30.0, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestShearY(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_sheary(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = ShearY(prob=0.5, level=2, min_mag=-30.) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = ShearY(prob=0.5, level=2, max_mag=100.) + + # test case when no shear vertically (level=0) + transform = ShearY( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_sheary = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_sheary, + self.check_keys) + + # test shear vertically, magnitude=1 + transform = ShearY(prob=1., level=10, max_mag=45., reversal_prob=0.) + results_sheared = transform(copy.deepcopy(self.results_mask)) + results_gt = copy.deepcopy(self.results_mask) + img_gt = np.array( + [[1, 6, 11, 128], [5, 10, 128, 128], [9, 128, 128, 128]], + dtype=np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[1, 0, 2, 1]], dtype=np.float32) + results_gt['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + gt_masks = np.array([[0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 13, 255, 255], [255, 255, 255, 255]], + dtype=self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_sheared, self.check_keys) + + # test PolygonMasks with shear vertically, magnitude=-1 + results_sheared = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([1, 1, 1, 0, 2, 0], dtype=np.float32)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_sheared, self.check_keys) + + def test_sheary_use_box_type(self): + # test case when no shear vertically (level=0) + transform = ShearY( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_sheary = transform(copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_sheary, + self.check_keys) + + # test shear vertically, magnitude=1 + transform = ShearY(prob=1., level=10, max_mag=45., reversal_prob=0.) + results_sheared = transform(copy.deepcopy(self.results_mask_boxtype)) + results_gt = copy.deepcopy(self.results_mask_boxtype) + img_gt = np.array( + [[1, 6, 11, 128], [5, 10, 128, 128], [9, 128, 128, 128]], + dtype=np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[1, 0, 2, 1]], dtype=np.float32)) + results_gt['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + gt_masks = np.array([[0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 13, 255, 255], [255, 255, 255, 255]], + dtype=self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_sheared, self.check_keys) + + def test_repr(self): + transform = ShearY(prob=0.5, level=10) + self.assertEqual( + repr(transform), ('ShearY(prob=0.5, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=30.0, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestRotate(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_rotate(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = ShearY(prob=0.5, level=2, min_mag=-90.0) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = ShearY(prob=0.5, level=2, max_mag=270.0) + + # test case when no rotate aug (level=0) + transform = Rotate( + prob=1., + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_rotate = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_rotate, + self.check_keys) + + # test clockwise rotation with angle 90 + transform = Rotate( + prob=1., + level=10, + max_mag=90.0, + # set reversal_prob to 1 for clockwise rotation + reversal_prob=1., + ) + results_rotated = transform(copy.deepcopy(self.results_mask)) + # The image, masks, and semantic segmentation map + # will be bilinearly interpolated. + img_gt = np.array([[69, 8, 4, 65], [69, 9, 5, 65], + [70, 10, 6, 66]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[0.5, 0.5, 2.5, 1.5]], + dtype=np.float32) + gt_masks = np.array([[0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 13, 13], [255, 255, 13, 255], + [255, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_rotated, self.check_keys) + + # test clockwise rotation with angle 90, PolygonMasks + results_rotated = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([0, 1, 0, 1, 0, 2], dtype=np.float)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_rotated, self.check_keys) + + # test counter-clockwise rotation with angle 90 + transform = Rotate( + prob=1.0, + level=10, + max_mag=90.0, + # set reversal_prob to 0 for counter-clockwise rotation + reversal_prob=0.0, + ) + results_rotated = transform(copy.deepcopy(self.results_mask)) + # The image, masks, and semantic segmentation map + # will be bilinearly interpolated. + img_gt = np.array([[66, 6, 10, 70], [65, 5, 9, 69], + [65, 4, 8, 69]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[0.5, 0.5, 2.5, 1.5]], + dtype=np.float32) + gt_masks = np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 255, 255, 255], [255, 13, 255, 255], + [13, 13, 13, 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_rotated, self.check_keys) + + # test counter-clockwise rotation with angle 90, PolygonMasks + results_rotated = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([2, 0, 0, 0, 1, 0], dtype=np.float)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_rotated, self.check_keys) + + def test_rotate_use_box_type(self): + # test case when no rotate aug (level=0) + transform = Rotate( + prob=1., + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_rotate = transform(copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_rotate, + self.check_keys) + + # test clockwise rotation with angle 90 + transform = Rotate( + prob=1., + level=10, + max_mag=90.0, + # set reversal_prob to 1 for clockwise rotation + reversal_prob=1., + ) + results_rotated = transform(copy.deepcopy(self.results_mask_boxtype)) + # The image, masks, and semantic segmentation map + # will be bilinearly interpolated. + img_gt = np.array([[69, 8, 4, 65], [69, 9, 5, 65], + [70, 10, 6, 66]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask_boxtype) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[0.5, 0.5, 2.5, 1.5]], dtype=np.float32)) + gt_masks = np.array([[0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 13, 13], [255, 255, 13, 255], + [255, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_rotated, self.check_keys) + + # test counter-clockwise rotation with angle 90 + transform = Rotate( + prob=1.0, + level=10, + max_mag=90.0, + # set reversal_prob to 0 for counter-clockwise rotation + reversal_prob=0.0, + ) + results_rotated = transform(copy.deepcopy(self.results_mask_boxtype)) + # The image, masks, and semantic segmentation map + # will be bilinearly interpolated. + img_gt = np.array([[66, 6, 10, 70], [65, 5, 9, 69], + [65, 4, 8, 69]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask_boxtype) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[0.5, 0.5, 2.5, 1.5]], dtype=np.float32)) + gt_masks = np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 255, 255, 255], [255, 13, 255, 255], + [13, 13, 13, 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_rotated, self.check_keys) + + def test_repr(self): + transform = Rotate(prob=0.5, level=5) + self.assertEqual( + repr(transform), ('Rotate(prob=0.5, ' + 'level=5, ' + 'min_mag=0.0, ' + 'max_mag=30.0, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestTranslateX(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_translatex(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = TranslateX(prob=0.5, level=2, min_mag=-1.) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = TranslateX(prob=0.5, level=2, max_mag=1.1) + + # test case when level=0 (without translate aug) + transform = TranslateX( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_wo_translatex = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_translatex, + self.check_keys) + + # test translate horizontally, magnitude=-1 + transform = TranslateX( + prob=1.0, + level=10, + max_mag=0.3, + reversal_prob=0.0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_translated = transform(copy.deepcopy(self.results_mask)) + img_gt = np.array([[2, 3, 4, 0], [6, 7, 8, 0], [10, 11, 12, + 0]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + img_gt[:, 3, :] = np.array(self.img_border_value) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[0, 0, 1, 2]], dtype=np.float32) + gt_masks = np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[13, 255, 255, 255], [13, 13, 255, 255], + [13, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_translated, self.check_keys) + + # test PolygonMasks with translate horizontally. + results_translated = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([0, 2, 0, 0, 1, 1], dtype=np.float32)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_translated, self.check_keys) + + def test_translatex_use_box_type(self): + # test case when level=0 (without translate aug) + transform = TranslateX( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_wo_translatex = transform( + copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_translatex, + self.check_keys) + + # test translate horizontally, magnitude=-1 + transform = TranslateX( + prob=1.0, + level=10, + max_mag=0.3, + reversal_prob=0.0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_translated = transform( + copy.deepcopy(self.results_mask_boxtype)) + img_gt = np.array([[2, 3, 4, 0], [6, 7, 8, 0], [10, 11, 12, + 0]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + img_gt[:, 3, :] = np.array(self.img_border_value) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[0, 0, 1, 2]], dtype=np.float32)) + gt_masks = np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[13, 255, 255, 255], [13, 13, 255, 255], + [13, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_translated, self.check_keys) + + def test_repr(self): + transform = TranslateX(prob=0.5, level=5) + self.assertEqual( + repr(transform), ('TranslateX(prob=0.5, ' + 'level=5, ' + 'min_mag=0.0, ' + 'max_mag=0.1, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestTranslateY(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_translatey(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = TranslateY(prob=0.5, level=2, min_mag=-1.0) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = TranslateY(prob=0.5, level=2, max_mag=1.1) + + # test case when level=0 (without translate aug) + transform = TranslateY( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_wo_translatey = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_translatey, + self.check_keys) + + # test translate vertically, magnitude=-1 + transform = TranslateY( + prob=1.0, + level=10, + max_mag=0.4, + reversal_prob=0.0, + seg_ignore_label=self.seg_ignore_label) + + results_translated = transform(copy.deepcopy(self.results_mask)) + img_gt = np.array([[5, 6, 7, 8], [9, 10, 11, 12], + [128, 128, 128, 128]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[1, 0, 2, 1]], dtype=np.float32) + gt_masks = np.array([[0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 13, 255], [255, 13, 255, 255], + [255, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_translated, self.check_keys) + + # test PolygonMasks with translate vertically. + results_translated = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([1, 1, 1, 0, 2, 0], dtype=np.float32)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_translated, self.check_keys) + + def test_translatey_use_box_type(self): + # test case when level=0 (without translate aug) + transform = TranslateY( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_wo_translatey = transform( + copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_translatey, + self.check_keys) + + # test translate vertically, magnitude=-1 + transform = TranslateY( + prob=1.0, + level=10, + max_mag=0.4, + reversal_prob=0.0, + seg_ignore_label=self.seg_ignore_label) + + results_translated = transform( + copy.deepcopy(self.results_mask_boxtype)) + img_gt = np.array([[5, 6, 7, 8], [9, 10, 11, 12], + [128, 128, 128, 128]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask_boxtype) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[1, 0, 2, 1]], dtype=np.float32)) + gt_masks = np.array([[0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 13, 255], [255, 13, 255, 255], + [255, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_translated, self.check_keys) + + def test_repr(self): + transform = TranslateX(prob=0.5, level=5) + self.assertEqual( + repr(transform), ('TranslateX(prob=0.5, ' + 'level=5, ' + 'min_mag=0.0, ' + 'max_mag=0.1, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_instaboost.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_instaboost.py new file mode 100644 index 0000000000000000000000000000000000000000..325b737ea6002d9d824c831ce8a7d43f7a38e5c4 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_instaboost.py @@ -0,0 +1,58 @@ +import os.path as osp +import unittest + +import numpy as np + +from mmdet.registry import TRANSFORMS +from mmdet.utils import register_all_modules + +register_all_modules() + + +class TestInstaboost(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + img_path = osp.join(osp.dirname(__file__), '../../data/gray.jpg') + self.results = { + 'img_path': + img_path, + 'img_shape': (300, 400), + 'instances': [{ + 'bbox': [0, 0, 10, 20], + 'bbox_label': 1, + 'mask': [[0, 0, 0, 20, 10, 20, 10, 0]], + 'ignore_flag': 0 + }, { + 'bbox': [10, 10, 110, 120], + 'bbox_label': 2, + 'mask': [[10, 10, 110, 10, 110, 120, 110, 10]], + 'ignore_flag': 0 + }, { + 'bbox': [50, 50, 60, 80], + 'bbox_label': 2, + 'mask': [[50, 50, 60, 50, 60, 80, 50, 80]], + 'ignore_flag': 1 + }] + } + + def test_transform(self): + load = TRANSFORMS.build(dict(type='LoadImageFromFile')) + instaboost_transform = TRANSFORMS.build(dict(type='InstaBoost')) + + # Execute transforms + results = load(self.results) + results = instaboost_transform(results) + + self.assertEqual(results['img'].dtype, np.uint8) + self.assertIn('instances', results) + + def test_repr(self): + instaboost_transform = TRANSFORMS.build(dict(type='InstaBoost')) + + self.assertEqual( + repr(instaboost_transform), 'InstaBoost(aug_ratio=0.5)') diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_loading.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..840ad51c4ed85782d80ddcbb42803e39732ab456 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_loading.py @@ -0,0 +1,539 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os +import os.path as osp +import sys +import unittest +from unittest.mock import MagicMock, Mock, patch + +import mmcv +import numpy as np + +from mmdet.datasets.transforms import (FilterAnnotations, LoadAnnotations, + LoadEmptyAnnotations, + LoadImageFromNDArray, + LoadMultiChannelImageFromFiles, + LoadProposals, LoadTrackAnnotations) +from mmdet.evaluation import INSTANCE_OFFSET +from mmdet.structures.mask import BitmapMasks, PolygonMasks + +try: + import panopticapi +except ImportError: + panopticapi = None + + +class TestLoadAnnotations(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + data_prefix = osp.join(osp.dirname(__file__), '../../data') + seg_map = osp.join(data_prefix, 'gray.jpg') + self.results = { + 'ori_shape': (300, 400), + 'seg_map_path': + seg_map, + 'instances': [{ + 'bbox': [0, 0, 10, 20], + 'bbox_label': 1, + 'mask': [[0, 0, 0, 20, 10, 20, 10, 0]], + 'ignore_flag': 0 + }, { + 'bbox': [10, 10, 110, 120], + 'bbox_label': 2, + 'mask': [[10, 10, 110, 10, 110, 120, 110, 10]], + 'ignore_flag': 0 + }, { + 'bbox': [50, 50, 60, 80], + 'bbox_label': 2, + 'mask': [[50, 50, 60, 50, 60, 80, 50, 80]], + 'ignore_flag': 1 + }] + } + + def test_load_bboxes(self): + transform = LoadAnnotations( + with_bbox=True, + with_label=False, + with_seg=False, + with_mask=False, + box_type=None) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_bboxes', results) + self.assertTrue((results['gt_bboxes'] == np.array([[0, 0, 10, 20], + [10, 10, 110, 120], + [50, 50, 60, + 80]])).all()) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + self.assertTrue((results['gt_ignore_flags'] == np.array([0, 0, + 1])).all()) + self.assertEqual(results['gt_ignore_flags'].dtype, bool) + + def test_load_labels(self): + transform = LoadAnnotations( + with_bbox=False, + with_label=True, + with_seg=False, + with_mask=False, + ) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_bboxes_labels', results) + self.assertTrue((results['gt_bboxes_labels'] == np.array([1, 2, + 2])).all()) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + + def test_load_mask(self): + transform = LoadAnnotations( + with_bbox=False, + with_label=False, + with_seg=False, + with_mask=True, + poly2mask=False) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_masks', results) + self.assertEqual(len(results['gt_masks']), 3) + self.assertIsInstance(results['gt_masks'], PolygonMasks) + + def test_load_mask_poly2mask(self): + transform = LoadAnnotations( + with_bbox=False, + with_label=False, + with_seg=False, + with_mask=True, + poly2mask=True) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_masks', results) + self.assertEqual(len(results['gt_masks']), 3) + self.assertIsInstance(results['gt_masks'], BitmapMasks) + + def test_load_semseg(self): + transform = LoadAnnotations( + with_bbox=False, with_label=False, with_seg=True, with_mask=False) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_seg_map', results) + self.assertIn('ignore_index', results) + self.assertEqual(results['gt_seg_map'].shape, (288, 512)) + + # test reduce_zero_label and ignore_index + transform = LoadAnnotations( + with_bbox=False, + with_label=False, + with_seg=True, + with_mask=False, + reduce_zero_label=True, + ignore_index=10) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_seg_map', results) + self.assertIn('ignore_index', results) + self.assertEqual(results['ignore_index'], 10) + self.assertEqual(results['gt_seg_map'].shape, (288, 512)) + + def test_repr(self): + transform = LoadAnnotations( + with_bbox=True, + with_label=False, + with_seg=False, + with_mask=False, + ) + self.assertEqual( + repr(transform), ('LoadAnnotations(with_bbox=True, ' + 'with_label=False, with_mask=False, ' + 'with_seg=False, poly2mask=True, ' + "imdecode_backend='cv2', " + 'backend_args=None)')) + + +class TestFilterAnnotations(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]]), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=np.bool8), + 'gt_masks': + BitmapMasks(rng.rand(3, 224, 224), height=224, width=224), + } + + def test_transform(self): + # test keep_empty = True + transform = FilterAnnotations( + min_gt_bbox_wh=(50, 50), + keep_empty=True, + ) + results = transform(copy.deepcopy(self.results)) + self.assertIsNone(results) + + # test keep_empty = False + transform = FilterAnnotations( + min_gt_bbox_wh=(50, 50), + keep_empty=False, + ) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(isinstance(results, dict)) + + # test filter annotations + transform = FilterAnnotations(min_gt_bbox_wh=(15, 15), ) + results = transform(copy.deepcopy(self.results)) + + self.assertIsInstance(results, dict) + self.assertTrue((results['gt_bboxes_labels'] == np.array([2, + 3])).all()) + self.assertTrue((results['gt_bboxes'] == np.array([[20, 20, 40, 40], + [40, 40, 80, + 80]])).all()) + self.assertEqual(len(results['gt_masks']), 2) + self.assertEqual(len(results['gt_ignore_flags']), 2) + + def test_repr(self): + transform = FilterAnnotations( + min_gt_bbox_wh=(1, 1), + keep_empty=False, + ) + self.assertEqual( + repr(transform), ('FilterAnnotations(min_gt_bbox_wh=(1, 1), ' + 'keep_empty=False)')) + + +class TestLoadPanopticAnnotations(unittest.TestCase): + + def setUp(self): + seg_map = np.zeros((10, 10), dtype=np.int32) + seg_map[:5, :10] = 1 + 10 * INSTANCE_OFFSET + seg_map[5:10, :5] = 4 + 11 * INSTANCE_OFFSET + seg_map[5:10, 5:10] = 6 + 0 * INSTANCE_OFFSET + rgb_seg_map = np.zeros((10, 10, 3), dtype=np.uint8) + rgb_seg_map[:, :, 0] = seg_map / (256 * 256) + rgb_seg_map[:, :, 1] = seg_map % (256 * 256) / 256 + rgb_seg_map[:, :, 2] = seg_map % 256 + self.seg_map_path = './1.png' + mmcv.imwrite(rgb_seg_map, self.seg_map_path) + + self.seg_map = seg_map + self.rgb_seg_map = rgb_seg_map + self.results = { + 'ori_shape': (10, 10), + 'instances': [{ + 'bbox': [0, 0, 10, 5], + 'bbox_label': 0, + 'ignore_flag': 0, + }, { + 'bbox': [0, 5, 5, 10], + 'bbox_label': 1, + 'ignore_flag': 1, + }], + 'segments_info': [ + { + 'id': 1 + 10 * INSTANCE_OFFSET, + 'category': 0, + 'is_thing': True, + }, + { + 'id': 4 + 11 * INSTANCE_OFFSET, + 'category': 1, + 'is_thing': True, + }, + { + 'id': 6 + 0 * INSTANCE_OFFSET, + 'category': 2, + 'is_thing': False, + }, + ], + 'seg_map_path': + self.seg_map_path + } + + self.gt_mask = BitmapMasks([ + (seg_map == 1 + 10 * INSTANCE_OFFSET).astype(np.uint8), + (seg_map == 4 + 11 * INSTANCE_OFFSET).astype(np.uint8), + ], 10, 10) + self.gt_bboxes = np.array([[0, 0, 10, 5], [0, 5, 5, 10]], + dtype=np.float32) + self.gt_bboxes_labels = np.array([0, 1], dtype=np.int64) + self.gt_ignore_flags = np.array([0, 1], dtype=bool) + self.gt_seg_map = np.zeros((10, 10), dtype=np.int32) + self.gt_seg_map[:5, :10] = 0 + self.gt_seg_map[5:10, :5] = 1 + self.gt_seg_map[5:10, 5:10] = 2 + + def tearDown(self): + os.remove(self.seg_map_path) + + @unittest.skipIf(panopticapi is not None, 'panopticapi is installed') + def test_init_without_panopticapi(self): + # test if panopticapi is not installed + from mmdet.datasets.transforms import LoadPanopticAnnotations + with self.assertRaisesRegex( + ImportError, + 'panopticapi is not installed, please install it by'): + LoadPanopticAnnotations() + + def test_transform(self): + sys.modules['panopticapi'] = MagicMock() + sys.modules['panopticapi.utils'] = MagicMock() + from mmdet.datasets.transforms import LoadPanopticAnnotations + mock_rgb2id = Mock(return_value=self.seg_map) + with patch('panopticapi.utils.rgb2id', mock_rgb2id): + # test with all False + transform = LoadPanopticAnnotations( + with_bbox=False, + with_label=False, + with_mask=False, + with_seg=False) + results = transform(copy.deepcopy(self.results)) + self.assertDictEqual(results, self.results) + # test with with_mask=True + transform = LoadPanopticAnnotations( + with_bbox=False, + with_label=False, + with_mask=True, + with_seg=False) + results = transform(copy.deepcopy(self.results)) + self.assertTrue( + (results['gt_masks'].masks == self.gt_mask.masks).all()) + + # test with with_seg=True + transform = LoadPanopticAnnotations( + with_bbox=False, + with_label=False, + with_mask=False, + with_seg=True) + results = transform(copy.deepcopy(self.results)) + self.assertNotIn('gt_masks', results) + self.assertTrue((results['gt_seg_map'] == self.gt_seg_map).all()) + + # test with all True + transform = LoadPanopticAnnotations( + with_bbox=True, + with_label=True, + with_mask=True, + with_seg=True, + box_type=None) + results = transform(copy.deepcopy(self.results)) + self.assertTrue( + (results['gt_masks'].masks == self.gt_mask.masks).all()) + self.assertTrue((results['gt_bboxes'] == self.gt_bboxes).all()) + self.assertTrue( + (results['gt_bboxes_labels'] == self.gt_bboxes_labels).all()) + self.assertTrue( + (results['gt_ignore_flags'] == self.gt_ignore_flags).all()) + self.assertTrue((results['gt_seg_map'] == self.gt_seg_map).all()) + + +class TestLoadImageFromNDArray(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.results = {'img': np.zeros((256, 256, 3), dtype=np.uint8)} + + def test_transform(self): + transform = LoadImageFromNDArray() + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape, (256, 256, 3)) + self.assertEqual(results['img'].dtype, np.uint8) + self.assertEqual(results['img_shape'], (256, 256)) + self.assertEqual(results['ori_shape'], (256, 256)) + + # to_float32 + transform = LoadImageFromNDArray(to_float32=True) + results = transform(copy.deepcopy(results)) + self.assertEqual(results['img'].dtype, np.float32) + + def test_repr(self): + transform = LoadImageFromNDArray() + self.assertEqual( + repr(transform), ('LoadImageFromNDArray(' + 'ignore_empty=False, ' + 'to_float32=False, ' + "color_type='color', " + "imdecode_backend='cv2', " + 'backend_args=None)')) + + +class TestLoadMultiChannelImageFromFiles(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.img_path = [] + for i in range(4): + img_channel_path = f'./part_{i}.jpg' + img_channel = np.zeros((10, 10), dtype=np.uint8) + mmcv.imwrite(img_channel, img_channel_path) + self.img_path.append(img_channel_path) + self.results = {'img_path': self.img_path} + + def tearDown(self): + for filename in self.img_path: + os.remove(filename) + + def test_transform(self): + transform = LoadMultiChannelImageFromFiles() + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape, (10, 10, 4)) + self.assertEqual(results['img'].dtype, np.uint8) + self.assertEqual(results['img_shape'], (10, 10)) + self.assertEqual(results['ori_shape'], (10, 10)) + + # to_float32 + transform = LoadMultiChannelImageFromFiles(to_float32=True) + results = transform(copy.deepcopy(results)) + self.assertEqual(results['img'].dtype, np.float32) + + def test_rper(self): + transform = LoadMultiChannelImageFromFiles() + self.assertEqual( + repr(transform), ('LoadMultiChannelImageFromFiles(' + 'to_float32=False, ' + "color_type='unchanged', " + "imdecode_backend='cv2', " + 'backend_args=None)')) + + +class TestLoadProposals(unittest.TestCase): + + def test_transform(self): + transform = LoadProposals() + results = { + 'proposals': + dict( + bboxes=np.zeros((5, 4), dtype=np.int64), + scores=np.zeros((5, ), dtype=np.int64)) + } + results = transform(results) + self.assertEqual(results['proposals'].dtype, np.float32) + self.assertEqual(results['proposals'].shape[-1], 4) + self.assertEqual(results['proposals_scores'].dtype, np.float32) + + # bboxes.shape[1] should be 4 + results = {'proposals': dict(bboxes=np.zeros((5, 5), dtype=np.int64))} + with self.assertRaises(AssertionError): + transform(results) + + # bboxes.shape[0] should equal to scores.shape[0] + results = { + 'proposals': + dict( + bboxes=np.zeros((5, 4), dtype=np.int64), + scores=np.zeros((3, ), dtype=np.int64)) + } + with self.assertRaises(AssertionError): + transform(results) + + # empty bboxes + results = { + 'proposals': dict(bboxes=np.zeros((0, 4), dtype=np.float32)) + } + results = transform(results) + excepted_proposals = np.zeros((0, 4), dtype=np.float32) + excepted_proposals_scores = np.zeros(0, dtype=np.float32) + self.assertTrue((results['proposals'] == excepted_proposals).all()) + self.assertTrue( + (results['proposals_scores'] == excepted_proposals_scores).all()) + + transform = LoadProposals(num_max_proposals=2) + results = { + 'proposals': + dict( + bboxes=np.zeros((5, 4), dtype=np.int64), + scores=np.zeros((5, ), dtype=np.int64)) + } + results = transform(results) + self.assertEqual(results['proposals'].shape[0], 2) + + def test_repr(self): + transform = LoadProposals() + self.assertEqual( + repr(transform), 'LoadProposals(num_max_proposals=None)') + + +class TestLoadEmptyAnnotations(unittest.TestCase): + + def test_transform(self): + transform = LoadEmptyAnnotations( + with_bbox=True, with_label=True, with_mask=True, with_seg=True) + results = {'img_shape': (224, 224)} + results = transform(results) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + self.assertEqual(results['gt_bboxes'].shape[-1], 4) + self.assertEqual(results['gt_ignore_flags'].dtype, bool) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + self.assertEqual(results['gt_masks'].masks.dtype, np.uint8) + self.assertEqual(results['gt_masks'].masks.shape[-2:], + results['img_shape']) + self.assertEqual(results['gt_seg_map'].dtype, np.uint8) + self.assertEqual(results['gt_seg_map'].shape, results['img_shape']) + + def test_repr(self): + transform = LoadEmptyAnnotations() + self.assertEqual( + repr(transform), 'LoadEmptyAnnotations(with_bbox=True, ' + 'with_label=True, ' + 'with_mask=False, ' + 'with_seg=False, ' + 'seg_ignore_label=255)') + + +class TestLoadTrackAnnotations(unittest.TestCase): + + def setUp(self): + data_prefix = osp.join(osp.dirname(__file__), '../data') + seg_map = osp.join(data_prefix, 'grayscale.jpg') + self.results = { + 'seg_map_path': + seg_map, + 'instances': [{ + 'bbox': [0, 0, 10, 20], + 'bbox_label': 1, + 'instance_id': 100, + 'keypoints': [1, 2, 3] + }, { + 'bbox': [10, 10, 110, 120], + 'bbox_label': 2, + 'instance_id': 102, + 'keypoints': [4, 5, 6] + }] + } + + def test_load_instances_id(self): + transform = LoadTrackAnnotations( + with_bbox=False, + with_label=True, + with_seg=False, + with_keypoints=False, + ) + results = transform(copy.deepcopy(self.results)) + assert 'gt_instances_ids' in results + assert (results['gt_instances_ids'] == np.array([100, 102])).all() + assert results['gt_instances_ids'].dtype == np.int32 + + def test_repr(self): + transform = LoadTrackAnnotations( + with_bbox=True, with_label=False, with_seg=False, with_mask=False) + assert repr(transform) == ('LoadTrackAnnotations(with_bbox=True, ' + 'with_label=False, with_mask=False,' + ' with_seg=False, poly2mask=True,' + " imdecode_backend='cv2', " + 'file_client_args=None)') diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_transforms.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..134e5de8a7ccf6fe1d5988b80792b064d13d0148 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_transforms.py @@ -0,0 +1,1790 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +import unittest + +import mmcv +import numpy as np +import torch +from mmcv.transforms import LoadImageFromFile + +# yapf:disable +from mmdet.datasets.transforms import (CopyPaste, CutOut, Expand, + FixScaleResize, FixShapeResize, + MinIoURandomCrop, MixUp, Mosaic, Pad, + PhotoMetricDistortion, RandomAffine, + RandomCenterCropPad, RandomCrop, + RandomErasing, RandomFlip, RandomShift, + Resize, ResizeShortestEdge, SegRescale, + YOLOXHSVRandomAug) +# yapf:enable +from mmdet.evaluation import bbox_overlaps +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import HorizontalBoxes, bbox_project +from mmdet.structures.mask import BitmapMasks +from .utils import construct_toy_data, create_full_masks, create_random_bboxes + +try: + import albumentations + from albumentations import Compose +except ImportError: + albumentations = None + Compose = None +# yapf:enable + + +class TestResize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() + -> tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.data_info1 = dict( + img=np.random.random((400, 500, 3)), + gt_seg_map=np.random.random((400, 500, 3)), + gt_bboxes=np.array([[0, 0, 112, 112]], dtype=np.float32), + gt_masks=BitmapMasks(rng.rand(1, 400, 500), height=400, width=500)) + self.data_info2 = dict( + img=np.random.random((200, 100, 3)), + gt_bboxes=np.array([[20, 15, 60, 45]], dtype=np.float32), + dtype=np.float32) + self.data_info3 = dict(img=np.random.random((200, 100, 3))) + + def test_resize(self): + # test keep_ratio is True + transform = Resize(scale=(100, 100), keep_ratio=True) + results = transform(copy.deepcopy(self.data_info1)) + self.assertEqual(results['img_shape'], (80, 100)) + self.assertEqual(results['scale_factor'], (80 / 400, 100 / 500)) + + # test resize_bboxes/seg/masks + transform = Resize(scale_factor=(1.5, 2)) + results = transform(copy.deepcopy(self.data_info1)) + self.assertTrue( + (results['gt_bboxes'] == np.array([[0., 0., 168., 224.]])).all()) + self.assertEqual(results['gt_masks'].height, 800) + self.assertEqual(results['gt_masks'].width, 750) + self.assertEqual(results['gt_seg_map'].shape[:2], (800, 750)) + + # test clip_object_border = False + transform = Resize(scale=(200, 150), clip_object_border=False) + results = transform(self.data_info2) + self.assertTrue( + (results['gt_bboxes'] == np.array([40., 11.25, 120., + 33.75])).all()) + + # test only with image + transform = Resize(scale=(200, 150), clip_object_border=False) + results = transform(self.data_info3) + self.assertTupleEqual(results['img'].shape[:2], (150, 200)) + + # test geometric transformation with homography matrix + transform = Resize(scale_factor=(1.5, 2)) + results = transform(copy.deepcopy(self.data_info1)) + self.assertTrue((bbox_project( + copy.deepcopy(self.data_info1['gt_bboxes']), + results['homography_matrix']) == results['gt_bboxes']).all()) + + def test_resize_use_box_type(self): + data_info1 = copy.deepcopy(self.data_info1) + data_info1['gt_bboxes'] = HorizontalBoxes(data_info1['gt_bboxes']) + data_info2 = copy.deepcopy(self.data_info2) + data_info2['gt_bboxes'] = HorizontalBoxes(data_info2['gt_bboxes']) + # test keep_ratio is True + transform = Resize(scale=(100, 150), keep_ratio=True) + results = transform(copy.deepcopy(data_info1)) + self.assertEqual(results['img_shape'], (100, 125)) + self.assertEqual(results['scale_factor'], (100 / 400, 125 / 500)) + + # test resize_bboxes/seg/masks + transform = Resize(scale_factor=(1.5, 2)) + results = transform(copy.deepcopy(data_info1)) + self.assertTrue( + (results['gt_bboxes'].numpy() == np.array([[0, 0, 168, + 224]])).all()) + self.assertEqual(results['gt_masks'].height, 800) + self.assertEqual(results['gt_masks'].width, 750) + self.assertEqual(results['gt_seg_map'].shape[:2], (800, 750)) + + # test clip_object_border = False + transform = Resize(scale=(200, 150), clip_object_border=False) + results = transform(data_info2) + self.assertTrue((results['gt_bboxes'].numpy() == np.array( + [40., 11.25, 120., 33.75])).all()) + + # test geometric transformation with homography matrix + transform = Resize(scale_factor=(1.5, 2)) + results = transform(copy.deepcopy(data_info1)) + self.assertTrue((bbox_project( + copy.deepcopy(data_info1['gt_bboxes'].numpy()), + results['homography_matrix']) == results['gt_bboxes'].numpy() + ).all()) + + def test_repr(self): + transform = Resize(scale=(100, 100), keep_ratio=True) + self.assertEqual( + repr(transform), ('Resize(scale=(100, 100), ' + 'scale_factor=None, keep_ratio=True, ' + 'clip_object_border=True), backend=cv2), ' + 'interpolation=bilinear)')) + + +class TestFixScaleResize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() + -> tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.data_info1 = dict( + img=np.random.random((200, 300, 3)), + gt_seg_map=np.random.random((200, 300, 3)), + gt_bboxes=np.array([[0, 0, 112, 112]], dtype=np.float32), + gt_masks=BitmapMasks(rng.rand(1, 200, 300), height=200, width=300)) + + def test_resize(self): + # test keep_ratio is True + transform = FixScaleResize(scale=(101, 201), keep_ratio=True) + results = transform(copy.deepcopy(self.data_info1)) + self.assertEqual(results['img_shape'], (101, 151)) + self.assertEqual(results['scale_factor'], (151 / 300, 101 / 200)) + + +class TestFixShapeResize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.data_info1 = dict( + img=np.random.random((200, 300, 3)), + gt_seg_map=np.random.random((200, 300, 3)), + gt_bboxes=np.array([[0, 0, 112, 133]], dtype=np.float32), + gt_masks=BitmapMasks(rng.rand(1, 200, 300), height=200, width=300)) + self.data_info2 = dict( + img=np.random.random((300, 400, 3)), + gt_bboxes=np.array([[200, 150, 600, 450]], dtype=np.float32), + dtype=np.float32) + self.data_info3 = dict(img=np.random.random((300, 400, 3))) + self.data_info4 = dict( + img=np.random.random((400, 450, 3)), + gt_bboxes=np.array([[200, 150, 300, 400]], dtype=np.float32), + dtype=np.float32) + + def test_resize(self): + # test keep_ratio is True + transform = FixShapeResize(width=100, height=50, keep_ratio=True) + results = transform(copy.deepcopy(self.data_info1)) + self.assertEqual(results['img_shape'], (50, 100)) + self.assertEqual(results['scale_factor'], (50 / 200, 50 / 200)) + # test resize_bboxes/seg/masks + transform = FixShapeResize(width=120, height=100, keep_ratio=False) + results = transform(copy.deepcopy(self.data_info1)) + self.assertEqual(results['gt_masks'].height, 100) + self.assertEqual(results['gt_masks'].width, 120) + self.assertEqual(results['gt_seg_map'].shape[:2], (100, 120)) + + # test clip_object_border = False + transform = FixShapeResize( + width=200, height=150, clip_object_border=False) + results = transform(copy.deepcopy(self.data_info2)) + self.assertTrue((results['gt_bboxes'] == np.array([100, 75, 300, + 225])).all()) + + # test only with image + transform = FixShapeResize( + width=200, height=150, clip_object_border=False) + results = transform(self.data_info3) + self.assertTupleEqual(results['img'].shape[:2], (150, 200)) + + # test geometric transformation with homography matrix + transform = FixShapeResize(width=400, height=300) + results = transform(copy.deepcopy(self.data_info4)) + self.assertTrue((bbox_project( + copy.deepcopy(self.data_info4['gt_bboxes']), + results['homography_matrix']) == results['gt_bboxes']).all()) + + def test_resize_with_boxlist(self): + data_info1 = copy.deepcopy(self.data_info1) + data_info1['gt_bboxes'] = HorizontalBoxes(data_info1['gt_bboxes']) + data_info2 = copy.deepcopy(self.data_info2) + data_info2['gt_bboxes'] = HorizontalBoxes(data_info2['gt_bboxes']) + data_info4 = copy.deepcopy(self.data_info4) + data_info4['gt_bboxes'] = HorizontalBoxes(data_info4['gt_bboxes']) + # test keep_ratio is True + transform = FixShapeResize(width=100, height=200, keep_ratio=True) + results = transform(copy.deepcopy(data_info1)) + self.assertEqual(results['img_shape'], (200, 100)) + self.assertEqual(results['scale_factor'], (100 / 300, 100 / 300)) + + # test resize_bboxes/seg/masks + transform = FixShapeResize(width=150, height=200, keep_ratio=False) + results = transform(copy.deepcopy(data_info1)) + self.assertTrue( + (results['gt_bboxes'].numpy() == np.array([[0, 0, 56, + 133]])).all()) + self.assertEqual(results['gt_masks'].height, 200) + self.assertEqual(results['gt_masks'].width, 150) + self.assertEqual(results['gt_seg_map'].shape[:2], (200, 150)) + + # test clip_object_border = False + transform = FixShapeResize( + width=200, height=150, clip_object_border=False) + results = transform(copy.deepcopy(data_info2)) + self.assertTrue( + (results['gt_bboxes'].numpy() == np.array([100, 75, 300, + 225])).all()) + + # test only with image + transform = FixShapeResize( + width=200, height=150, clip_object_border=False) + results = transform(self.data_info3) + self.assertTupleEqual(results['img'].shape[:2], (150, 200)) + + # test geometric transformation with homography matrix + transform = FixShapeResize(width=400, height=300) + results = transform(copy.deepcopy(data_info4)) + self.assertTrue((bbox_project( + copy.deepcopy(self.data_info4['gt_bboxes']), + results['homography_matrix']) == results['gt_bboxes'].numpy() + ).all()) + + def test_repr(self): + transform = FixShapeResize(width=100, height=50, keep_ratio=True) + self.assertEqual( + repr(transform), ('FixShapeResize(width=100, height=50, ' + 'keep_ratio=True, ' + 'clip_object_border=True), backend=cv2), ' + 'interpolation=bilinear)')) + + +class TestRandomFlip(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results1 = { + 'img': np.random.random((224, 224, 3)), + 'gt_bboxes': np.array([[0, 1, 100, 101]], dtype=np.float32), + 'gt_masks': + BitmapMasks(rng.rand(1, 224, 224), height=224, width=224), + 'gt_seg_map': np.random.random((224, 224)) + } + + self.results2 = {'img': self.results1['img']} + + def test_transform(self): + # test with image, gt_bboxes, gt_masks, gt_seg_map + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(self.results1)) + self.assertTrue( + (results_update['gt_bboxes'] == np.array([[124, 1, 224, + 101]])).all()) + # test only with image + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(self.results2)) + self.assertTrue( + (results_update['img'] == self.results2['img'][:, ::-1]).all()) + + # test geometric transformation with homography matrix + # (1) Horizontal Flip + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(self.results1)) + bboxes = copy.deepcopy(self.results1['gt_bboxes']) + self.assertTrue((bbox_project( + bboxes, + results_update['homography_matrix']) == results_update['gt_bboxes'] + ).all()) + # (2) Vertical Flip + transform = RandomFlip(1.0, direction='vertical') + results_update = transform.transform(copy.deepcopy(self.results1)) + bboxes = copy.deepcopy(self.results1['gt_bboxes']) + self.assertTrue((bbox_project( + bboxes, + results_update['homography_matrix']) == results_update['gt_bboxes'] + ).all()) + # (3) Diagonal Flip + transform = RandomFlip(1.0, direction='diagonal') + results_update = transform.transform(copy.deepcopy(self.results1)) + bboxes = copy.deepcopy(self.results1['gt_bboxes']) + self.assertTrue((bbox_project( + bboxes, + results_update['homography_matrix']) == results_update['gt_bboxes'] + ).all()) + + def test_transform_use_box_type(self): + results1 = copy.deepcopy(self.results1) + results1['gt_bboxes'] = HorizontalBoxes(results1['gt_bboxes']) + # test with image, gt_bboxes, gt_masks, gt_seg_map + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(results1)) + self.assertTrue((results_update['gt_bboxes'].numpy() == np.array( + [[124, 1, 224, 101]])).all()) + + # test geometric transformation with homography matrix + # (1) Horizontal Flip + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(results1)) + bboxes = copy.deepcopy(results1['gt_bboxes'].numpy()) + self.assertTrue((bbox_project(bboxes, + results_update['homography_matrix']) == + results_update['gt_bboxes'].numpy()).all()) + # (2) Vertical Flip + transform = RandomFlip(1.0, direction='vertical') + results_update = transform.transform(copy.deepcopy(results1)) + bboxes = copy.deepcopy(results1['gt_bboxes'].numpy()) + self.assertTrue((bbox_project(bboxes, + results_update['homography_matrix']) == + results_update['gt_bboxes'].numpy()).all()) + # (3) Diagonal Flip + transform = RandomFlip(1.0, direction='diagonal') + results_update = transform.transform(copy.deepcopy(results1)) + bboxes = copy.deepcopy(results1['gt_bboxes'].numpy()) + self.assertTrue((bbox_project(bboxes, + results_update['homography_matrix']) == + results_update['gt_bboxes'].numpy()).all()) + + def test_repr(self): + transform = RandomFlip(0.1) + transform_str = str(transform) + self.assertIsInstance(transform_str, str) + + +class TestPad(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': np.random.random((100, 80, 3)), + 'gt_masks': + BitmapMasks(rng.rand(4, 100, 80), height=100, width=80) + } + + def test_transform(self): + # test pad img/gt_masks with size + transform = Pad(size=(120, 110)) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (110, 120)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (110, 120)) + + # test pad img/gt_masks with size_divisor + transform = Pad(size_divisor=11) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (110, 88)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (110, 88)) + + # test pad img/gt_masks with pad_to_square + transform = Pad(pad_to_square=True) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (100, 100)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (100, 100)) + + # test pad img/gt_masks with pad_to_square and size_divisor + transform = Pad(pad_to_square=True, size_divisor=11) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (110, 110)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (110, 110)) + + # test pad img/gt_masks with pad_to_square and size_divisor + transform = Pad(pad_to_square=True, size_divisor=11) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (110, 110)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (110, 110)) + + def test_repr(self): + transform = Pad( + pad_to_square=True, size_divisor=11, padding_mode='edge') + self.assertEqual( + repr(transform), + ('Pad(size=None, size_divisor=11, pad_to_square=True, ' + "pad_val={'img': 0, 'seg': 255}), padding_mode=edge)")) + + +class TestMinIoURandomCrop(unittest.TestCase): + + def test_transform(self): + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + results['img'] = img + results['img_shape'] = img.shape[:2] + gt_bboxes = create_random_bboxes(1, results['img_shape'][1], + results['img_shape'][0]) + results['gt_labels'] = np.ones(gt_bboxes.shape[0], dtype=np.int64) + results['gt_bboxes'] = gt_bboxes + transform = MinIoURandomCrop() + results = transform.transform(copy.deepcopy(results)) + + self.assertEqual(results['gt_labels'].shape[0], + results['gt_bboxes'].shape[0]) + self.assertEqual(results['gt_labels'].dtype, np.int64) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + patch = np.array( + [0, 0, results['img_shape'][1], results['img_shape'][0]]) + ious = bbox_overlaps(patch.reshape(-1, 4), + results['gt_bboxes']).reshape(-1) + mode = transform.mode + if mode == 1: + self.assertTrue(np.equal(results['gt_bboxes'], gt_bboxes).all()) + else: + self.assertTrue((ious >= mode).all()) + + def test_transform_use_box_type(self): + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + results['img'] = img + results['img_shape'] = img.shape[:2] + gt_bboxes = create_random_bboxes(1, results['img_shape'][1], + results['img_shape'][0]) + results['gt_labels'] = np.ones(gt_bboxes.shape[0], dtype=np.int64) + results['gt_bboxes'] = HorizontalBoxes(gt_bboxes) + transform = MinIoURandomCrop() + results = transform.transform(copy.deepcopy(results)) + + self.assertEqual(results['gt_labels'].shape[0], + results['gt_bboxes'].shape[0]) + self.assertEqual(results['gt_labels'].dtype, np.int64) + self.assertEqual(results['gt_bboxes'].dtype, torch.float32) + + patch = np.array( + [0, 0, results['img_shape'][1], results['img_shape'][0]]) + ious = bbox_overlaps( + patch.reshape(-1, 4), results['gt_bboxes'].numpy()).reshape(-1) + mode = transform.mode + if mode == 1: + self.assertTrue((results['gt_bboxes'].numpy() == gt_bboxes).all()) + else: + self.assertTrue((ious >= mode).all()) + + def test_repr(self): + transform = MinIoURandomCrop() + self.assertEqual( + repr(transform), ('MinIoURandomCrop' + '(min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), ' + 'min_crop_size=0.3, ' + 'bbox_clip_border=True)')) + + +class TestPhotoMetricDistortion(unittest.TestCase): + + def test_transform(self): + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + transform = PhotoMetricDistortion() + + # test uint8 input + results = dict() + results['img'] = img + results = transform.transform(copy.deepcopy(results)) + self.assertEqual(results['img'].dtype, np.float32) + + # test float32 input + results = dict() + results['img'] = img.astype(np.float32) + results = transform.transform(copy.deepcopy(results)) + self.assertEqual(results['img'].dtype, np.float32) + + def test_repr(self): + transform = PhotoMetricDistortion() + self.assertEqual( + repr(transform), ('PhotoMetricDistortion' + '(brightness_delta=32, ' + 'contrast_range=(0.5, 1.5), ' + 'saturation_range=(0.5, 1.5), ' + 'hue_delta=18)')) + + +class TestExpand(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes': np.array([[0, 1, 100, 101]]), + 'gt_masks': + BitmapMasks(rng.rand(1, 224, 224), height=224, width=224), + 'gt_seg_map': np.random.random((224, 224)) + } + + def test_transform(self): + transform = Expand() + results = transform.transform(copy.deepcopy(self.results)) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + self.assertEqual( + results['img_shape'], + (results['gt_masks'].height, results['gt_masks'].width)) + self.assertEqual(results['img_shape'], results['gt_seg_map'].shape) + + def test_transform_use_box_type(self): + results = copy.deepcopy(self.results) + results['gt_bboxes'] = HorizontalBoxes(results['gt_bboxes']) + transform = Expand() + results = transform.transform(results) + self.assertEqual( + results['img_shape'], + (results['gt_masks'].height, results['gt_masks'].width)) + self.assertEqual(results['img_shape'], results['gt_seg_map'].shape) + + def test_repr(self): + transform = Expand() + self.assertEqual( + repr(transform), ('Expand' + '(mean=(0, 0, 0), to_rgb=True, ' + 'ratio_range=(1, 4), ' + 'seg_ignore_label=None, ' + 'prob=0.5)')) + + +class TestSegRescale(unittest.TestCase): + + def setUp(self) -> None: + seg_map = np.random.randint(0, 255, size=(32, 32), dtype=np.int32) + self.results = {'gt_seg_map': seg_map} + + def test_transform(self): + # test scale_factor != 1 + transform = SegRescale(scale_factor=2) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['gt_seg_map'].shape[:2], (64, 64)) + # test scale_factor = 1 + transform = SegRescale(scale_factor=1) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['gt_seg_map'].shape[:2], (32, 32)) + + def test_repr(self): + transform = SegRescale(scale_factor=2) + self.assertEqual( + repr(transform), ('SegRescale(scale_factor=2, backend=cv2)')) + + +class TestRandomCrop(unittest.TestCase): + + def test_init(self): + # test invalid crop_type + with self.assertRaisesRegex(ValueError, 'Invalid crop_type'): + RandomCrop(crop_size=(10, 10), crop_type='unknown') + + crop_type_list = ['absolute', 'absolute_range'] + for crop_type in crop_type_list: + # test h > 0 and w > 0 + for crop_size in [(0, 0), (0, 1), (1, 0)]: + with self.assertRaises(AssertionError): + RandomCrop(crop_size=crop_size, crop_type=crop_type) + # test type(h) = int and type(w) = int + for crop_size in [(1.0, 1), (1, 1.0), (1.0, 1.0)]: + with self.assertRaises(AssertionError): + RandomCrop(crop_size=crop_size, crop_type=crop_type) + + # test crop_size[0] <= crop_size[1] + with self.assertRaises(AssertionError): + RandomCrop(crop_size=(10, 5), crop_type='absolute_range') + + # test h in (0, 1] and w in (0, 1] + crop_type_list = ['relative_range', 'relative'] + for crop_type in crop_type_list: + for crop_size in [(0, 1), (1, 0), (1.1, 0.5), (0.5, 1.1)]: + with self.assertRaises(AssertionError): + RandomCrop(crop_size=crop_size, crop_type=crop_type) + + def test_transform(self): + # test relative and absolute crop + src_results = { + 'img': np.random.randint(0, 255, size=(24, 32), dtype=np.int32) + } + target_shape = (12, 16) + for crop_type, crop_size in zip(['relative', 'absolute'], [(0.5, 0.5), + (16, 12)]): + transform = RandomCrop(crop_size=crop_size, crop_type=crop_type) + results = transform(copy.deepcopy(src_results)) + print(results['img'].shape[:2]) + self.assertEqual(results['img'].shape[:2], target_shape) + + # test absolute_range crop + transform = RandomCrop(crop_size=(10, 20), crop_type='absolute_range') + results = transform(copy.deepcopy(src_results)) + h, w = results['img'].shape + self.assertTrue(10 <= w <= 20) + self.assertTrue(10 <= h <= 20) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + # test relative_range crop + transform = RandomCrop( + crop_size=(0.5, 0.5), crop_type='relative_range') + results = transform(copy.deepcopy(src_results)) + h, w = results['img'].shape + self.assertTrue(16 <= w <= 32) + self.assertTrue(12 <= h <= 24) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + # test with gt_bboxes, gt_bboxes_labels, gt_ignore_flags, + # gt_masks, gt_seg_map, gt_instances_ids + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = np.array([[0, 0, 7, 7], [2, 3, 9, 9]], dtype=np.float32) + gt_bboxes_labels = np.array([0, 1], dtype=np.int64) + gt_ignore_flags = np.array([0, 1], dtype=bool) + gt_masks_ = np.zeros((2, 10, 10), np.uint8) + gt_masks_[0, 0:7, 0:7] = 1 + gt_masks_[1, 2:7, 3:8] = 1 + gt_masks = BitmapMasks(gt_masks_.copy(), height=10, width=10) + gt_seg_map = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_instances_ids = np.array([0, 1], dtype=np.int64) + src_results = { + 'img': img, + 'gt_bboxes': gt_bboxes, + 'gt_bboxes_labels': gt_bboxes_labels, + 'gt_ignore_flags': gt_ignore_flags, + 'gt_masks': gt_masks, + 'gt_seg_map': gt_seg_map, + 'gt_instances_ids': gt_instances_ids + } + transform = RandomCrop( + crop_size=(7, 5), + allow_negative_crop=False, + recompute_bbox=False, + bbox_clip_border=True) + results = transform(copy.deepcopy(src_results)) + h, w = results['img'].shape + self.assertEqual(h, 5) + self.assertEqual(w, 7) + self.assertEqual(results['gt_bboxes'].shape[0], 2) + self.assertEqual(results['gt_bboxes_labels'].shape[0], 2) + self.assertEqual(results['gt_ignore_flags'].shape[0], 2) + self.assertTupleEqual(results['gt_seg_map'].shape[:2], (5, 7)) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + self.assertEqual(results['gt_instances_ids'].shape[0], 2) + + # test geometric transformation with homography matrix + bboxes = copy.deepcopy(src_results['gt_bboxes']) + self.assertTrue((bbox_project(bboxes, results['homography_matrix'], + (5, 7)) == results['gt_bboxes']).all()) + + # test recompute_bbox = True + gt_masks_ = np.zeros((2, 10, 10), np.uint8) + gt_masks = BitmapMasks(gt_masks_.copy(), height=10, width=10) + gt_bboxes = np.array([[0.1, 0.1, 0.2, 0.2]]) + src_results = { + 'img': img, + 'gt_bboxes': gt_bboxes, + 'gt_masks': gt_masks + } + target_gt_bboxes = np.zeros((1, 4), dtype=np.float32) + transform = RandomCrop( + crop_size=(10, 11), + allow_negative_crop=False, + recompute_bbox=True, + bbox_clip_border=True) + results = transform(copy.deepcopy(src_results)) + self.assertTrue((results['gt_bboxes'] == target_gt_bboxes).all()) + + # test bbox_clip_border = False + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop( + crop_size=(10, 11), + allow_negative_crop=False, + recompute_bbox=True, + bbox_clip_border=False) + results = transform(copy.deepcopy(src_results)) + self.assertTrue( + (results['gt_bboxes'] == src_results['gt_bboxes']).all()) + + # test the crop does not contain any gt-bbox + # allow_negative_crop = False + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = np.zeros((0, 4), dtype=np.float32) + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop(crop_size=(5, 3), allow_negative_crop=False) + results = transform(copy.deepcopy(src_results)) + self.assertIsNone(results) + + # allow_negative_crop = True + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = np.zeros((0, 4), dtype=np.float32) + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop(crop_size=(5, 3), allow_negative_crop=True) + results = transform(copy.deepcopy(src_results)) + self.assertTrue(isinstance(results, dict)) + + def test_transform_use_box_type(self): + # test with gt_bboxes, gt_bboxes_labels, gt_ignore_flags, + # gt_masks, gt_seg_map + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = np.array([[0, 0, 7, 7], [2, 3, 9, 9]], dtype=np.float32) + gt_bboxes_labels = np.array([0, 1], dtype=np.int64) + gt_ignore_flags = np.array([0, 1], dtype=bool) + gt_masks_ = np.zeros((2, 10, 10), np.uint8) + gt_masks_[0, 0:7, 0:7] = 1 + gt_masks_[1, 2:7, 3:8] = 1 + gt_masks = BitmapMasks(gt_masks_.copy(), height=10, width=10) + gt_seg_map = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_instances_ids = np.array([0, 1], dtype=np.int64) + src_results = { + 'img': img, + 'gt_bboxes': HorizontalBoxes(gt_bboxes), + 'gt_bboxes_labels': gt_bboxes_labels, + 'gt_ignore_flags': gt_ignore_flags, + 'gt_masks': gt_masks, + 'gt_seg_map': gt_seg_map, + 'gt_instances_ids': gt_instances_ids + } + transform = RandomCrop( + crop_size=(7, 5), + allow_negative_crop=False, + recompute_bbox=False, + bbox_clip_border=True) + results = transform(copy.deepcopy(src_results)) + h, w = results['img'].shape + self.assertEqual(h, 5) + self.assertEqual(w, 7) + self.assertEqual(results['gt_bboxes'].shape[0], 2) + self.assertEqual(results['gt_bboxes_labels'].shape[0], 2) + self.assertEqual(results['gt_ignore_flags'].shape[0], 2) + self.assertTupleEqual(results['gt_seg_map'].shape[:2], (5, 7)) + self.assertEqual(results['gt_instances_ids'].shape[0], 2) + + # test geometric transformation with homography matrix + bboxes = copy.deepcopy(src_results['gt_bboxes'].numpy()) + print(bboxes, results['gt_bboxes']) + self.assertTrue( + (bbox_project(bboxes, results['homography_matrix'], + (5, 7)) == results['gt_bboxes'].numpy()).all()) + + # test recompute_bbox = True + gt_masks_ = np.zeros((2, 10, 10), np.uint8) + gt_masks = BitmapMasks(gt_masks_.copy(), height=10, width=10) + gt_bboxes = HorizontalBoxes(np.array([[0.1, 0.1, 0.2, 0.2]])) + src_results = { + 'img': img, + 'gt_bboxes': gt_bboxes, + 'gt_masks': gt_masks + } + target_gt_bboxes = np.zeros((1, 4), dtype=np.float32) + transform = RandomCrop( + crop_size=(10, 11), + allow_negative_crop=False, + recompute_bbox=True, + bbox_clip_border=True) + results = transform(copy.deepcopy(src_results)) + self.assertTrue( + (results['gt_bboxes'].numpy() == target_gt_bboxes).all()) + + # test bbox_clip_border = False + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop( + crop_size=(10, 10), + allow_negative_crop=False, + recompute_bbox=True, + bbox_clip_border=False) + results = transform(copy.deepcopy(src_results)) + self.assertTrue( + (results['gt_bboxes'].numpy() == src_results['gt_bboxes'].numpy() + ).all()) + + # test the crop does not contain any gt-bbox + # allow_negative_crop = False + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = HorizontalBoxes(np.zeros((0, 4), dtype=np.float32)) + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop(crop_size=(5, 2), allow_negative_crop=False) + results = transform(copy.deepcopy(src_results)) + self.assertIsNone(results) + + # allow_negative_crop = True + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = HorizontalBoxes(np.zeros((0, 4), dtype=np.float32)) + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop(crop_size=(5, 2), allow_negative_crop=True) + results = transform(copy.deepcopy(src_results)) + self.assertTrue(isinstance(results, dict)) + + def test_repr(self): + crop_type = 'absolute' + crop_size = (10, 5) + allow_negative_crop = False + recompute_bbox = True + bbox_clip_border = False + transform = RandomCrop( + crop_size=crop_size, + crop_type=crop_type, + allow_negative_crop=allow_negative_crop, + recompute_bbox=recompute_bbox, + bbox_clip_border=bbox_clip_border) + self.assertEqual( + repr(transform), + f'RandomCrop(crop_size={crop_size}, crop_type={crop_type}, ' + f'allow_negative_crop={allow_negative_crop}, ' + f'recompute_bbox={recompute_bbox}, ' + f'bbox_clip_border={bbox_clip_border})') + + +class TestCutOut(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + self.results = {'img': img} + + def test_transform(self): + # test n_holes + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=(5, 3), cutout_shape=(8, 8)) + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=(3, 4, 5), cutout_shape=(8, 8)) + + # test cutout_shape and cutout_ratio + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=1, cutout_shape=8) + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=1, cutout_ratio=0.2) + + # either of cutout_shape and cutout_ratio should be given + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=1) + with self.assertRaises(AssertionError): + transform = CutOut( + n_holes=1, cutout_shape=(2, 2), cutout_ratio=(0.4, 0.4)) + + transform = CutOut(n_holes=1, cutout_shape=(10, 10)) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() < self.results['img'].sum()) + + transform = CutOut( + n_holes=(2, 4), + cutout_shape=[(10, 10), (15, 15)], + fill_in=(255, 255, 255)) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() > self.results['img'].sum()) + + transform = CutOut( + n_holes=1, cutout_ratio=(0.8, 0.8), fill_in=(255, 255, 255)) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() > self.results['img'].sum()) + + def test_repr(self): + transform = CutOut(n_holes=1, cutout_shape=(10, 10)) + self.assertEqual( + repr(transform), ('CutOut(n_holes=(1, 1), ' + 'cutout_shape=[(10, 10)], ' + 'fill_in=(0, 0, 0))')) + transform = CutOut( + n_holes=1, cutout_ratio=(0.8, 0.8), fill_in=(255, 255, 255)) + self.assertEqual( + repr(transform), ('CutOut(n_holes=(1, 1), ' + 'cutout_ratio=[(0.8, 0.8)], ' + 'fill_in=(255, 255, 255))')) + + +class TestMosaic(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + 'gt_masks': + BitmapMasks(rng.rand(3, 224, 224), height=224, width=224), + } + + def test_transform(self): + # test assertion for invalid img_scale + with self.assertRaises(AssertionError): + transform = Mosaic(img_scale=640) + + # test assertion for invalid probability + with self.assertRaises(AssertionError): + transform = Mosaic(prob=1.5) + + transform = Mosaic(img_scale=(12, 10)) + # test assertion for invalid mix_results + with self.assertRaises(AssertionError): + results = transform(copy.deepcopy(self.results)) + + self.results['mix_results'] = [copy.deepcopy(self.results)] * 3 + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].shape[:2] == (20, 24)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + def test_transform_with_no_gt(self): + self.results['gt_bboxes'] = np.empty((0, 4), dtype=np.float32) + self.results['gt_bboxes_labels'] = np.empty((0, ), dtype=np.int64) + self.results['gt_ignore_flags'] = np.empty((0, ), dtype=bool) + transform = Mosaic(img_scale=(12, 10)) + self.results['mix_results'] = [copy.deepcopy(self.results)] * 3 + results = transform(copy.deepcopy(self.results)) + self.assertIsInstance(results, dict) + self.assertTrue(results['img'].shape[:2] == (20, 24)) + self.assertTrue( + results['gt_bboxes_labels'].shape[0] == results['gt_bboxes']. + shape[0] == results['gt_ignore_flags'].shape[0] == 0) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_transform_use_box_type(self): + transform = Mosaic(img_scale=(12, 10)) + results = copy.deepcopy(self.results) + results['gt_bboxes'] = HorizontalBoxes(results['gt_bboxes']) + results['mix_results'] = [results] * 3 + results = transform(results) + self.assertTrue(results['img'].shape[:2] == (20, 24)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == torch.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_repr(self): + transform = Mosaic(img_scale=(640, 640), ) + self.assertEqual( + repr(transform), ('Mosaic(img_scale=(640, 640), ' + 'center_ratio_range=(0.5, 1.5), ' + 'pad_val=114.0, ' + 'prob=1.0)')) + + +class TestMixUp(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + 'gt_masks': + BitmapMasks(rng.rand(3, 224, 224), height=224, width=224), + } + + def test_transform(self): + # test assertion for invalid img_scale + with self.assertRaises(AssertionError): + transform = MixUp(img_scale=640) + + transform = MixUp(img_scale=(12, 10)) + # test assertion for invalid mix_results + with self.assertRaises(AssertionError): + results = transform(copy.deepcopy(self.results)) + + with self.assertRaises(AssertionError): + self.results['mix_results'] = [copy.deepcopy(self.results)] * 2 + results = transform(copy.deepcopy(self.results)) + + self.results['mix_results'] = [copy.deepcopy(self.results)] + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].shape[:2] == (224, 224)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + def test_transform_use_box_type(self): + results = copy.deepcopy(self.results) + results['gt_bboxes'] = HorizontalBoxes(results['gt_bboxes']) + + transform = MixUp(img_scale=(12, 10)) + results['mix_results'] = [results] + results = transform(results) + self.assertTrue(results['img'].shape[:2] == (224, 224)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == torch.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_repr(self): + transform = MixUp( + img_scale=(640, 640), + ratio_range=(0.8, 1.6), + pad_val=114.0, + ) + self.assertEqual( + repr(transform), ('MixUp(dynamic_scale=(640, 640), ' + 'ratio_range=(0.8, 1.6), ' + 'flip_ratio=0.5, ' + 'pad_val=114.0, ' + 'max_iters=15, ' + 'bbox_clip_border=True)')) + + +class TestRandomAffine(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + } + + def test_transform(self): + # test assertion for invalid translate_ratio + with self.assertRaises(AssertionError): + transform = RandomAffine(max_translate_ratio=1.5) + + # test assertion for invalid scaling_ratio_range + with self.assertRaises(AssertionError): + transform = RandomAffine(scaling_ratio_range=(1.5, 0.5)) + + with self.assertRaises(AssertionError): + transform = RandomAffine(scaling_ratio_range=(0, 0.5)) + + transform = RandomAffine() + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].shape[:2] == (224, 224)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + def test_transform_use_box_type(self): + results = copy.deepcopy(self.results) + results['gt_bboxes'] = HorizontalBoxes(results['gt_bboxes']) + + transform = RandomAffine() + results = transform(copy.deepcopy(results)) + self.assertTrue(results['img'].shape[:2] == (224, 224)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == torch.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_repr(self): + transform = RandomAffine( + scaling_ratio_range=(0.1, 2), + border=(-320, -320), + ) + self.assertEqual( + repr(transform), ('RandomAffine(max_rotate_degree=10.0, ' + 'max_translate_ratio=0.1, ' + 'scaling_ratio_range=(0.1, 2), ' + 'max_shear_degree=2.0, ' + 'border=(-320, -320), ' + 'border_val=(114, 114, 114), ' + 'bbox_clip_border=True)')) + + +class TestYOLOXHSVRandomAug(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + self.results = { + 'img': + img, + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + } + + def test_transform(self): + transform = YOLOXHSVRandomAug() + results = transform(copy.deepcopy(self.results)) + self.assertTrue( + results['img'].shape[:2] == self.results['img'].shape[:2]) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_repr(self): + transform = YOLOXHSVRandomAug() + self.assertEqual( + repr(transform), ('YOLOXHSVRandomAug(hue_delta=5, ' + 'saturation_delta=30, ' + 'value_delta=30)')) + + +class TestRandomCenterCropPad(unittest.TestCase): + + def test_init(self): + # test assertion for invalid crop_size while test_mode=False + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=(-1, 0), test_mode=False, test_pad_mode=None) + + # test assertion for invalid ratios while test_mode=False + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=(511, 511), + ratios=(1.0, 1.0), + test_mode=False, + test_pad_mode=None) + + # test assertion for invalid mean, std and to_rgb + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=(511, 511), + mean=None, + std=None, + to_rgb=None, + test_mode=False, + test_pad_mode=None) + + # test assertion for invalid crop_size while test_mode=True + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=(511, 511), + ratios=None, + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + + # test assertion for invalid ratios while test_mode=True + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=None, + ratios=(0.9, 1.0, 1.1), + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + + # test assertion for invalid border while test_mode=True + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=None, + ratios=None, + border=128, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + + # test assertion for invalid test_pad_mode while test_mode=True + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=None, + ratios=None, + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('do_nothing', 100)) + + def test_transform(self): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../../data/color.jpg')) + + load = LoadImageFromFile(to_float32=True) + results = load(results) + test_results = copy.deepcopy(results) + + h, w = results['img_shape'] + gt_bboxes = create_random_bboxes(4, w, h) + gt_bboxes_labels = np.array([1, 2, 3, 1], dtype=np.int64) + gt_ignore_flags = np.array([0, 0, 1, 1], dtype=bool) + results['gt_bboxes'] = gt_bboxes + results['gt_bboxes_labels'] = gt_bboxes_labels + results['gt_ignore_flags'] = gt_ignore_flags + crop_module = RandomCenterCropPad( + crop_size=(w - 20, h - 20), + ratios=(1.0, ), + border=128, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=False, + test_pad_mode=None) + train_results = crop_module(results) + assert train_results['img'].shape[:2] == (h - 20, w - 20) + # All bboxes should be reserved after crop + assert train_results['img_shape'][:2] == (h - 20, w - 20) + assert train_results['gt_bboxes'].shape[0] == 4 + assert train_results['gt_bboxes'].dtype == np.float32 + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + crop_module = RandomCenterCropPad( + crop_size=None, + ratios=None, + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + test_results = crop_module(test_results) + assert test_results['img'].shape[:2] == (h | 127, w | 127) + assert test_results['img_shape'][:2] == (h | 127, w | 127) + assert 'border' in test_results + + def test_transform_use_box_type(self): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../../data/color.jpg')) + + load = LoadImageFromFile(to_float32=True) + results = load(results) + test_results = copy.deepcopy(results) + + h, w = results['img_shape'] + gt_bboxes = create_random_bboxes(4, w, h) + gt_bboxes_labels = np.array([1, 2, 3, 1], dtype=np.int64) + gt_ignore_flags = np.array([0, 0, 1, 1], dtype=bool) + results['gt_bboxes'] = HorizontalBoxes(gt_bboxes) + results['gt_bboxes_labels'] = gt_bboxes_labels + results['gt_ignore_flags'] = gt_ignore_flags + crop_module = RandomCenterCropPad( + crop_size=(w - 20, h - 20), + ratios=(1.0, ), + border=128, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=False, + test_pad_mode=None) + train_results = crop_module(results) + assert train_results['img'].shape[:2] == (h - 20, w - 20) + # All bboxes should be reserved after crop + assert train_results['img_shape'][:2] == (h - 20, w - 20) + assert train_results['gt_bboxes'].shape[0] == 4 + assert train_results['gt_bboxes'].dtype == torch.float32 + + crop_module = RandomCenterCropPad( + crop_size=None, + ratios=None, + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + test_results = crop_module(test_results) + assert test_results['img'].shape[:2] == (h | 127, w | 127) + assert test_results['img_shape'][:2] == (h | 127, w | 127) + assert 'border' in test_results + + +class TestCopyPaste(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + h, w, _ = img.shape + dst_bboxes = np.array([[0.2 * w, 0.2 * h, 0.4 * w, 0.4 * h], + [0.5 * w, 0.5 * h, 0.6 * w, 0.6 * h]], + dtype=np.float32) + src_bboxes = np.array([[0.1 * w, 0.1 * h, 0.3 * w, 0.5 * h], + [0.4 * w, 0.4 * h, 0.7 * w, 0.7 * h], + [0.8 * w, 0.8 * h, 0.9 * w, 0.9 * h]], + dtype=np.float32) + + self.dst_results = { + 'img': img.copy(), + 'gt_bboxes': dst_bboxes, + 'gt_bboxes_labels': np.ones(dst_bboxes.shape[0], dtype=np.int64), + 'gt_masks': create_full_masks(dst_bboxes, w, h), + 'gt_ignore_flags': np.array([0, 1], dtype=bool), + } + self.src_results = { + 'img': img.copy(), + 'gt_bboxes': src_bboxes, + 'gt_bboxes_labels': + np.ones(src_bboxes.shape[0], dtype=np.int64) * 2, + 'gt_masks': create_full_masks(src_bboxes, w, h), + 'gt_ignore_flags': np.array([0, 0, 1], dtype=bool), + } + + def test_transform(self): + transform = CopyPaste(selected=False) + # test assertion for invalid mix_results + with self.assertRaises(AssertionError): + results = transform(copy.deepcopy(self.dst_results)) + + results = copy.deepcopy(self.dst_results) + results['mix_results'] = [copy.deepcopy(self.src_results)] + results = transform(results) + + self.assertEqual(results['img'].shape[:2], + self.dst_results['img'].shape[:2]) + + # one object of destination image is totally occluded + self.assertEqual( + results['gt_bboxes'].shape[0], + self.dst_results['gt_bboxes'].shape[0] + + self.src_results['gt_bboxes'].shape[0] - 1) + self.assertEqual( + results['gt_bboxes_labels'].shape[0], + self.dst_results['gt_bboxes_labels'].shape[0] + + self.src_results['gt_bboxes_labels'].shape[0] - 1) + self.assertEqual( + results['gt_masks'].masks.shape[0], + self.dst_results['gt_masks'].masks.shape[0] + + self.src_results['gt_masks'].masks.shape[0] - 1) + self.assertEqual( + results['gt_ignore_flags'].shape[0], + self.dst_results['gt_ignore_flags'].shape[0] + + self.src_results['gt_ignore_flags'].shape[0] - 1) + + # the object of destination image is partially occluded + ori_bbox = self.dst_results['gt_bboxes'][0] + occ_bbox = results['gt_bboxes'][0] + ori_mask = self.dst_results['gt_masks'].masks[0] + occ_mask = results['gt_masks'].masks[0] + self.assertTrue(ori_mask.sum() > occ_mask.sum()) + self.assertTrue( + np.all(np.abs(occ_bbox - ori_bbox) <= transform.bbox_occluded_thr) + or occ_mask.sum() > transform.mask_occluded_thr) + + # test copypaste with selected objects + transform = CopyPaste() + results = copy.deepcopy(self.dst_results) + results['mix_results'] = [copy.deepcopy(self.src_results)] + results = transform(results) + + # test copypaste with an empty source image + results = copy.deepcopy(self.dst_results) + valid_inds = [False] * self.src_results['gt_bboxes'].shape[0] + results['mix_results'] = [{ + 'img': + self.src_results['img'].copy(), + 'gt_bboxes': + self.src_results['gt_bboxes'][valid_inds], + 'gt_bboxes_labels': + self.src_results['gt_bboxes_labels'][valid_inds], + 'gt_masks': + self.src_results['gt_masks'][valid_inds], + 'gt_ignore_flags': + self.src_results['gt_ignore_flags'][valid_inds], + }] + results = transform(results) + + # test copypaste with an empty mask results + transform = CopyPaste() + results = copy.deepcopy(self.dst_results) + results = {k: v for k, v in results.items() if 'mask' not in k} + results['mix_results'] = [copy.deepcopy(self.src_results)] + with self.assertRaises(RuntimeError): + results = transform(results) + + # test copypaste with boxes as masks + transform = CopyPaste(paste_by_box=True) + results = copy.deepcopy(self.dst_results) + results = {k: v for k, v in results.items() if 'mask' not in k} + src_results = copy.deepcopy(self.src_results) + src_results = {k: v for k, v in src_results.items() if 'mask' not in k} + results['mix_results'] = [src_results] + results = transform(results) + + self.assertEqual(results['img'].shape[:2], + self.dst_results['img'].shape[:2]) + + def test_transform_use_box_type(self): + src_results = copy.deepcopy(self.src_results) + src_results['gt_bboxes'] = HorizontalBoxes(src_results['gt_bboxes']) + dst_results = copy.deepcopy(self.dst_results) + dst_results['gt_bboxes'] = HorizontalBoxes(dst_results['gt_bboxes']) + transform = CopyPaste(selected=False) + + results = copy.deepcopy(dst_results) + results['mix_results'] = [copy.deepcopy(src_results)] + results = transform(results) + + self.assertEqual(results['img'].shape[:2], + self.dst_results['img'].shape[:2]) + + # one object of destination image is totally occluded + self.assertEqual( + results['gt_bboxes'].shape[0], + self.dst_results['gt_bboxes'].shape[0] + + self.src_results['gt_bboxes'].shape[0] - 1) + self.assertEqual( + results['gt_bboxes_labels'].shape[0], + self.dst_results['gt_bboxes_labels'].shape[0] + + self.src_results['gt_bboxes_labels'].shape[0] - 1) + self.assertEqual( + results['gt_masks'].masks.shape[0], + self.dst_results['gt_masks'].masks.shape[0] + + self.src_results['gt_masks'].masks.shape[0] - 1) + self.assertEqual( + results['gt_ignore_flags'].shape[0], + self.dst_results['gt_ignore_flags'].shape[0] + + self.src_results['gt_ignore_flags'].shape[0] - 1) + + # the object of destination image is partially occluded + ori_bbox = dst_results['gt_bboxes'][0].numpy() + occ_bbox = results['gt_bboxes'][0].numpy() + ori_mask = dst_results['gt_masks'].masks[0] + occ_mask = results['gt_masks'].masks[0] + self.assertTrue(ori_mask.sum() > occ_mask.sum()) + self.assertTrue( + np.all(np.abs(occ_bbox - ori_bbox) <= transform.bbox_occluded_thr) + or occ_mask.sum() > transform.mask_occluded_thr) + + # test copypaste with selected objects + transform = CopyPaste() + results = copy.deepcopy(dst_results) + results['mix_results'] = [copy.deepcopy(src_results)] + results = transform(results) + + # test copypaste with an empty source image + results = copy.deepcopy(dst_results) + valid_inds = [False] * self.src_results['gt_bboxes'].shape[0] + results['mix_results'] = [{ + 'img': + src_results['img'].copy(), + 'gt_bboxes': + src_results['gt_bboxes'][valid_inds], + 'gt_bboxes_labels': + src_results['gt_bboxes_labels'][valid_inds], + 'gt_masks': + src_results['gt_masks'][valid_inds], + 'gt_ignore_flags': + src_results['gt_ignore_flags'][valid_inds], + }] + results = transform(results) + + def test_repr(self): + transform = CopyPaste() + self.assertEqual( + repr(transform), ('CopyPaste(max_num_pasted=100, ' + 'bbox_occluded_thr=10, ' + 'mask_occluded_thr=300, ' + 'selected=True), ' + 'paste_by_box=False)')) + + +class TestAlbu(unittest.TestCase): + + @unittest.skipIf(albumentations is None, 'albumentations is not installed') + def test_transform(self): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../../data/color.jpg')) + + # Define simple pipeline + load = dict(type='LoadImageFromFile') + load = TRANSFORMS.build(load) + + albu_transform = dict( + type='Albu', transforms=[dict(type='ChannelShuffle', p=1)]) + albu_transform = TRANSFORMS.build(albu_transform) + + # Execute transforms + results = load(results) + results = albu_transform(results) + + self.assertEqual(results['img'].dtype, np.uint8) + + # test bbox + albu_transform = dict( + type='Albu', + transforms=[dict(type='ChannelShuffle', p=1)], + bbox_params=dict( + type='BboxParams', + format='pascal_voc', + label_fields=['gt_bboxes_labels', 'gt_ignore_flags']), + keymap={ + 'img': 'image', + 'gt_bboxes': 'bboxes' + }) + albu_transform = TRANSFORMS.build(albu_transform) + results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + } + results = albu_transform(results) + self.assertEqual(results['img'].dtype, np.float64) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + self.assertEqual(results['gt_ignore_flags'].dtype, bool) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + @unittest.skipIf(albumentations is None, 'albumentations is not installed') + def test_repr(self): + albu_transform = dict( + type='Albu', transforms=[dict(type='ChannelShuffle', p=1)]) + albu_transform = TRANSFORMS.build(albu_transform) + + self.assertEqual( + repr(albu_transform), 'Albu(transforms=[' + '{\'type\': \'ChannelShuffle\', ' + '\'p\': 1}])') + + +class TestCorrupt(unittest.TestCase): + + def test_transform(self): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../../data/color.jpg')) + + # Define simple pipeline + load = dict(type='LoadImageFromFile') + load = TRANSFORMS.build(load) + + corrupt_transform = dict(type='Corrupt', corruption='gaussian_blur') + corrupt_transform = TRANSFORMS.build(corrupt_transform) + + # Execute transforms + results = load(results) + results = corrupt_transform(results) + + self.assertEqual(results['img'].dtype, np.uint8) + + def test_repr(self): + corrupt_transform = dict(type='Corrupt', corruption='gaussian_blur') + corrupt_transform = TRANSFORMS.build(corrupt_transform) + + self.assertEqual( + repr(corrupt_transform), 'Corrupt(corruption=gaussian_blur, ' + 'severity=1)') + + +class TestRandomShift(unittest.TestCase): + + def test_init(self): + # test assertion for invalid shift_ratio + with self.assertRaises(AssertionError): + RandomShift(prob=1.5) + + # test assertion for invalid max_shift_px + with self.assertRaises(AssertionError): + RandomShift(max_shift_px=-1) + + def test_transform(self): + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + results['img'] = img + h, w, _ = img.shape + gt_bboxes = create_random_bboxes(8, w, h) + results['gt_bboxes_labels'] = np.ones( + gt_bboxes.shape[0], dtype=np.int64) + results['gt_bboxes'] = gt_bboxes + transform = RandomShift(prob=1.0) + results = transform(results) + + self.assertEqual(results['img'].shape[:2], (h, w)) + self.assertEqual(results['gt_bboxes_labels'].shape[0], + results['gt_bboxes'].shape[0]) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + + def test_transform_use_box_type(self): + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + results['img'] = img + h, w, _ = img.shape + gt_bboxes = create_random_bboxes(8, w, h) + results['gt_bboxes_labels'] = np.ones( + gt_bboxes.shape[0], dtype=np.int64) + results['gt_bboxes'] = HorizontalBoxes(gt_bboxes) + transform = RandomShift(prob=1.0) + results = transform(results) + + self.assertEqual(results['img'].shape[:2], (h, w)) + self.assertEqual(results['gt_bboxes_labels'].shape[0], + results['gt_bboxes'].shape[0]) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + self.assertEqual(results['gt_bboxes'].dtype, torch.float32) + + def test_repr(self): + transform = RandomShift() + self.assertEqual( + repr(transform), ('RandomShift(prob=0.5, ' + 'max_shift_px=32, ' + 'filter_thr_px=1)')) + + +class TestRandomErasing(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.results = construct_toy_data(poly2mask=True) + + def test_transform(self): + transform = RandomErasing( + n_patches=(1, 5), ratio=(0.4, 0.8), img_border_value=0) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() < self.results['img'].sum()) + + transform = RandomErasing( + n_patches=1, ratio=0.999, img_border_value=255) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() > self.results['img'].sum()) + # test empty results + empty_results = copy.deepcopy(self.results) + empty_results['gt_bboxes'] = np.zeros((0, 4), dtype=np.float32) + empty_results['gt_bboxes_labels'] = np.zeros((0, ), dtype=np.int64) + empty_results['gt_masks'] = empty_results['gt_masks'][False] + empty_results['gt_ignore_flags'] = np.zeros((0, ), dtype=bool) + empty_results['gt_seg_map'] = np.ones_like( + empty_results['gt_seg_map']) * 255 + results = transform(copy.deepcopy(empty_results)) + self.assertTrue(results['img'].sum() > self.results['img'].sum()) + + def test_transform_use_box_type(self): + src_results = copy.deepcopy(self.results) + src_results['gt_bboxes'] = HorizontalBoxes(src_results['gt_bboxes']) + + transform = RandomErasing( + n_patches=(1, 5), ratio=(0.4, 0.8), img_border_value=0) + results = transform(copy.deepcopy(src_results)) + self.assertTrue(results['img'].sum() < src_results['img'].sum()) + + transform = RandomErasing( + n_patches=1, ratio=0.999, img_border_value=255) + results = transform(copy.deepcopy(src_results)) + self.assertTrue(results['img'].sum() > src_results['img'].sum()) + # test empty results + empty_results = copy.deepcopy(src_results) + empty_results['gt_bboxes'] = HorizontalBoxes([], dtype=torch.float32) + empty_results['gt_bboxes_labels'] = np.zeros((0, ), dtype=np.int64) + empty_results['gt_masks'] = empty_results['gt_masks'][False] + empty_results['gt_ignore_flags'] = np.zeros((0, ), dtype=bool) + empty_results['gt_seg_map'] = np.ones_like( + empty_results['gt_seg_map']) * 255 + results = transform(copy.deepcopy(empty_results)) + self.assertTrue(results['img'].sum() > src_results['img'].sum()) + + def test_repr(self): + transform = RandomErasing(n_patches=(1, 5), ratio=(0, 0.2)) + self.assertEqual( + repr(transform), ('RandomErasing(n_patches=(1, 5), ' + 'ratio=(0, 0.2), ' + 'squared=True, ' + 'bbox_erased_thr=0.9, ' + 'img_border_value=128, ' + 'mask_border_value=0, ' + 'seg_ignore_label=255)')) + + +class TestResizeShortestEdge(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() + -> tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.data_info = dict( + img=np.random.random((220, 100, 3)), + gt_seg_map=np.random.random((220, 100, 3)), + gt_bboxes=np.array([[0, 0, 112, 12]], dtype=np.float32), + gt_masks=BitmapMasks(rng.rand(1, 220, 100), height=220, width=100)) + + def test_resize(self): + transform = ResizeShortestEdge(scale=200) + results = transform(copy.deepcopy(self.data_info)) + self.assertEqual(results['img_shape'], (440, 200)) + self.assertEqual(results['scale_factor'], (200 / 100, 440 / 220)) + + transform = ResizeShortestEdge(scale=200, max_size=301) + results = transform(copy.deepcopy(self.data_info)) + self.assertEqual(results['img_shape'], (301, 137)) + self.assertEqual(results['scale_factor'], (137 / 100, 301 / 220)) + + transform = ResizeShortestEdge(scale=201, keep_ratio=True) + results = transform(copy.deepcopy(self.data_info)) + self.assertEqual(results['img_shape'], (442, 201)) + self.assertEqual(results['scale_factor'], (201 / 100, 442 / 220)) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_wrappers.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..4232fac1d4bb110953b7ce012f3e6ee92320f2e0 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/test_wrappers.py @@ -0,0 +1,173 @@ +import copy +import os.path as osp +import unittest + +from mmcv.transforms import Compose + +from mmdet.datasets.transforms import MultiBranch, RandomOrder +from mmdet.utils import register_all_modules +from .utils import construct_toy_data + +register_all_modules() + + +class TestMultiBranch(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + data_prefix = osp.join(osp.dirname(__file__), '../../data') + img_path = osp.join(data_prefix, 'color.jpg') + seg_map = osp.join(data_prefix, 'gray.jpg') + self.meta_keys = ('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix') + self.results = { + 'img_path': + img_path, + 'img_id': + 12345, + 'img_shape': (300, 400), + 'seg_map_path': + seg_map, + 'instances': [{ + 'bbox': [0, 0, 10, 20], + 'bbox_label': 1, + 'mask': [[0, 0, 0, 20, 10, 20, 10, 0]], + 'ignore_flag': 0 + }, { + 'bbox': [10, 10, 110, 120], + 'bbox_label': 2, + 'mask': [[10, 10, 110, 10, 110, 120, 110, 10]], + 'ignore_flag': 0 + }, { + 'bbox': [50, 50, 60, 80], + 'bbox_label': 2, + 'mask': [[50, 50, 60, 50, 60, 80, 50, 80]], + 'ignore_flag': 1 + }] + } + self.branch_field = ['sup', 'sup_teacher', 'sup_student'] + self.weak_pipeline = [ + dict(type='ShearX'), + dict(type='PackDetInputs', meta_keys=self.meta_keys) + ] + self.strong_pipeline = [ + dict(type='ShearX'), + dict(type='ShearY'), + dict(type='PackDetInputs', meta_keys=self.meta_keys) + ] + self.labeled_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='LoadAnnotations', + with_bbox=True, + with_mask=True, + with_seg=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='MultiBranch', + branch_field=self.branch_field, + sup_teacher=self.weak_pipeline, + sup_student=self.strong_pipeline), + ] + self.unlabeled_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='MultiBranch', + branch_field=self.branch_field, + unsup_teacher=self.weak_pipeline, + unsup_student=self.strong_pipeline), + ] + + def test_transform(self): + labeled_pipeline = Compose(self.labeled_pipeline) + labeled_results = labeled_pipeline(copy.deepcopy(self.results)) + unlabeled_pipeline = Compose(self.unlabeled_pipeline) + unlabeled_results = unlabeled_pipeline(copy.deepcopy(self.results)) + + # test branch sup_teacher and sup_student + sup_branches = ['sup_teacher', 'sup_student'] + for branch in sup_branches: + self.assertIn(branch, labeled_results['data_samples']) + self.assertIn('homography_matrix', + labeled_results['data_samples'][branch]) + self.assertIn('labels', + labeled_results['data_samples'][branch].gt_instances) + self.assertIn('bboxes', + labeled_results['data_samples'][branch].gt_instances) + self.assertIn('masks', + labeled_results['data_samples'][branch].gt_instances) + self.assertIn('gt_sem_seg', + labeled_results['data_samples'][branch]) + # test branch unsup_teacher and unsup_student + unsup_branches = ['unsup_teacher', 'unsup_student'] + for branch in unsup_branches: + self.assertIn(branch, unlabeled_results['data_samples']) + self.assertIn('homography_matrix', + unlabeled_results['data_samples'][branch]) + self.assertNotIn( + 'labels', + unlabeled_results['data_samples'][branch].gt_instances) + self.assertNotIn( + 'bboxes', + unlabeled_results['data_samples'][branch].gt_instances) + self.assertNotIn( + 'masks', + unlabeled_results['data_samples'][branch].gt_instances) + self.assertNotIn('gt_sem_seg', + unlabeled_results['data_samples'][branch]) + + def test_repr(self): + pipeline = [dict(type='PackDetInputs', meta_keys=())] + transform = MultiBranch( + branch_field=self.branch_field, sup=pipeline, unsup=pipeline) + self.assertEqual( + repr(transform), + ("MultiBranch(branch_pipelines=['sup', 'unsup'])")) + + +class TestRandomOrder(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.results = construct_toy_data(poly2mask=True) + self.pipeline = [ + dict(type='Sharpness'), + dict(type='Contrast'), + dict(type='Brightness'), + dict(type='Rotate'), + dict(type='ShearX'), + dict(type='TranslateY') + ] + + def test_transform(self): + transform = RandomOrder(self.pipeline) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img_shape'], self.results['img_shape']) + self.assertEqual(results['gt_bboxes'].shape, + self.results['gt_bboxes'].shape) + self.assertEqual(results['gt_bboxes_labels'], + self.results['gt_bboxes_labels']) + self.assertEqual(results['gt_ignore_flags'], + self.results['gt_ignore_flags']) + self.assertEqual(results['gt_masks'].masks.shape, + self.results['gt_masks'].masks.shape) + self.assertEqual(results['gt_seg_map'].shape, + self.results['gt_seg_map'].shape) + + def test_repr(self): + transform = RandomOrder(self.pipeline) + self.assertEqual( + repr(transform), ('RandomOrder(Sharpness, Contrast, ' + 'Brightness, Rotate, ShearX, TranslateY, )')) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/utils.py b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9c81f568e72603b2649fa8c6dfe78ce595af8939 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_transforms/utils.py @@ -0,0 +1,76 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +from mmengine.testing import assert_allclose + +from mmdet.structures.bbox import BaseBoxes, HorizontalBoxes +from mmdet.structures.mask import BitmapMasks, PolygonMasks + + +def create_random_bboxes(num_bboxes, img_w, img_h): + bboxes_left_top = np.random.uniform(0, 0.5, size=(num_bboxes, 2)) + bboxes_right_bottom = np.random.uniform(0.5, 1, size=(num_bboxes, 2)) + bboxes = np.concatenate((bboxes_left_top, bboxes_right_bottom), 1) + bboxes = (bboxes * np.array([img_w, img_h, img_w, img_h])).astype( + np.float32) + return bboxes + + +def create_full_masks(gt_bboxes, img_w, img_h): + xmin, ymin = gt_bboxes[:, 0:1], gt_bboxes[:, 1:2] + xmax, ymax = gt_bboxes[:, 2:3], gt_bboxes[:, 3:4] + gt_masks = np.zeros((len(gt_bboxes), img_h, img_w), dtype=np.uint8) + for i in range(len(gt_bboxes)): + gt_masks[i, int(ymin[i]):int(ymax[i]), int(xmin[i]):int(xmax[i])] = 1 + gt_masks = BitmapMasks(gt_masks, img_h, img_w) + return gt_masks + + +def construct_toy_data(poly2mask, use_box_type=False): + img = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], + dtype=np.uint8) + img = np.stack([img, img, img], axis=-1) + results = dict() + results['img'] = img + results['img_shape'] = img.shape[:2] + if use_box_type: + results['gt_bboxes'] = HorizontalBoxes( + np.array([[1, 0, 2, 2]], dtype=np.float32)) + else: + results['gt_bboxes'] = np.array([[1, 0, 2, 2]], dtype=np.float32) + results['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + if poly2mask: + gt_masks = np.array([[0, 1, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0]], + dtype=np.uint8)[None, :, :] + results['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + else: + raw_masks = [[np.array([1, 2, 1, 0, 2, 1], dtype=np.float32)]] + results['gt_masks'] = PolygonMasks(raw_masks, 3, 4) + results['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 13, 13, 255], [255, 13, 255, 255]], + dtype=np.uint8) + return results + + +def check_result_same(results, pipeline_results, check_keys): + """Check whether the ``pipeline_results`` is the same with the predefined + ``results``. + + Args: + results (dict): Predefined results which should be the standard + output of the transform pipeline. + pipeline_results (dict): Results processed by the transform + pipeline. + check_keys (tuple): Keys that need to be checked between + results and pipeline_results. + """ + for key in check_keys: + if results.get(key, None) is None: + continue + if isinstance(results[key], (BitmapMasks, PolygonMasks)): + assert_allclose(pipeline_results[key].to_ndarray(), + results[key].to_ndarray()) + elif isinstance(results[key], BaseBoxes): + assert_allclose(pipeline_results[key].tensor, results[key].tensor) + else: + assert_allclose(pipeline_results[key], results[key]) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_tta.py b/mmdet_code/SR-TOD/tests/test_datasets/test_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a5f23b09813f33394fbdd106b16657f203a231 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_tta.py @@ -0,0 +1,177 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from unittest import TestCase + +import mmcv +import pytest + +from mmdet.datasets.transforms import * # noqa +from mmdet.registry import TRANSFORMS + + +class TestMuitiScaleFlipAug(TestCase): + + def test_exception(self): + with pytest.raises(TypeError): + tta_transform = dict( + type='TestTimeAug', + transforms=[dict(type='Resize', keep_ratio=False)], + ) + TRANSFORMS.build(tta_transform) + + def test_multi_scale_flip_aug(self): + tta_transform = dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=scale, keep_ratio=False) + for scale in [(256, 256), (512, 512), (1024, 1024)] + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor')) + ]]) + tta_module = TRANSFORMS.build(tta_transform) + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + results['img_id'] = '1' + results['img_path'] = 'data/color.jpg' + results['img'] = img + results['ori_shape'] = img.shape + results['ori_height'] = img.shape[0] + results['ori_width'] = img.shape[1] + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + tta_results = tta_module(results.copy()) + assert [img.shape + for img in tta_results['inputs']] == [(3, 256, 256), + (3, 512, 512), + (3, 1024, 1024)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [ + dict(type='Resize', scale=scale, keep_ratio=False) + for scale in [(256, 256), (512, 512), (1024, 1024)] + ], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results: dict = tta_module(results.copy()) + assert [img.shape + for img in tta_results['inputs']] == [(3, 256, 256), + (3, 256, 256), + (3, 512, 512), + (3, 512, 512), + (3, 1024, 1024), + (3, 1024, 1024)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True, False, True, False, True] + + tta_transform = dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=(512, 512), keep_ratio=False) + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor')) + ]]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [tta_results['inputs'][0].shape] == [(3, 512, 512)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [dict(type='Resize', scale=(512, 512), keep_ratio=False)], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 512, 512), + (3, 512, 512)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True] + + tta_transform = dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale_factor=r, keep_ratio=False) + for r in [0.5, 1.0, 2.0] + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor')) + ]]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 144, 256), + (3, 288, 512), + (3, 576, 1024)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [ + dict(type='Resize', scale_factor=r, keep_ratio=True) + for r in [0.5, 1.0, 2.0] + ], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 144, 256), + (3, 144, 256), + (3, 288, 512), + (3, 288, 512), + (3, 576, 1024), + (3, 576, 1024)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True, False, True, False, True] diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_wider_face.py b/mmdet_code/SR-TOD/tests/test_datasets/test_wider_face.py new file mode 100644 index 0000000000000000000000000000000000000000..aad3869b005e290310a73fa8fe40dd532bcc5040 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_wider_face.py @@ -0,0 +1,28 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import cv2 +import numpy as np + +from mmdet.datasets import WIDERFaceDataset + + +class TestWIDERFaceDataset(unittest.TestCase): + + def setUp(self) -> None: + img_path = 'tests/data/WIDERFace/WIDER_train/0--Parade/0_Parade_marchingband_1_5.jpg' # noqa: E501 + dummy_img = np.zeros((683, 1024, 3), dtype=np.uint8) + cv2.imwrite(img_path, dummy_img) + + def test_wider_face_dataset(self): + dataset = WIDERFaceDataset( + data_root='tests/data/WIDERFace', + ann_file='train.txt', + data_prefix=dict(img='WIDER_train'), + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + + data_list = dataset.load_data_list() + self.assertEqual(len(data_list), 1) + self.assertEqual(len(data_list[0]['instances']), 10) diff --git a/mmdet_code/SR-TOD/tests/test_datasets/test_youtube_vis_dataset.py b/mmdet_code/SR-TOD/tests/test_datasets/test_youtube_vis_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..6a32a0c1b79d42806e2ef1898f72ebb1e57ec9f1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_datasets/test_youtube_vis_dataset.py @@ -0,0 +1,17 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +from mmdet.datasets import YouTubeVISDataset + + +class TestYouTubeVISDataset(TestCase): + + @classmethod + def setUpClass(cls): + + cls.dataset = YouTubeVISDataset( + ann_file='tests/data/vis_sample.json', dataset_version='2019') + + def test_set_dataset_classes(self): + assert isinstance(self.dataset.metainfo, dict) + assert len(self.dataset.metainfo['classes']) == 40 diff --git a/mmdet_code/SR-TOD/tests/test_engine/__init__.py b/mmdet_code/SR-TOD/tests/test_engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_checkloss_hook.py b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_checkloss_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..3164f7328e9040f0a3fcf2e18a39832003e924e5 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_checkloss_hook.py @@ -0,0 +1,37 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock + +import torch + +from mmdet.engine.hooks import CheckInvalidLossHook + + +class TestCheckInvalidLossHook(TestCase): + + def test_after_train_iter(self): + n = 50 + hook = CheckInvalidLossHook(n) + runner = Mock() + runner.logger = Mock() + runner.logger.info = Mock() + + # Test `after_train_iter` function within the n iteration. + runner.iter = 10 + outputs = dict(loss=torch.LongTensor([2])) + hook.after_train_iter(runner, 10, outputs=outputs) + outputs = dict(loss=torch.tensor(float('nan'))) + hook.after_train_iter(runner, 10, outputs=outputs) + outputs = dict(loss=torch.tensor(float('inf'))) + hook.after_train_iter(runner, 10, outputs=outputs) + + # Test `after_train_iter` at the n iteration. + runner.iter = n - 1 + outputs = dict(loss=torch.LongTensor([2])) + hook.after_train_iter(runner, n - 1, outputs=outputs) + outputs = dict(loss=torch.tensor(float('nan'))) + with self.assertRaises(AssertionError): + hook.after_train_iter(runner, n - 1, outputs=outputs) + outputs = dict(loss=torch.tensor(float('inf'))) + with self.assertRaises(AssertionError): + hook.after_train_iter(runner, n - 1, outputs=outputs) diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_mean_teacher_hook.py b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_mean_teacher_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..41d056e4071a70f8b02e6caa39620dbd6cc02e71 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_mean_teacher_hook.py @@ -0,0 +1,175 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile +from unittest import TestCase + +import torch +import torch.nn as nn +from mmengine.evaluator import BaseMetric +from mmengine.model import BaseModel +from mmengine.optim import OptimWrapper +from mmengine.registry import MODEL_WRAPPERS +from mmengine.runner import Runner +from torch.utils.data import Dataset + +from mmdet.registry import DATASETS +from mmdet.utils import register_all_modules + +register_all_modules() + + +class ToyModel(nn.Module): + + def __init__(self): + super().__init__() + self.linear = nn.Linear(2, 1) + + def forward(self, inputs, data_samples, mode='tensor'): + labels = torch.stack(data_samples) + inputs = torch.stack(inputs) + outputs = self.linear(inputs) + if mode == 'tensor': + return outputs + elif mode == 'loss': + loss = (labels - outputs).sum() + outputs = dict(loss=loss) + return outputs + else: + return outputs + + +class ToyModel1(BaseModel, ToyModel): + + def __init__(self): + super().__init__() + + def forward(self, *args, **kwargs): + return super(BaseModel, self).forward(*args, **kwargs) + + +class ToyModel2(BaseModel): + + def __init__(self): + super().__init__() + self.teacher = ToyModel1() + self.student = ToyModel1() + + def forward(self, *args, **kwargs): + return self.student(*args, **kwargs) + + +@DATASETS.register_module(force=True) +class DummyDataset(Dataset): + METAINFO = dict() # type: ignore + data = torch.randn(12, 2) + label = torch.ones(12) + + @property + def metainfo(self): + return self.METAINFO + + def __len__(self): + return self.data.size(0) + + def __getitem__(self, index): + return dict(inputs=self.data[index], data_samples=self.label[index]) + + +class ToyMetric1(BaseMetric): + + def __init__(self, collect_device='cpu', dummy_metrics=None): + super().__init__(collect_device=collect_device) + self.dummy_metrics = dummy_metrics + + def process(self, data_batch, predictions): + result = {'acc': 1} + self.results.append(result) + + def compute_metrics(self, results): + return dict(acc=1) + + +class TestMeanTeacherHook(TestCase): + + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.temp_dir.cleanup() + + def test_mean_teacher_hook(self): + device = 'cuda:0' if torch.cuda.is_available() else 'cpu' + model = ToyModel2().to(device) + runner = Runner( + model=model, + train_dataloader=dict( + dataset=DummyDataset(), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=3, + num_workers=0), + val_dataloader=dict( + dataset=DummyDataset(), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=0), + val_evaluator=[ToyMetric1()], + work_dir=self.temp_dir.name, + default_scope='mmdet', + optim_wrapper=OptimWrapper( + torch.optim.Adam(ToyModel().parameters())), + train_cfg=dict(by_epoch=True, max_epochs=2, val_interval=1), + val_cfg=dict(), + default_hooks=dict(logger=None), + custom_hooks=[dict(type='MeanTeacherHook')], + experiment_name='test1') + runner.train() + + self.assertTrue( + osp.exists(osp.join(self.temp_dir.name, 'epoch_2.pth'))) + # checkpoint = torch.load(osp.join(self.temp_dir.name, 'epoch_2.pth')) + + # load and testing + runner = Runner( + model=model, + test_dataloader=dict( + dataset=DummyDataset(), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=3, + num_workers=0), + test_evaluator=[ToyMetric1()], + test_cfg=dict(), + work_dir=self.temp_dir.name, + default_scope='mmdet', + load_from=osp.join(self.temp_dir.name, 'epoch_2.pth'), + default_hooks=dict(logger=None), + custom_hooks=[dict(type='MeanTeacherHook')], + experiment_name='test2') + runner.test() + + @MODEL_WRAPPERS.register_module() + class DummyWrapper(BaseModel): + + def __init__(self, model): + super().__init__() + self.module = model + + def forward(self, *args, **kwargs): + return self.module(*args, **kwargs) + + # with model wrapper + runner = Runner( + model=DummyWrapper(ToyModel2()), + test_dataloader=dict( + dataset=DummyDataset(), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=3, + num_workers=0), + test_evaluator=[ToyMetric1()], + test_cfg=dict(), + work_dir=self.temp_dir.name, + default_scope='mmdet', + load_from=osp.join(self.temp_dir.name, 'epoch_2.pth'), + default_hooks=dict(logger=None), + custom_hooks=[dict(type='MeanTeacherHook')], + experiment_name='test3') + runner.test() diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_memory_profiler_hook.py b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_memory_profiler_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9711840f9662c01b7e7adfab2bf039e65f13e2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_memory_profiler_hook.py @@ -0,0 +1,38 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock + +from mmdet.engine.hooks import MemoryProfilerHook + + +class TestMemoryProfilerHook(TestCase): + + def test_after_train_iter(self): + hook = MemoryProfilerHook(2) + runner = Mock() + runner.logger = Mock() + runner.logger.info = Mock() + hook.after_train_iter(runner, 0) + runner.logger.info.assert_not_called() + hook.after_train_iter(runner, 1) + runner.logger.info.assert_called_once() + + def test_after_val_iter(self): + hook = MemoryProfilerHook(2) + runner = Mock() + runner.logger = Mock() + runner.logger.info = Mock() + hook.after_val_iter(runner, 0) + runner.logger.info.assert_not_called() + hook.after_val_iter(runner, 1) + runner.logger.info.assert_called_once() + + def test_after_test_iter(self): + hook = MemoryProfilerHook(2) + runner = Mock() + runner.logger = Mock() + runner.logger.info = Mock() + hook.after_test_iter(runner, 0) + runner.logger.info.assert_not_called() + hook.after_test_iter(runner, 1) + runner.logger.info.assert_called_once() diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_num_class_check_hook.py b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_num_class_check_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..f2cd7a6d2eb3a3ec428e68e3f0ca23a8048dede8 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_num_class_check_hook.py @@ -0,0 +1,106 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from copy import deepcopy +from unittest import TestCase +from unittest.mock import Mock + +from mmcv.cnn import VGG +from mmengine.dataset import BaseDataset +from torch import nn + +from mmdet.engine.hooks import NumClassCheckHook +from mmdet.models.roi_heads.mask_heads import FusedSemanticHead + + +class TestNumClassCheckHook(TestCase): + + def setUp(self): + # Setup NumClassCheckHook + hook = NumClassCheckHook() + self.hook = hook + + # Setup runner mock + runner = Mock() + runner.model = Mock() + runner.logger = Mock() + runner.logger.warning = Mock() + runner.train_dataloader = Mock() + runner.val_dataloader = Mock() + self.runner = runner + + # Setup dataset + metainfo = dict(classes=None) + self.none_classmeta_dataset = BaseDataset( + metainfo=metainfo, lazy_init=True) + metainfo = dict(classes='class_name') + self.str_classmeta_dataset = BaseDataset( + metainfo=metainfo, lazy_init=True) + metainfo = dict(classes=('bus', 'car')) + self.normal_classmeta_dataset = BaseDataset( + metainfo=metainfo, lazy_init=True) + + # Setup valid model + valid_model = nn.Module() + valid_model.add_module('backbone', VGG(depth=11)) + fused_semantic_head = FusedSemanticHead( + num_ins=1, + fusion_level=0, + num_convs=1, + in_channels=1, + conv_out_channels=1) + valid_model.add_module('semantic_head', fused_semantic_head) + rpn_head = nn.Module() + rpn_head.num_classes = 1 + valid_model.add_module('rpn_head', rpn_head) + bbox_head = nn.Module() + bbox_head.num_classes = 2 + valid_model.add_module('bbox_head', bbox_head) + self.valid_model = valid_model + + # Setup invalid model + invalid_model = nn.Module() + bbox_head = nn.Module() + bbox_head.num_classes = 4 + invalid_model.add_module('bbox_head', bbox_head) + self.invalid_model = invalid_model + + def test_before_train_epch(self): + runner = deepcopy(self.runner) + + # Test when dataset.metainfo['classes'] is None + runner.train_dataloader.dataset = self.none_classmeta_dataset + self.hook.before_train_epoch(runner) + runner.logger.warning.assert_called_once() + # Test when dataset.metainfo['classes'] is a str + runner.train_dataloader.dataset = self.str_classmeta_dataset + with self.assertRaises(AssertionError): + self.hook.before_train_epoch(runner) + + runner.train_dataloader.dataset = self.normal_classmeta_dataset + # Test `num_classes` of model is compatible with dataset + runner.model = self.valid_model + self.hook.before_train_epoch(runner) + # Test `num_classes` of model is not compatible with dataset + runner.model = self.invalid_model + with self.assertRaises(AssertionError): + self.hook.before_train_epoch(runner) + + def test_before_val_epoch(self): + runner = deepcopy(self.runner) + + # Test when dataset.metainfo['classes'] is None + runner.val_dataloader.dataset = self.none_classmeta_dataset + self.hook.before_val_epoch(runner) + runner.logger.warning.assert_called_once() + # Test when dataset.metainfo['classes'] is a str + runner.val_dataloader.dataset = self.str_classmeta_dataset + with self.assertRaises(AssertionError): + self.hook.before_val_epoch(runner) + + runner.val_dataloader.dataset = self.normal_classmeta_dataset + # Test `num_classes` of model is compatible with dataset + runner.model = self.valid_model + self.hook.before_val_epoch(runner) + # Test `num_classes` of model is not compatible with dataset + runner.model = self.invalid_model + with self.assertRaises(AssertionError): + self.hook.before_val_epoch(runner) diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_pipeline_switch_hook.py b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_pipeline_switch_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..067812c0d973eb39e3a603ae4558d9f4edf9f80a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_pipeline_switch_hook.py @@ -0,0 +1,84 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock + +from mmdet.engine.hooks import PipelineSwitchHook + + +class TestPipelineSwitchHook(TestCase): + + def test_persistent_workers_on(self): + runner = Mock() + runner.model = Mock() + runner.model.module = Mock() + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = True + runner.train_dataloader._DataLoader__initialized = True + + stage2 = [dict(type='RandomResize', scale=(1280, 1280))] + + runner.epoch = 284 # epoch < switch_epoch + hook = PipelineSwitchHook(switch_epoch=285, switch_pipeline=stage2) + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + runner.epoch = 285 # epoch == switch_epoch + hook.before_train_epoch(runner) + self.assertTrue(hook._restart_dataloader) + self.assertFalse(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) + + runner.epoch = 286 # epoch > switch_epoch + hook.before_train_epoch(runner) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) + + def test_persistent_workers_off(self): + runner = Mock() + runner.model = Mock() + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = False + runner.train_dataloader._DataLoader__initialized = True + + stage2 = [dict(type='RandomResize', scale=(1280, 1280))] + + runner.epoch = 284 # epoch < switch_epoch + hook = PipelineSwitchHook(switch_epoch=285, switch_pipeline=stage2) + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + runner.epoch = 285 # epoch == switch_epoch + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) + + runner.epoch = 286 # epoch > switch_epoch + hook.before_train_epoch(runner) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) + + def test_initialize_after_switching(self): + # This simulates the resumption after the switching. + runner = Mock() + runner.model = Mock() + runner.model.module = Mock() + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = True + runner.train_dataloader._DataLoader__initialized = True + + stage2 = [dict(type='RandomResize', scale=(1280, 1280))] + + runner.epoch = 286 # epoch > switch_epoch + hook = PipelineSwitchHook(switch_epoch=285, switch_pipeline=stage2) + hook.before_train_epoch(runner) + self.assertTrue(hook._restart_dataloader) + self.assertFalse(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_sync_norm_hook.py b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_sync_norm_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..4664cf05359c4354b170a3478396c0155e9c12a3 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_sync_norm_hook.py @@ -0,0 +1,41 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock, patch + +import torch.nn as nn + +from mmdet.engine.hooks import SyncNormHook + + +class TestSyncNormHook(TestCase): + + @patch( + 'mmdet.engine.hooks.sync_norm_hook.get_dist_info', return_value=(0, 1)) + def test_before_val_epoch_non_dist(self, mock): + model = nn.Sequential( + nn.Conv2d(1, 5, kernel_size=3), nn.BatchNorm2d(5, momentum=0.3), + nn.Linear(5, 10)) + runner = Mock() + runner.model = model + hook = SyncNormHook() + hook.before_val_epoch(runner) + + @patch( + 'mmdet.engine.hooks.sync_norm_hook.get_dist_info', return_value=(0, 2)) + def test_before_val_epoch_dist(self, mock): + model = nn.Sequential( + nn.Conv2d(1, 5, kernel_size=3), nn.BatchNorm2d(5, momentum=0.3), + nn.Linear(5, 10)) + runner = Mock() + runner.model = model + hook = SyncNormHook() + hook.before_val_epoch(runner) + + @patch( + 'mmdet.engine.hooks.sync_norm_hook.get_dist_info', return_value=(0, 2)) + def test_before_val_epoch_dist_no_norm(self, mock): + model = nn.Sequential(nn.Conv2d(1, 5, kernel_size=3), nn.Linear(5, 10)) + runner = Mock() + runner.model = model + hook = SyncNormHook() + hook.before_val_epoch(runner) diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_visualization_hook.py b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_visualization_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..e7cd0771b28fd9fadbe0ba3e50bba89df6a7f721 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_visualization_hook.py @@ -0,0 +1,120 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import shutil +import time +from unittest import TestCase +from unittest.mock import Mock + +import torch +from mmengine.structures import InstanceData + +from mmdet.engine.hooks import DetVisualizationHook, TrackVisualizationHook +from mmdet.structures import DetDataSample, TrackDataSample +from mmdet.visualization import DetLocalVisualizer, TrackLocalVisualizer + + +def _rand_bboxes(num_boxes, h, w): + cx, cy, bw, bh = torch.rand(num_boxes, 4).T + + tl_x = ((cx * w) - (w * bw / 2)).clamp(0, w) + tl_y = ((cy * h) - (h * bh / 2)).clamp(0, h) + br_x = ((cx * w) + (w * bw / 2)).clamp(0, w) + br_y = ((cy * h) + (h * bh / 2)).clamp(0, h) + + bboxes = torch.stack([tl_x, tl_y, br_x, br_y], dim=0).T + return bboxes + + +class TestVisualizationHook(TestCase): + + def setUp(self) -> None: + DetLocalVisualizer.get_instance('current_visualizer') + + pred_instances = InstanceData() + pred_instances.bboxes = _rand_bboxes(5, 10, 12) + pred_instances.labels = torch.randint(0, 2, (5, )) + pred_instances.scores = torch.rand((5, )) + pred_det_data_sample = DetDataSample() + pred_det_data_sample.set_metainfo({ + 'img_path': + osp.join(osp.dirname(__file__), '../../data/color.jpg') + }) + pred_det_data_sample.pred_instances = pred_instances + self.outputs = [pred_det_data_sample] * 2 + + def test_after_val_iter(self): + runner = Mock() + runner.iter = 1 + hook = DetVisualizationHook() + hook.after_val_iter(runner, 1, {}, self.outputs) + + def test_after_test_iter(self): + runner = Mock() + runner.iter = 1 + hook = DetVisualizationHook(draw=True) + hook.after_test_iter(runner, 1, {}, self.outputs) + self.assertEqual(hook._test_index, 2) + + # test + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + test_out_dir = timestamp + '1' + runner.work_dir = timestamp + runner.timestamp = '1' + hook = DetVisualizationHook(draw=False, test_out_dir=test_out_dir) + hook.after_test_iter(runner, 1, {}, self.outputs) + self.assertTrue(not osp.exists(f'{timestamp}/1/{test_out_dir}')) + + hook = DetVisualizationHook(draw=True, test_out_dir=test_out_dir) + hook.after_test_iter(runner, 1, {}, self.outputs) + self.assertTrue(osp.exists(f'{timestamp}/1/{test_out_dir}')) + shutil.rmtree(f'{timestamp}') + + +class TestTrackVisualizationHook(TestCase): + + def setUp(self) -> None: + TrackLocalVisualizer.get_instance('visualizer') + # pseudo data_batch + self.data_batch = dict(data_samples=None, inputs=None) + + pred_instances_data = dict( + bboxes=torch.tensor([[100, 100, 200, 200], [150, 150, 400, 200]]), + instances_id=torch.tensor([1, 2]), + labels=torch.tensor([0, 1]), + scores=torch.tensor([0.955, 0.876])) + pred_instances = InstanceData(**pred_instances_data) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = pred_instances + img_data_sample.gt_instances = pred_instances + img_data_sample.set_metainfo( + dict( + img_path=osp.join( + osp.dirname(__file__), '../../data/color.jpg'), + scale_factor=(1.0, 1.0))) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + track_data_sample.set_metainfo(dict(ori_length=1)) + self.outputs = [track_data_sample] + + def test_after_val_iter_image(self): + runner = Mock() + runner.iter = 1 + hook = TrackVisualizationHook(frame_interval=10, draw=True) + hook.after_val_iter(runner, 9, self.data_batch, self.outputs) + + def test_after_test_iter(self): + runner = Mock() + runner.iter = 1 + hook = TrackVisualizationHook(frame_interval=10, draw=True) + hook.after_val_iter(runner, 9, self.data_batch, self.outputs) + + # test test_out_dir + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + test_out_dir = timestamp + '1' + runner.work_dir = timestamp + runner.timestamp = '1' + hook = TrackVisualizationHook( + frame_interval=10, draw=True, test_out_dir=test_out_dir) + hook.after_test_iter(runner, 9, self.data_batch, self.outputs) + self.assertTrue(osp.exists(f'{timestamp}/1/{test_out_dir}')) + shutil.rmtree(f'{timestamp}') diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_yolox_mode_switch_hook.py b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_yolox_mode_switch_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..c6201872443498c392f6845b30232e39d61e3fe7 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_hooks/test_yolox_mode_switch_hook.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock, patch + +from mmdet.engine.hooks import YOLOXModeSwitchHook + + +class TestYOLOXModeSwitchHook(TestCase): + + @patch('mmdet.engine.hooks.yolox_mode_switch_hook.is_model_wrapper') + def test_is_model_wrapper_and_persistent_workers_on( + self, mock_is_model_wrapper): + mock_is_model_wrapper.return_value = True + runner = Mock() + runner.model = Mock() + runner.model.module = Mock() + runner.model.module.detector.bbox_head.use_l1 = False + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = True + runner.train_dataloader._DataLoader__initialized = True + runner.epoch = 284 + runner.max_epochs = 300 + + hook = YOLOXModeSwitchHook(num_last_epochs=15) + hook.before_train_epoch(runner) + self.assertTrue(hook._restart_dataloader) + self.assertTrue(runner.model.module.detector.bbox_head.use_l1) + self.assertFalse(runner.train_dataloader._DataLoader__initialized) + + runner.epoch = 285 + hook.before_train_epoch(runner) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + def test_not_model_wrapper_and_persistent_workers_off(self): + runner = Mock() + runner.model = Mock() + runner.model.detector.bbox_head.use_l1 = False + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = False + runner.train_dataloader._DataLoader__initialized = True + runner.epoch = 284 + runner.max_epochs = 300 + + hook = YOLOXModeSwitchHook(num_last_epochs=15) + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.model.detector.bbox_head.use_l1) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + runner.epoch = 285 + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + @patch('mmdet.engine.hooks.yolox_mode_switch_hook.is_model_wrapper') + def test_initialize_after_switching(self, mock_is_model_wrapper): + # This simulates the resumption after the switching. + mock_is_model_wrapper.return_value = True + runner = Mock() + runner.model = Mock() + runner.model.module = Mock() + runner.model.module.bbox_head.use_l1 = False + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = True + runner.train_dataloader._DataLoader__initialized = True + runner.epoch = 285 + runner.max_epochs = 300 + + # epoch + 1 > max_epochs - num_last_epochs . + hook = YOLOXModeSwitchHook(num_last_epochs=15) + hook.before_train_epoch(runner) + self.assertTrue(hook._restart_dataloader) + self.assertTrue(runner.model.module.detector.bbox_head.use_l1) + self.assertFalse(runner.train_dataloader._DataLoader__initialized) diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_optimizers/__init__.py b/mmdet_code/SR-TOD/tests/test_engine/test_optimizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_optimizers/test_layer_decay_optimizer_constructor.py b/mmdet_code/SR-TOD/tests/test_engine/test_optimizers/test_layer_decay_optimizer_constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..bac43e224d60cb8df49fa1b8eb09dd92ab33e6f5 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_optimizers/test_layer_decay_optimizer_constructor.py @@ -0,0 +1,168 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmdet.engine import LearningRateDecayOptimizerConstructor + +base_lr = 1 +decay_rate = 2 +base_wd = 0.05 +weight_decay = 0.05 + +expected_stage_wise_lr_wd_convnext = [{ + 'weight_decay': 0.0, + 'lr_scale': 128 +}, { + 'weight_decay': 0.0, + 'lr_scale': 1 +}, { + 'weight_decay': 0.05, + 'lr_scale': 64 +}, { + 'weight_decay': 0.0, + 'lr_scale': 64 +}, { + 'weight_decay': 0.05, + 'lr_scale': 32 +}, { + 'weight_decay': 0.0, + 'lr_scale': 32 +}, { + 'weight_decay': 0.05, + 'lr_scale': 16 +}, { + 'weight_decay': 0.0, + 'lr_scale': 16 +}, { + 'weight_decay': 0.05, + 'lr_scale': 8 +}, { + 'weight_decay': 0.0, + 'lr_scale': 8 +}, { + 'weight_decay': 0.05, + 'lr_scale': 128 +}, { + 'weight_decay': 0.05, + 'lr_scale': 1 +}] + +expected_layer_wise_lr_wd_convnext = [{ + 'weight_decay': 0.0, + 'lr_scale': 128 +}, { + 'weight_decay': 0.0, + 'lr_scale': 1 +}, { + 'weight_decay': 0.05, + 'lr_scale': 64 +}, { + 'weight_decay': 0.0, + 'lr_scale': 64 +}, { + 'weight_decay': 0.05, + 'lr_scale': 32 +}, { + 'weight_decay': 0.0, + 'lr_scale': 32 +}, { + 'weight_decay': 0.05, + 'lr_scale': 16 +}, { + 'weight_decay': 0.0, + 'lr_scale': 16 +}, { + 'weight_decay': 0.05, + 'lr_scale': 2 +}, { + 'weight_decay': 0.0, + 'lr_scale': 2 +}, { + 'weight_decay': 0.05, + 'lr_scale': 128 +}, { + 'weight_decay': 0.05, + 'lr_scale': 1 +}] + + +class ToyConvNeXt(nn.Module): + + def __init__(self): + super().__init__() + self.stages = nn.ModuleList() + for i in range(4): + stage = nn.Sequential(ConvModule(3, 4, kernel_size=1, bias=True)) + self.stages.append(stage) + self.norm0 = nn.BatchNorm2d(2) + + # add some variables to meet unit test coverate rate + self.cls_token = nn.Parameter(torch.ones(1)) + self.mask_token = nn.Parameter(torch.ones(1)) + self.pos_embed = nn.Parameter(torch.ones(1)) + self.stem_norm = nn.Parameter(torch.ones(1)) + self.downsample_norm0 = nn.BatchNorm2d(2) + self.downsample_norm1 = nn.BatchNorm2d(2) + self.downsample_norm2 = nn.BatchNorm2d(2) + self.lin = nn.Parameter(torch.ones(1)) + self.lin.requires_grad = False + self.downsample_layers = nn.ModuleList() + for _ in range(4): + stage = nn.Sequential(nn.Conv2d(3, 4, kernel_size=1, bias=True)) + self.downsample_layers.append(stage) + + +class ToyDetector(nn.Module): + + def __init__(self, backbone): + super().__init__() + self.backbone = backbone + self.head = nn.Conv2d(2, 2, kernel_size=1, groups=2) + + +class PseudoDataParallel(nn.Module): + + def __init__(self, model): + super().__init__() + self.module = model + + +def check_optimizer_lr_wd(optimizer, gt_lr_wd): + assert isinstance(optimizer, torch.optim.AdamW) + assert optimizer.defaults['lr'] == base_lr + assert optimizer.defaults['weight_decay'] == base_wd + param_groups = optimizer.param_groups + print(param_groups) + assert len(param_groups) == len(gt_lr_wd) + for i, param_dict in enumerate(param_groups): + assert param_dict['weight_decay'] == gt_lr_wd[i]['weight_decay'] + assert param_dict['lr_scale'] == gt_lr_wd[i]['lr_scale'] + assert param_dict['lr_scale'] == param_dict['lr'] + + +def test_learning_rate_decay_optimizer_constructor(): + + # Test lr wd for ConvNeXT + backbone = ToyConvNeXt() + model = PseudoDataParallel(ToyDetector(backbone)) + optim_wrapper_cfg = dict( + type='OptimWrapper', + optimizer=dict( + type='AdamW', lr=base_lr, betas=(0.9, 0.999), weight_decay=0.05)) + # stagewise decay + stagewise_paramwise_cfg = dict( + decay_rate=decay_rate, decay_type='stage_wise', num_layers=6) + optim_constructor = LearningRateDecayOptimizerConstructor( + optim_wrapper_cfg, stagewise_paramwise_cfg) + optim_wrapper = optim_constructor(model) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_stage_wise_lr_wd_convnext) + # layerwise decay + layerwise_paramwise_cfg = dict( + decay_rate=decay_rate, decay_type='layer_wise', num_layers=6) + optim_constructor = LearningRateDecayOptimizerConstructor( + optim_wrapper_cfg, layerwise_paramwise_cfg) + optim_wrapper = optim_constructor(model) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_layer_wise_lr_wd_convnext) diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_runner/test_loops.py b/mmdet_code/SR-TOD/tests/test_engine/test_runner/test_loops.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf9cb4795a802eb0beef60e04938056c2eefebf --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_runner/test_loops.py @@ -0,0 +1,113 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import tempfile +from unittest import TestCase +from unittest.mock import Mock + +import torch +import torch.nn as nn +from mmengine.evaluator import Evaluator +from mmengine.model import BaseModel +from mmengine.optim import OptimWrapper +from mmengine.runner import Runner +from torch.utils.data import Dataset + +from mmdet.registry import DATASETS +from mmdet.utils import register_all_modules + +register_all_modules() + + +class ToyModel(nn.Module): + + def __init__(self): + super().__init__() + self.linear = nn.Linear(2, 1) + + def forward(self, inputs, data_samples, mode='tensor'): + labels = torch.stack(data_samples) + inputs = torch.stack(inputs) + outputs = self.linear(inputs) + if mode == 'tensor': + return outputs + elif mode == 'loss': + loss = (labels - outputs).sum() + outputs = dict(loss=loss) + return outputs + else: + return outputs + + +class ToyModel1(BaseModel, ToyModel): + + def __init__(self): + super().__init__() + + def forward(self, *args, **kwargs): + return super(BaseModel, self).forward(*args, **kwargs) + + +class ToyModel2(BaseModel): + + def __init__(self): + super().__init__() + self.teacher = ToyModel1() + self.student = ToyModel1() + self.semi_test_cfg = dict(predict_on='teacher') + + def forward(self, *args, **kwargs): + return self.student(*args, **kwargs) + + +@DATASETS.register_module(force=True) +class DummyDataset(Dataset): + METAINFO = dict() # type: ignore + data = torch.randn(12, 2) + label = torch.ones(12) + + @property + def metainfo(self): + return self.METAINFO + + def __len__(self): + return self.data.size(0) + + def __getitem__(self, index): + return dict(inputs=self.data[index], data_samples=self.label[index]) + + +class TestTeacherStudentValLoop(TestCase): + + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.temp_dir.cleanup() + + def test_teacher_student_val_loop(self): + device = 'cuda:0' if torch.cuda.is_available() else 'cpu' + model = ToyModel2().to(device) + evaluator = Mock() + evaluator.evaluate = Mock(return_value=dict(acc=0.5)) + evaluator.__class__ = Evaluator + runner = Runner( + model=model, + train_dataloader=dict( + dataset=dict(type='DummyDataset'), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=3, + num_workers=0), + val_dataloader=dict( + dataset=dict(type='DummyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=0), + val_evaluator=evaluator, + work_dir=self.temp_dir.name, + default_scope='mmdet', + optim_wrapper=OptimWrapper( + torch.optim.Adam(ToyModel().parameters())), + train_cfg=dict(by_epoch=True, max_epochs=2, val_interval=1), + val_cfg=dict(type='TeacherStudentValLoop'), + default_hooks=dict(logger=dict(type='LoggerHook', interval=1)), + experiment_name='test1') + runner.train() diff --git a/mmdet_code/SR-TOD/tests/test_engine/test_schedulers/test_quadratic_warmup.py b/mmdet_code/SR-TOD/tests/test_engine/test_schedulers/test_quadratic_warmup.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec3c4e8ebb9e9980a72ac8fb2c0edc98c647185 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_engine/test_schedulers/test_quadratic_warmup.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +import torch.nn.functional as F +import torch.optim as optim +from mmengine.optim.scheduler import _ParamScheduler +from mmengine.testing import assert_allclose + +from mmdet.engine.schedulers import (QuadraticWarmupLR, + QuadraticWarmupMomentum, + QuadraticWarmupParamScheduler) + + +class ToyModel(torch.nn.Module): + + def __init__(self): + super().__init__() + self.conv1 = torch.nn.Conv2d(1, 1, 1) + self.conv2 = torch.nn.Conv2d(1, 1, 1) + + def forward(self, x): + return self.conv2(F.relu(self.conv1(x))) + + +class TestQuadraticWarmupScheduler(TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.model = ToyModel() + self.optimizer = optim.SGD( + self.model.parameters(), lr=0.05, momentum=0.01, weight_decay=5e-4) + + def _test_scheduler_value(self, + schedulers, + targets, + epochs=10, + param_name='lr'): + if isinstance(schedulers, _ParamScheduler): + schedulers = [schedulers] + for epoch in range(epochs): + for param_group, target in zip(self.optimizer.param_groups, + targets): + print(param_group[param_name]) + assert_allclose( + target[epoch], + param_group[param_name], + msg='{} is wrong in epoch {}: expected {}, got {}'.format( + param_name, epoch, target[epoch], + param_group[param_name]), + atol=1e-5, + rtol=0) + [scheduler.step() for scheduler in schedulers] + + def test_quadratic_warmup_scheduler(self): + with self.assertRaises(ValueError): + QuadraticWarmupParamScheduler(self.optimizer, param_name='lr') + epochs = 10 + iters = 5 + warmup_factor = [pow((i + 1) / float(iters), 2) for i in range(iters)] + single_targets = [x * 0.05 for x in warmup_factor] + [0.05] * ( + epochs - iters) + targets = [single_targets, [x * epochs for x in single_targets]] + scheduler = QuadraticWarmupParamScheduler( + self.optimizer, param_name='lr', end=iters) + self._test_scheduler_value(scheduler, targets, epochs) + + def test_quadratic_warmup_scheduler_convert_iterbased(self): + epochs = 10 + end = 5 + epoch_length = 11 + + iters = end * epoch_length + warmup_factor = [pow((i + 1) / float(iters), 2) for i in range(iters)] + single_targets = [x * 0.05 for x in warmup_factor] + [0.05] * ( + epochs * epoch_length - iters) + targets = [single_targets, [x * epochs for x in single_targets]] + scheduler = QuadraticWarmupParamScheduler.build_iter_from_epoch( + self.optimizer, + param_name='lr', + end=end, + epoch_length=epoch_length) + self._test_scheduler_value(scheduler, targets, epochs * epoch_length) + + def test_quadratic_warmup_lr(self): + epochs = 10 + iters = 5 + warmup_factor = [pow((i + 1) / float(iters), 2) for i in range(iters)] + single_targets = [x * 0.05 for x in warmup_factor] + [0.05] * ( + epochs - iters) + targets = [single_targets, [x * epochs for x in single_targets]] + scheduler = QuadraticWarmupLR(self.optimizer, end=iters) + self._test_scheduler_value(scheduler, targets, epochs) + + def test_quadratic_warmup_momentum(self): + epochs = 10 + iters = 5 + warmup_factor = [pow((i + 1) / float(iters), 2) for i in range(iters)] + single_targets = [x * 0.01 for x in warmup_factor] + [0.01] * ( + epochs - iters) + targets = [single_targets, [x * epochs for x in single_targets]] + scheduler = QuadraticWarmupMomentum(self.optimizer, end=iters) + self._test_scheduler_value( + scheduler, targets, epochs, param_name='momentum') diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/__init__.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_cityscapes_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_cityscapes_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ee6eb9ba4a1dbf5fdaa5b16a60c5699c1d9688 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_cityscapes_metric.py @@ -0,0 +1,102 @@ +import os +import os.path as osp +import tempfile +import unittest + +import numpy as np +import torch +from PIL import Image + +from mmdet.evaluation import CityScapesMetric + +try: + import cityscapesscripts +except ImportError: + cityscapesscripts = None + + +class TestCityScapesMetric(unittest.TestCase): + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + @unittest.skipIf(cityscapesscripts is None, + 'cityscapesscripts is not installed.') + def test_init(self): + # test with outfile_prefix = None + with self.assertRaises(AssertionError): + CityScapesMetric(outfile_prefix=None) + + @unittest.skipIf(cityscapesscripts is None, + 'cityscapesscripts is not installed.') + def test_evaluate(self): + dummy_mask1 = np.zeros((1, 20, 20), dtype=np.uint8) + dummy_mask1[:, :10, :10] = 1 + dummy_mask2 = np.zeros((1, 20, 20), dtype=np.uint8) + dummy_mask2[:, :10, :10] = 1 + + self.outfile_prefix = osp.join(self.tmp_dir.name, 'test') + self.seg_prefix = osp.join(self.tmp_dir.name, 'cityscapes/gtFine/val') + city = 'lindau' + sequenceNb = '000000' + frameNb = '000019' + img_name1 = f'{city}_{sequenceNb}_{frameNb}_gtFine_instanceIds.png' + img_path1 = osp.join(self.seg_prefix, city, img_name1) + + frameNb = '000020' + img_name2 = f'{city}_{sequenceNb}_{frameNb}_gtFine_instanceIds.png' + img_path2 = osp.join(self.seg_prefix, city, img_name2) + os.makedirs(osp.join(self.seg_prefix, city)) + + masks1 = np.zeros((20, 20), dtype=np.int32) + masks1[:10, :10] = 24 * 1000 + Image.fromarray(masks1).save(img_path1) + + masks2 = np.zeros((20, 20), dtype=np.int32) + masks2[:10, :10] = 24 * 1000 + 1 + Image.fromarray(masks2).save(img_path2) + + data_samples = [{ + 'img_path': img_path1, + 'pred_instances': { + 'scores': torch.from_numpy(np.array([1.0])), + 'labels': torch.from_numpy(np.array([0])), + 'masks': torch.from_numpy(dummy_mask1) + } + }, { + 'img_path': img_path2, + 'pred_instances': { + 'scores': torch.from_numpy(np.array([0.98])), + 'labels': torch.from_numpy(np.array([1])), + 'masks': torch.from_numpy(dummy_mask2) + } + }] + + target = {'cityscapes/mAP': 0.5, 'cityscapes/AP@50': 0.5} + metric = CityScapesMetric( + seg_prefix=self.seg_prefix, + format_only=False, + outfile_prefix=self.outfile_prefix) + metric.dataset_meta = dict( + classes=('person', 'rider', 'car', 'truck', 'bus', 'train', + 'motorcycle', 'bicycle')) + metric.process({}, data_samples) + results = metric.evaluate(size=2) + self.assertDictEqual(results, target) + del metric + self.assertTrue(not osp.exists('{self.outfile_prefix}.results')) + + # test format_only + metric = CityScapesMetric( + seg_prefix=self.seg_prefix, + format_only=True, + outfile_prefix=self.outfile_prefix) + metric.dataset_meta = dict( + classes=('person', 'rider', 'car', 'truck', 'bus', 'train', + 'motorcycle', 'bicycle')) + metric.process({}, data_samples) + results = metric.evaluate(size=2) + self.assertDictEqual(results, dict()) diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..547b8f21e0fcff5323162323aa3a31c9d60f4ee6 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_metric.py @@ -0,0 +1,401 @@ +import os.path as osp +import tempfile +from unittest import TestCase + +import numpy as np +import pycocotools.mask as mask_util +import torch +from mmengine.fileio import dump + +from mmdet.evaluation import CocoMetric + + +class TestCocoMetric(TestCase): + + def _create_dummy_coco_json(self, json_name): + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + image = { + 'id': 0, + 'width': 640, + 'height': 640, + 'file_name': 'fake_name.jpg', + } + + annotation_1 = { + 'id': 1, + 'image_id': 0, + 'category_id': 0, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_2 = { + 'id': 2, + 'image_id': 0, + 'category_id': 0, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_3 = { + 'id': 3, + 'image_id': 0, + 'category_id': 1, + 'area': 1600, + 'bbox': [150, 160, 40, 40], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_4 = { + 'id': 4, + 'image_id': 0, + 'category_id': 0, + 'area': 10000, + 'bbox': [250, 260, 100, 100], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + categories = [ + { + 'id': 0, + 'name': 'car', + 'supercategory': 'car', + }, + { + 'id': 1, + 'name': 'bicycle', + 'supercategory': 'bicycle', + }, + ] + + fake_json = { + 'images': [image], + 'annotations': + [annotation_1, annotation_2, annotation_3, annotation_4], + 'categories': categories + } + + dump(fake_json, json_name) + + def _create_dummy_results(self): + bboxes = np.array([[50, 60, 70, 80], [100, 120, 130, 150], + [150, 160, 190, 200], [250, 260, 350, 360]]) + scores = np.array([1.0, 0.98, 0.96, 0.95]) + labels = np.array([0, 0, 1, 0]) + dummy_mask = np.zeros((4, 10, 10), dtype=np.uint8) + dummy_mask[:, :5, :5] = 1 + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_init(self): + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + with self.assertRaisesRegex(KeyError, 'metric should be one of'): + CocoMetric(ann_file=fake_json_file, metric='unknown') + + def test_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single coco dataset evaluation + coco_metric = CocoMetric( + ann_file=fake_json_file, + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + + # test box and segm coco dataset evaluation + coco_metric = CocoMetric( + ann_file=fake_json_file, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/segm_mAP': 1.0, + 'coco/segm_mAP_50': 1.0, + 'coco/segm_mAP_75': 1.0, + 'coco/segm_mAP_s': 1.0, + 'coco/segm_mAP_m': 1.0, + 'coco/segm_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + + # test invalid custom metric_items + with self.assertRaisesRegex(KeyError, + 'metric item "invalid" is not supported'): + coco_metric = CocoMetric( + ann_file=fake_json_file, metric_items=['invalid']) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process({}, [ + dict( + pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640)) + ]) + coco_metric.evaluate(size=1) + + # test custom metric_items + coco_metric = CocoMetric( + ann_file=fake_json_file, metric_items=['mAP_m']) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = { + 'coco/bbox_mAP_m': 1.0, + } + self.assertDictEqual(eval_results, target) + + def test_classwise_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single coco dataset evaluation + coco_metric = CocoMetric( + ann_file=fake_json_file, metric='bbox', classwise=True) + # coco_metric1 = CocoMetric( + # ann_file=fake_json_file, metric='bbox', classwise=True) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/car_precision': 1.0, + 'coco/bicycle_precision': 1.0, + } + self.assertDictEqual(eval_results, target) + + def test_manually_set_iou_thrs(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + + # test single coco dataset evaluation + coco_metric = CocoMetric( + ann_file=fake_json_file, metric='bbox', iou_thrs=[0.3, 0.6]) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + self.assertEqual(coco_metric.iou_thrs, [0.3, 0.6]) + + def test_fast_eval_recall(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test default proposal nums + coco_metric = CocoMetric( + ann_file=fake_json_file, metric='proposal_fast') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = {'coco/AR@100': 1.0, 'coco/AR@300': 1.0, 'coco/AR@1000': 1.0} + self.assertDictEqual(eval_results, target) + + # test manually set proposal nums + coco_metric = CocoMetric( + ann_file=fake_json_file, + metric='proposal_fast', + proposal_nums=(2, 4)) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = {'coco/AR@2': 0.5, 'coco/AR@4': 1.0} + self.assertDictEqual(eval_results, target) + + def test_evaluate_proposal(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + coco_metric = CocoMetric(ann_file=fake_json_file, metric='proposal') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + print(eval_results) + target = { + 'coco/AR@100': 1, + 'coco/AR@300': 1.0, + 'coco/AR@1000': 1.0, + 'coco/AR_s@1000': 1.0, + 'coco/AR_m@1000': 1.0, + 'coco/AR_l@1000': 1.0 + } + self.assertDictEqual(eval_results, target) + + def test_empty_results(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + coco_metric = CocoMetric(ann_file=fake_json_file, metric='bbox') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + bboxes = np.zeros((0, 4)) + labels = np.array([]) + scores = np.array([]) + dummy_mask = np.zeros((0, 10, 10), dtype=np.uint8) + empty_pred = dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + coco_metric.process( + {}, + [dict(pred_instances=empty_pred, img_id=0, ori_shape=(640, 640))]) + # coco api Index error will be caught + coco_metric.evaluate(size=1) + + def test_evaluate_without_json(self): + dummy_pred = self._create_dummy_results() + + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + instances = [{ + 'bbox_label': 0, + 'bbox': [50, 60, 70, 80], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 0, + 'bbox': [100, 120, 130, 150], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 1, + 'bbox': [150, 160, 190, 200], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 0, + 'bbox': [250, 260, 350, 360], + 'ignore_flag': 0, + 'mask': rle_mask, + }] + coco_metric = CocoMetric( + ann_file=None, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process({}, [ + dict( + pred_instances=dummy_pred, + img_id=0, + ori_shape=(640, 640), + instances=instances) + ]) + eval_results = coco_metric.evaluate(size=1) + print(eval_results) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/segm_mAP': 1.0, + 'coco/segm_mAP_50': 1.0, + 'coco/segm_mAP_75': 1.0, + 'coco/segm_mAP_s': 1.0, + 'coco/segm_mAP_m': 1.0, + 'coco/segm_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.gt.json'))) + + def test_format_only(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + with self.assertRaises(AssertionError): + CocoMetric( + ann_file=fake_json_file, + classwise=False, + format_only=True, + outfile_prefix=None) + + coco_metric = CocoMetric( + ann_file=fake_json_file, + metric='bbox', + classwise=False, + format_only=True, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + self.assertDictEqual(eval_results, dict()) + self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.bbox.json')) diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_occluded_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_occluded_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..29c4d568554cbd60c7b5424109706f4d869ac184 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_occluded_metric.py @@ -0,0 +1,46 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from tempfile import TemporaryDirectory + +import mmengine +import numpy as np + +from mmdet.datasets import CocoDataset +from mmdet.evaluation import CocoOccludedSeparatedMetric + + +def test_coco_occluded_separated_metric(): + ann = [[ + 'fake1.jpg', 'person', 8, [219.9, 176.12, 11.14, 34.23], { + 'size': [480, 640], + 'counts': b'nYW31n>2N2FNbA48Kf=?XBDe=m0OM3M4YOPB8_>L4JXao5' + } + ]] * 3 + dummy_mask = np.zeros((10, 10), dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle = { + 'size': [480, 640], + 'counts': b'nYW31n>2N2FNbA48Kf=?XBDe=m0OM3M4YOPB8_>L4JXao5' + } + res = [(None, + dict( + img_id=0, + bboxes=np.array([[50, 60, 70, 80]] * 2), + masks=[rle] * 2, + labels=np.array([0, 1], dtype=np.int64), + scores=np.array([0.77, 0.77])))] * 3 + + tempdir = TemporaryDirectory() + ann_path = osp.join(tempdir.name, 'coco_occluded.pkl') + mmengine.dump(ann, ann_path) + + metric = CocoOccludedSeparatedMetric( + ann_file='tests/data/coco_sample.json', + occluded_ann=ann_path, + separated_ann=ann_path, + metric=[]) + metric.dataset_meta = CocoDataset.METAINFO + eval_res = metric.compute_metrics(res) + assert isinstance(eval_res, dict) + assert eval_res['occluded_recall'] == 100 + assert eval_res['separated_recall'] == 100 diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_panoptic_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_panoptic_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..caae63e728b3db146e3ccda9c36b0e4ccb33658a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_panoptic_metric.py @@ -0,0 +1,285 @@ +import os +import os.path as osp +import tempfile +import unittest +from copy import deepcopy + +import mmcv +import numpy as np +import torch +from mmengine.fileio import dump + +from mmdet.evaluation import INSTANCE_OFFSET, CocoPanopticMetric + +try: + import panopticapi +except ImportError: + panopticapi = None + + +class TestCocoPanopticMetric(unittest.TestCase): + + def _create_panoptic_gt_annotations(self, ann_file, seg_map_dir): + categories = [{ + 'id': 0, + 'name': 'person', + 'supercategory': 'person', + 'isthing': 1 + }, { + 'id': 1, + 'name': 'cat', + 'supercategory': 'cat', + 'isthing': 1 + }, { + 'id': 2, + 'name': 'dog', + 'supercategory': 'dog', + 'isthing': 1 + }, { + 'id': 3, + 'name': 'wall', + 'supercategory': 'wall', + 'isthing': 0 + }] + + images = [{ + 'id': 0, + 'width': 80, + 'height': 60, + 'file_name': 'fake_name1.jpg', + }] + + annotations = [{ + 'segments_info': [{ + 'id': 1, + 'category_id': 0, + 'area': 400, + 'bbox': [10, 10, 10, 40], + 'iscrowd': 0 + }, { + 'id': 2, + 'category_id': 0, + 'area': 400, + 'bbox': [30, 10, 10, 40], + 'iscrowd': 0 + }, { + 'id': 3, + 'category_id': 2, + 'iscrowd': 0, + 'bbox': [50, 10, 10, 5], + 'area': 50 + }, { + 'id': 4, + 'category_id': 3, + 'iscrowd': 0, + 'bbox': [0, 0, 80, 60], + 'area': 3950 + }], + 'file_name': + 'fake_name1.png', + 'image_id': + 0 + }] + + gt_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories + } + + # 4 is the id of the background class annotation. + gt = np.zeros((60, 80), dtype=np.int64) + 4 + gt_bboxes = np.array( + [[10, 10, 10, 40], [30, 10, 10, 40], [50, 10, 10, 5]], + dtype=np.int64) + for i in range(3): + x, y, w, h = gt_bboxes[i] + gt[y:y + h, x:x + w] = i + 1 # id starts from 1 + + rgb_gt_seg_map = np.zeros(gt.shape + (3, ), dtype=np.uint8) + rgb_gt_seg_map[:, :, 2] = gt // (256 * 256) + rgb_gt_seg_map[:, :, 1] = gt % (256 * 256) // 256 + rgb_gt_seg_map[:, :, 0] = gt % 256 + + img_path = osp.join(seg_map_dir, 'fake_name1.png') + mmcv.imwrite(rgb_gt_seg_map[:, :, ::-1], img_path) + dump(gt_json, ann_file) + + return gt_json + + def _create_panoptic_data_samples(self): + # predictions + # TP for background class, IoU=3576/4324=0.827 + # 2 the category id of the background class + pred = np.zeros((60, 80), dtype=np.int64) + 2 + pred_bboxes = np.array( + [ + [11, 11, 10, 40], # TP IoU=351/449=0.78 + [38, 10, 10, 40], # FP + [51, 10, 10, 5] # TP IoU=45/55=0.818 + ], + dtype=np.int64) + pred_labels = np.array([0, 0, 1], dtype=np.int64) + for i in range(3): + x, y, w, h = pred_bboxes[i] + pred[y:y + h, x:x + w] = (i + 1) * INSTANCE_OFFSET + pred_labels[i] + + data_samples = [{ + 'img_id': + 0, + 'ori_shape': (60, 80), + 'img_path': + 'xxx/fake_name1.jpg', + 'segments_info': [{ + 'id': 1, + 'category': 0, + 'is_thing': 1 + }, { + 'id': 2, + 'category': 0, + 'is_thing': 1 + }, { + 'id': 3, + 'category': 1, + 'is_thing': 1 + }, { + 'id': 4, + 'category': 2, + 'is_thing': 0 + }], + 'seg_map_path': + osp.join(self.gt_seg_dir, 'fake_name1.png'), + 'pred_panoptic_seg': { + 'sem_seg': torch.from_numpy(pred).unsqueeze(0) + }, + }] + + return data_samples + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + self.gt_json_path = osp.join(self.tmp_dir.name, 'gt.json') + self.gt_seg_dir = osp.join(self.tmp_dir.name, 'gt_seg') + os.mkdir(self.gt_seg_dir) + self._create_panoptic_gt_annotations(self.gt_json_path, + self.gt_seg_dir) + self.dataset_meta = { + 'classes': ('person', 'dog', 'wall'), + 'thing_classes': ('person', 'dog'), + 'stuff_classes': ('wall', ) + } + self.target = { + 'coco_panoptic/PQ': 67.86874803219071, + 'coco_panoptic/SQ': 80.89770126158936, + 'coco_panoptic/RQ': 83.33333333333334, + 'coco_panoptic/PQ_th': 60.45252075318891, + 'coco_panoptic/SQ_th': 79.9959505972869, + 'coco_panoptic/RQ_th': 75.0, + 'coco_panoptic/PQ_st': 82.70120259019427, + 'coco_panoptic/SQ_st': 82.70120259019427, + 'coco_panoptic/RQ_st': 100.0 + } + self.data_samples = self._create_panoptic_data_samples() + + def tearDown(self): + self.tmp_dir.cleanup() + + @unittest.skipIf(panopticapi is not None, 'panopticapi is installed') + def test_init(self): + with self.assertRaises(RuntimeError): + CocoPanopticMetric() + + @unittest.skipIf(panopticapi is None, 'panopticapi is not installed') + def test_evaluate_without_json(self): + # with tmpfile, without json + metric = CocoPanopticMetric( + ann_file=None, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + outfile_prefix=None) + + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + # without tmpfile and json + outfile_prefix = f'{self.tmp_dir.name}/test' + metric = CocoPanopticMetric( + ann_file=None, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + outfile_prefix=outfile_prefix) + + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + @unittest.skipIf(panopticapi is None, 'panopticapi is not installed') + def test_evaluate_with_json(self): + # with tmpfile and json + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + outfile_prefix=None) + + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + # classwise + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=True, + nproc=1, + outfile_prefix=None) + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + # without tmpfile, with json + outfile_prefix = f'{self.tmp_dir.name}/test1' + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + outfile_prefix=outfile_prefix) + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + @unittest.skipIf(panopticapi is None, 'panopticapi is not installed') + def test_format_only(self): + with self.assertRaises(AssertionError): + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + format_only=True, + outfile_prefix=None) + + outfile_prefix = f'{self.tmp_dir.name}/test' + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + format_only=True, + outfile_prefix=outfile_prefix) + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, dict()) + self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.panoptic')) + self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.panoptic.json')) diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_video_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_video_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..a3d7d1f0c74e60d484c4ea2b34b0aa3f587f2b48 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_coco_video_metric.py @@ -0,0 +1,413 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile +from unittest import TestCase + +import numpy as np +import pycocotools.mask as mask_util +import torch +from mmengine.fileio import dump +from mmengine.structures import BaseDataElement, InstanceData + +from mmdet.evaluation import CocoVideoMetric +from mmdet.structures import DetDataSample, TrackDataSample + + +class TestCocoVideoMetric(TestCase): + + def _create_dummy_coco_json(self, json_name): + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + image = { + 'id': 0, + 'width': 640, + 'height': 640, + 'file_name': 'fake_name.jpg', + } + + annotation_1 = { + 'id': 1, + 'image_id': 0, + 'category_id': 0, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_2 = { + 'id': 2, + 'image_id': 0, + 'category_id': 0, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_3 = { + 'id': 3, + 'image_id': 0, + 'category_id': 1, + 'area': 1600, + 'bbox': [150, 160, 40, 40], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_4 = { + 'id': 4, + 'image_id': 0, + 'category_id': 0, + 'area': 10000, + 'bbox': [250, 260, 100, 100], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + categories = [ + { + 'id': 0, + 'name': 'car', + 'supercategory': 'car', + }, + { + 'id': 1, + 'name': 'bicycle', + 'supercategory': 'bicycle', + }, + ] + + fake_json = { + 'images': [image], + 'annotations': + [annotation_1, annotation_2, annotation_3, annotation_4], + 'categories': categories + } + + dump(fake_json, json_name) + + def _create_dummy_results(self): + bboxes = np.array([[50, 60, 70, 80], [100, 120, 130, 150], + [150, 160, 190, 200], [250, 260, 350, 360]]) + scores = np.array([1.0, 0.98, 0.96, 0.95]) + labels = np.array([0, 0, 1, 0]) + dummy_mask = np.zeros((4, 10, 10), dtype=np.uint8) + dummy_mask[:, :5, :5] = 1 + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_init(self): + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + with self.assertRaisesRegex(KeyError, 'metric should be one of'): + CocoVideoMetric(ann_file=fake_json_file, metric='unknown') + + def test_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single coco dataset evaluation + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + + # test box and segm coco dataset evaluation + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/segm_mAP': 1.0, + 'coco/segm_mAP_50': 1.0, + 'coco/segm_mAP_75': 1.0, + 'coco/segm_mAP_s': 1.0, + 'coco/segm_mAP_m': 1.0, + 'coco/segm_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + + # test invalid custom metric_items + with self.assertRaisesRegex(KeyError, + 'metric item "invalid" is not supported'): + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric_items=['invalid']) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + dict(inputs=None, data_samples=None), predictions) + coco_metric.evaluate() + + # test custom metric_items + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric_items=['mAP_m']) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = { + 'coco/bbox_mAP_m': 1.0, + } + self.assertDictEqual(eval_results, target) + + def test_classwise_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single coco dataset evaluation + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric='bbox', classwise=True) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/car_precision': 1.0, + 'coco/bicycle_precision': 1.0, + } + self.assertDictEqual(eval_results, target) + + def test_manually_set_iou_thrs(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + + # test single coco dataset evaluation + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric='bbox', iou_thrs=[0.3, 0.6]) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + self.assertEqual(coco_metric.iou_thrs, [0.3, 0.6]) + + def test_fast_eval_recall(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test default proposal nums + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric='proposal_fast') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = {'coco/AR@100': 1.0, 'coco/AR@300': 1.0, 'coco/AR@1000': 1.0} + self.assertDictEqual(eval_results, target) + + # test manually set proposal nums + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, + metric='proposal_fast', + proposal_nums=(2, 4)) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = {'coco/AR@2': 0.5, 'coco/AR@4': 1.0} + self.assertDictEqual(eval_results, target) + + def test_evaluate_proposal(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric='proposal') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + print(eval_results) + target = { + 'coco/AR@100': 1, + 'coco/AR@300': 1.0, + 'coco/AR@1000': 1.0, + 'coco/AR_s@1000': 1.0, + 'coco/AR_m@1000': 1.0, + 'coco/AR_l@1000': 1.0 + } + self.assertDictEqual(eval_results, target) + + def test_empty_results(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + coco_metric = CocoVideoMetric(ann_file=fake_json_file, metric='bbox') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + bboxes = np.zeros((0, 4)) + labels = np.array([]) + scores = np.array([]) + dummy_mask = np.zeros((0, 10, 10), dtype=np.uint8) + empty_pred = dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + pred_det_instances = InstanceData(**empty_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + # coco api Index error will be caught + coco_metric.evaluate() + + def test_evaluate_without_json(self): + dummy_pred = self._create_dummy_results() + + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + instances = [{ + 'bbox_label': 0, + 'bbox': [50, 60, 70, 80], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 0, + 'bbox': [100, 120, 130, 150], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 1, + 'bbox': [150, 160, 190, 200], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 0, + 'bbox': [250, 260, 350, 360], + 'ignore_flag': 0, + 'mask': rle_mask, + }] + coco_metric = CocoVideoMetric( + ann_file=None, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.instances = instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + print(eval_results) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/segm_mAP': 1.0, + 'coco/segm_mAP_50': 1.0, + 'coco/segm_mAP_75': 1.0, + 'coco/segm_mAP_s': 1.0, + 'coco/segm_mAP_m': 1.0, + 'coco/segm_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.gt.json'))) diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_crowdhuman_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_crowdhuman_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5e04e1a9fbdf20e43cd4fa7cff179a6702082b --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_crowdhuman_metric.py @@ -0,0 +1,54 @@ +import os.path as osp +import tempfile +from unittest import TestCase + +import numpy as np +import torch + +from mmdet.evaluation import CrowdHumanMetric + + +class TestCrowdHumanMetric(TestCase): + + def _create_dummy_results(self): + bboxes = np.array([[1330, 317, 418, 1338], [792, 24, 723, 2017], + [693, 291, 307, 894], [522, 290, 285, 826], + [728, 336, 175, 602], [92, 337, 267, 681]]) + bboxes[:, 2:4] += bboxes[:, 0:2] + scores = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + return dict( + bboxes=torch.from_numpy(bboxes), scores=torch.from_numpy(scores)) + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + self.ann_file_path = \ + 'tests/data/crowdhuman_dataset/test_annotation_train.odgt', + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_init(self): + with self.assertRaisesRegex(KeyError, 'metric should be one of'): + CrowdHumanMetric(ann_file=self.ann_file_path[0], metric='unknown') + + def test_evaluate(self): + # create dummy data + dummy_pred = self._create_dummy_results() + + crowdhuman_metric = CrowdHumanMetric( + ann_file=self.ann_file_path[0], + outfile_prefix=f'{self.tmp_dir.name}/test') + crowdhuman_metric.process({}, [ + dict( + pred_instances=dummy_pred, + img_id='283554,35288000868e92d4', + ori_shape=(1640, 1640)) + ]) + eval_results = crowdhuman_metric.evaluate(size=1) + target = { + 'crowd_human/mAP': 0.8333, + 'crowd_human/mMR': 0.0, + 'crowd_human/JI': 1.0 + } + self.assertDictEqual(eval_results, target) + self.assertTrue(osp.isfile(osp.join(self.tmp_dir.name, 'test.json'))) diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_dump_det_results.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_dump_det_results.py new file mode 100644 index 0000000000000000000000000000000000000000..fc7932297304cb7120e9416a6c13038bb589df40 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_dump_det_results.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile +from unittest import TestCase + +import torch +from mmengine.fileio import load +from torch import Tensor + +from mmdet.evaluation import DumpDetResults +from mmdet.structures.mask import encode_mask_results + + +class TestDumpResults(TestCase): + + def test_init(self): + with self.assertRaisesRegex(ValueError, + 'The output file must be a pkl file.'): + DumpDetResults(out_file_path='./results.json') + + def test_process(self): + metric = DumpDetResults(out_file_path='./results.pkl') + data_samples = [dict(data=(Tensor([1, 2, 3]), Tensor([4, 5, 6])))] + metric.process(None, data_samples) + self.assertEqual(len(metric.results), 1) + self.assertEqual(metric.results[0]['data'][0].device, + torch.device('cpu')) + + metric = DumpDetResults(out_file_path='./results.pkl') + masks = torch.zeros(10, 10, 4) + data_samples = [ + dict(pred_instances=dict(masks=masks), gt_instances=[]) + ] + metric.process(None, data_samples) + self.assertEqual(len(metric.results), 1) + self.assertEqual(metric.results[0]['pred_instances']['masks'], + encode_mask_results(masks.numpy())) + self.assertNotIn('gt_instances', metric.results[0]) + + def test_compute_metrics(self): + temp_dir = tempfile.TemporaryDirectory() + path = osp.join(temp_dir.name, 'results.pkl') + metric = DumpDetResults(out_file_path=path) + data_samples = [dict(data=(Tensor([1, 2, 3]), Tensor([4, 5, 6])))] + metric.process(None, data_samples) + metric.compute_metrics(metric.results) + self.assertTrue(osp.isfile(path)) + + results = load(path) + self.assertEqual(len(results), 1) + self.assertEqual(results[0]['data'][0].device, torch.device('cpu')) + + temp_dir.cleanup() diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_lvis_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_lvis_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..6f4eecc5144ac51a73122a641a60743be9aea05d --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_lvis_metric.py @@ -0,0 +1,363 @@ +import os.path as osp +import tempfile +import unittest + +import numpy as np +import pycocotools.mask as mask_util +import torch + +from mmdet.evaluation.metrics import LVISMetric + +try: + import lvis +except ImportError: + lvis = None + +from mmengine.fileio import dump + + +class TestLVISMetric(unittest.TestCase): + + def _create_dummy_lvis_json(self, json_name): + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + image = { + 'id': 0, + 'width': 640, + 'height': 640, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'coco_url': 'http://images.cocodataset.org/val2017/0.jpg', + } + + annotation_1 = { + 'id': 1, + 'image_id': 0, + 'category_id': 1, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'segmentation': rle_mask, + } + + annotation_2 = { + 'id': 2, + 'image_id': 0, + 'category_id': 1, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'segmentation': rle_mask, + } + + annotation_3 = { + 'id': 3, + 'image_id': 0, + 'category_id': 2, + 'area': 1600, + 'bbox': [150, 160, 40, 40], + 'segmentation': rle_mask, + } + + annotation_4 = { + 'id': 4, + 'image_id': 0, + 'category_id': 1, + 'area': 10000, + 'bbox': [250, 260, 100, 100], + 'segmentation': rle_mask, + } + + categories = [ + { + 'id': 1, + 'name': 'aerosol_can', + 'frequency': 'c', + 'image_count': 64 + }, + { + 'id': 2, + 'name': 'air_conditioner', + 'frequency': 'f', + 'image_count': 364 + }, + ] + + fake_json = { + 'images': [image], + 'annotations': + [annotation_1, annotation_2, annotation_3, annotation_4], + 'categories': categories + } + + dump(fake_json, json_name) + + def _create_dummy_results(self): + bboxes = np.array([[50, 60, 70, 80], [100, 120, 130, 150], + [150, 160, 190, 200], [250, 260, 350, 360]]) + scores = np.array([1.0, 0.98, 0.96, 0.95]) + labels = np.array([0, 0, 1, 0]) + dummy_mask = np.zeros((4, 10, 10), dtype=np.uint8) + dummy_mask[:, :5, :5] = 1 + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_init(self): + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + with self.assertRaisesRegex(KeyError, 'metric should be one of'): + LVISMetric(ann_file=fake_json_file, metric='unknown') + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single lvis dataset evaluation + lvis_metric = LVISMetric( + ann_file=fake_json_file, + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/bbox_AP': 1.0, + 'lvis/bbox_AP50': 1.0, + 'lvis/bbox_AP75': 1.0, + 'lvis/bbox_APs': 1.0, + 'lvis/bbox_APm': 1.0, + 'lvis/bbox_APl': 1.0, + 'lvis/bbox_APr': -1.0, + 'lvis/bbox_APc': 1.0, + 'lvis/bbox_APf': 1.0 + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + + # test box and segm lvis dataset evaluation + lvis_metric = LVISMetric( + ann_file=fake_json_file, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/bbox_AP': 1.0, + 'lvis/bbox_AP50': 1.0, + 'lvis/bbox_AP75': 1.0, + 'lvis/bbox_APs': 1.0, + 'lvis/bbox_APm': 1.0, + 'lvis/bbox_APl': 1.0, + 'lvis/bbox_APr': -1.0, + 'lvis/bbox_APc': 1.0, + 'lvis/bbox_APf': 1.0, + 'lvis/segm_AP': 1.0, + 'lvis/segm_AP50': 1.0, + 'lvis/segm_AP75': 1.0, + 'lvis/segm_APs': 1.0, + 'lvis/segm_APm': 1.0, + 'lvis/segm_APl': 1.0, + 'lvis/segm_APr': -1.0, + 'lvis/segm_APc': 1.0, + 'lvis/segm_APf': 1.0 + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + + # test invalid custom metric_items + with self.assertRaisesRegex( + KeyError, + "metric should be one of 'bbox', 'segm', 'proposal', " + "'proposal_fast', but got invalid."): + lvis_metric = LVISMetric( + ann_file=fake_json_file, metric=['invalid']) + lvis_metric.evaluate(size=1) + + # test custom metric_items + lvis_metric = LVISMetric(ann_file=fake_json_file, metric_items=['APm']) + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/bbox_APm': 1.0, + } + self.assertDictEqual(eval_results, target) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_classwise_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single lvis dataset evaluation + lvis_metric = LVISMetric( + ann_file=fake_json_file, metric='bbox', classwise=True) + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/bbox_AP': 1.0, + 'lvis/bbox_AP50': 1.0, + 'lvis/bbox_AP75': 1.0, + 'lvis/bbox_APs': 1.0, + 'lvis/bbox_APm': 1.0, + 'lvis/bbox_APl': 1.0, + 'lvis/bbox_APr': -1.0, + 'lvis/bbox_APc': 1.0, + 'lvis/bbox_APf': 1.0, + 'lvis/aerosol_can_precision': 1.0, + 'lvis/air_conditioner_precision': 1.0, + } + self.assertDictEqual(eval_results, target) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_manually_set_iou_thrs(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + + # test single lvis dataset evaluation + lvis_metric = LVISMetric( + ann_file=fake_json_file, metric='bbox', iou_thrs=[0.3, 0.6]) + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + self.assertEqual(lvis_metric.iou_thrs, [0.3, 0.6]) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_fast_eval_recall(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test default proposal nums + lvis_metric = LVISMetric( + ann_file=fake_json_file, metric='proposal_fast') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = {'lvis/AR@100': 1.0, 'lvis/AR@300': 1.0, 'lvis/AR@1000': 1.0} + self.assertDictEqual(eval_results, target) + + # test manually set proposal nums + lvis_metric = LVISMetric( + ann_file=fake_json_file, + metric='proposal_fast', + proposal_nums=(2, 4)) + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = {'lvis/AR@2': 0.5, 'lvis/AR@4': 1.0} + self.assertDictEqual(eval_results, target) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_evaluate_proposal(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + lvis_metric = LVISMetric(ann_file=fake_json_file, metric='proposal') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/AR@300': 1.0, + 'lvis/ARs@300': 1.0, + 'lvis/ARm@300': 1.0, + 'lvis/ARl@300': 1.0 + } + self.assertDictEqual(eval_results, target) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_empty_results(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + lvis_metric = LVISMetric(ann_file=fake_json_file, metric='bbox') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + bboxes = np.zeros((0, 4)) + labels = np.array([]) + scores = np.array([]) + dummy_mask = np.zeros((0, 10, 10), dtype=np.uint8) + empty_pred = dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + lvis_metric.process( + {}, + [dict(pred_instances=empty_pred, img_id=0, ori_shape=(640, 640))]) + # lvis api Index error will be caught + lvis_metric.evaluate(size=1) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_format_only(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + with self.assertRaises(AssertionError): + LVISMetric( + ann_file=fake_json_file, + classwise=False, + format_only=True, + outfile_prefix=None) + + lvis_metric = LVISMetric( + ann_file=fake_json_file, + metric='bbox', + classwise=False, + format_only=True, + outfile_prefix=f'{self.tmp_dir.name}/test') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + self.assertDictEqual(eval_results, dict()) + self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.bbox.json')) diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_mot_challenge_metrics.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_mot_challenge_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4636b8e785a9db92938378781a5a46547eb94fa2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_mot_challenge_metrics.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os +import tempfile +from unittest import TestCase + +import torch +from mmengine.structures import BaseDataElement, InstanceData + +from mmdet.evaluation import MOTChallengeMetric +from mmdet.structures import DetDataSample, TrackDataSample + + +class TestMOTChallengeMetric(TestCase): + + def test_init(self): + with self.assertRaisesRegex(KeyError, 'metric unknown is not'): + MOTChallengeMetric(metric='unknown') + with self.assertRaises(AssertionError): + MOTChallengeMetric(benchmark='MOT21') + + def __del__(self): + self.tmp_dir.cleanup() + + @staticmethod + def _get_predictions_demo(): + instances = [{ + 'bbox_label': 0, + 'bbox': [0, 0, 100, 100], + 'ignore_flag': 0, + 'instance_id': 1, + 'mot_conf': 1.0, + 'category_id': 1, + 'visibility': 1.0 + }, { + 'bbox_label': 0, + 'bbox': [0, 0, 100, 100], + 'ignore_flag': 0, + 'instance_id': 2, + 'mot_conf': 1.0, + 'category_id': 1, + 'visibility': 1.0 + }] + instances_2 = copy.deepcopy(instances) + sep = os.sep + pred_instances_data = dict( + bboxes=torch.tensor([ + [0, 0, 100, 100], + [0, 0, 100, 40], + ]), + instances_id=torch.tensor([1, 2]), + scores=torch.tensor([1.0, 1.0])) + pred_instances_data_2 = copy.deepcopy(pred_instances_data) + pred_instances = InstanceData(**pred_instances_data) + pred_instances_2 = InstanceData(**pred_instances_data_2) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = pred_instances + img_data_sample.instances = instances + img_data_sample.set_metainfo( + dict( + frame_id=0, + ori_video_length=2, + video_length=2, + img_id=1, + img_path=f'xxx{sep}MOT17-09-DPM{sep}img1{sep}000001.jpg', + )) + img_data_sample_2 = DetDataSample() + img_data_sample_2.pred_track_instances = pred_instances_2 + img_data_sample_2.instances = instances_2 + img_data_sample_2.set_metainfo( + dict( + frame_id=1, + ori_video_length=2, + video_length=2, + img_id=2, + img_path=f'xxx{sep}MOT17-09-DPM{sep}img1{sep}000002.jpg', + )) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [ + img_data_sample, img_data_sample_2 + ] + # [TrackDataSample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + return predictions + + def _test_evaluate(self, format_only, outfile_predix=None): + """Test using the metric in the same way as Evaluator.""" + metric = MOTChallengeMetric( + metric=['HOTA', 'CLEAR', 'Identity'], + format_only=format_only, + outfile_prefix=outfile_predix) + metric.dataset_meta = {'classes': ('pedestrian', )} + data_batch = dict(input=None, data_samples=None) + predictions = self._get_predictions_demo() + metric.process(data_batch, predictions) + eval_results = metric.evaluate() + return eval_results + + def test_evaluate(self): + eval_results = self._test_evaluate(False) + target = { + 'motchallenge-metric/IDF1': 0.5, + 'motchallenge-metric/MOTA': 0, + 'motchallenge-metric/HOTA': 0.755, + 'motchallenge-metric/IDSW': 0, + } + for key in target: + assert eval_results[key] - target[key] < 1e-3 + + def test_evaluate_format_only(self): + self.tmp_dir = tempfile.TemporaryDirectory() + eval_results = self._test_evaluate( + True, outfile_predix=self.tmp_dir.name) + assert eval_results == dict() diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_openimages_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_openimages_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..d64b1dfa2d6b10ce8afd734fcf37b95d5ab1f9e8 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_openimages_metric.py @@ -0,0 +1,72 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import numpy as np +import torch + +from mmdet.datasets import OpenImagesDataset +from mmdet.evaluation import OpenImagesMetric +from mmdet.utils import register_all_modules + + +class TestOpenImagesMetric(unittest.TestCase): + + def _create_dummy_results(self): + bboxes = np.array([[23.2172, 31.7541, 987.3413, 357.8443], + [100, 120, 130, 150], [150, 160, 190, 200], + [250, 260, 350, 360]]) + scores = np.array([1.0, 0.98, 0.96, 0.95]) + labels = np.array([0, 0, 0, 0]) + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels)) + + def test_init(self): + # test invalid iou_thrs + with self.assertRaises(AssertionError): + OpenImagesMetric(iou_thrs={'a', 0.5}, ioa_thrs={'b', 0.5}) + # test ioa and iou_thrs length not equal + with self.assertRaises(AssertionError): + OpenImagesMetric(iou_thrs=[0.5, 0.75], ioa_thrs=[0.5]) + + metric = OpenImagesMetric(iou_thrs=0.6) + self.assertEqual(metric.iou_thrs, [0.6]) + + def test_eval(self): + register_all_modules() + dataset = OpenImagesDataset( + data_root='tests/data/OpenImages/', + ann_file='annotations/oidv6-train-annotations-bbox.csv', + data_prefix=dict(img='OpenImages/train/'), + label_file='annotations/class-descriptions-boxable.csv', + hierarchy_file='annotations/bbox_labels_600_hierarchy.json', + meta_file='annotations/image-metas.pkl', + pipeline=[ + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'instances')) + ]) + dataset.full_init() + data_sample = dataset[0]['data_samples'].to_dict() + data_sample['pred_instances'] = self._create_dummy_results() + + metric = OpenImagesMetric() + metric.dataset_meta = dataset.metainfo + metric.process({}, [data_sample]) + results = metric.evaluate(size=len(dataset)) + targets = {'openimages/AP50': 1.0, 'openimages/mAP': 1.0} + self.assertDictEqual(results, targets) + + # test multi-threshold + metric = OpenImagesMetric(iou_thrs=[0.1, 0.5], ioa_thrs=[0.1, 0.5]) + metric.dataset_meta = dataset.metainfo + metric.process({}, [data_sample]) + results = metric.evaluate(size=len(dataset)) + targets = { + 'openimages/AP10': 1.0, + 'openimages/AP50': 1.0, + 'openimages/mAP': 1.0 + } + self.assertDictEqual(results, targets) diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_reid_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_reid_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc6218ad3f69ee8ebf8974a446c04028828ace9 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_reid_metric.py @@ -0,0 +1,55 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.registry import init_default_scope + +from mmdet.registry import METRICS +from mmdet.structures import ReIDDataSample + + +class TestReIDMetrics(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + def test_evaluate(self): + """Test using the metric in the same way as Evaluator.""" + data_samples = [ + ReIDDataSample().set_gt_label(i).to_dict() + for i in [0, 0, 1, 1, 1, 1] + ] + pred_batch = [ + dict(pred_feature=torch.tensor( + [1., .0, .1])), # [x,√,x,x,x],R1=0,R5=1,AP=0.50 + dict(pred_feature=torch.tensor( + [.8, .0, .0])), # [x,√,x,x,x],R1=0,R5=1,AP=0.50 + dict(pred_feature=torch.tensor( + [.1, 1., .1])), # [√,√,x,√,x],R1=1,R5=1,AP≈0.92 + dict(pred_feature=torch.tensor( + [.0, .9, .1])), # [√,√,√,x,x],R1=1,R5=1,AP=1.00 + dict(pred_feature=torch.tensor( + [.9, .1, .0])), # [x,x,√,√,√],R1=0,R5=1,AP≈0.48 + dict(pred_feature=torch.tensor( + [.0, .1, 1.])), # [√,√,x,√,x],R1=1,R5=1,AP≈0.92 + ] + # get union + for idx in range(len(data_samples)): + data_samples[idx] = {**data_samples[idx], **pred_batch[idx]} + + metric = METRICS.build( + dict( + type='ReIDMetrics', + metric=['mAP', 'CMC'], + metric_options=dict(rank_list=[1, 5], max_rank=5), + )) + + prefix = 'reid-metric' + data_batch = dict(input=None, data_samples=None) + metric.process(data_batch, data_samples) + results = metric.evaluate(6) + self.assertIsInstance(results, dict) + self.assertEqual(results[f'{prefix}/mAP'], 0.719) + self.assertEqual(results[f'{prefix}/R1'], 0.5) + self.assertEqual(results[f'{prefix}/R5'], 1.0) diff --git a/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_youtube_vis_metric.py b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_youtube_vis_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..dd46437c6efe447724775c09e7a876df2d0dbc90 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_evaluation/test_metrics/test_youtube_vis_metric.py @@ -0,0 +1,171 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import tempfile +from unittest import TestCase + +import numpy as np +import pycocotools.mask as mask_util +import torch +from mmengine.registry import init_default_scope +from mmengine.structures import BaseDataElement, InstanceData + +from mmdet.registry import METRICS +from mmdet.structures import DetDataSample, TrackDataSample + + +class TestYouTubeVISMetric(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + def _create_dummy_results(self, track_id): + bboxes = np.array([[100, 100, 150, 150]]) + scores = np.array([1.0]) + labels = np.array([0]) + instance_id = np.array([track_id]) + dummy_mask = np.zeros((1, 720, 1280), dtype=np.uint8) + dummy_mask[:, 100:150, 100:150] = 1 + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + instances_id=torch.from_numpy(instance_id), + masks=torch.from_numpy(dummy_mask)) + + def test_format_only(self): + outfile_prefix = f'{self.tmp_dir.name}/result' + vis_metric = METRICS.build( + dict( + type='YouTubeVISMetric', + format_only=True, + outfile_prefix=outfile_prefix, + )) + dummy_pred = self._create_dummy_results(track_id=0) + dummy_mask = np.zeros((720, 1280), order='F', dtype=np.uint8) + dummy_mask[100:150, 100:150] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + instances = [{ + 'bbox_label': 0, + 'bbox': [100, 100, 150, 150], + 'ignore_flag': 0, + 'instance_id': 1, + 'mask': rle_mask, + }] + vis_metric.dataset_meta = dict(classes=['car', 'train']) + data_batch = dict(inputs=None, data_samples=None) + gt_insatnce = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = gt_insatnce + img_data_sample.set_metainfo( + dict( + img_id=0, + video_id=1, + ori_video_length=1, + ori_shape=(720, 1280), + instances=instances)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + vis_metric.process(data_batch, predictions) + vis_metric.evaluate(size=1) + assert os.path.exists(f'{outfile_prefix}.json') + assert os.path.exists(f'{outfile_prefix}.submission_file.zip') + + def test_evaluate(self): + """Test using the metric in the same way as Evaluator.""" + dummy_pred_1 = self._create_dummy_results(track_id=1) + dummy_pred_2 = self._create_dummy_results(track_id=1) + dummy_pred_3 = self._create_dummy_results(track_id=2) + + dummy_mask = np.zeros((720, 1280), order='F', dtype=np.uint8) + dummy_mask[100:150, 100:150] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + instances_1 = [{ + 'bbox_label': 0, + 'bbox': [100, 100, 150, 150], + 'ignore_flag': 0, + 'instance_id': 1, + 'mask': rle_mask, + }] + instances_2 = [{ + 'bbox_label': 0, + 'bbox': [100, 100, 150, 150], + 'ignore_flag': 0, + 'instance_id': 2, + 'mask': rle_mask, + }] + vis_metric = METRICS.build( + dict( + type='YouTubeVISMetric', + outfile_prefix=f'{self.tmp_dir.name}/test', + )) + + vis_metric.dataset_meta = dict(classes=['car', 'train']) + data_batch = dict(inputs=None, data_samples=None) + gt_insatnce = InstanceData(**dummy_pred_1) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = gt_insatnce + img_data_sample.set_metainfo( + dict( + img_id=1, + video_id=1, + ori_video_length=2, + ori_shape=(720, 1280), + instances=instances_1)) + gt_insatnce_2 = InstanceData(**dummy_pred_2) + img_data_sample_2 = DetDataSample() + img_data_sample_2.pred_track_instances = gt_insatnce_2 + img_data_sample_2.set_metainfo( + dict( + img_id=2, + video_id=1, + ori_video_length=2, + ori_shape=(720, 1280), + instances=instances_1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [ + img_data_sample, img_data_sample_2 + ] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + vis_metric.process(data_batch, predictions) + + gt_insatnce = InstanceData(**dummy_pred_3) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = gt_insatnce + img_data_sample.set_metainfo( + dict( + img_id=3, + video_id=2, + ori_video_length=1, + ori_shape=(720, 1280), + instances=instances_2)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + vis_metric.process(data_batch, predictions) + + eval_results = vis_metric.evaluate(size=3) + target = { + 'youtube_vis/segm_mAP': 1.0, + 'youtube_vis/segm_mAP_50': 1.0, + 'youtube_vis/segm_mAP_75': 1.0, + 'youtube_vis/segm_mAP_s': 1.0, + 'youtube_vis/segm_mAP_m': -1.0, + 'youtube_vis/segm_mAP_l': -1.0, + } + self.assertDictEqual(eval_results, target) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/__init__.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb431ba20bd3a89c0750862f7a4874f0ecd55ffb --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .utils import check_norm_state, is_block, is_norm + +__all__ = ['is_block', 'is_norm', 'check_norm_state'] diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_csp_darknet.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_csp_darknet.py new file mode 100644 index 0000000000000000000000000000000000000000..2a2ad41dba941d85ab59781d27731dac9a9dfb72 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_csp_darknet.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.backbones.csp_darknet import CSPDarknet +from .utils import check_norm_state, is_norm + + +def test_csp_darknet_backbone(): + with pytest.raises(ValueError): + # frozen_stages must in range(-1, len(arch_setting) + 1) + CSPDarknet(frozen_stages=6) + + with pytest.raises(AssertionError): + # out_indices in range(len(arch_setting) + 1) + CSPDarknet(out_indices=[6]) + + # Test CSPDarknet with first stage frozen + frozen_stages = 1 + model = CSPDarknet(frozen_stages=frozen_stages) + model.train() + + for mod in model.stem.modules(): + for param in mod.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'stage{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test CSPDarknet with norm_eval=True + model = CSPDarknet(norm_eval=True) + model.train() + + assert check_norm_state(model.modules(), False) + + # Test CSPDarknet-P5 forward with widen_factor=0.5 + model = CSPDarknet(arch='P5', widen_factor=0.25, out_indices=range(0, 5)) + model.train() + + imgs = torch.randn(1, 3, 64, 64) + feat = model(imgs) + assert len(feat) == 5 + assert feat[0].shape == torch.Size((1, 16, 32, 32)) + assert feat[1].shape == torch.Size((1, 32, 16, 16)) + assert feat[2].shape == torch.Size((1, 64, 8, 8)) + assert feat[3].shape == torch.Size((1, 128, 4, 4)) + assert feat[4].shape == torch.Size((1, 256, 2, 2)) + + # Test CSPDarknet-P6 forward with widen_factor=0.5 + model = CSPDarknet( + arch='P6', + widen_factor=0.25, + out_indices=range(0, 6), + spp_kernal_sizes=(3, 5, 7)) + model.train() + + imgs = torch.randn(1, 3, 128, 128) + feat = model(imgs) + assert feat[0].shape == torch.Size((1, 16, 64, 64)) + assert feat[1].shape == torch.Size((1, 32, 32, 32)) + assert feat[2].shape == torch.Size((1, 64, 16, 16)) + assert feat[3].shape == torch.Size((1, 128, 8, 8)) + assert feat[4].shape == torch.Size((1, 192, 4, 4)) + assert feat[5].shape == torch.Size((1, 256, 2, 2)) + + # Test CSPDarknet forward with dict(type='ReLU') + model = CSPDarknet( + widen_factor=0.125, act_cfg=dict(type='ReLU'), out_indices=range(0, 5)) + model.train() + + imgs = torch.randn(1, 3, 64, 64) + feat = model(imgs) + assert len(feat) == 5 + assert feat[0].shape == torch.Size((1, 8, 32, 32)) + assert feat[1].shape == torch.Size((1, 16, 16, 16)) + assert feat[2].shape == torch.Size((1, 32, 8, 8)) + assert feat[3].shape == torch.Size((1, 64, 4, 4)) + assert feat[4].shape == torch.Size((1, 128, 2, 2)) + + # Test CSPDarknet with BatchNorm forward + model = CSPDarknet(widen_factor=0.125, out_indices=range(0, 5)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, _BatchNorm) + model.train() + + imgs = torch.randn(1, 3, 64, 64) + feat = model(imgs) + assert len(feat) == 5 + assert feat[0].shape == torch.Size((1, 8, 32, 32)) + assert feat[1].shape == torch.Size((1, 16, 16, 16)) + assert feat[2].shape == torch.Size((1, 32, 8, 8)) + assert feat[3].shape == torch.Size((1, 64, 4, 4)) + assert feat[4].shape == torch.Size((1, 128, 2, 2)) + + # Test CSPDarknet with custom arch forward + arch_ovewrite = [[32, 56, 3, True, False], [56, 224, 2, True, False], + [224, 512, 1, True, False]] + model = CSPDarknet( + arch_ovewrite=arch_ovewrite, + widen_factor=0.25, + out_indices=(0, 1, 2, 3)) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size((1, 8, 16, 16)) + assert feat[1].shape == torch.Size((1, 14, 8, 8)) + assert feat[2].shape == torch.Size((1, 56, 4, 4)) + assert feat[3].shape == torch.Size((1, 128, 2, 2)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_detectors_resnet.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_detectors_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..69f462a5433592c117ffe4a450bbdd7d60303681 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_detectors_resnet.py @@ -0,0 +1,47 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest + +from mmdet.models.backbones import DetectoRS_ResNet + + +def test_detectorrs_resnet_backbone(): + detectorrs_cfg = dict( + 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', + conv_cfg=dict(type='ConvAWS'), + sac=dict(type='SAC', use_deform=True), + stage_with_sac=(False, True, True, True), + output_img=True) + """Test init_weights config""" + with pytest.raises(AssertionError): + # pretrained and init_cfg cannot be specified at the same time + DetectoRS_ResNet( + **detectorrs_cfg, pretrained='Pretrained', init_cfg='Pretrained') + + with pytest.raises(AssertionError): + # init_cfg must be a dict + DetectoRS_ResNet( + **detectorrs_cfg, pretrained=None, init_cfg=['Pretrained']) + + with pytest.raises(KeyError): + # init_cfg must contain the key `type` + DetectoRS_ResNet( + **detectorrs_cfg, + pretrained=None, + init_cfg=dict(checkpoint='Pretrained')) + + with pytest.raises(AssertionError): + # init_cfg only support initialize pretrained model way + DetectoRS_ResNet( + **detectorrs_cfg, pretrained=None, init_cfg=dict(type='Trained')) + + with pytest.raises(TypeError): + # pretrained mast be a str or None + model = DetectoRS_ResNet( + **detectorrs_cfg, pretrained=['Pretrained'], init_cfg=None) + model.init_weights() diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_efficientnet.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_efficientnet.py new file mode 100644 index 0000000000000000000000000000000000000000..aa21770481986ccc908d2c859e1afddc3b22b5e8 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_efficientnet.py @@ -0,0 +1,25 @@ +import pytest +import torch + +from mmdet.models.backbones import EfficientNet + + +def test_efficientnet_backbone(): + """Test EfficientNet backbone.""" + with pytest.raises(AssertionError): + # EfficientNet arch should be a key in EfficientNet.arch_settings + EfficientNet(arch='c3') + + model = EfficientNet(arch='b0', out_indices=(0, 1, 2, 3, 4, 5, 6)) + model.train() + + imgs = torch.randn(2, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size([2, 32, 16, 16]) + assert feat[1].shape == torch.Size([2, 16, 16, 16]) + assert feat[2].shape == torch.Size([2, 24, 8, 8]) + assert feat[3].shape == torch.Size([2, 40, 4, 4]) + assert feat[4].shape == torch.Size([2, 112, 2, 2]) + assert feat[5].shape == torch.Size([2, 320, 1, 1]) + assert feat[6].shape == torch.Size([2, 1280, 1, 1]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_hourglass.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_hourglass.py new file mode 100644 index 0000000000000000000000000000000000000000..c26f9c05e6987e01e18b135de788ae3113b85de4 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_hourglass.py @@ -0,0 +1,49 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones.hourglass import HourglassNet + + +def test_hourglass_backbone(): + with pytest.raises(AssertionError): + # HourglassNet's num_stacks should larger than 0 + HourglassNet(num_stacks=0) + + with pytest.raises(AssertionError): + # len(stage_channels) should equal len(stage_blocks) + HourglassNet( + stage_channels=[256, 256, 384, 384, 384], + stage_blocks=[2, 2, 2, 2, 2, 4]) + + with pytest.raises(AssertionError): + # len(stage_channels) should lagrer than downsample_times + HourglassNet( + downsample_times=5, + stage_channels=[256, 256, 384, 384, 384], + stage_blocks=[2, 2, 2, 2, 2]) + + # Test HourglassNet-52 + model = HourglassNet( + num_stacks=1, + stage_channels=(64, 64, 96, 96, 96, 128), + feat_channel=64) + model.train() + + imgs = torch.randn(1, 3, 256, 256) + feat = model(imgs) + assert len(feat) == 1 + assert feat[0].shape == torch.Size([1, 64, 64, 64]) + + # Test HourglassNet-104 + model = HourglassNet( + num_stacks=2, + stage_channels=(64, 64, 96, 96, 96, 128), + feat_channel=64) + model.train() + + imgs = torch.randn(1, 3, 256, 256) + feat = model(imgs) + assert len(feat) == 2 + assert feat[0].shape == torch.Size([1, 64, 64, 64]) + assert feat[1].shape == torch.Size([1, 64, 64, 64]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_hrnet.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_hrnet.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae367b4eaf87a34c54841c1b4c4b4b79ca2f2f3 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_hrnet.py @@ -0,0 +1,111 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones.hrnet import HRModule, HRNet +from mmdet.models.backbones.resnet import BasicBlock, Bottleneck + + +@pytest.mark.parametrize('block', [BasicBlock, Bottleneck]) +def test_hrmodule(block): + # Test multiscale forward + num_channles = (32, 64) + in_channels = [c * block.expansion for c in num_channles] + hrmodule = HRModule( + num_branches=2, + blocks=block, + in_channels=in_channels, + num_blocks=(4, 4), + num_channels=num_channles, + ) + + feats = [ + torch.randn(1, in_channels[0], 64, 64), + torch.randn(1, in_channels[1], 32, 32) + ] + feats = hrmodule(feats) + + assert len(feats) == 2 + assert feats[0].shape == torch.Size([1, in_channels[0], 64, 64]) + assert feats[1].shape == torch.Size([1, in_channels[1], 32, 32]) + + # Test single scale forward + num_channles = (32, 64) + in_channels = [c * block.expansion for c in num_channles] + hrmodule = HRModule( + num_branches=2, + blocks=block, + in_channels=in_channels, + num_blocks=(4, 4), + num_channels=num_channles, + multiscale_output=False, + ) + + feats = [ + torch.randn(1, in_channels[0], 64, 64), + torch.randn(1, in_channels[1], 32, 32) + ] + feats = hrmodule(feats) + + assert len(feats) == 1 + assert feats[0].shape == torch.Size([1, in_channels[0], 64, 64]) + + +def test_hrnet_backbone(): + # only have 3 stages + extra = dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128))) + + with pytest.raises(AssertionError): + # HRNet now only support 4 stages + HRNet(extra=extra) + extra['stage4'] = dict( + num_modules=3, + num_branches=3, # should be 4 + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256)) + + with pytest.raises(AssertionError): + # len(num_blocks) should equal num_branches + HRNet(extra=extra) + + extra['stage4']['num_branches'] = 4 + + # Test hrnetv2p_w32 + model = HRNet(extra=extra) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 256, 256) + feats = model(imgs) + assert len(feats) == 4 + assert feats[0].shape == torch.Size([1, 32, 64, 64]) + assert feats[3].shape == torch.Size([1, 256, 8, 8]) + + # Test single scale output + model = HRNet(extra=extra, multiscale_output=False) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 256, 256) + feats = model(imgs) + assert len(feats) == 1 + assert feats[0].shape == torch.Size([1, 32, 64, 64]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_mobilenet_v2.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_mobilenet_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..77df7ea50f105f95cdd79a0271e28ece99452b1c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_mobilenet_v2.py @@ -0,0 +1,173 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from torch.nn.modules import GroupNorm +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.backbones.mobilenet_v2 import MobileNetV2 +from .utils import check_norm_state, is_block, is_norm + + +def test_mobilenetv2_backbone(): + with pytest.raises(ValueError): + # frozen_stages must in range(-1, 8) + MobileNetV2(frozen_stages=8) + + with pytest.raises(ValueError): + # out_indices in range(-1, 8) + MobileNetV2(out_indices=[8]) + + # Test MobileNetV2 with first stage frozen + frozen_stages = 1 + model = MobileNetV2(frozen_stages=frozen_stages) + model.train() + + for mod in model.conv1.modules(): + for param in mod.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'layer{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test MobileNetV2 with norm_eval=True + model = MobileNetV2(norm_eval=True) + model.train() + + assert check_norm_state(model.modules(), False) + + # Test MobileNetV2 forward with widen_factor=1.0 + model = MobileNetV2(widen_factor=1.0, out_indices=range(0, 8)) + model.train() + + assert check_norm_state(model.modules(), True) + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 8 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) + assert feat[7].shape == torch.Size((1, 1280, 7, 7)) + + # Test MobileNetV2 forward with widen_factor=0.5 + model = MobileNetV2(widen_factor=0.5, out_indices=range(0, 7)) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 8, 112, 112)) + assert feat[1].shape == torch.Size((1, 16, 56, 56)) + assert feat[2].shape == torch.Size((1, 16, 28, 28)) + assert feat[3].shape == torch.Size((1, 32, 14, 14)) + assert feat[4].shape == torch.Size((1, 48, 14, 14)) + assert feat[5].shape == torch.Size((1, 80, 7, 7)) + assert feat[6].shape == torch.Size((1, 160, 7, 7)) + + # Test MobileNetV2 forward with widen_factor=2.0 + model = MobileNetV2(widen_factor=2.0, out_indices=range(0, 8)) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[0].shape == torch.Size((1, 32, 112, 112)) + assert feat[1].shape == torch.Size((1, 48, 56, 56)) + assert feat[2].shape == torch.Size((1, 64, 28, 28)) + assert feat[3].shape == torch.Size((1, 128, 14, 14)) + assert feat[4].shape == torch.Size((1, 192, 14, 14)) + assert feat[5].shape == torch.Size((1, 320, 7, 7)) + assert feat[6].shape == torch.Size((1, 640, 7, 7)) + assert feat[7].shape == torch.Size((1, 2560, 7, 7)) + + # Test MobileNetV2 forward with dict(type='ReLU') + model = MobileNetV2( + widen_factor=1.0, act_cfg=dict(type='ReLU'), out_indices=range(0, 7)) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) + + # Test MobileNetV2 with BatchNorm forward + model = MobileNetV2(widen_factor=1.0, out_indices=range(0, 7)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, _BatchNorm) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) + + # Test MobileNetV2 with GroupNorm forward + model = MobileNetV2( + widen_factor=1.0, + norm_cfg=dict(type='GN', num_groups=2, requires_grad=True), + out_indices=range(0, 7)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, GroupNorm) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) + + # Test MobileNetV2 with layers 1, 3, 5 out forward + model = MobileNetV2(widen_factor=1.0, out_indices=(0, 2, 4)) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 32, 28, 28)) + assert feat[2].shape == torch.Size((1, 96, 14, 14)) + + # Test MobileNetV2 with checkpoint forward + model = MobileNetV2( + widen_factor=1.0, with_cp=True, out_indices=range(0, 7)) + for m in model.modules(): + if is_block(m): + assert m.with_cp + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_pvt.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_pvt.py new file mode 100644 index 0000000000000000000000000000000000000000..029fdb327803b838001a9121a738e890fbc14780 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_pvt.py @@ -0,0 +1,103 @@ +import pytest +import torch + +from mmdet.models.backbones.pvt import (PVTEncoderLayer, + PyramidVisionTransformer, + PyramidVisionTransformerV2) + + +def test_pvt_block(): + # test PVT structure and forward + block = PVTEncoderLayer( + embed_dims=64, num_heads=4, feedforward_channels=256) + assert block.ffn.embed_dims == 64 + assert block.attn.num_heads == 4 + assert block.ffn.feedforward_channels == 256 + x = torch.randn(1, 56 * 56, 64) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + +def test_pvt(): + """Test PVT backbone.""" + + with pytest.raises(TypeError): + # Pretrained arg must be str or None. + PyramidVisionTransformer(pretrained=123) + + # test pretrained image size + with pytest.raises(AssertionError): + PyramidVisionTransformer(pretrain_img_size=(224, 224, 224)) + + # Test absolute position embedding + temp = torch.randn((1, 3, 224, 224)) + model = PyramidVisionTransformer( + pretrain_img_size=224, use_abs_pos_embed=True) + model.init_weights() + model(temp) + + # Test normal inference + temp = torch.randn((1, 3, 32, 32)) + model = PyramidVisionTransformer() + outs = model(temp) + assert outs[0].shape == (1, 64, 8, 8) + assert outs[1].shape == (1, 128, 4, 4) + assert outs[2].shape == (1, 320, 2, 2) + assert outs[3].shape == (1, 512, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 33, 33)) + model = PyramidVisionTransformer() + outs = model(temp) + assert outs[0].shape == (1, 64, 8, 8) + assert outs[1].shape == (1, 128, 4, 4) + assert outs[2].shape == (1, 320, 2, 2) + assert outs[3].shape == (1, 512, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 112, 137)) + model = PyramidVisionTransformer() + outs = model(temp) + assert outs[0].shape == (1, 64, 28, 34) + assert outs[1].shape == (1, 128, 14, 17) + assert outs[2].shape == (1, 320, 7, 8) + assert outs[3].shape == (1, 512, 3, 4) + + +def test_pvtv2(): + """Test PVTv2 backbone.""" + + with pytest.raises(TypeError): + # Pretrained arg must be str or None. + PyramidVisionTransformerV2(pretrained=123) + + # test pretrained image size + with pytest.raises(AssertionError): + PyramidVisionTransformerV2(pretrain_img_size=(224, 224, 224)) + + # Test normal inference + temp = torch.randn((1, 3, 32, 32)) + model = PyramidVisionTransformerV2() + outs = model(temp) + assert outs[0].shape == (1, 64, 8, 8) + assert outs[1].shape == (1, 128, 4, 4) + assert outs[2].shape == (1, 320, 2, 2) + assert outs[3].shape == (1, 512, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 31, 31)) + model = PyramidVisionTransformerV2() + outs = model(temp) + assert outs[0].shape == (1, 64, 8, 8) + assert outs[1].shape == (1, 128, 4, 4) + assert outs[2].shape == (1, 320, 2, 2) + assert outs[3].shape == (1, 512, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 112, 137)) + model = PyramidVisionTransformerV2() + outs = model(temp) + assert outs[0].shape == (1, 64, 28, 35) + assert outs[1].shape == (1, 128, 14, 18) + assert outs[2].shape == (1, 320, 7, 9) + assert outs[3].shape == (1, 512, 4, 5) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_regnet.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_regnet.py new file mode 100644 index 0000000000000000000000000000000000000000..2f94b1156d5ddd6805a74d41c6211d98d6ec1f0d --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_regnet.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import RegNet + +regnet_test_data = [ + ('regnetx_400mf', + dict(w0=24, wa=24.48, wm=2.54, group_w=16, depth=22, + bot_mul=1.0), [32, 64, 160, 384]), + ('regnetx_800mf', + dict(w0=56, wa=35.73, wm=2.28, group_w=16, depth=16, + bot_mul=1.0), [64, 128, 288, 672]), + ('regnetx_1.6gf', + dict(w0=80, wa=34.01, wm=2.25, group_w=24, depth=18, + bot_mul=1.0), [72, 168, 408, 912]), + ('regnetx_3.2gf', + dict(w0=88, wa=26.31, wm=2.25, group_w=48, depth=25, + bot_mul=1.0), [96, 192, 432, 1008]), + ('regnetx_4.0gf', + dict(w0=96, wa=38.65, wm=2.43, group_w=40, depth=23, + bot_mul=1.0), [80, 240, 560, 1360]), + ('regnetx_6.4gf', + dict(w0=184, wa=60.83, wm=2.07, group_w=56, depth=17, + bot_mul=1.0), [168, 392, 784, 1624]), + ('regnetx_8.0gf', + dict(w0=80, wa=49.56, wm=2.88, group_w=120, depth=23, + bot_mul=1.0), [80, 240, 720, 1920]), + ('regnetx_12gf', + dict(w0=168, wa=73.36, wm=2.37, group_w=112, depth=19, + bot_mul=1.0), [224, 448, 896, 2240]), +] + + +@pytest.mark.parametrize('arch_name,arch,out_channels', regnet_test_data) +def test_regnet_backbone(arch_name, arch, out_channels): + with pytest.raises(AssertionError): + # ResNeXt depth should be in [50, 101, 152] + RegNet(arch_name + '233') + + # Test RegNet with arch_name + model = RegNet(arch_name) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, out_channels[0], 8, 8]) + assert feat[1].shape == torch.Size([1, out_channels[1], 4, 4]) + assert feat[2].shape == torch.Size([1, out_channels[2], 2, 2]) + assert feat[3].shape == torch.Size([1, out_channels[3], 1, 1]) + + # Test RegNet with arch + model = RegNet(arch) + assert feat[0].shape == torch.Size([1, out_channels[0], 8, 8]) + assert feat[1].shape == torch.Size([1, out_channels[1], 4, 4]) + assert feat[2].shape == torch.Size([1, out_channels[2], 2, 2]) + assert feat[3].shape == torch.Size([1, out_channels[3], 1, 1]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_renext.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_renext.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce2ee6137d77084ccb47a32c8f40557e576e74d --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_renext.py @@ -0,0 +1,105 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import ResNeXt +from mmdet.models.backbones.resnext import Bottleneck as BottleneckX +from .utils import is_block + + +def test_renext_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + BottleneckX(64, 64, groups=32, base_width=4, style='tensorflow') + + # Test ResNeXt Bottleneck structure + block = BottleneckX( + 64, 64, groups=32, base_width=4, stride=2, style='pytorch') + assert block.conv2.stride == (2, 2) + assert block.conv2.groups == 32 + assert block.conv2.out_channels == 128 + + # Test ResNeXt Bottleneck with DCN + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + with pytest.raises(AssertionError): + # conv_cfg must be None if dcn is not None + BottleneckX( + 64, + 64, + groups=32, + base_width=4, + dcn=dcn, + conv_cfg=dict(type='Conv')) + BottleneckX(64, 64, dcn=dcn) + + # Test ResNeXt Bottleneck forward + block = BottleneckX(64, 16, groups=32, base_width=4) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test ResNeXt Bottleneck forward with plugins + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + stages=(False, False, True, True), + position='after_conv2') + ] + block = BottleneckX(64, 16, groups=32, base_width=4, plugins=plugins) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnext_backbone(): + with pytest.raises(KeyError): + # ResNeXt depth should be in [50, 101, 152] + ResNeXt(depth=18) + + # Test ResNeXt with group 32, base_width 4 + model = ResNeXt(depth=50, groups=32, base_width=4) + for m in model.modules(): + if is_block(m): + assert m.conv2.groups == 32 + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 256, 8, 8]) + assert feat[1].shape == torch.Size([1, 512, 4, 4]) + assert feat[2].shape == torch.Size([1, 1024, 2, 2]) + assert feat[3].shape == torch.Size([1, 2048, 1, 1]) + + +regnet_test_data = [ + ('regnetx_400mf', + dict(w0=24, wa=24.48, wm=2.54, group_w=16, depth=22, + bot_mul=1.0), [32, 64, 160, 384]), + ('regnetx_800mf', + dict(w0=56, wa=35.73, wm=2.28, group_w=16, depth=16, + bot_mul=1.0), [64, 128, 288, 672]), + ('regnetx_1.6gf', + dict(w0=80, wa=34.01, wm=2.25, group_w=24, depth=18, + bot_mul=1.0), [72, 168, 408, 912]), + ('regnetx_3.2gf', + dict(w0=88, wa=26.31, wm=2.25, group_w=48, depth=25, + bot_mul=1.0), [96, 192, 432, 1008]), + ('regnetx_4.0gf', + dict(w0=96, wa=38.65, wm=2.43, group_w=40, depth=23, + bot_mul=1.0), [80, 240, 560, 1360]), + ('regnetx_6.4gf', + dict(w0=184, wa=60.83, wm=2.07, group_w=56, depth=17, + bot_mul=1.0), [168, 392, 784, 1624]), + ('regnetx_8.0gf', + dict(w0=80, wa=49.56, wm=2.88, group_w=120, depth=23, + bot_mul=1.0), [80, 240, 720, 1920]), + ('regnetx_12gf', + dict(w0=168, wa=73.36, wm=2.37, group_w=112, depth=19, + bot_mul=1.0), [224, 448, 896, 2240]), +] diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_res2net.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_res2net.py new file mode 100644 index 0000000000000000000000000000000000000000..6757869d5a663738bd8c8321e22d491d3a92dbbf --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_res2net.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import Res2Net +from mmdet.models.backbones.res2net import Bottle2neck +from .utils import is_block + + +def test_res2net_bottle2neck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + Bottle2neck(64, 64, base_width=26, scales=4, style='tensorflow') + + with pytest.raises(AssertionError): + # Scale must be larger than 1 + Bottle2neck(64, 64, base_width=26, scales=1, style='pytorch') + + # Test Res2Net Bottle2neck structure + block = Bottle2neck( + 64, 64, base_width=26, stride=2, scales=4, style='pytorch') + assert block.scales == 4 + + # Test Res2Net Bottle2neck with DCN + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + with pytest.raises(AssertionError): + # conv_cfg must be None if dcn is not None + Bottle2neck( + 64, + 64, + base_width=26, + scales=4, + dcn=dcn, + conv_cfg=dict(type='Conv')) + Bottle2neck(64, 64, dcn=dcn) + + # Test Res2Net Bottle2neck forward + block = Bottle2neck(64, 16, base_width=26, scales=4) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_res2net_backbone(): + with pytest.raises(KeyError): + # Res2Net depth should be in [50, 101, 152] + Res2Net(depth=18) + + # Test Res2Net with scales 4, base_width 26 + model = Res2Net(depth=50, scales=4, base_width=26) + for m in model.modules(): + if is_block(m): + assert m.scales == 4 + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 256, 8, 8]) + assert feat[1].shape == torch.Size([1, 512, 4, 4]) + assert feat[2].shape == torch.Size([1, 1024, 2, 2]) + assert feat[3].shape == torch.Size([1, 2048, 1, 1]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_resnest.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_resnest.py new file mode 100644 index 0000000000000000000000000000000000000000..245fdfd3181096afd3bc1c90d790f95186360ace --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_resnest.py @@ -0,0 +1,47 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import ResNeSt +from mmdet.models.backbones.resnest import Bottleneck as BottleneckS + + +def test_resnest_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + BottleneckS(64, 64, radix=2, reduction_factor=4, style='tensorflow') + + # Test ResNeSt Bottleneck structure + block = BottleneckS( + 2, 4, radix=2, reduction_factor=4, stride=2, style='pytorch') + assert block.avd_layer.stride == 2 + assert block.conv2.channels == 4 + + # Test ResNeSt Bottleneck forward + block = BottleneckS(16, 4, radix=2, reduction_factor=4) + x = torch.randn(2, 16, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([2, 16, 56, 56]) + + +def test_resnest_backbone(): + with pytest.raises(KeyError): + # ResNeSt depth should be in [50, 101, 152, 200] + ResNeSt(depth=18) + + # Test ResNeSt with radix 2, reduction_factor 4 + model = ResNeSt( + depth=50, + base_channels=4, + radix=2, + reduction_factor=4, + out_indices=(0, 1, 2, 3)) + model.train() + + imgs = torch.randn(2, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([2, 16, 8, 8]) + assert feat[1].shape == torch.Size([2, 32, 4, 4]) + assert feat[2].shape == torch.Size([2, 64, 2, 2]) + assert feat[3].shape == torch.Size([2, 128, 1, 1]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_resnet.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f648f3b5e00a9191595553fcd75e8c7482a8d2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_resnet.py @@ -0,0 +1,654 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmcv.ops import DeformConv2dPack +from torch.nn.modules import AvgPool2d, GroupNorm +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.backbones import ResNet, ResNetV1d +from mmdet.models.backbones.resnet import BasicBlock, Bottleneck +from mmdet.models.layers import ResLayer, SimplifiedBasicBlock +from .utils import check_norm_state, is_block, is_norm + + +def assert_params_all_zeros(module) -> bool: + """Check if the parameters of the module is all zeros. + + Args: + module (nn.Module): The module to be checked. + + Returns: + bool: Whether the parameters of the module is all zeros. + """ + weight_data = module.weight.data + is_weight_zero = weight_data.allclose( + weight_data.new_zeros(weight_data.size())) + + if hasattr(module, 'bias') and module.bias is not None: + bias_data = module.bias.data + is_bias_zero = bias_data.allclose( + bias_data.new_zeros(bias_data.size())) + else: + is_bias_zero = True + + return is_weight_zero and is_bias_zero + + +def test_resnet_basic_block(): + with pytest.raises(AssertionError): + # Not implemented yet. + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + BasicBlock(64, 64, dcn=dcn) + + with pytest.raises(AssertionError): + # Not implemented yet. + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + BasicBlock(64, 64, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + BasicBlock(64, 64, plugins=plugins) + + # test BasicBlock structure and forward + block = BasicBlock(64, 64) + assert block.conv1.in_channels == 64 + assert block.conv1.out_channels == 64 + assert block.conv1.kernel_size == (3, 3) + assert block.conv2.in_channels == 64 + assert block.conv2.out_channels == 64 + assert block.conv2.kernel_size == (3, 3) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test BasicBlock with checkpoint forward + block = BasicBlock(64, 64, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnet_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + Bottleneck(64, 64, style='tensorflow') + + with pytest.raises(AssertionError): + # Allowed positions are 'after_conv1', 'after_conv2', 'after_conv3' + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv4') + ] + Bottleneck(64, 16, plugins=plugins) + + with pytest.raises(AssertionError): + # Need to specify different postfix to avoid duplicate plugin name + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + Bottleneck(64, 16, plugins=plugins) + + with pytest.raises(KeyError): + # Plugin type is not supported + plugins = [dict(cfg=dict(type='WrongPlugin'), position='after_conv3')] + Bottleneck(64, 16, plugins=plugins) + + # Test Bottleneck with checkpoint forward + block = Bottleneck(64, 16, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck style + block = Bottleneck(64, 64, stride=2, style='pytorch') + assert block.conv1.stride == (1, 1) + assert block.conv2.stride == (2, 2) + block = Bottleneck(64, 64, stride=2, style='caffe') + assert block.conv1.stride == (2, 2) + assert block.conv2.stride == (1, 1) + + # Test Bottleneck DCN + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + with pytest.raises(AssertionError): + Bottleneck(64, 64, dcn=dcn, conv_cfg=dict(type='Conv')) + block = Bottleneck(64, 64, dcn=dcn) + assert isinstance(block.conv2, DeformConv2dPack) + + # Test Bottleneck forward + block = Bottleneck(64, 16) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2, 1 NonLocal2D + # after conv2, 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2'), + dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + assert block.nonlocal_block.in_channels == 16 + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv2, 2 ContextBlock after + # conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), + position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=3), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.context_block1.in_channels == 16 + assert block.context_block2.in_channels == 64 + assert block.context_block3.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_simplied_basic_block(): + with pytest.raises(AssertionError): + # Not implemented yet. + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + SimplifiedBasicBlock(64, 64, dcn=dcn) + + with pytest.raises(AssertionError): + # Not implemented yet. + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + SimplifiedBasicBlock(64, 64, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + SimplifiedBasicBlock(64, 64, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + SimplifiedBasicBlock(64, 64, with_cp=True) + + # test SimplifiedBasicBlock structure and forward + block = SimplifiedBasicBlock(64, 64) + assert block.conv1.in_channels == 64 + assert block.conv1.out_channels == 64 + assert block.conv1.kernel_size == (3, 3) + assert block.conv2.in_channels == 64 + assert block.conv2.out_channels == 64 + assert block.conv2.kernel_size == (3, 3) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # test SimplifiedBasicBlock without norm + block = SimplifiedBasicBlock(64, 64, norm_cfg=None) + assert block.norm1 is None + assert block.norm2 is None + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnet_res_layer(): + # Test ResLayer of 3 Bottleneck w\o downsample + layer = ResLayer(Bottleneck, 64, 16, 3) + assert len(layer) == 3 + assert layer[0].conv1.in_channels == 64 + assert layer[0].conv1.out_channels == 16 + for i in range(1, len(layer)): + assert layer[i].conv1.in_channels == 64 + assert layer[i].conv1.out_channels == 16 + for i in range(len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test ResLayer of 3 Bottleneck with downsample + layer = ResLayer(Bottleneck, 64, 64, 3) + assert layer[0].downsample[0].out_channels == 256 + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 56, 56]) + + # Test ResLayer of 3 Bottleneck with stride=2 + layer = ResLayer(Bottleneck, 64, 64, 3, stride=2) + assert layer[0].downsample[0].out_channels == 256 + assert layer[0].downsample[0].stride == (2, 2) + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 28, 28]) + + # Test ResLayer of 3 Bottleneck with stride=2 and average downsample + layer = ResLayer(Bottleneck, 64, 64, 3, stride=2, avg_down=True) + assert isinstance(layer[0].downsample[0], AvgPool2d) + assert layer[0].downsample[1].out_channels == 256 + assert layer[0].downsample[1].stride == (1, 1) + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 28, 28]) + + # Test ResLayer of 3 BasicBlock with stride=2 and downsample_first=False + layer = ResLayer(BasicBlock, 64, 64, 3, stride=2, downsample_first=False) + assert layer[2].downsample[0].out_channels == 64 + assert layer[2].downsample[0].stride == (2, 2) + for i in range(len(layer) - 1): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 64, 28, 28]) + + +def test_resnest_stem(): + # Test default stem_channels + model = ResNet(50) + assert model.stem_channels == 64 + assert model.conv1.out_channels == 64 + assert model.norm1.num_features == 64 + + # Test default stem_channels, with base_channels=3 + model = ResNet(50, base_channels=3) + assert model.stem_channels == 3 + assert model.conv1.out_channels == 3 + assert model.norm1.num_features == 3 + assert model.layer1[0].conv1.in_channels == 3 + + # Test stem_channels=3 + model = ResNet(50, stem_channels=3) + assert model.stem_channels == 3 + assert model.conv1.out_channels == 3 + assert model.norm1.num_features == 3 + assert model.layer1[0].conv1.in_channels == 3 + + # Test stem_channels=3, with base_channels=2 + model = ResNet(50, stem_channels=3, base_channels=2) + assert model.stem_channels == 3 + assert model.conv1.out_channels == 3 + assert model.norm1.num_features == 3 + assert model.layer1[0].conv1.in_channels == 3 + + # Test V1d stem_channels + model = ResNetV1d(depth=50, stem_channels=6) + model.train() + assert model.stem[0].out_channels == 3 + assert model.stem[1].num_features == 3 + assert model.stem[3].out_channels == 3 + assert model.stem[4].num_features == 3 + assert model.stem[6].out_channels == 6 + assert model.stem[7].num_features == 6 + assert model.layer1[0].conv1.in_channels == 6 + + +def test_resnet_backbone(): + """Test resnet backbone.""" + with pytest.raises(KeyError): + # ResNet depth should be in [18, 34, 50, 101, 152] + ResNet(20) + + with pytest.raises(AssertionError): + # In ResNet: 1 <= num_stages <= 4 + ResNet(50, num_stages=0) + + with pytest.raises(AssertionError): + # len(stage_with_dcn) == num_stages + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + ResNet(50, dcn=dcn, stage_with_dcn=(True, )) + + with pytest.raises(AssertionError): + # len(stage_with_plugin) == num_stages + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + stages=(False, True, True), + position='after_conv3') + ] + ResNet(50, plugins=plugins) + + with pytest.raises(AssertionError): + # In ResNet: 1 <= num_stages <= 4 + ResNet(50, num_stages=5) + + with pytest.raises(AssertionError): + # len(strides) == len(dilations) == num_stages + ResNet(50, strides=(1, ), dilations=(1, 1), num_stages=3) + + with pytest.raises(TypeError): + # pretrained must be a string path + model = ResNet(50, pretrained=0) + + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + ResNet(50, style='tensorflow') + + # Test ResNet50 norm_eval=True + model = ResNet(50, norm_eval=True, base_channels=1) + model.train() + assert check_norm_state(model.modules(), False) + + # Test ResNet50 with torchvision pretrained weight + model = ResNet( + depth=50, norm_eval=True, pretrained='torchvision://resnet50') + model.train() + assert check_norm_state(model.modules(), False) + + # Test ResNet50 with first stage frozen + frozen_stages = 1 + model = ResNet(50, frozen_stages=frozen_stages, base_channels=1) + model.train() + assert model.norm1.training is False + for layer in [model.conv1, model.norm1]: + for param in layer.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'layer{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test ResNet50V1d with first stage frozen + model = ResNetV1d(depth=50, frozen_stages=frozen_stages, base_channels=2) + assert len(model.stem) == 9 + model.train() + assert check_norm_state(model.stem, False) + for param in model.stem.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'layer{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test ResNet18 forward + model = ResNet(18) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 8, 8]) + assert feat[1].shape == torch.Size([1, 128, 4, 4]) + assert feat[2].shape == torch.Size([1, 256, 2, 2]) + assert feat[3].shape == torch.Size([1, 512, 1, 1]) + + # Test ResNet18 with checkpoint forward + model = ResNet(18, with_cp=True) + for m in model.modules(): + if is_block(m): + assert m.with_cp + + # Test ResNet50 with BatchNorm forward + model = ResNet(50, base_channels=1) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, _BatchNorm) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 4, 8, 8]) + assert feat[1].shape == torch.Size([1, 8, 4, 4]) + assert feat[2].shape == torch.Size([1, 16, 2, 2]) + assert feat[3].shape == torch.Size([1, 32, 1, 1]) + + # Test ResNet50 with layers 1, 2, 3 out forward + model = ResNet(50, out_indices=(0, 1, 2), base_channels=1) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == torch.Size([1, 4, 8, 8]) + assert feat[1].shape == torch.Size([1, 8, 4, 4]) + assert feat[2].shape == torch.Size([1, 16, 2, 2]) + + # Test ResNet50 with checkpoint forward + model = ResNet(50, with_cp=True, base_channels=1) + for m in model.modules(): + if is_block(m): + assert m.with_cp + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 4, 8, 8]) + assert feat[1].shape == torch.Size([1, 8, 4, 4]) + assert feat[2].shape == torch.Size([1, 16, 2, 2]) + assert feat[3].shape == torch.Size([1, 32, 1, 1]) + + # Test ResNet50 with GroupNorm forward + model = ResNet( + 50, + base_channels=4, + norm_cfg=dict(type='GN', num_groups=2, requires_grad=True)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, GroupNorm) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 16, 8, 8]) + assert feat[1].shape == torch.Size([1, 32, 4, 4]) + assert feat[2].shape == torch.Size([1, 64, 2, 2]) + assert feat[3].shape == torch.Size([1, 128, 1, 1]) + + # Test ResNet50 with 1 GeneralizedAttention after conv2, 1 NonLocal2D + # after conv2, 1 ContextBlock after conv3 in layers 2, 3, 4 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + stages=(False, True, True, True), + position='after_conv2'), + dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + stages=(False, True, True, False), + position='after_conv3') + ] + model = ResNet(50, plugins=plugins, base_channels=8) + for m in model.layer1.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'gen_attention_block') + assert m.nonlocal_block.in_channels == 8 + for m in model.layer2.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 16 + assert m.gen_attention_block.in_channels == 16 + assert m.context_block.in_channels == 64 + + for m in model.layer3.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 32 + assert m.gen_attention_block.in_channels == 32 + assert m.context_block.in_channels == 128 + + for m in model.layer4.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 64 + assert m.gen_attention_block.in_channels == 64 + assert not hasattr(m, 'context_block') + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 32, 8, 8]) + assert feat[1].shape == torch.Size([1, 64, 4, 4]) + assert feat[2].shape == torch.Size([1, 128, 2, 2]) + assert feat[3].shape == torch.Size([1, 256, 1, 1]) + + # Test ResNet50 with 1 ContextBlock after conv2, 1 ContextBlock after + # conv3 in layers 2, 3, 4 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), + stages=(False, True, True, False), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), + stages=(False, True, True, False), + position='after_conv3') + ] + + model = ResNet(50, plugins=plugins, base_channels=8) + for m in model.layer1.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'context_block1') + assert not hasattr(m, 'context_block2') + for m in model.layer2.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert m.context_block1.in_channels == 64 + assert m.context_block2.in_channels == 64 + + for m in model.layer3.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert m.context_block1.in_channels == 128 + assert m.context_block2.in_channels == 128 + + for m in model.layer4.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'context_block1') + assert not hasattr(m, 'context_block2') + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 32, 8, 8]) + assert feat[1].shape == torch.Size([1, 64, 4, 4]) + assert feat[2].shape == torch.Size([1, 128, 2, 2]) + assert feat[3].shape == torch.Size([1, 256, 1, 1]) + + # Test ResNet50 zero initialization of residual + model = ResNet(50, zero_init_residual=True, base_channels=1) + model.init_weights() + for m in model.modules(): + if isinstance(m, Bottleneck): + assert assert_params_all_zeros(m.norm3) + elif isinstance(m, BasicBlock): + assert assert_params_all_zeros(m.norm2) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 4, 8, 8]) + assert feat[1].shape == torch.Size([1, 8, 4, 4]) + assert feat[2].shape == torch.Size([1, 16, 2, 2]) + assert feat[3].shape == torch.Size([1, 32, 1, 1]) + + # Test ResNetV1d forward + model = ResNetV1d(depth=50, base_channels=2) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 8, 8, 8]) + assert feat[1].shape == torch.Size([1, 16, 4, 4]) + assert feat[2].shape == torch.Size([1, 32, 2, 2]) + assert feat[3].shape == torch.Size([1, 64, 1, 1]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_swin.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_swin.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6420cf8e3f67f9f0c47cc48f6197d1b7302283 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_swin.py @@ -0,0 +1,82 @@ +import pytest +import torch + +from mmdet.models.backbones.swin import SwinBlock, SwinTransformer + + +def test_swin_block(): + # test SwinBlock structure and forward + block = SwinBlock(embed_dims=64, num_heads=4, feedforward_channels=256) + assert block.ffn.embed_dims == 64 + assert block.attn.w_msa.num_heads == 4 + assert block.ffn.feedforward_channels == 256 + x = torch.randn(1, 56 * 56, 64) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + # Test BasicBlock with checkpoint forward + block = SwinBlock( + embed_dims=64, num_heads=4, feedforward_channels=256, with_cp=True) + assert block.with_cp + x = torch.randn(1, 56 * 56, 64) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + +def test_swin_transformer(): + """Test Swin Transformer backbone.""" + + with pytest.raises(TypeError): + # Pretrained arg must be str or None. + SwinTransformer(pretrained=123) + + with pytest.raises(AssertionError): + # Because swin uses non-overlapping patch embed, so the stride of patch + # embed must be equal to patch size. + SwinTransformer(strides=(2, 2, 2, 2), patch_size=4) + + # test pretrained image size + with pytest.raises(AssertionError): + SwinTransformer(pretrain_img_size=(224, 224, 224)) + + # Test absolute position embedding + temp = torch.randn((1, 3, 224, 224)) + model = SwinTransformer(pretrain_img_size=224, use_abs_pos_embed=True) + model.init_weights() + model(temp) + + # Test patch norm + model = SwinTransformer(patch_norm=False) + model(temp) + + # Test normal inference + temp = torch.randn((1, 3, 32, 32)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 8, 8) + assert outs[1].shape == (1, 192, 4, 4) + assert outs[2].shape == (1, 384, 2, 2) + assert outs[3].shape == (1, 768, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 31, 31)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 8, 8) + assert outs[1].shape == (1, 192, 4, 4) + assert outs[2].shape == (1, 384, 2, 2) + assert outs[3].shape == (1, 768, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 112, 137)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 28, 35) + assert outs[1].shape == (1, 192, 14, 18) + assert outs[2].shape == (1, 384, 7, 9) + assert outs[3].shape == (1, 768, 4, 5) + + model = SwinTransformer(frozen_stages=4) + model.train() + for p in model.parameters(): + assert not p.requires_grad diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_trident_resnet.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_trident_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..a79b97e1d1560663013c4b60ccde6ba47b7fc72c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/test_trident_resnet.py @@ -0,0 +1,180 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import TridentResNet +from mmdet.models.backbones.trident_resnet import TridentBottleneck + + +def test_trident_resnet_bottleneck(): + trident_dilations = (1, 2, 3) + test_branch_idx = 1 + concat_output = True + trident_build_config = (trident_dilations, test_branch_idx, concat_output) + + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + TridentBottleneck( + *trident_build_config, inplanes=64, planes=64, style='tensorflow') + + with pytest.raises(AssertionError): + # Allowed positions are 'after_conv1', 'after_conv2', 'after_conv3' + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv4') + ] + TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + + with pytest.raises(AssertionError): + # Need to specify different postfix to avoid duplicate plugin name + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + + with pytest.raises(KeyError): + # Plugin type is not supported + plugins = [dict(cfg=dict(type='WrongPlugin'), position='after_conv3')] + TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + + # Test Bottleneck with checkpoint forward + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck style + block = TridentBottleneck( + *trident_build_config, + inplanes=64, + planes=64, + stride=2, + style='pytorch') + assert block.conv1.stride == (1, 1) + assert block.conv2.stride == (2, 2) + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=64, stride=2, style='caffe') + assert block.conv1.stride == (2, 2) + assert block.conv2.stride == (1, 1) + + # Test Bottleneck forward + block = TridentBottleneck(*trident_build_config, inplanes=64, planes=16) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2, 1 NonLocal2D + # after conv2, 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2'), + dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + assert block.nonlocal_block.in_channels == 16 + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv2, 2 ContextBlock after + # conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), + position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=3), + position='after_conv3') + ] + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + assert block.context_block1.in_channels == 16 + assert block.context_block2.in_channels == 64 + assert block.context_block3.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + +def test_trident_resnet_backbone(): + tridentresnet_config = dict( + num_branch=3, + test_branch_idx=1, + strides=(1, 2, 2), + dilations=(1, 1, 1), + trident_dilations=(1, 2, 3), + out_indices=(2, ), + ) + """Test tridentresnet backbone.""" + with pytest.raises(AssertionError): + # TridentResNet depth should be in [50, 101, 152] + TridentResNet(18, **tridentresnet_config) + + with pytest.raises(AssertionError): + # In TridentResNet: num_stages == 3 + TridentResNet(50, num_stages=4, **tridentresnet_config) + + model = TridentResNet(50, num_stages=3, **tridentresnet_config) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 1 + assert feat[0].shape == torch.Size([3, 1024, 2, 2]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_backbones/utils.py b/mmdet_code/SR-TOD/tests/test_models/test_backbones/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0f69a9e339e2a4e082dd0ffc7ede68cd834a4a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_backbones/utils.py @@ -0,0 +1,32 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from torch.nn.modules import GroupNorm +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.backbones.res2net import Bottle2neck +from mmdet.models.backbones.resnet import BasicBlock, Bottleneck +from mmdet.models.backbones.resnext import Bottleneck as BottleneckX +from mmdet.models.layers import SimplifiedBasicBlock + + +def is_block(modules): + """Check if is ResNet building block.""" + if isinstance(modules, (BasicBlock, Bottleneck, BottleneckX, Bottle2neck, + SimplifiedBasicBlock)): + return True + return False + + +def is_norm(modules): + """Check if is one of the norms.""" + if isinstance(modules, (GroupNorm, _BatchNorm)): + return True + return False + + +def check_norm_state(modules, train_state): + """Check if norm layer is in correct train state.""" + for mod in modules: + if isinstance(mod, _BatchNorm): + if mod.training != train_state: + return False + return True diff --git a/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_batch_resize.py b/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_batch_resize.py new file mode 100644 index 0000000000000000000000000000000000000000..9278d4957800319ca32a24a8fc7878f44bc0652f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_batch_resize.py @@ -0,0 +1,27 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +from mmdet.models.data_preprocessors import BatchResize, DetDataPreprocessor +from mmdet.testing import demo_mm_inputs + + +class TestDetDataPreprocessor(TestCase): + + def test_batch_resize(self): + + processor = DetDataPreprocessor( + mean=[103.53, 116.28, 123.675], + std=[57.375, 57.12, 58.395], + bgr_to_rgb=False, + batch_augments=[ + dict(type='BatchResize', scale=(32, 32), pad_size_divisor=32) + ]) + self.assertTrue(isinstance(processor.batch_augments[0], BatchResize)) + + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], use_box_type=True) + data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = data['inputs'], data['data_samples'] + self.assertEqual(batch_inputs.shape[-2:], (32, 32)) + self.assertEqual(batch_data_samples[0].scale_factor, + batch_data_samples[1].scale_factor) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_boxinst_preprocessor.py b/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_boxinst_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..57038fe80dd54c0853edf530e2fc6160fb49dd1e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_boxinst_preprocessor.py @@ -0,0 +1,59 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models.data_preprocessors import BoxInstDataPreprocessor +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs + + +class TestBoxInstDataPreprocessor(TestCase): + + def test_forward(self): + processor = BoxInstDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + + data = { + 'inputs': [torch.randint(0, 256, (3, 256, 256))], + 'data_samples': [DetDataSample()] + } + + # Test evaluation mode + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + + self.assertEqual(batch_inputs.shape, (1, 3, 256, 256)) + self.assertEqual(len(batch_data_samples), 1) + + # Test traning mode without gt bboxes + packed_inputs = demo_mm_inputs( + 2, [[3, 256, 256], [3, 128, 128]], num_items=[0, 0]) + out_data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + + self.assertEqual(batch_inputs.shape, (2, 3, 256, 256)) + self.assertEqual(len(batch_data_samples), 2) + self.assertEqual(len(batch_data_samples[0].gt_instances.masks), 0) + self.assertEqual( + len(batch_data_samples[0].gt_instances.pairwise_masks), 0) + self.assertEqual(len(batch_data_samples[1].gt_instances.masks), 0) + self.assertEqual( + len(batch_data_samples[1].gt_instances.pairwise_masks), 0) + + # Test traning mode with gt bboxes + packed_inputs = demo_mm_inputs( + 2, [[3, 256, 256], [3, 128, 128]], num_items=[2, 1]) + out_data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + + self.assertEqual(batch_inputs.shape, (2, 3, 256, 256)) + self.assertEqual(len(batch_data_samples), 2) + self.assertEqual(len(batch_data_samples[0].gt_instances.masks), 2) + self.assertEqual( + len(batch_data_samples[0].gt_instances.pairwise_masks), 2) + self.assertEqual(len(batch_data_samples[1].gt_instances.masks), 1) + self.assertEqual( + len(batch_data_samples[1].gt_instances.pairwise_masks), 1) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_data_preprocessor.py b/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_data_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..1638666bfc1f0004e3a7e3989897dcda69a7a4f8 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_data_preprocessor.py @@ -0,0 +1,357 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub + +from mmdet.models.data_preprocessors import (BatchFixedSizePad, + BatchSyncRandomResize, + DetDataPreprocessor, + MultiBranchDataPreprocessor) +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs + + +class TestDetDataPreprocessor(TestCase): + + def test_init(self): + # test mean is None + processor = DetDataPreprocessor() + self.assertTrue(not hasattr(processor, 'mean')) + self.assertTrue(processor._enable_normalize is False) + + # test mean is not None + processor = DetDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + self.assertTrue(hasattr(processor, 'mean')) + self.assertTrue(hasattr(processor, 'std')) + self.assertTrue(processor._enable_normalize) + + # please specify both mean and std + with self.assertRaises(AssertionError): + DetDataPreprocessor(mean=[0, 0, 0]) + + # bgr2rgb and rgb2bgr cannot be set to True at the same time + with self.assertRaises(AssertionError): + DetDataPreprocessor(bgr_to_rgb=True, rgb_to_bgr=True) + + def test_forward(self): + processor = DetDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + + data = { + 'inputs': [torch.randint(0, 256, (3, 11, 10))], + 'data_samples': [DetDataSample()] + } + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + + self.assertEqual(batch_inputs.shape, (1, 3, 11, 10)) + self.assertEqual(len(batch_data_samples), 1) + + # test channel_conversion + processor = DetDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], bgr_to_rgb=True) + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + self.assertEqual(batch_inputs.shape, (1, 3, 11, 10)) + self.assertEqual(len(batch_data_samples), 1) + + # test padding + data = { + 'inputs': [ + torch.randint(0, 256, (3, 10, 11)), + torch.randint(0, 256, (3, 9, 14)) + ] + } + processor = DetDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], bgr_to_rgb=True) + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + self.assertEqual(batch_inputs.shape, (2, 3, 10, 14)) + self.assertIsNone(batch_data_samples) + + # test pad_size_divisor + data = { + 'inputs': [ + torch.randint(0, 256, (3, 10, 11)), + torch.randint(0, 256, (3, 9, 24)) + ], + 'data_samples': [DetDataSample()] * 2 + } + processor = DetDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], pad_size_divisor=5) + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + self.assertEqual(batch_inputs.shape, (2, 3, 10, 25)) + self.assertEqual(len(batch_data_samples), 2) + for data_samples, expected_shape in zip(batch_data_samples, + [(10, 15), (10, 25)]): + self.assertEqual(data_samples.pad_shape, expected_shape) + + # test pad_mask=True and pad_seg=True + processor = DetDataPreprocessor( + pad_mask=True, mask_pad_value=0, pad_seg=True, seg_pad_value=0) + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], + with_mask=True, + with_semantic=True, + use_box_type=True) + packed_inputs['data_samples'][0].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 10, 11)) + packed_inputs['data_samples'][1].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 9, 24)) + mask_pad_sums = [ + x.gt_instances.masks.masks.sum() + for x in packed_inputs['data_samples'] + ] + seg_pad_sums = [ + x.gt_sem_seg.sem_seg.sum() for x in packed_inputs['data_samples'] + ] + batch_data_samples = processor( + packed_inputs, training=True)['data_samples'] + for data_samples, expected_shape, mask_pad_sum, seg_pad_sum in zip( + batch_data_samples, [(10, 24), (10, 24)], mask_pad_sums, + seg_pad_sums): + self.assertEqual(data_samples.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_instances.masks.masks.sum(), + mask_pad_sum) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.sum(), + seg_pad_sum) + + def test_batch_sync_random_resize(self): + processor = DetDataPreprocessor(batch_augments=[ + dict( + type='BatchSyncRandomResize', + random_size_range=(320, 320), + size_divisor=32, + interval=1) + ]) + self.assertTrue( + isinstance(processor.batch_augments[0], BatchSyncRandomResize)) + message_hub = MessageHub.get_instance('test_batch_sync_random_resize') + message_hub.update_info('iter', 0) + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 128, 128]], use_box_type=True) + batch_inputs = processor(packed_inputs, training=True)['inputs'] + self.assertEqual(batch_inputs.shape, (2, 3, 128, 128)) + + # resize after one iter + message_hub.update_info('iter', 1) + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 128, 128]], use_box_type=True) + batch_inputs = processor(packed_inputs, training=True)['inputs'] + self.assertEqual(batch_inputs.shape, (2, 3, 320, 320)) + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 128, 128]], use_box_type=True) + batch_inputs = processor(packed_inputs, training=False)['inputs'] + self.assertEqual(batch_inputs.shape, (2, 3, 128, 128)) + + def test_batch_fixed_size_pad(self): + # test pad_mask=False and pad_seg=False + processor = DetDataPreprocessor( + pad_mask=False, + pad_seg=False, + batch_augments=[ + dict( + type='BatchFixedSizePad', + size=(32, 32), + img_pad_value=0, + pad_mask=True, + mask_pad_value=0, + pad_seg=True, + seg_pad_value=0) + ]) + self.assertTrue( + isinstance(processor.batch_augments[0], BatchFixedSizePad)) + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], + with_mask=True, + with_semantic=True, + use_box_type=True) + packed_inputs['data_samples'][0].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 10, 11)) + packed_inputs['data_samples'][1].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 9, 24)) + mask_pad_sums = [ + x.gt_instances.masks.masks.sum() + for x in packed_inputs['data_samples'] + ] + seg_pad_sums = [ + x.gt_sem_seg.sem_seg.sum() for x in packed_inputs['data_samples'] + ] + data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = data['inputs'], data['data_samples'] + self.assertEqual(batch_inputs.shape[-2:], (32, 32)) + for data_samples, expected_shape, mask_pad_sum, seg_pad_sum in zip( + batch_data_samples, [(32, 32), (32, 32)], mask_pad_sums, + seg_pad_sums): + self.assertEqual(data_samples.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_instances.masks.masks.sum(), + mask_pad_sum) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.sum(), + seg_pad_sum) + + # test pad_mask=True and pad_seg=True + processor = DetDataPreprocessor( + pad_mask=True, + pad_seg=True, + seg_pad_value=0, + mask_pad_value=0, + batch_augments=[ + dict( + type='BatchFixedSizePad', + size=(32, 32), + img_pad_value=0, + pad_mask=True, + mask_pad_value=0, + pad_seg=True, + seg_pad_value=0) + ]) + self.assertTrue( + isinstance(processor.batch_augments[0], BatchFixedSizePad)) + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], + with_mask=True, + with_semantic=True, + use_box_type=True) + packed_inputs['data_samples'][0].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 10, 11)) + packed_inputs['data_samples'][1].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 9, 24)) + mask_pad_sums = [ + x.gt_instances.masks.masks.sum() + for x in packed_inputs['data_samples'] + ] + seg_pad_sums = [ + x.gt_sem_seg.sem_seg.sum() for x in packed_inputs['data_samples'] + ] + data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = data['inputs'], data['data_samples'] + self.assertEqual(batch_inputs.shape[-2:], (32, 32)) + for data_samples, expected_shape, mask_pad_sum, seg_pad_sum in zip( + batch_data_samples, [(32, 32), (32, 32)], mask_pad_sums, + seg_pad_sums): + self.assertEqual(data_samples.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_instances.masks.masks.sum(), + mask_pad_sum) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.sum(), + seg_pad_sum) + + # test negative pad/no pad + processor = DetDataPreprocessor( + pad_mask=True, + pad_seg=True, + seg_pad_value=0, + mask_pad_value=0, + batch_augments=[ + dict( + type='BatchFixedSizePad', + size=(5, 5), + img_pad_value=0, + pad_mask=True, + mask_pad_value=1, + pad_seg=True, + seg_pad_value=1) + ]) + self.assertTrue( + isinstance(processor.batch_augments[0], BatchFixedSizePad)) + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], + with_mask=True, + with_semantic=True, + use_box_type=True) + packed_inputs['data_samples'][0].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 10, 11)) + packed_inputs['data_samples'][1].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 9, 24)) + mask_pad_sums = [ + x.gt_instances.masks.masks.sum() + for x in packed_inputs['data_samples'] + ] + seg_pad_sums = [ + x.gt_sem_seg.sem_seg.sum() for x in packed_inputs['data_samples'] + ] + data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = data['inputs'], data['data_samples'] + self.assertEqual(batch_inputs.shape[-2:], (10, 24)) + for data_samples, expected_shape, mask_pad_sum, seg_pad_sum in zip( + batch_data_samples, [(10, 24), (10, 24)], mask_pad_sums, + seg_pad_sums): + self.assertEqual(data_samples.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_instances.masks.masks.sum(), + mask_pad_sum) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.sum(), + seg_pad_sum) + + +class TestMultiBranchDataPreprocessor(TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.data_preprocessor = dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_size_divisor=32) + self.multi_data = { + 'inputs': { + 'sup': [torch.randint(0, 256, (3, 224, 224))], + 'unsup_teacher': [ + torch.randint(0, 256, (3, 400, 600)), + torch.randint(0, 256, (3, 600, 400)) + ], + 'unsup_student': [ + torch.randint(0, 256, (3, 700, 500)), + torch.randint(0, 256, (3, 500, 700)) + ] + }, + 'data_samples': { + 'sup': [DetDataSample()], + 'unsup_teacher': [DetDataSample(), + DetDataSample()], + 'unsup_student': [DetDataSample(), + DetDataSample()], + } + } + self.data = { + 'inputs': [torch.randint(0, 256, (3, 224, 224))], + 'data_samples': [DetDataSample()] + } + + def test_multi_data_preprocessor(self): + processor = MultiBranchDataPreprocessor(self.data_preprocessor) + # test processing multi_data when training + multi_data = processor(self.multi_data, training=True) + self.assertEqual(multi_data['inputs']['sup'].shape, (1, 3, 224, 224)) + self.assertEqual(multi_data['inputs']['unsup_teacher'].shape, + (2, 3, 608, 608)) + self.assertEqual(multi_data['inputs']['unsup_student'].shape, + (2, 3, 704, 704)) + self.assertEqual(len(multi_data['data_samples']['sup']), 1) + self.assertEqual(len(multi_data['data_samples']['unsup_teacher']), 2) + self.assertEqual(len(multi_data['data_samples']['unsup_student']), 2) + # test processing data when testing + data = processor(self.data) + self.assertEqual(data['inputs'].shape, (1, 3, 224, 224)) + self.assertEqual(len(data['data_samples']), 1) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_track_data_preprocessor.py b/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_track_data_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..d5810167e61f01e1021ebdf698f69169aaaefe0c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_data_preprocessors/test_track_data_preprocessor.py @@ -0,0 +1,102 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +from mmdet.models.data_preprocessors import TrackDataPreprocessor +from mmdet.testing import demo_track_inputs + + +class TestTrackDataPreprocessor(TestCase): + + def test_init(self): + # test mean is None + processor = TrackDataPreprocessor() + self.assertTrue(not hasattr(processor, 'mean')) + self.assertTrue(processor._enable_normalize is False) + + # test mean is not None + processor = TrackDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + self.assertTrue(hasattr(processor, 'mean')) + self.assertTrue(hasattr(processor, 'std')) + self.assertTrue(processor._enable_normalize) + + # please specify both mean and std + with self.assertRaises(AssertionError): + TrackDataPreprocessor(mean=[0, 0, 0]) + + # bgr2rgb and rgb2bgr cannot be set to True at the same time + with self.assertRaises(AssertionError): + TrackDataPreprocessor(bgr_to_rgb=True, rgb_to_bgr=True) + + def test_forward(self): + processor = TrackDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + + data = demo_track_inputs( + batch_size=1, + num_frames=1, + image_shapes=(3, 11, 10), + num_items=[1]) + out_data = processor(data) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + self.assertEqual(inputs.shape, (1, 1, 3, 11, 10)) + self.assertEqual(len(data_samples), 1) + + # test channel_conversion + processor = TrackDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], bgr_to_rgb=True) + out_data = processor(data) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + self.assertEqual(len(data_samples), 1) + + # test padding + data = demo_track_inputs( + batch_size=2, + num_frames=2, + image_shapes=[(3, 10, 11), (3, 9, 14)], + num_items=[1, 1]) + out_data = processor(data) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + self.assertEqual(inputs.shape, (2, 2, 3, 10, 14)) + + # test pad_size_divisor + data = demo_track_inputs( + batch_size=2, + num_frames=2, + image_shapes=[(3, 10, 11), (3, 9, 24)], + num_items=[1, 1]) + processor = TrackDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], pad_size_divisor=5) + out_data = processor(data) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + self.assertEqual(inputs.shape, (2, 2, 3, 10, 25)) + self.assertEqual(len(data_samples), 2) + for track_data_sample, expected_shape in zip(data_samples, [(10, 15), + (10, 25)]): + for det_data_sample in track_data_sample.video_data_samples: + self.assertEqual(det_data_sample.pad_shape, expected_shape) + + # test pad_mask=True + data = demo_track_inputs( + batch_size=2, + num_frames=2, + image_shapes=[(3, 10, 11), (3, 9, 24)], + num_items=[1, 1], + with_mask=True) + processor = TrackDataPreprocessor(pad_mask=True, mask_pad_value=0) + mask_pad_sums = [] + for track_data_sample in data['data_samples']: + pad_sum_per_sample = [] + for x in track_data_sample.video_data_samples: + pad_sum_per_sample.append(x.gt_instances.masks.masks.sum()) + mask_pad_sums.append(pad_sum_per_sample) + out_data = processor(data, training=True) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + for track_data_sample, expected_shape, mask_pad_sum in zip( + data_samples, [(10, 24), (10, 24)], mask_pad_sums): + for i, det_data_sample in enumerate( + track_data_sample.video_data_samples): + self.assertEqual( + det_data_sample.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual( + det_data_sample.gt_instances.masks.masks.sum(), + mask_pad_sum[i]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_anchor_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_anchor_head.py new file mode 100644 index 0000000000000000000000000000000000000000..80781f8ddaaa0eebefa235b3a0967d4f885bc9d6 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_anchor_head.py @@ -0,0 +1,77 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import AnchorHead + + +class TestAnchorHead(TestCase): + + def test_anchor_head_loss(self): + """Tests anchor head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + cfg = Config( + 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=0, + pos_weight=-1, + debug=False)) + anchor_head = AnchorHead(num_classes=4, in_channels=1, train_cfg=cfg) + + # Anchor head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(len(anchor_head.prior_generator.strides))) + cls_scores, bbox_preds = anchor_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' + assert empty_box_loss.item() == 0, ( + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' + assert onegt_box_loss.item() > 0, 'box loss should be non-zero' diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_atss_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_atss_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e85154bbb8b0ecfc1460393438ebea07ef5547c1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_atss_head.py @@ -0,0 +1,94 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import ATSSHead + + +class TestATSSHead(TestCase): + + def test_atss_head_loss(self): + """Tests atss head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False)) + atss_head = ATSSHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=1, + norm_cfg=None, + train_cfg=cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [8, 16, 32, 64, 128] + ] + cls_scores, bbox_preds, centernesses = atss_head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + empty_centerness_loss = sum(empty_gt_losses['loss_centerness']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_centerness_loss.item(), 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + onegt_centerness_loss = sum(one_gt_losses['loss_centerness']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_centerness_loss.item(), 0, + 'centerness loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_autoassign_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_autoassign_head.py new file mode 100644 index 0000000000000000000000000000000000000000..8328edee7ab79bed500955daeb0e83e3098a7690 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_autoassign_head.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import AutoAssignHead + + +class TestAutoAssignHead(TestCase): + + def test_autoassign_head_loss(self): + """Tests autoassign head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + autoassign_head = AutoAssignHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=1, + strides=[8, 16, 32, 64, 128], + loss_bbox=dict(type='GIoULoss', loss_weight=5.0), + norm_cfg=None) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in autoassign_head.prior_generator.strides) + cls_scores, bbox_preds, centernesses = autoassign_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = autoassign_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, + [gt_instances], + img_metas) + # When there is no truth, the neg loss should be nonzero but + # pos loss and center loss should be zero + empty_pos_loss = empty_gt_losses['loss_pos'].item() + empty_neg_loss = empty_gt_losses['loss_neg'].item() + empty_ctr_loss = empty_gt_losses['loss_center'].item() + self.assertGreater(empty_neg_loss, 0, 'neg loss should be non-zero') + self.assertEqual( + empty_pos_loss, 0, + 'there should be no pos loss when there are no true boxes') + self.assertEqual( + empty_ctr_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all pos, neg loss and center loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = autoassign_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, + [gt_instances], img_metas) + onegt_pos_loss = one_gt_losses['loss_pos'].item() + onegt_neg_loss = one_gt_losses['loss_neg'].item() + onegt_ctr_loss = one_gt_losses['loss_center'].item() + self.assertGreater(onegt_pos_loss, 0, 'pos loss should be non-zero') + self.assertGreater(onegt_neg_loss, 0, 'neg loss should be non-zero') + self.assertGreater(onegt_ctr_loss, 0, 'center loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_boxinst_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_boxinst_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d677a1d2047fe91d9f9485e8891ca7e9a9c73b8e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_boxinst_head.py @@ -0,0 +1,125 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine import MessageHub +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import BoxInstBboxHead, BoxInstMaskHead +from mmdet.structures.mask import BitmapMasks + + +def _rand_masks(num_items, bboxes, img_w, img_h): + rng = np.random.RandomState(0) + masks = np.zeros((num_items, img_h, img_w), dtype=np.float32) + for i, bbox in enumerate(bboxes): + bbox = bbox.astype(np.int32) + mask = (rng.rand(1, bbox[3] - bbox[1], bbox[2] - bbox[0]) > + 0.3).astype(np.int64) + masks[i:i + 1, bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask + return BitmapMasks(masks, height=img_h, width=img_w) + + +def _fake_mask_feature_head(): + mask_feature_head = ConfigDict( + in_channels=1, + feat_channels=1, + start_level=0, + end_level=2, + out_channels=8, + mask_stride=8, + num_stacked_convs=4, + norm_cfg=dict(type='BN', requires_grad=True)) + return mask_feature_head + + +class TestBoxInstHead(TestCase): + + def test_boxinst_maskhead_loss(self): + """Tests boxinst maskhead loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + boxinst_bboxhead = BoxInstBboxHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + mask_feature_head = _fake_mask_feature_head() + boxinst_maskhead = BoxInstMaskHead( + mask_feature_head=mask_feature_head, + loss_mask=dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + eps=5e-6, + loss_weight=1.0)) + + # Fcos head expects a multiple levels of features per image + feats = [] + for i in range(len(boxinst_bboxhead.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 3)), s // (2**(i + 3)))) + feats = tuple(feats) + cls_scores, bbox_preds, centernesses, param_preds =\ + boxinst_bboxhead.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + gt_instances.pairwise_masks = _rand_masks( + 0, gt_instances.bboxes.numpy(), s // 4, s // 4).to_tensor( + dtype=torch.float32, + device='cpu').unsqueeze(1).repeat(1, 8, 1, 1) + message_hub = MessageHub.get_instance('runtime_info') + message_hub.update_info('iter', 1) + _ = boxinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, centernesses, + param_preds, [gt_instances], + img_metas) + # When truth is empty then all mask loss + # should be zero for random inputs + positive_infos = boxinst_bboxhead.get_positive_infos() + mask_outs = boxinst_maskhead.forward(feats, positive_infos) + empty_gt_mask_losses = boxinst_maskhead.loss_by_feat( + *mask_outs, [gt_instances], img_metas, positive_infos) + loss_mask_project = empty_gt_mask_losses['loss_mask_project'] + loss_mask_pairwise = empty_gt_mask_losses['loss_mask_pairwise'] + self.assertEqual(loss_mask_project, 0, + 'mask project loss should be zero') + self.assertEqual(loss_mask_pairwise, 0, + 'mask pairwise loss should be zero') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor([[0.111, 0.222, 25.6667, 29.8757]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + gt_instances.pairwise_masks = _rand_masks( + 1, gt_instances.bboxes.numpy(), s // 4, s // 4).to_tensor( + dtype=torch.float32, + device='cpu').unsqueeze(1).repeat(1, 8, 1, 1) + + _ = boxinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, centernesses, + param_preds, [gt_instances], + img_metas) + positive_infos = boxinst_bboxhead.get_positive_infos() + mask_outs = boxinst_maskhead.forward(feats, positive_infos) + one_gt_mask_losses = boxinst_maskhead.loss_by_feat( + *mask_outs, [gt_instances], img_metas, positive_infos) + loss_mask_project = one_gt_mask_losses['loss_mask_project'] + loss_mask_pairwise = one_gt_mask_losses['loss_mask_pairwise'] + self.assertGreater(loss_mask_project, 0, + 'mask project loss should be nonzero') + self.assertGreater(loss_mask_pairwise, 0, + 'mask pairwise loss should be nonzero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_cascade_rpn_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_cascade_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c1058c51341628f907e31fdf0a962fae99486265 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_cascade_rpn_head.py @@ -0,0 +1,179 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CascadeRPNHead +from mmdet.structures import DetDataSample + +rpn_weight = 0.7 +cascade_rpn_config = ConfigDict( + dict( + num_stages=2, + num_classes=1, + stages=[ + dict( + type='StageCascadeRPNHead', + in_channels=1, + feat_channels=1, + anchor_generator=dict( + type='AnchorGenerator', + scales=[8], + ratios=[1.0], + strides=[4, 8, 16, 32, 64]), + adapt_cfg=dict(type='dilation', dilation=3), + bridged_feature=True, + with_cls=False, + reg_decoded_bbox=True, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=(.0, .0, .0, .0), + target_stds=(0.1, 0.1, 0.5, 0.5)), + loss_bbox=dict( + type='IoULoss', linear=True, + loss_weight=10.0 * rpn_weight)), + dict( + type='StageCascadeRPNHead', + in_channels=1, + feat_channels=1, + adapt_cfg=dict(type='offset'), + bridged_feature=False, + with_cls=True, + reg_decoded_bbox=True, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=(.0, .0, .0, .0), + target_stds=(0.05, 0.05, 0.1, 0.1)), + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=True, + loss_weight=1.0 * rpn_weight), + loss_bbox=dict( + type='IoULoss', linear=True, + loss_weight=10.0 * rpn_weight)) + ], + train_cfg=[ + dict( + assigner=dict( + type='RegionAssigner', center_ratio=0.2, ignore_ratio=0.5), + allowed_border=-1, + pos_weight=-1, + debug=False), + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.7, + min_pos_iou=0.3, + 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) + ], + test_cfg=dict(max_per_img=300, nms=dict(iou_threshold=0.8)))) + + +class TestStageCascadeRPNHead(TestCase): + + def test_cascade_rpn_head_loss(self): + """Tests cascade rpn head loss when truth is empty and non-empty.""" + cascade_rpn_head = CascadeRPNHead(**cascade_rpn_config) + + s = 256 + feats = [ + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in cascade_rpn_head.stages[0].prior_generator.strides + ] + img_metas = { + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + } + sample = DetDataSample() + sample.set_metainfo(img_metas) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + sample.gt_instances = gt_instances + + empty_gt_losses = cascade_rpn_head.loss(feats, [sample]) + for key, loss in empty_gt_losses.items(): + loss = sum(loss) + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'reg' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no reg loss when no ground true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([0]) + sample.gt_instances = gt_instances + + one_gt_losses = cascade_rpn_head.loss(feats, [sample]) + for loss in one_gt_losses.values(): + loss = sum(loss) + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + def test_cascade_rpn_head_loss_and_predict(self): + """Tests cascade rpn head loss and predict function.""" + cascade_rpn_head = CascadeRPNHead(**cascade_rpn_config) + + s = 256 + feats = [ + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in cascade_rpn_head.stages[0].prior_generator.strides + ] + img_metas = { + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + } + sample = DetDataSample() + sample.set_metainfo(img_metas) + + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + sample.gt_instances = gt_instances + proposal_cfg = ConfigDict( + dict(max_per_img=300, nms=dict(iou_threshold=0.8))) + + cascade_rpn_head.loss_and_predict(feats, [sample], proposal_cfg) + + def test_cascade_rpn_head_predict(self): + """Tests cascade rpn head predict function.""" + cascade_rpn_head = CascadeRPNHead(**cascade_rpn_config) + + s = 256 + feats = [ + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in cascade_rpn_head.stages[0].prior_generator.strides + ] + img_metas = { + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + } + sample = DetDataSample() + sample.set_metainfo(img_metas) + + cascade_rpn_head.predict(feats, [sample]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centernet_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centernet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5c474d8a904467139e3a285d485f834acd7c41d4 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centernet_head.py @@ -0,0 +1,158 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CenterNetHead + + +class TestCenterNetHead(TestCase): + + def test_center_head_loss(self): + """Tests center head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{'batch_input_shape': (s, s, 3)}] + test_cfg = dict(topK=100, max_per_img=100) + centernet_head = CenterNetHead( + num_classes=4, in_channels=1, feat_channels=4, test_cfg=test_cfg) + + feat = [torch.rand(1, 1, s, s)] + center_out, wh_out, offset_out = centernet_head.forward(feat) + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = centernet_head.loss_by_feat(center_out, wh_out, + offset_out, + [gt_instances], + img_metas) + loss_center = empty_gt_losses['loss_center_heatmap'] + loss_wh = empty_gt_losses['loss_wh'] + loss_offset = empty_gt_losses['loss_offset'] + assert loss_center.item() > 0, 'loss_center should be non-zero' + assert loss_wh.item() == 0, ( + 'there should be no loss_wh when there are no true boxes') + assert loss_offset.item() == 0, ( + 'there should be no loss_offset when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = centernet_head.loss_by_feat(center_out, wh_out, + offset_out, [gt_instances], + img_metas) + loss_center = one_gt_losses['loss_center_heatmap'] + loss_wh = one_gt_losses['loss_wh'] + loss_offset = one_gt_losses['loss_offset'] + assert loss_center.item() > 0, 'loss_center should be non-zero' + assert loss_wh.item() > 0, 'loss_wh should be non-zero' + assert loss_offset.item() > 0, 'loss_offset should be non-zero' + + def test_centernet_head_get_targets(self): + """Tests center head generating and decoding the heatmap.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'batch_input_shape': (s, s), + }] + test_cfg = ConfigDict( + dict(topk=100, local_maximum_kernel=3, max_per_img=100)) + gt_bboxes = [ + torch.Tensor([[10, 20, 200, 240], [40, 50, 100, 200], + [10, 20, 100, 240]]) + ] + gt_labels = [torch.LongTensor([1, 1, 2])] + + centernet_head = CenterNetHead( + num_classes=4, in_channels=1, feat_channels=4, test_cfg=test_cfg) + self.feat_shape = (1, 1, s // 4, s // 4) + targets, _ = centernet_head.get_targets(gt_bboxes, gt_labels, + self.feat_shape, + img_metas[0]['img_shape']) + center_target = targets['center_heatmap_target'] + wh_target = targets['wh_target'] + offset_target = targets['offset_target'] + # make sure assign target right + for i in range(len(gt_bboxes[0])): + bbox, label = gt_bboxes[0][i] / 4, gt_labels[0][i] + ctx, cty = sum(bbox[0::2]) / 2, sum(bbox[1::2]) / 2 + int_ctx, int_cty = int(sum(bbox[0::2]) / 2), int( + sum(bbox[1::2]) / 2) + w, h = bbox[2] - bbox[0], bbox[3] - bbox[1] + x_off = ctx - int(ctx) + y_off = cty - int(cty) + assert center_target[0, label, int_cty, int_ctx] == 1 + assert wh_target[0, 0, int_cty, int_ctx] == w + assert wh_target[0, 1, int_cty, int_ctx] == h + assert offset_target[0, 0, int_cty, int_ctx] == x_off + assert offset_target[0, 1, int_cty, int_ctx] == y_off + + def test_centernet_head_get_results(self): + """Tests center head generating and decoding the heatmap.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'batch_input_shape': (s, s), + 'border': (0, 0, 0, 0), + }] + test_cfg = ConfigDict( + dict( + topk=100, + local_maximum_kernel=3, + max_per_img=100, + nms=dict(type='nms', iou_threshold=0.5))) + gt_bboxes = [ + torch.Tensor([[10, 20, 200, 240], [40, 50, 100, 200], + [10, 20, 100, 240]]) + ] + gt_labels = [torch.LongTensor([1, 1, 2])] + + centernet_head = CenterNetHead( + num_classes=4, in_channels=1, feat_channels=4, test_cfg=test_cfg) + self.feat_shape = (1, 1, s // 4, s // 4) + targets, _ = centernet_head.get_targets(gt_bboxes, gt_labels, + self.feat_shape, + img_metas[0]['img_shape']) + center_target = targets['center_heatmap_target'] + wh_target = targets['wh_target'] + offset_target = targets['offset_target'] + # make sure get_bboxes is right + detections = centernet_head.predict_by_feat([center_target], + [wh_target], + [offset_target], + img_metas, + rescale=True, + with_nms=False) + + pred_instances = detections[0] + out_bboxes = pred_instances.bboxes[:3] + out_clses = pred_instances.labels[:3] + for bbox, cls in zip(out_bboxes, out_clses): + flag = False + for gt_bbox, gt_cls in zip(gt_bboxes[0], gt_labels[0]): + if (bbox[:4] == gt_bbox[:4]).all(): + flag = True + assert flag, 'get_bboxes is wrong' + + detections = centernet_head.predict_by_feat([center_target], + [wh_target], + [offset_target], + img_metas, + rescale=True, + with_nms=True) + + pred_instances = detections[0] + out_bboxes = pred_instances.bboxes[:3] + out_clses = pred_instances.labels[:3] + for bbox, cls in zip(out_bboxes, out_clses): + flag = False + for gt_bbox, gt_cls in zip(gt_bboxes[0], gt_labels[0]): + if (bbox[:4] == gt_bbox[:4]).all(): + flag = True + assert flag, 'get_bboxes is wrong' diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centernet_update_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centernet_update_head.py new file mode 100644 index 0000000000000000000000000000000000000000..325ce7e6cd9bda4e0a4ec807e11c54636f45fe2a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centernet_update_head.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CenterNetUpdateHead + + +class TestCenterNetUpdateHead(TestCase): + + def test_centernet_update_head_loss(self): + """Tests fcos head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + centernet_head = CenterNetUpdateHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in centernet_head.prior_generator.strides) + cls_scores, bbox_preds = centernet_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = centernet_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = empty_gt_losses['loss_cls'].item() + empty_box_loss = empty_gt_losses['loss_bbox'].item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = centernet_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].item() + onegt_box_loss = one_gt_losses['loss_bbox'].item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centripetal_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centripetal_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6811ef7699ab70fc63e33a07103d3c6d4e16970c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_centripetal_head.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CentripetalHead + + +class TestCentripetalHead(TestCase): + + def test_centripetal_head_loss(self): + """Tests corner head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + }] + + centripetal_head = CentripetalHead( + num_classes=4, in_channels=1, corner_emb_channels=0) + + # Corner head expects a multiple levels of features per image + feat = [ + torch.rand(1, 1, s // 4, s // 4) + for _ in range(centripetal_head.num_feat_levels) + ] + forward_outputs = centripetal_head.forward(feat) + + # Test that empty ground truth encourages the network + # to predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + + empty_gt_losses = centripetal_head.loss_by_feat( + *forward_outputs, [gt_instances], img_metas, gt_bboxes_ignore) + empty_det_loss = sum(empty_gt_losses['det_loss']) + empty_guiding_loss = sum(empty_gt_losses['guiding_loss']) + empty_centripetal_loss = sum(empty_gt_losses['centripetal_loss']) + empty_off_loss = sum(empty_gt_losses['off_loss']) + self.assertTrue(empty_det_loss.item() > 0, + 'det loss should be non-zero') + self.assertTrue( + empty_guiding_loss.item() == 0, + 'there should be no guiding loss when there are no true boxes') + self.assertTrue( + empty_centripetal_loss.item() == 0, + 'there should be no centripetal loss when there are no true boxes') + self.assertTrue( + empty_off_loss.item() == 0, + 'there should be no box loss when there are no true boxes') + + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874], + [123.6667, 123.8757, 138.6326, 251.8874]]) + gt_instances.labels = torch.LongTensor([2, 3]) + + two_gt_losses = centripetal_head.loss_by_feat(*forward_outputs, + [gt_instances], + img_metas, + gt_bboxes_ignore) + twogt_det_loss = sum(two_gt_losses['det_loss']) + twogt_guiding_loss = sum(two_gt_losses['guiding_loss']) + twogt_centripetal_loss = sum(two_gt_losses['centripetal_loss']) + twogt_off_loss = sum(two_gt_losses['off_loss']) + assert twogt_det_loss.item() > 0, 'det loss should be non-zero' + assert twogt_guiding_loss.item() > 0, 'push loss should be non-zero' + assert twogt_centripetal_loss.item( + ) > 0, 'pull loss should be non-zero' + assert twogt_off_loss.item() > 0, 'off loss should be non-zero' diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_condinst_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_condinst_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b2938f86cbb36df03dfd50e36a2ff9b261c7dc5b --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_condinst_head.py @@ -0,0 +1,200 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CondInstBboxHead, CondInstMaskHead +from mmdet.structures.mask import BitmapMasks + + +def _rand_masks(num_items, bboxes, img_w, img_h): + rng = np.random.RandomState(0) + masks = np.zeros((num_items, img_h, img_w), dtype=np.float32) + for i, bbox in enumerate(bboxes): + bbox = bbox.astype(np.int32) + mask = (rng.rand(1, bbox[3] - bbox[1], bbox[2] - bbox[0]) > + 0.3).astype(np.int64) + masks[i:i + 1, bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask + return BitmapMasks(masks, height=img_h, width=img_w) + + +def _fake_mask_feature_head(): + mask_feature_head = ConfigDict( + in_channels=1, + feat_channels=1, + start_level=0, + end_level=2, + out_channels=8, + mask_stride=8, + num_stacked_convs=4, + norm_cfg=dict(type='BN', requires_grad=True)) + return mask_feature_head + + +class TestCondInstHead(TestCase): + + def test_condinst_bboxhead_loss(self): + """Tests condinst bboxhead loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + condinst_bboxhead = CondInstBboxHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in condinst_bboxhead.prior_generator.strides) + cls_scores, bbox_preds, centernesses, param_preds =\ + condinst_bboxhead.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + + empty_gt_losses = condinst_bboxhead.loss_by_feat( + cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = empty_gt_losses['loss_cls'].item() + empty_box_loss = empty_gt_losses['loss_bbox'].item() + empty_ctr_loss = empty_gt_losses['loss_centerness'].item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_ctr_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + + one_gt_losses = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, + centernesses, + param_preds, + [gt_instances], + img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].item() + onegt_box_loss = one_gt_losses['loss_bbox'].item() + onegt_ctr_loss = one_gt_losses['loss_centerness'].item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_ctr_loss, 0, + 'centerness loss should be non-zero') + + # Test the `center_sampling` works fine. + condinst_bboxhead.center_sampling = True + ctrsamp_losses = condinst_bboxhead.loss_by_feat( + cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], + img_metas) + ctrsamp_cls_loss = ctrsamp_losses['loss_cls'].item() + ctrsamp_box_loss = ctrsamp_losses['loss_bbox'].item() + ctrsamp_ctr_loss = ctrsamp_losses['loss_centerness'].item() + self.assertGreater(ctrsamp_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(ctrsamp_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(ctrsamp_ctr_loss, 0, + 'centerness loss should be non-zero') + + # Test the `norm_on_bbox` works fine. + condinst_bboxhead.norm_on_bbox = True + normbox_losses = condinst_bboxhead.loss_by_feat( + cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], + img_metas) + normbox_cls_loss = normbox_losses['loss_cls'].item() + normbox_box_loss = normbox_losses['loss_bbox'].item() + normbox_ctr_loss = normbox_losses['loss_centerness'].item() + self.assertGreater(normbox_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(normbox_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(normbox_ctr_loss, 0, + 'centerness loss should be non-zero') + + def test_condinst_maskhead_loss(self): + """Tests condinst maskhead loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + condinst_bboxhead = CondInstBboxHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + mask_feature_head = _fake_mask_feature_head() + condinst_maskhead = CondInstMaskHead( + mask_feature_head=mask_feature_head, + loss_mask=dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + eps=5e-6, + loss_weight=1.0)) + + # Fcos head expects a multiple levels of features per image + feats = [] + for i in range(len(condinst_bboxhead.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 3)), s // (2**(i + 3)))) + feats = tuple(feats) + cls_scores, bbox_preds, centernesses, param_preds =\ + condinst_bboxhead.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + + _ = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, + centernesses, param_preds, + [gt_instances], img_metas) + # When truth is empty then all mask loss + # should be zero for random inputs + positive_infos = condinst_bboxhead.get_positive_infos() + mask_outs = condinst_maskhead.forward(feats, positive_infos) + empty_gt_mask_losses = condinst_maskhead.loss_by_feat( + *mask_outs, [gt_instances], img_metas, positive_infos) + loss_mask = empty_gt_mask_losses['loss_mask'] + self.assertEqual(loss_mask, 0, 'mask loss should be zero') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + + _ = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, + centernesses, param_preds, + [gt_instances], img_metas) + positive_infos = condinst_bboxhead.get_positive_infos() + mask_outs = condinst_maskhead.forward(feats, positive_infos) + one_gt_mask_losses = condinst_maskhead.loss_by_feat( + *mask_outs, [gt_instances], img_metas, positive_infos) + loss_mask = one_gt_mask_losses['loss_mask'] + self.assertGreater(loss_mask, 0, 'mask loss should be nonzero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_corner_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_corner_head.py new file mode 100644 index 0000000000000000000000000000000000000000..8bd92f5731e9916ac46e82cc81776f2fe22d980f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_corner_head.py @@ -0,0 +1,178 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.evaluation import bbox_overlaps +from mmdet.models.dense_heads import CornerHead + + +class TestCornerHead(TestCase): + + def test_corner_head_loss(self): + """Tests corner head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + }] + + corner_head = CornerHead(num_classes=4, in_channels=1) + + # Corner head expects a multiple levels of features per image + feat = [ + torch.rand(1, 1, s // 4, s // 4) + for _ in range(corner_head.num_feat_levels) + ] + forward_outputs = corner_head.forward(feat) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + + empty_gt_losses = corner_head.loss_by_feat(*forward_outputs, + [gt_instances], img_metas, + gt_bboxes_ignore) + empty_det_loss = sum(empty_gt_losses['det_loss']) + empty_push_loss = sum(empty_gt_losses['push_loss']) + empty_pull_loss = sum(empty_gt_losses['pull_loss']) + empty_off_loss = sum(empty_gt_losses['off_loss']) + self.assertTrue(empty_det_loss.item() > 0, + 'det loss should be non-zero') + self.assertTrue( + empty_push_loss.item() == 0, + 'there should be no push loss when there are no true boxes') + self.assertTrue( + empty_pull_loss.item() == 0, + 'there should be no pull loss when there are no true boxes') + self.assertTrue( + empty_off_loss.item() == 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = corner_head.loss_by_feat(*forward_outputs, + [gt_instances], img_metas, + gt_bboxes_ignore) + onegt_det_loss = sum(one_gt_losses['det_loss']) + onegt_push_loss = sum(one_gt_losses['push_loss']) + onegt_pull_loss = sum(one_gt_losses['pull_loss']) + onegt_off_loss = sum(one_gt_losses['off_loss']) + self.assertTrue(onegt_det_loss.item() > 0, + 'det loss should be non-zero') + self.assertTrue( + onegt_push_loss.item() == 0, + 'there should be no push loss when there are only one true box') + self.assertTrue(onegt_pull_loss.item() > 0, + 'pull loss should be non-zero') + self.assertTrue(onegt_off_loss.item() > 0, + 'off loss should be non-zero') + + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874], + [123.6667, 123.8757, 138.6326, 251.8874]]) + gt_instances.labels = torch.LongTensor([2, 3]) + + two_gt_losses = corner_head.loss_by_feat(*forward_outputs, + [gt_instances], img_metas, + gt_bboxes_ignore) + twogt_det_loss = sum(two_gt_losses['det_loss']) + twogt_push_loss = sum(two_gt_losses['push_loss']) + twogt_pull_loss = sum(two_gt_losses['pull_loss']) + twogt_off_loss = sum(two_gt_losses['off_loss']) + self.assertTrue(twogt_det_loss.item() > 0, + 'det loss should be non-zero') + # F.relu limits push loss larger than or equal to 0. + self.assertTrue(twogt_push_loss.item() >= 0, + 'push loss should be non-zero') + self.assertTrue(twogt_pull_loss.item() > 0, + 'pull loss should be non-zero') + self.assertTrue(twogt_off_loss.item() > 0, + 'off loss should be non-zero') + + def test_corner_head_encode_and_decode_heatmap(self): + """Tests corner head generating and decoding the heatmap.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3), + 'border': (0, 0, 0, 0) + }] + + gt_bboxes = [ + torch.Tensor([[10, 20, 200, 240], [40, 50, 100, 200], + [10, 20, 200, 240]]) + ] + gt_labels = [torch.LongTensor([1, 1, 2])] + + corner_head = CornerHead( + num_classes=4, in_channels=1, corner_emb_channels=1) + + feat = [ + torch.rand(1, 1, s // 4, s // 4) + for _ in range(corner_head.num_feat_levels) + ] + + targets = corner_head.get_targets( + gt_bboxes, + gt_labels, + feat[0].shape, + img_metas[0]['batch_input_shape'], + with_corner_emb=corner_head.with_corner_emb) + + gt_tl_heatmap = targets['topleft_heatmap'] + gt_br_heatmap = targets['bottomright_heatmap'] + gt_tl_offset = targets['topleft_offset'] + gt_br_offset = targets['bottomright_offset'] + embedding = targets['corner_embedding'] + [top, left], [bottom, right] = embedding[0][0] + gt_tl_embedding_heatmap = torch.zeros([1, 1, s // 4, s // 4]) + gt_br_embedding_heatmap = torch.zeros([1, 1, s // 4, s // 4]) + gt_tl_embedding_heatmap[0, 0, top, left] = 1 + gt_br_embedding_heatmap[0, 0, bottom, right] = 1 + + batch_bboxes, batch_scores, batch_clses = corner_head._decode_heatmap( + tl_heat=gt_tl_heatmap, + br_heat=gt_br_heatmap, + tl_off=gt_tl_offset, + br_off=gt_br_offset, + tl_emb=gt_tl_embedding_heatmap, + br_emb=gt_br_embedding_heatmap, + img_meta=img_metas[0], + k=100, + kernel=3, + distance_threshold=0.5) + + bboxes = batch_bboxes.view(-1, 4) + scores = batch_scores.view(-1, 1) + clses = batch_clses.view(-1, 1) + + idx = scores.argsort(dim=0, descending=True) + bboxes = bboxes[idx].view(-1, 4) + scores = scores[idx].view(-1) + clses = clses[idx].view(-1) + + valid_bboxes = bboxes[torch.where(scores > 0.05)] + valid_labels = clses[torch.where(scores > 0.05)] + max_coordinate = valid_bboxes.max() + offsets = valid_labels.to(valid_bboxes) * (max_coordinate + 1) + gt_offsets = gt_labels[0].to(gt_bboxes[0]) * (max_coordinate + 1) + + offset_bboxes = valid_bboxes + offsets[:, None] + offset_gtbboxes = gt_bboxes[0] + gt_offsets[:, None] + + iou_matrix = bbox_overlaps(offset_bboxes.numpy(), + offset_gtbboxes.numpy()) + self.assertEqual((iou_matrix == 1).sum(), 3) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ddod_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ddod_head.py new file mode 100644 index 0000000000000000000000000000000000000000..753bb3ae46f1a5eca537889dc461723ee9a18724 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ddod_head.py @@ -0,0 +1,98 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import DDODHead + + +class TestDDODHead(TestCase): + + def test_ddod_head_loss(self): + """Tests ddod head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9, alpha=0.8), + reg_assigner=dict(type='ATSSAssigner', topk=9, alpha=0.5), + allowed_border=-1, + pos_weight=-1, + debug=False)) + atss_head = DDODHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=1, + use_dcn=False, + norm_cfg=None, + train_cfg=cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + loss_iou=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [8, 16, 32, 64, 128] + ] + cls_scores, bbox_preds, centernesses = atss_head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + empty_centerness_loss = sum(empty_gt_losses['loss_iou']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_centerness_loss.item(), 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + onegt_centerness_loss = sum(one_gt_losses['loss_iou']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_centerness_loss.item(), 0, + 'centerness loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_embedding_rpn_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_embedding_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f713da586d7cb7303d50fcbecd9eaa9ce8ec4f84 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_embedding_rpn_head.py @@ -0,0 +1,55 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import pytest +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import EmbeddingRPNHead +from mmdet.structures import DetDataSample + + +class TestEmbeddingRPNHead(TestCase): + + def test_init(self): + """Test init rpn head.""" + rpn_head = EmbeddingRPNHead( + num_proposals=100, proposal_feature_channel=256) + rpn_head.init_weights() + self.assertTrue(rpn_head.init_proposal_bboxes) + self.assertTrue(rpn_head.init_proposal_features) + + def test_loss_and_predict(self): + s = 256 + img_meta = { + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + } + rpn_head = EmbeddingRPNHead( + num_proposals=100, proposal_feature_channel=256) + + feats = [ + torch.rand(2, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(5) + ] + + data_sample = DetDataSample() + data_sample.set_metainfo(img_meta) + + # test predict + result_list = rpn_head.predict(feats, [data_sample]) + self.assertTrue(isinstance(result_list, list)) + self.assertTrue(isinstance(result_list[0], InstanceData)) + + # test loss_and_predict + result_list = rpn_head.loss_and_predict(feats, [data_sample]) + self.assertTrue(isinstance(result_list, tuple)) + self.assertTrue(isinstance(result_list[0], dict)) + self.assertEqual(len(result_list[0]), 0) + self.assertTrue(isinstance(result_list[1], list)) + self.assertTrue(isinstance(result_list[1][0], InstanceData)) + + # test loss + with pytest.raises(NotImplementedError): + rpn_head.loss(feats, [data_sample]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fcos_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fcos_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ba0f9dadac83a07cdf3f26f8006405fef2d5f27a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fcos_head.py @@ -0,0 +1,97 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import FCOSHead + + +class TestFCOSHead(TestCase): + + def test_fcos_head_loss(self): + """Tests fcos head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + fcos_head = FCOSHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in fcos_head.prior_generator.strides) + cls_scores, bbox_preds, centernesses = fcos_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = fcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = empty_gt_losses['loss_cls'].item() + empty_box_loss = empty_gt_losses['loss_bbox'].item() + empty_ctr_loss = empty_gt_losses['loss_centerness'].item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_ctr_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = fcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].item() + onegt_box_loss = one_gt_losses['loss_bbox'].item() + onegt_ctr_loss = one_gt_losses['loss_centerness'].item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_ctr_loss, 0, + 'centerness loss should be non-zero') + + # Test the `center_sampling` works fine. + fcos_head.center_sampling = True + ctrsamp_losses = fcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + ctrsamp_cls_loss = ctrsamp_losses['loss_cls'].item() + ctrsamp_box_loss = ctrsamp_losses['loss_bbox'].item() + ctrsamp_ctr_loss = ctrsamp_losses['loss_centerness'].item() + self.assertGreater(ctrsamp_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(ctrsamp_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(ctrsamp_ctr_loss, 0, + 'centerness loss should be non-zero') + + # Test the `norm_on_bbox` works fine. + fcos_head.norm_on_bbox = True + normbox_losses = fcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + normbox_cls_loss = normbox_losses['loss_cls'].item() + normbox_box_loss = normbox_losses['loss_bbox'].item() + normbox_ctr_loss = normbox_losses['loss_centerness'].item() + self.assertGreater(normbox_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(normbox_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(normbox_ctr_loss, 0, + 'centerness loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fovea_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fovea_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c00f980354e5fed36f1b734132ff965c24ab2b17 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fovea_head.py @@ -0,0 +1,61 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import FoveaHead + + +class TestFOVEAHead(TestCase): + + def test_fovea_head_loss(self): + """Tests anchor head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + fovea_head = FoveaHead(num_classes=4, in_channels=1) + + # Anchor head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(len(fovea_head.prior_generator.strides))) + cls_scores, bbox_preds = fovea_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = fovea_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = fovea_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_free_anchor_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_free_anchor_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d2698bc225f3dee06893c33f5c2860bf05662a7c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_free_anchor_head.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import FreeAnchorRetinaHead + + +class TestFreeAnchorRetinaHead(TestCase): + + def test_free_anchor_head_loss(self): + """Tests rpn head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + anchor_head = FreeAnchorRetinaHead(num_classes=1, in_channels=1) + + # Anchor head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(len(anchor_head.prior_generator.strides))) + cls_scores, bbox_preds = anchor_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + positive_bag_loss = empty_gt_losses['positive_bag_loss'] + negative_bag_loss = empty_gt_losses['negative_bag_loss'] + self.assertGreater(negative_bag_loss.item(), 0, + 'negative_bag loss should be non-zero') + self.assertEqual( + positive_bag_loss.item(), 0, + 'there should be no positive_bag loss when there are no true boxes' + ) + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([0]) + + one_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['positive_bag_loss'] + onegt_box_loss = one_gt_losses['negative_bag_loss'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'positive bag loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'negative bag loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fsaf_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fsaf_head.py new file mode 100644 index 0000000000000000000000000000000000000000..155af5fd5264b245c918e314289996d3f0471b3e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_fsaf_head.py @@ -0,0 +1,93 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from math import ceil +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import FSAFHead + + +class TestFSAFHead(TestCase): + + def test_fsaf_head_loss(self): + """Tests fsaf head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + }] + cfg = Config( + dict( + assigner=dict( + type='CenterRegionAssigner', + pos_scale=0.2, + neg_scale=0.2, + min_pos_iof=0.01), + allowed_border=-1, + pos_weight=-1, + debug=False)) + fsaf_head = FSAFHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=1, + reg_decoded_bbox=True, + anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=1, + scales_per_octave=1, + ratios=[1.0], + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict(type='TBLRBBoxCoder', normalizer=4.0), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0, + reduction='none'), + loss_bbox=dict( + type='IoULoss', eps=1e-6, loss_weight=1.0, reduction='none'), + train_cfg=cfg) + + # FSAF head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, ceil(s / stride[0]), ceil(s / stride[0])) + for stride in fsaf_head.prior_generator.strides) + cls_scores, bbox_preds = fsaf_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = fsaf_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss should be zero + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = fsaf_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ga_retina_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ga_retina_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e129ec419f9625769ca2a940bcdc3005122f9e25 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ga_retina_head.py @@ -0,0 +1,97 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict + +from mmdet.models.dense_heads import GARetinaHead + +ga_retina_head_config = ConfigDict( + dict( + num_classes=4, + in_channels=4, + feat_channels=4, + stacked_convs=1, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[4], + strides=[8, 16, 32, 64, 128]), + anchor_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + loc_filter_thr=0.01, + loss_loc=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_shape=dict(type='BoundedIoULoss', beta=0.2, loss_weight=1.0), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=0.04, loss_weight=1.0), + train_cfg=dict( + ga_assigner=dict( + type='ApproxMaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0.4, + ignore_iof_thr=-1), + ga_sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + center_ratio=0.2, + ignore_ratio=0.5, + debug=False), + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100))) + + +class TestGARetinaHead(TestCase): + + def test_ga_retina_head_init_and_forward(self): + """The GARetinaHead inherit loss and prediction function from + GuidedAchorHead. + + Here, we only test GARetinaHet initialization and forward. + """ + # Test initializaion + ga_retina_head = GARetinaHead(**ga_retina_head_config) + + # Test forward + s = 256 + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in ga_retina_head.square_anchor_generator.strides) + ga_retina_head(feats) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ga_rpn_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ga_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b0fc555586a46066485dc62633588c8fdfc02cb2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ga_rpn_head.py @@ -0,0 +1,143 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import GARPNHead + +ga_rpn_config = ConfigDict( + dict( + num_classes=1, + in_channels=4, + feat_channels=4, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=8, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[4, 8, 16, 32, 64]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[8], + strides=[4, 8, 16, 32, 64]), + anchor_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[0.07, 0.07, 0.14, 0.14]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[0.07, 0.07, 0.11, 0.11]), + loc_filter_thr=0.01, + loss_loc=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_shape=dict(type='BoundedIoULoss', beta=0.2, loss_weight=1.0), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0), + train_cfg=dict( + ga_assigner=dict( + type='ApproxMaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.3, + min_pos_iou=0.3, + ignore_iof_thr=-1), + ga_sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + 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, + center_ratio=0.2, + ignore_ratio=0.5, + pos_weight=-1, + debug=False), + test_cfg=dict( + nms_pre=1000, + ms_post=1000, + max_per_img=300, + nms=dict(type='nms', iou_threshold=0.7), + min_bbox_size=0))) + + +class TestGARPNHead(TestCase): + + def test_ga_rpn_head_loss(self): + """Tests ga rpn head loss.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': (1, 1) + }] + ga_rpn_head = GARPNHead(**ga_rpn_config) + + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in ga_rpn_head.square_anchor_generator.strides) + outs = ga_rpn_head(feats) + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([0]) + + one_gt_losses = ga_rpn_head.loss_by_feat(*outs, [gt_instances], + img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_rpn_cls']).item() + onegt_box_loss = sum(one_gt_losses['loss_rpn_bbox']).item() + onegt_shape_loss = sum(one_gt_losses['loss_anchor_shape']).item() + onegt_loc_loss = sum(one_gt_losses['loss_anchor_loc']).item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_shape_loss, 0, + 'shape loss should be non-zero') + self.assertGreater(onegt_loc_loss, 0, + 'location loss should be non-zero') + + def test_ga_rpn_head_predict_by_feat(self): + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': (1, 1) + }] + ga_rpn_head = GARPNHead(**ga_rpn_config) + + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in ga_rpn_head.square_anchor_generator.strides) + outs = ga_rpn_head(feats) + + cfg = ConfigDict( + dict( + nms_pre=2000, + nms_post=1000, + max_per_img=300, + nms=dict(type='nms', iou_threshold=0.7), + min_bbox_size=0)) + ga_rpn_head.predict_by_feat( + *outs, batch_img_metas=img_metas, cfg=cfg, rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_gfl_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_gfl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..247627c05d09047db1faec2ce667cb83e75a19a5 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_gfl_head.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import GFLHead + + +class TestGFLHead(TestCase): + + def test_gfl_head_loss(self): + """Tests gfl head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + train_cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False)) + gfl_head = GFLHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + loss_cls=dict( + type='QualityFocalLoss', + use_sigmoid=True, + beta=2.0, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + cls_scores, bbox_preds = gfl_head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = gfl_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + empty_dfl_loss = sum(empty_gt_losses['loss_dfl']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_dfl_loss.item(), 0, + 'there should be no dfl loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = gfl_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + onegt_dfl_loss = sum(one_gt_losses['loss_dfl']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_dfl_loss.item(), 0, + 'dfl loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_guided_anchor_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_guided_anchor_head.py new file mode 100644 index 0000000000000000000000000000000000000000..410f4eebd39a7c6e55729fde639b67f25f456e7f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_guided_anchor_head.py @@ -0,0 +1,157 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import GuidedAnchorHead + +guided_anchor_head_config = ConfigDict( + dict( + num_classes=4, + in_channels=4, + feat_channels=4, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[4], + strides=[8, 16, 32, 64, 128]), + anchor_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + loc_filter_thr=0.01, + loss_loc=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_shape=dict(type='BoundedIoULoss', beta=0.2, loss_weight=1.0), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=0.04, loss_weight=1.0), + train_cfg=dict( + ga_assigner=dict( + type='ApproxMaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0.4, + ignore_iof_thr=-1), + ga_sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + center_ratio=0.2, + ignore_ratio=0.5, + debug=False), + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100))) + + +class TestGuidedAnchorHead(TestCase): + + def test_guided_anchor_head_loss(self): + """Tests guided anchor loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': (1, 1) + }] + guided_anchor_head = GuidedAnchorHead(**guided_anchor_head_config) + + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in guided_anchor_head.square_anchor_generator.strides) + outs = guided_anchor_head(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = guided_anchor_head.loss_by_feat( + *outs, [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # box shape and location loss should be zero + empty_cls_loss = sum(empty_gt_losses['loss_cls']).item() + empty_box_loss = sum(empty_gt_losses['loss_bbox']).item() + empty_shape_loss = sum(empty_gt_losses['loss_shape']).item() + empty_loc_loss = sum(empty_gt_losses['loss_loc']).item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(empty_loc_loss, 0, + 'location loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_shape_loss, 0, + 'there should be no shape loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = guided_anchor_head.loss_by_feat( + *outs, [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']).item() + onegt_box_loss = sum(one_gt_losses['loss_bbox']).item() + onegt_shape_loss = sum(one_gt_losses['loss_shape']).item() + onegt_loc_loss = sum(one_gt_losses['loss_loc']).item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_shape_loss, 0, + 'shape loss should be non-zero') + self.assertGreater(onegt_loc_loss, 0, + 'location loss should be non-zero') + + def test_guided_anchor_head_predict_by_feat(self): + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': (1, 1) + }] + guided_anchor_head = GuidedAnchorHead(**guided_anchor_head_config) + + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in guided_anchor_head.square_anchor_generator.strides) + outs = guided_anchor_head(feats) + + guided_anchor_head.predict_by_feat( + *outs, batch_img_metas=img_metas, rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_lad_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_lad_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0dfd17d5864d2c10ac315b541eeebf7cdb18e92f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_lad_head.py @@ -0,0 +1,168 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import LADHead, lad_head +from mmdet.models.dense_heads.lad_head import levels_to_images + + +class TestLADHead(TestCase): + + def test_lad_head_loss(self): + """Tests lad head loss when truth is empty and non-empty.""" + + class mock_skm: + + def GaussianMixture(self, *args, **kwargs): + return self + + def fit(self, loss): + pass + + def predict(self, loss): + components = np.zeros_like(loss, dtype=np.long) + return components.reshape(-1) + + def score_samples(self, loss): + scores = np.random.random(len(loss)) + return scores + + lad_head.skm = mock_skm() + + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + train_cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.1, + neg_iou_thr=0.1, + min_pos_iou=0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + debug=False)) + # since Focal Loss is not supported on CPU + # since Focal Loss is not supported on CPU + lad = LADHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + teacher_model = LADHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + lad.init_weights() + teacher_model.init_weights() + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + batch_gt_instances_ignore = None + + outs_teacher = teacher_model(feat) + label_assignment_results = teacher_model.get_label_assignment( + *outs_teacher, [gt_instances], img_metas, + batch_gt_instances_ignore) + + outs = teacher_model(feat) + empty_gt_losses = lad.loss_by_feat(*outs, [gt_instances], img_metas, + batch_gt_instances_ignore, + label_assignment_results) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + empty_iou_loss = empty_gt_losses['loss_iou'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_iou_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + batch_gt_instances_ignore = None + + label_assignment_results = teacher_model.get_label_assignment( + *outs_teacher, [gt_instances], img_metas, + batch_gt_instances_ignore) + one_gt_losses = lad.loss_by_feat(*outs, [gt_instances], img_metas, + batch_gt_instances_ignore, + label_assignment_results) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + onegt_iou_loss = one_gt_losses['loss_iou'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_iou_loss.item(), 0, + 'box loss should be non-zero') + n, c, h, w = 10, 4, 20, 20 + mlvl_tensor = [torch.ones(n, c, h, w) for i in range(5)] + results = levels_to_images(mlvl_tensor) + self.assertEqual(len(results), n) + self.assertEqual(results[0].size(), (h * w * 5, c)) + self.assertTrue(lad.with_score_voting) + + lad = LADHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8]), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + cls_scores = [torch.ones(2, 4, 5, 5)] + bbox_preds = [torch.ones(2, 4, 5, 5)] + iou_preds = [torch.ones(2, 1, 5, 5)] + cfg = Config( + dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + rescale = False + lad.predict_by_feat( + cls_scores, bbox_preds, iou_preds, img_metas, cfg, rescale=rescale) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ld_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ld_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ce49b5385677aa1fdc9cc2a815cec40ea06b7a0c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ld_head.py @@ -0,0 +1,149 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import GFLHead, LDHead + + +class TestLDHead(TestCase): + + def test_ld_head_loss(self): + """Tests ld head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + train_cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9, ignore_iof_thr=0.1), + allowed_border=-1, + pos_weight=-1, + debug=False)) + + ld_head = LDHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_ld=dict( + type='KnowledgeDistillationKLDivLoss', loss_weight=1.0), + loss_cls=dict( + type='QualityFocalLoss', + use_sigmoid=True, + beta=2.0, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128])) + + teacher_model = GFLHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_cls=dict( + type='QualityFocalLoss', + use_sigmoid=True, + beta=2.0, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128])) + + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + cls_scores, bbox_preds = ld_head.forward(feat) + rand_soft_target = teacher_model.forward(feat)[1] + + # Test that empty ground truth encourages the network to predict + # background + + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + batch_gt_instances_ignore = None + + empty_gt_losses = ld_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + rand_soft_target, + batch_gt_instances_ignore) + + # When there is no truth, the cls loss should be nonzero, ld loss + # should be non-negative but there should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + empty_ld_loss = sum(empty_gt_losses['loss_ld']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertGreaterEqual(empty_ld_loss.item(), 0, + 'ld loss should be non-negative') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + batch_gt_instances_ignore = None + + one_gt_losses = ld_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + rand_soft_target, + batch_gt_instances_ignore) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + + batch_gt_instances_ignore = gt_instances + + # When truth is non-empty but ignored then the cls loss should be + # nonzero, but there should be no box loss. + ignore_gt_losses = ld_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + rand_soft_target, + batch_gt_instances_ignore) + ignore_cls_loss = sum(ignore_gt_losses['loss_cls']) + ignore_box_loss = sum(ignore_gt_losses['loss_bbox']) + + self.assertGreater(ignore_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual(ignore_box_loss.item(), 0, + 'gt bbox ignored loss should be zero') + + # When truth is non-empty and not ignored then both cls and box loss + # should be nonzero for random inputs + batch_gt_instances_ignore = InstanceData() + batch_gt_instances_ignore.bboxes = torch.randn(1, 4) + + not_ignore_gt_losses = ld_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + rand_soft_target, + batch_gt_instances_ignore) + not_ignore_cls_loss = sum(not_ignore_gt_losses['loss_cls']) + not_ignore_box_loss = sum(not_ignore_gt_losses['loss_bbox']) + + self.assertGreater(not_ignore_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreaterEqual(not_ignore_box_loss.item(), 0, + 'gt bbox not ignored loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_nasfcos_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_nasfcos_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1194e5c5fbca5d872b034e1c9b668eae4b930305 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_nasfcos_head.py @@ -0,0 +1,70 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import NASFCOSHead + + +class TestNASFCOSHead(TestCase): + + def test_nasfcos_head_loss(self): + """Tests nasfcos head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + nasfcos_head = NASFCOSHead( + num_classes=4, + in_channels=2, # the same as `deform_groups` in dconv3x3_config + feat_channels=2, + norm_cfg=None) + + # Nasfcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 2, s // stride[1], s // stride[0]).float() + for stride in nasfcos_head.prior_generator.strides) + cls_scores, bbox_preds, centernesses = nasfcos_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = nasfcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = empty_gt_losses['loss_cls'].item() + empty_box_loss = empty_gt_losses['loss_bbox'].item() + empty_ctr_loss = empty_gt_losses['loss_centerness'].item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_ctr_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = nasfcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].item() + onegt_box_loss = one_gt_losses['loss_bbox'].item() + onegt_ctr_loss = one_gt_losses['loss_centerness'].item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_ctr_loss, 0, + 'centerness loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_paa_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_paa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..137b2c55e17390612771b0844629cde28876aa68 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_paa_head.py @@ -0,0 +1,148 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import PAAHead, paa_head +from mmdet.models.utils import levels_to_images + + +class TestPAAHead(TestCase): + + def test_paa_head_loss(self): + """Tests paa head loss when truth is empty and non-empty.""" + + class mock_skm: + + def GaussianMixture(self, *args, **kwargs): + return self + + def fit(self, loss): + pass + + def predict(self, loss): + components = np.zeros_like(loss, dtype=np.long) + return components.reshape(-1) + + def score_samples(self, loss): + scores = np.random.random(len(loss)) + return scores + + paa_head.skm = mock_skm() + + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + train_cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.1, + neg_iou_thr=0.1, + min_pos_iou=0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + debug=False)) + # since Focal Loss is not supported on CPU + paa = PAAHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + paa.init_weights() + cls_scores, bbox_preds, iou_preds = paa(feat) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = paa.loss_by_feat(cls_scores, bbox_preds, iou_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + empty_iou_loss = empty_gt_losses['loss_iou'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_iou_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = paa.loss_by_feat(cls_scores, bbox_preds, iou_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + onegt_iou_loss = one_gt_losses['loss_iou'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_iou_loss.item(), 0, + 'box loss should be non-zero') + n, c, h, w = 10, 4, 20, 20 + mlvl_tensor = [torch.ones(n, c, h, w) for i in range(5)] + results = levels_to_images(mlvl_tensor) + self.assertEqual(len(results), n) + self.assertEqual(results[0].size(), (h * w * 5, c)) + self.assertTrue(paa.with_score_voting) + + paa = PAAHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8]), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + cls_scores = [torch.ones(2, 4, 5, 5)] + bbox_preds = [torch.ones(2, 4, 5, 5)] + iou_preds = [torch.ones(2, 1, 5, 5)] + cfg = Config( + dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + rescale = False + paa.predict_by_feat( + cls_scores, bbox_preds, iou_preds, img_metas, cfg, rescale=rescale) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_pisa_retinanet_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_pisa_retinanet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf94404cfdab1a97a5960e9338aad15a2916626 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_pisa_retinanet_head.py @@ -0,0 +1,105 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from math import ceil +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import PISARetinaHead + + +class TestPISARetinaHead(TestCase): + + def test_pisa_reitnanet_head_loss(self): + """Tests pisa retinanet head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + }] + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0, + ignore_iof_thr=-1), + isr=dict(k=2., bias=0.), + carl=dict(k=1., bias=0.2), + sampler=dict(type='PseudoSampler'), + allowed_border=-1, + pos_weight=-1, + debug=False)) + pisa_retinanet_head = PISARetinaHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=256, + anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0), + train_cfg=cfg) + + # pisa retina head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, ceil(s / stride[0]), ceil(s / stride[0])) + for stride in pisa_retinanet_head.prior_generator.strides) + cls_scores, bbox_preds = pisa_retinanet_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = pisa_retinanet_head.loss_by_feat( + cls_scores, bbox_preds, [gt_instances], img_metas) + # When there is no truth, cls_loss and box_loss should all be zero. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + empty_carl_loss = empty_gt_losses['loss_carl'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_carl_loss.item(), 0, + 'there should be no carl loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = pisa_retinanet_head.loss_by_feat( + cls_scores, bbox_preds, [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + onegt_carl_loss = one_gt_losses['loss_carl'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_carl_loss.item(), 0, + 'carl loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_pisa_ssd_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_pisa_ssd_head.py new file mode 100644 index 0000000000000000000000000000000000000000..cfdc0c79862c127eea2b751e9bb11f5bab0ce731 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_pisa_ssd_head.py @@ -0,0 +1,127 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from math import ceil +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import PISASSDHead + + +class TestPISASSDHead(TestCase): + + def test_pisa_ssd_head_loss(self): + """Tests pisa ssd head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0., + ignore_iof_thr=-1, + gt_max_assign_all=False), + sampler=dict(type='PseudoSampler'), + smoothl1_beta=1., + allowed_border=-1, + pos_weight=-1, + neg_pos_ratio=3, + debug=False)) + pisa_ssd_head = PISASSDHead( + num_classes=4, + in_channels=(1, 1, 1, 1, 1, 1), + anchor_generator=dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=s, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]), + train_cfg=cfg) + + # PISA SSD head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, ceil(s / stride[0]), ceil(s / stride[0])) + for stride in pisa_ssd_head.prior_generator.strides) + cls_scores, bbox_preds = pisa_ssd_head.forward(feats) + + # test without isr and carl + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = pisa_ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, cls_loss and box_loss should all be zero. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = pisa_ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + + pisa_ssd_head.train_cfg.update( + dict(isr=dict(k=2., bias=0.), carl=dict(k=1., bias=0.2))) + + # test with isr and carl + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = pisa_ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, cls_loss and box_loss should all be zero. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = pisa_ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_reppoints_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_reppoints_head.py new file mode 100644 index 0000000000000000000000000000000000000000..96ec3caf496fc30c0c366458e095b9f36aad54ee --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_reppoints_head.py @@ -0,0 +1,143 @@ +import unittest + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet.models.dense_heads import RepPointsHead +from mmdet.structures import DetDataSample + + +class TestRepPointsHead(unittest.TestCase): + + @parameterized.expand(['moment', 'minmax', 'partial_minmax']) + def test_head_loss(self, transform_method='moment'): + cfg = ConfigDict( + dict( + num_classes=2, + in_channels=32, + point_feat_channels=10, + num_points=9, + gradient_mul=0.1, + point_strides=[8, 16, 32, 64, 128], + point_base_scale=4, + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox_init=dict( + type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=0.5), + loss_bbox_refine=dict( + type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0), + use_grid_points=False, + center_init=True, + transform_method=transform_method, + moment_mul=0.01, + init_cfg=dict( + type='Normal', + layer='Conv2d', + std=0.01, + override=dict( + type='Normal', + name='reppoints_cls_out', + std=0.01, + bias_prob=0.01)), + train_cfg=dict( + init=dict( + assigner=dict( + type='PointAssigner', scale=4, pos_num=1), + allowed_border=-1, + pos_weight=-1, + debug=False), + refine=dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + debug=False)), + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100))) + reppoints_head = RepPointsHead(**cfg) + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + }] + x = [ + torch.rand(1, 32, s // 2**(i + 2), s // 2**(i + 2)) + for i in range(5) + ] + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + + reppoints_head.train() + forward_outputs = reppoints_head.forward(x) + empty_gt_losses = reppoints_head.loss_by_feat(*forward_outputs, + [gt_instances], + img_metas, + gt_bboxes_ignore) + # When there is no truth, the cls loss should be nonzero but there + # should be no pts loss. + for key, losses in empty_gt_losses.items(): + for loss in losses: + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'pts' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no reg loss when no ground true boxes' + ) + + # When truth is non-empty then both cls and pts loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = reppoints_head.loss_by_feat(*forward_outputs, + [gt_instances], img_metas, + gt_bboxes_ignore) + # loss_cls should all be non-zero + self.assertTrue( + all([loss.item() > 0 for loss in one_gt_losses['loss_cls']])) + # only one level loss_pts_init is non-zero + cnt_non_zero = 0 + for loss in one_gt_losses['loss_pts_init']: + if loss.item() != 0: + cnt_non_zero += 1 + self.assertEqual(cnt_non_zero, 1) + + # only one level loss_pts_refine is non-zero + cnt_non_zero = 0 + for loss in one_gt_losses['loss_pts_init']: + if loss.item() != 0: + cnt_non_zero += 1 + self.assertEqual(cnt_non_zero, 1) + + # test loss + samples = DetDataSample() + samples.set_metainfo(img_metas[0]) + samples.gt_instances = gt_instances + reppoints_head.loss(x, [samples]) + # test only predict + reppoints_head.eval() + reppoints_head.predict(x, [samples], rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_retina_sepBN_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_retina_sepBN_head.py new file mode 100644 index 0000000000000000000000000000000000000000..95a18f64827290c1339ab5eba9d5bc9ce1a488ec --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_retina_sepBN_head.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import RetinaSepBNHead + + +class TestRetinaSepBNHead(TestCase): + + def test_init(self): + """Test init RetinaSepBN head.""" + anchor_head = RetinaSepBNHead(num_classes=1, num_ins=1, in_channels=1) + anchor_head.init_weights() + self.assertTrue(anchor_head.cls_convs) + self.assertTrue(anchor_head.reg_convs) + self.assertTrue(anchor_head.retina_cls) + self.assertTrue(anchor_head.retina_reg) + + def test_retina_sepbn_head_loss(self): + """Tests RetinaSepBN head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0, + ignore_iof_thr=-1), + sampler=dict(type='PseudoSampler' + ), # Focal loss should use PseudoSampler + allowed_border=-1, + pos_weight=-1, + debug=False)) + anchor_head = RetinaSepBNHead( + num_classes=4, num_ins=5, in_channels=1, train_cfg=cfg) + + # Anchor head expects a multiple levels of features per image + feats = [] + for i in range(len(anchor_head.prior_generator.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2)))) + + cls_scores, bbox_preds = anchor_head.forward(tuple(feats)) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_rpn_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1309d01d9917a82b48c91c520171eb6462626d94 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_rpn_head.py @@ -0,0 +1,124 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import pytest +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import RPNHead + + +class TestRPNHead(TestCase): + + def test_init(self): + """Test init rpn head.""" + rpn_head = RPNHead(num_classes=1, in_channels=1) + self.assertTrue(rpn_head.rpn_conv) + self.assertTrue(rpn_head.rpn_cls) + self.assertTrue(rpn_head.rpn_reg) + + # rpn_head.num_convs > 1 + rpn_head = RPNHead(num_classes=1, in_channels=1, num_convs=2) + self.assertTrue(rpn_head.rpn_conv) + self.assertTrue(rpn_head.rpn_cls) + self.assertTrue(rpn_head.rpn_reg) + + def test_rpn_head_loss(self): + """Tests rpn head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.3, + min_pos_iou=0.3, + 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=0, + pos_weight=-1, + debug=False)) + rpn_head = RPNHead(num_classes=1, in_channels=1, train_cfg=cfg) + + # Anchor head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(len(rpn_head.prior_generator.strides))) + cls_scores, bbox_preds = rpn_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = rpn_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_rpn_cls']) + empty_box_loss = sum(empty_gt_losses['loss_rpn_bbox']) + self.assertGreater(empty_cls_loss.item(), 0, + 'rpn cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([0]) + + one_gt_losses = rpn_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_rpn_cls']) + onegt_box_loss = sum(one_gt_losses['loss_rpn_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'rpn cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'rpn box loss should be non-zero') + + # When there is no valid anchor, the loss will be None, + # and this will raise a ValueError. + img_metas = [{ + 'img_shape': (8, 8, 3), + 'pad_shape': (8, 8, 3), + 'scale_factor': 1, + }] + with pytest.raises(ValueError): + rpn_head.loss_by_feat(cls_scores, bbox_preds, [gt_instances], + img_metas) + + def test_bbox_post_process(self): + """Test the length of detection instance results is 0.""" + from mmengine.config import ConfigDict + cfg = ConfigDict( + nms_pre=1000, + max_per_img=1000, + nms=dict(type='nms', iou_threshold=0.7), + min_bbox_size=0) + + rpn_head = RPNHead(num_classes=1, in_channels=1) + results = InstanceData(metainfo=dict()) + results.bboxes = torch.zeros((0, 4)) + results.scores = torch.zeros(0) + results = rpn_head._bbox_post_process(results, cfg, img_meta=dict()) + self.assertEqual(len(results), 0) + self.assertEqual(results.bboxes.size(), (0, 4)) + self.assertEqual(results.scores.size(), (0, )) + self.assertEqual(results.labels.size(), (0, )) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_sabl_retina_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_sabl_retina_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2f6638ff857717bd18e1f1d257c13277c7ea6be5 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_sabl_retina_head.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import SABLRetinaHead + + +class TestSABLRetinaHead(TestCase): + + def test_sabl_retina_head(self): + """Tests sabl retina head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': [1, 1], + }] + train_cfg = ConfigDict( + dict( + assigner=dict( + type='ApproxMaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0.0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + debug=False)) + sabl_retina_head = SABLRetinaHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[4], + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='BucketingBBoxCoder', num_buckets=14, scale_factor=3.0), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.5), + loss_bbox_reg=dict( + type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.5), + train_cfg=train_cfg) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in sabl_retina_head.square_anchor_generator.strides) + outs = sabl_retina_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = sabl_retina_head.loss_by_feat( + *outs, [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = sum(empty_gt_losses['loss_cls']).item() + empty_box_cls_loss = sum(empty_gt_losses['loss_bbox_cls']).item() + empty_box_reg_loss = sum(empty_gt_losses['loss_bbox_reg']).item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_cls_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_box_reg_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = sabl_retina_head.loss_by_feat(*outs, [gt_instances], + img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']).item() + onegt_box_cls_loss = sum(one_gt_losses['loss_bbox_cls']).item() + onegt_box_reg_loss = sum(one_gt_losses['loss_bbox_reg']).item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_cls_loss, 0, + 'box loss should be non-zero') + self.assertGreater(onegt_box_reg_loss, 0, + 'centerness loss should be non-zero') + + test_cfg = ConfigDict( + dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100)) + # test predict_by_feat + sabl_retina_head.predict_by_feat( + *outs, batch_img_metas=img_metas, cfg=test_cfg, rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_solo_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_solo_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1182d85b6f75da272a0c77cb18eae487778e86a6 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_solo_head.py @@ -0,0 +1,144 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet import * # noqa +from mmdet.models.dense_heads import (DecoupledSOLOHead, + DecoupledSOLOLightHead, SOLOHead) +from mmdet.structures.mask import BitmapMasks + + +def _rand_masks(num_items, bboxes, img_w, img_h): + rng = np.random.RandomState(0) + masks = np.zeros((num_items, img_h, img_w)) + for i, bbox in enumerate(bboxes): + bbox = bbox.astype(np.int32) + mask = (rng.rand(1, bbox[3] - bbox[1], bbox[2] - bbox[0]) > + 0.3).astype(np.int64) + masks[i:i + 1, bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask + return BitmapMasks(masks, height=img_h, width=img_w) + + +class TestSOLOHead(TestCase): + + @parameterized.expand([(SOLOHead, ), (DecoupledSOLOHead, ), + (DecoupledSOLOLightHead, )]) + def test_mask_head_loss(self, MaskHead): + """Tests mask head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + }] + + mask_head = MaskHead(num_classes=4, in_channels=1) + + # SOLO head expects a multiple levels of features per image + feats = [] + for i in range(len(mask_head.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2)))) + feats = tuple(feats) + + mask_outs = mask_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty(0, 4) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + + empty_gt_losses = mask_head.loss_by_feat( + *mask_outs, + batch_gt_instances=[gt_instances], + batch_img_metas=img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_mask_loss = empty_gt_losses['loss_mask'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_mask_loss.item(), 0, + 'there should be no mask loss when there are no true mask') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + + one_gt_losses = mask_head.loss_by_feat( + *mask_outs, + batch_gt_instances=[gt_instances], + batch_img_metas=img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_mask_loss = one_gt_losses['loss_mask'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_mask_loss.item(), 0, + 'mask loss should be non-zero') + + def test_solo_head_empty_result(self): + s = 256 + img_metas = { + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + } + + mask_head = SOLOHead(num_classes=4, in_channels=1) + + cls_scores = torch.empty(0, 80) + mask_preds = torch.empty(0, 16, 16) + test_cfg = ConfigDict( + score_thr=0.1, + mask_thr=0.5, + ) + results = mask_head._predict_by_feat_single( + cls_scores=cls_scores, + mask_preds=mask_preds, + img_meta=img_metas, + cfg=test_cfg) + + self.assertIsInstance(results, InstanceData) + self.assertEqual(len(results), 0) + + def test_decoupled_solo_head_empty_result(self): + s = 256 + img_metas = { + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + } + + mask_head = DecoupledSOLOHead(num_classes=4, in_channels=1) + + cls_scores = torch.empty(0, 80) + mask_preds_x = torch.empty(0, 16, 16) + mask_preds_y = torch.empty(0, 16, 16) + test_cfg = ConfigDict( + score_thr=0.1, + mask_thr=0.5, + ) + results = mask_head._predict_by_feat_single( + cls_scores=cls_scores, + mask_preds_x=mask_preds_x, + mask_preds_y=mask_preds_y, + img_meta=img_metas, + cfg=test_cfg) + + self.assertIsInstance(results, InstanceData) + self.assertEqual(len(results), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_solov2_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_solov2_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6abf91664dcf6d22850fdc971596b24a894cd487 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_solov2_head.py @@ -0,0 +1,130 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import SOLOV2Head +from mmdet.structures.mask import BitmapMasks + + +def _rand_masks(num_items, bboxes, img_w, img_h): + rng = np.random.RandomState(0) + masks = np.zeros((num_items, img_h, img_w)) + for i, bbox in enumerate(bboxes): + bbox = bbox.astype(np.int32) + mask = (rng.rand(1, bbox[3] - bbox[1], bbox[2] - bbox[0]) > + 0.3).astype(np.int64) + masks[i:i + 1, bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask + return BitmapMasks(masks, height=img_h, width=img_w) + + +def _fake_mask_feature_head(): + mask_feature_head = ConfigDict( + feat_channels=128, + start_level=0, + end_level=3, + out_channels=256, + mask_stride=4, + norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)) + return mask_feature_head + + +class TestSOLOv2Head(TestCase): + + def test_solov2_head_loss(self): + """Tests mask head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + }] + + mask_feature_head = _fake_mask_feature_head() + + mask_head = SOLOV2Head( + num_classes=4, in_channels=1, mask_feature_head=mask_feature_head) + + # SOLO head expects a multiple levels of features per image + feats = [] + for i in range(len(mask_head.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2)))) + feats = tuple(feats) + + mask_outs = mask_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty(0, 4) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + + empty_gt_losses = mask_head.loss_by_feat( + *mask_outs, + batch_gt_instances=[gt_instances], + batch_img_metas=img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_mask_loss = empty_gt_losses['loss_mask'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_mask_loss.item(), 0, + 'there should be no mask loss when there are no true mask') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + + one_gt_losses = mask_head.loss_by_feat( + *mask_outs, + batch_gt_instances=[gt_instances], + batch_img_metas=img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_mask_loss = one_gt_losses['loss_mask'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_mask_loss.item(), 0, + 'mask loss should be non-zero') + + def test_solov2_head_empty_result(self): + s = 256 + img_metas = { + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + } + + mask_feature_head = _fake_mask_feature_head() + mask_head = SOLOV2Head( + num_classes=4, in_channels=1, mask_feature_head=mask_feature_head) + + kernel_preds = torch.empty(0, 128) + cls_scores = torch.empty(0, 80) + mask_feats = torch.empty(0, 16, 16) + test_cfg = ConfigDict( + score_thr=0.1, + mask_thr=0.5, + ) + results = mask_head._predict_by_feat_single( + kernel_preds=kernel_preds, + cls_scores=cls_scores, + mask_feats=mask_feats, + img_meta=img_metas, + cfg=test_cfg) + + self.assertIsInstance(results, InstanceData) + self.assertEqual(len(results), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ssd_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ssd_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c76a5e2584783c21974c7796edeea604827886 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_ssd_head.py @@ -0,0 +1,91 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from math import ceil +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import SSDHead + + +class TestSSDHead(TestCase): + + def test_ssd_head_loss(self): + """Tests ssd head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0., + ignore_iof_thr=-1, + gt_max_assign_all=False), + sampler=dict(type='PseudoSampler'), + smoothl1_beta=1., + allowed_border=-1, + pos_weight=-1, + neg_pos_ratio=3, + debug=False)) + ssd_head = SSDHead( + num_classes=4, + in_channels=(1, 1, 1, 1, 1, 1), + stacked_convs=1, + feat_channels=1, + use_depthwise=True, + anchor_generator=dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=s, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]), + train_cfg=cfg) + + # SSD head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, ceil(s / stride[0]), ceil(s / stride[0])) + for stride in ssd_head.prior_generator.strides) + cls_scores, bbox_preds = ssd_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, cls_loss and box_loss should all be zero. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_tood_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_tood_head.py new file mode 100644 index 0000000000000000000000000000000000000000..346085553d637426fd2e60735163d83030882bf1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_tood_head.py @@ -0,0 +1,193 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config, MessageHub +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import TOODHead + + +def _tood_head(anchor_type): + """Set type of tood head.""" + train_cfg = Config( + dict( + initial_epoch=4, + initial_assigner=dict(type='ATSSAssigner', topk=9), + assigner=dict(type='TaskAlignedAssigner', topk=13), + alpha=1, + beta=6, + allowed_border=-1, + pos_weight=-1, + debug=False)) + test_cfg = Config( + dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + + tood_head = TOODHead( + num_classes=80, + in_channels=1, + stacked_convs=1, + feat_channels=8, # the same as `la_down_rate` in TaskDecomposition + norm_cfg=None, + anchor_type=anchor_type, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[0.1, 0.1, 0.2, 0.2]), + initial_loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + activated=True, # use probability instead of logit as input + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_cls=dict( + type='QualityFocalLoss', + use_sigmoid=True, + activated=True, # use probability instead of logit as input + beta=2.0, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + train_cfg=train_cfg, + test_cfg=test_cfg) + return tood_head + + +class TestTOODHead(TestCase): + + def test_tood_head_anchor_free_loss(self): + """Tests tood head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + tood_head = _tood_head('anchor_free') + tood_head.init_weights() + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [8, 16, 32, 64, 128] + ] + cls_scores, bbox_preds = tood_head(feat) + + message_hub = MessageHub.get_instance('runtime_info') + message_hub.update_info('epoch', 0) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + empty_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater( + sum(empty_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertEqual( + sum(empty_box_loss).item(), 0, + 'there should be no box loss when there are no true boxes') + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_bboxes_ignore = None + one_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater( + sum(onegt_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertGreater( + sum(onegt_box_loss).item(), 0, 'box loss should be non-zero') + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + empty_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater( + sum(empty_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertEqual( + sum(empty_box_loss).item(), 0, + 'there should be no box loss when there are no true boxes') + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_bboxes_ignore = None + one_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater( + sum(onegt_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertGreater( + sum(onegt_box_loss).item(), 0, 'box loss should be non-zero') + + def test_tood_head_anchor_based_loss(self): + """Tests tood head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + tood_head = _tood_head('anchor_based') + tood_head.init_weights() + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [8, 16, 32, 64, 128] + ] + cls_scores, bbox_preds = tood_head(feat) + + message_hub = MessageHub.get_instance('runtime_info') + message_hub.update_info('epoch', 0) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + empty_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater( + sum(empty_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertEqual( + sum(empty_box_loss).item(), 0, + 'there should be no box loss when there are no true boxes') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_vfnet_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_vfnet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..26f63c77079c23801b8ab527be7205eb7c1487b2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_vfnet_head.py @@ -0,0 +1,135 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import VFNetHead + + +class TestVFNetHead(TestCase): + + def test_vfnet_head_loss(self): + """Tests vfnet head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'pad_shape': (s, s, 3) + }] + train_cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False)) + # since VarFocal Loss is not supported on CPU + vfnet_head = VFNetHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_cls=dict( + type='VarifocalLoss', use_sigmoid=True, loss_weight=1.0)) + + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + cls_scores, bbox_preds, bbox_preds_refine = vfnet_head.forward(feat) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = vfnet_head.loss_by_feat(cls_scores, bbox_preds, + bbox_preds_refine, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = vfnet_head.loss_by_feat(cls_scores, bbox_preds, + bbox_preds_refine, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + + def test_vfnet_head_loss_without_atss(self): + """Tests vfnet head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'pad_shape': (s, s, 3) + }] + train_cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False)) + # since VarFocal Loss is not supported on CPU + vfnet_head = VFNetHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + use_atss=False, + loss_cls=dict( + type='VarifocalLoss', use_sigmoid=True, loss_weight=1.0)) + + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + cls_scores, bbox_preds, bbox_preds_refine = vfnet_head.forward(feat) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = vfnet_head.loss_by_feat(cls_scores, bbox_preds, + bbox_preds_refine, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = vfnet_head.loss_by_feat(cls_scores, bbox_preds, + bbox_preds_refine, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolo_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolo_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2c48170dbf7054da32e28c7eee9fd736c772caf4 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolo_head.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import Config +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import YOLOV3Head + + +class TestYOLOV3Head(TestCase): + + def test_yolo_head_loss(self): + """Tests YOLO head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + head = YOLOV3Head( + num_classes=4, + in_channels=[1, 1, 1], + out_channels=[1, 1, 1], + train_cfg=Config( + dict( + assigner=dict( + type='GridAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0)))) + head.init_weights() + + # YOLO head expects a multiple levels of features per image + feats = [ + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in head.prior_generator.strides + ] + predmaps, = head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = head.loss_by_feat(predmaps, [gt_instances], + img_metas) + # When there is no truth, the conf loss should be nonzero but + # cls loss and xy&wh loss should be zero + empty_cls_loss = sum(empty_gt_losses['loss_cls']).item() + empty_conf_loss = sum(empty_gt_losses['loss_conf']).item() + empty_xy_loss = sum(empty_gt_losses['loss_xy']).item() + empty_wh_loss = sum(empty_gt_losses['loss_wh']).item() + self.assertGreater(empty_conf_loss, 0, 'conf loss should be non-zero') + self.assertEqual( + empty_cls_loss, 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_xy_loss, 0, + 'there should be no xy loss when there are no true boxes') + self.assertEqual( + empty_wh_loss, 0, + 'there should be no wh loss when there are no true boxes') + + # When truth is non-empty then all conf, cls loss and xywh loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = head.loss_by_feat(predmaps, [gt_instances], img_metas) + one_gt_cls_loss = sum(one_gt_losses['loss_cls']).item() + one_gt_conf_loss = sum(one_gt_losses['loss_conf']).item() + one_gt_xy_loss = sum(one_gt_losses['loss_xy']).item() + one_gt_wh_loss = sum(one_gt_losses['loss_wh']).item() + self.assertGreater(one_gt_conf_loss, 0, 'conf loss should be non-zero') + self.assertGreater(one_gt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(one_gt_xy_loss, 0, 'xy loss should be non-zero') + self.assertGreater(one_gt_wh_loss, 0, 'wh loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolof_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolof_head.py new file mode 100644 index 0000000000000000000000000000000000000000..29375d19914d1ae950328adc90d7479d596fe4a1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolof_head.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import YOLOFHead + + +class TestYOLOFHead(TestCase): + + def test_yolof_head_loss(self): + """Tests yolof head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'pad_shape': (s, s, 3) + }] + train_cfg = Config( + dict( + assigner=dict( + type='UniformAssigner', + pos_ignore_thr=0.15, + neg_ignore_thr=0.7), + allowed_border=-1, + pos_weight=-1, + debug=False)) + yolof_head = YOLOFHead( + num_classes=4, + in_channels=1, + feat_channels=1, + reg_decoded_bbox=True, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[1, 2, 4, 8, 16], + strides=[32]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1., 1., 1., 1.], + add_ctr_clamp=True, + ctr_clamp=32), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.0)) + feat = [torch.rand(1, 1, s // 32, s // 32)] + cls_scores, bbox_preds = yolof_head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = yolof_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = yolof_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolox_head.py b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1c830f58016fe508e950c79c222a0951ef0e988e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_dense_heads/test_yolox_head.py @@ -0,0 +1,164 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule +from mmengine.config import Config +from mmengine.model import bias_init_with_prob +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.dense_heads import YOLOXHead + + +class TestYOLOXHead(TestCase): + + def test_init_weights(self): + head = YOLOXHead( + num_classes=4, in_channels=1, stacked_convs=1, use_depthwise=False) + head.init_weights() + bias_init = bias_init_with_prob(0.01) + for conv_cls, conv_obj in zip(head.multi_level_conv_cls, + head.multi_level_conv_obj): + assert_allclose(conv_cls.bias.data, + torch.ones_like(conv_cls.bias.data) * bias_init) + assert_allclose(conv_obj.bias.data, + torch.ones_like(conv_obj.bias.data) * bias_init) + + def test_predict_by_feat(self): + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': (1.0, 1.0), + }] + test_cfg = Config( + dict(score_thr=0.01, nms=dict(type='nms', iou_threshold=0.65))) + head = YOLOXHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + use_depthwise=False, + test_cfg=test_cfg) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16] + ] + cls_scores, bbox_preds, objectnesses = head.forward(feat) + head.predict_by_feat( + cls_scores, + bbox_preds, + objectnesses, + img_metas, + cfg=test_cfg, + rescale=True, + with_nms=True) + head.predict_by_feat( + cls_scores, + bbox_preds, + objectnesses, + img_metas, + cfg=test_cfg, + rescale=False, + with_nms=False) + + def test_loss_by_feat(self): + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + train_cfg = Config( + dict( + assigner=dict( + type='SimOTAAssigner', + center_radius=2.5, + candidate_topk=10, + iou_weight=3.0, + cls_weight=1.0))) + head = YOLOXHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + use_depthwise=False, + train_cfg=train_cfg) + assert not head.use_l1 + assert isinstance(head.multi_level_cls_convs[0][0], ConvModule) + + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16] + ] + cls_scores, bbox_preds, objectnesses = head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData( + bboxes=torch.empty((0, 4)), labels=torch.LongTensor([])) + + empty_gt_losses = head.loss_by_feat(cls_scores, bbox_preds, + objectnesses, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'].sum() + empty_box_loss = empty_gt_losses['loss_bbox'].sum() + empty_obj_loss = empty_gt_losses['loss_obj'].sum() + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertGreater(empty_obj_loss.item(), 0, + 'objectness loss should be non-zero') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + head = YOLOXHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + use_depthwise=True, + train_cfg=train_cfg) + assert isinstance(head.multi_level_cls_convs[0][0], + DepthwiseSeparableConvModule) + head.use_l1 = True + gt_instances = InstanceData( + bboxes=torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), + labels=torch.LongTensor([2])) + + one_gt_losses = head.loss_by_feat(cls_scores, bbox_preds, objectnesses, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].sum() + onegt_box_loss = one_gt_losses['loss_bbox'].sum() + onegt_obj_loss = one_gt_losses['loss_obj'].sum() + onegt_l1_loss = one_gt_losses['loss_l1'].sum() + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_obj_loss.item(), 0, + 'obj loss should be non-zero') + self.assertGreater(onegt_l1_loss.item(), 0, + 'l1 loss should be non-zero') + + # Test groud truth out of bound + gt_instances = InstanceData( + bboxes=torch.Tensor([[s * 4, s * 4, s * 4 + 10, s * 4 + 10]]), + labels=torch.LongTensor([2])) + empty_gt_losses = head.loss_by_feat(cls_scores, bbox_preds, + objectnesses, [gt_instances], + img_metas) + # When gt_bboxes out of bound, the assign results should be empty, + # so the cls and bbox loss should be zero. + empty_cls_loss = empty_gt_losses['loss_cls'].sum() + empty_box_loss = empty_gt_losses['loss_bbox'].sum() + empty_obj_loss = empty_gt_losses['loss_obj'].sum() + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when gt_bboxes out of bound') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when gt_bboxes out of bound') + self.assertGreater(empty_obj_loss.item(), 0, + 'objectness loss should be non-zero') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_conditional_detr.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_conditional_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..f907f6face1395bc56472b7c109b22448a7597b1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_conditional_detr.py @@ -0,0 +1,85 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestConditionalDETR(TestCase): + + def setUp(self) -> None: + register_all_modules() + + def test_conditional_detr_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + img_metas = DetDataSample() + img_metas.set_metainfo(metainfo) + batch_data_samples = [] + batch_data_samples.append(img_metas) + + config = get_detector_cfg( + 'conditional_detr/conditional-detr_r50_8xb2-50e_coco.py') + + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + img_metas.gt_instances = gt_instances + batch_data_samples1 = [] + batch_data_samples1.append(img_metas) + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'bbox' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no box loss when no ground true boxes') + elif 'iou' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no iou loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + img_metas.gt_instances = gt_instances + batch_data_samples2 = [] + batch_data_samples2.append(img_metas) + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward(random_image, batch_data_samples=batch_data_samples2) + # test only predict + model.predict( + random_image, batch_data_samples=batch_data_samples2, rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_cornernet.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_cornernet.py new file mode 100644 index 0000000000000000000000000000000000000000..10bc62649f699b9f6c38a9369091c38cd18c2c6c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_cornernet.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestCornerNet(TestCase): + + def setUp(self) -> None: + register_all_modules() + model_cfg = get_detector_cfg( + 'cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py') + + backbone = dict( + type='ResNet', + depth=18, + num_stages=4, + out_indices=(3, ), + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=True, + style='pytorch') + + neck = dict( + type='FPN', + in_channels=[512], + out_channels=256, + start_level=0, + add_extra_convs='on_input', + num_outs=1) + + model_cfg.backbone = ConfigDict(**backbone) + model_cfg.neck = ConfigDict(**neck) + model_cfg.bbox_head.num_feat_levels = 1 + self.model_cfg = model_cfg + + def test_init(self): + model = get_detector_cfg( + 'cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py') + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.bbox_head is not None) + self.assertTrue(detector.backbone is not None) + self.assertTrue(not hasattr(detector, 'neck')) + + @unittest.skipIf(not torch.cuda.is_available(), + 'test requires GPU and torch+cuda') + def test_cornernet_forward_loss_mode(self): + from mmdet.registry import MODELS + detector = MODELS.build(self.model_cfg) + detector.init_weights() + + packed_inputs = demo_mm_inputs(2, [[3, 511, 511], [3, 511, 511]]) + data = detector.data_preprocessor(packed_inputs, True) + losses = detector.forward(**data, mode='loss') + assert isinstance(losses, dict) + + @unittest.skipIf(not torch.cuda.is_available(), + 'test requires GPU and torch+cuda') + def test_cornernet_forward_predict_mode(self): + from mmdet.registry import MODELS + detector = MODELS.build(self.model_cfg) + detector.init_weights() + + packed_inputs = demo_mm_inputs(2, [[3, 512, 512], [3, 512, 512]]) + data = detector.data_preprocessor(packed_inputs, False) + + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + assert len(batch_results) == 2 + assert isinstance(batch_results[0], DetDataSample) + + @unittest.skipIf(not torch.cuda.is_available(), + 'test requires GPU and torch+cuda') + def test_cornernet_forward_tensor_mode(self): + from mmdet.registry import MODELS + detector = MODELS.build(self.model_cfg) + detector.init_weights() + + packed_inputs = demo_mm_inputs(2, [[3, 512, 512], [3, 512, 512]]) + data = detector.data_preprocessor(packed_inputs, False) + batch_results = detector.forward(**data, mode='tensor') + assert isinstance(batch_results, tuple) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_dab_detr.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_dab_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..37cc042c83441b24b71faa433e2b53e877cbddb9 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_dab_detr.py @@ -0,0 +1,84 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDABDETR(TestCase): + + def setUp(self) -> None: + register_all_modules() + + def test_dab_detr_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + img_metas = DetDataSample() + img_metas.set_metainfo(metainfo) + batch_data_samples = [] + batch_data_samples.append(img_metas) + + config = get_detector_cfg('dab_detr/dab-detr_r50_8xb2-50e_coco.py') + + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + img_metas.gt_instances = gt_instances + batch_data_samples1 = [] + batch_data_samples1.append(img_metas) + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'bbox' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no box loss when no ground true boxes') + elif 'iou' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no iou loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + img_metas.gt_instances = gt_instances + batch_data_samples2 = [] + batch_data_samples2.append(img_metas) + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward(random_image, batch_data_samples=batch_data_samples2) + # test only predict + model.predict( + random_image, batch_data_samples=batch_data_samples2, rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_deformable_detr.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_deformable_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..45be51db74457a794d6ed08bcc4ccc72aee17f3a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_deformable_detr.py @@ -0,0 +1,99 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDeformableDETR(TestCase): + + def setUp(self): + register_all_modules() + + def test_deformable_detr_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + img_metas = DetDataSample() + img_metas.set_metainfo(metainfo) + batch_data_samples = [] + batch_data_samples.append(img_metas) + + configs = [ + get_detector_cfg( + 'deformable_detr/deformable-detr_r50_16xb2-50e_coco.py'), + get_detector_cfg( + 'deformable_detr/deformable-detr-refine_r50_16xb2-50e_coco.py' # noqa + ), + get_detector_cfg( + 'deformable_detr/deformable-detr-refine-twostage_r50_16xb2-50e_coco.py' # noqa + ) + ] + + for config in configs: + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + img_metas.gt_instances = gt_instances + batch_data_samples1 = [] + batch_data_samples1.append(img_metas) + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'bbox' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no box loss when no ground true boxes' + ) + elif 'iou' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no iou loss when no ground true boxes' + ) + + # When truth is non-empty then both cls and box loss should + # be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + img_metas.gt_instances = gt_instances + batch_data_samples2 = [] + batch_data_samples2.append(img_metas) + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward( + random_image, batch_data_samples=batch_data_samples2) + # test only predict + model.predict( + random_image, + batch_data_samples=batch_data_samples2, + rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_detr.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..8af26da2eb4258eac02f3c3645da577b2fe20558 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_detr.py @@ -0,0 +1,84 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDETR(TestCase): + + def setUp(self) -> None: + register_all_modules() + + def test_detr_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + img_metas = DetDataSample() + img_metas.set_metainfo(metainfo) + batch_data_samples = [] + batch_data_samples.append(img_metas) + + config = get_detector_cfg('detr/detr_r50_8xb2-150e_coco.py') + + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + img_metas.gt_instances = gt_instances + batch_data_samples1 = [] + batch_data_samples1.append(img_metas) + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'bbox' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no box loss when no ground true boxes') + elif 'iou' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no iou loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + img_metas.gt_instances = gt_instances + batch_data_samples2 = [] + batch_data_samples2.append(img_metas) + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward(random_image, batch_data_samples=batch_data_samples2) + # test only predict + model.predict( + random_image, batch_data_samples=batch_data_samples2, rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_dino.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_dino.py new file mode 100644 index 0000000000000000000000000000000000000000..99885c1dfee9c57ee044c410844aead51b8cfbd3 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_dino.py @@ -0,0 +1,81 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDINO(TestCase): + + def setUp(self): + register_all_modules() + + def test_dino_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + data_sample = DetDataSample() + data_sample.set_metainfo(metainfo) + + configs = [get_detector_cfg('dino/dino-4scale_r50_8xb2-12e_coco.py')] + + for config in configs: + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + data_sample.gt_instances = gt_instances + batch_data_samples_1 = [data_sample] + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples_1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + _loss = loss.item() + if 'bbox' in key or 'iou' in key or 'dn' in key: + self.assertEqual( + _loss, 0, f'there should be no {key}({_loss}) ' + f'when no ground true boxes') + elif 'cls' in key: + self.assertGreater(_loss, 0, + f'{key}({_loss}) should be non-zero') + + # When truth is non-empty then both cls and box loss should + # be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + data_sample.gt_instances = gt_instances + batch_data_samples_2 = [data_sample] + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples_2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward( + random_image, batch_data_samples=batch_data_samples_2) + # test only predict + model.predict( + random_image, + batch_data_samples=batch_data_samples_2, + rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_glip.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_glip.py new file mode 100644 index 0000000000000000000000000000000000000000..8be3d8d719fce26710e5ade01b2fddca319c259c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_glip.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestGLIP(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand( + ['glip/glip_atss_swin-t_a_fpn_dyhead_pretrain_obj365.py']) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.language_model) + self.assertTrue(detector.neck) + self.assertTrue(detector.bbox_head) + + @parameterized.expand([ + ('glip/glip_atss_swin-t_a_fpn_dyhead_pretrain_obj365.py', ('cpu', + 'cuda')) + ]) + def test_glip_forward_predict_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + # test custom_entities is True + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + texts=['a', 'b'], + custom_entities=True) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + # test custom_entities is False + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + texts=['a', 'b'], + custom_entities=False) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_kd_single_stage.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_kd_single_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..93d886263a87c6472ac83135e792f3ced6a5dd30 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_kd_single_stage.py @@ -0,0 +1,78 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet import * # noqa +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestKDSingleStageDetector(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand(['ld/ld_r18-gflv1-r101_fpn_1x_coco.py']) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.bbox_head) + + @parameterized.expand([('ld/ld_r18-gflv1-r101_fpn_1x_coco.py', ('cpu', + 'cuda'))]) + def test_single_stage_forward_train(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, True) + # Test forward train + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([('ld/ld_r18-gflv1-r101_fpn_1x_coco.py', ('cpu', + 'cuda'))]) + def test_single_stage_forward_test(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_maskformer.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_maskformer.py new file mode 100644 index 0000000000000000000000000000000000000000..3eeb04bfd55fcebaeaf0cc403880951c2123bcb3 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_maskformer.py @@ -0,0 +1,236 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing._utils import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestMaskFormer(unittest.TestCase): + + def setUp(self): + register_all_modules() + + def _create_model_cfg(self): + cfg_path = 'maskformer/maskformer_r50_ms-16xb1-75e_coco.py' + model_cfg = get_detector_cfg(cfg_path) + base_channels = 32 + model_cfg.backbone.depth = 18 + model_cfg.backbone.init_cfg = None + model_cfg.backbone.base_channels = base_channels + model_cfg.panoptic_head.in_channels = [ + base_channels * 2**i for i in range(4) + ] + model_cfg.panoptic_head.feat_channels = base_channels + model_cfg.panoptic_head.out_channels = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.self_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.ffn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.ffn_cfg.feedforward_channels = base_channels * 8 + model_cfg.panoptic_head.pixel_decoder.\ + positional_encoding.num_feats = base_channels // 2 + model_cfg.panoptic_head.positional_encoding.\ + num_feats = base_channels // 2 + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.self_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder. \ + layer_cfg.cross_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.ffn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.ffn_cfg.feedforward_channels = base_channels * 8 + return model_cfg + + def test_init(self): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + detector.init_weights() + assert detector.backbone + assert detector.panoptic_head + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_loss_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_predict_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_tensor_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, False) + out = detector.forward(**data, mode='tensor') + self.assertIsInstance(out, tuple) + + +class TestMask2Former(unittest.TestCase): + + def setUp(self): + register_all_modules() + + def _create_model_cfg(self, cfg_path): + model_cfg = get_detector_cfg(cfg_path) + base_channels = 32 + model_cfg.backbone.depth = 18 + model_cfg.backbone.init_cfg = None + model_cfg.backbone.base_channels = base_channels + model_cfg.panoptic_head.in_channels = [ + base_channels * 2**i for i in range(4) + ] + model_cfg.panoptic_head.feat_channels = base_channels + model_cfg.panoptic_head.out_channels = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.self_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.ffn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.ffn_cfg.feedforward_channels = base_channels * 4 + model_cfg.panoptic_head.pixel_decoder.\ + positional_encoding.num_feats = base_channels // 2 + model_cfg.panoptic_head.positional_encoding.\ + num_feats = base_channels // 2 + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.self_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder. \ + layer_cfg.cross_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.ffn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.ffn_cfg.feedforward_channels = base_channels * 8 + + return model_cfg + + def test_init(self): + model_cfg = self._create_model_cfg( + 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py') + detector = MODELS.build(model_cfg) + detector.init_weights() + assert detector.backbone + assert detector.panoptic_head + + @parameterized.expand([ + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py') + ]) + def test_forward_loss_mode(self, device, cfg_path): + print(device, cfg_path) + with_semantic = 'panoptic' in cfg_path + model_cfg = self._create_model_cfg(cfg_path) + detector = MODELS.build(model_cfg) + + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=with_semantic) + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py') + ]) + def test_forward_predict_mode(self, device, cfg_path): + with_semantic = 'panoptic' in cfg_path + model_cfg = self._create_model_cfg(cfg_path) + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=with_semantic) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([ + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py') + ]) + def test_forward_tensor_mode(self, device, cfg_path): + with_semantic = 'panoptic' in cfg_path + model_cfg = self._create_model_cfg(cfg_path) + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=with_semantic) + data = detector.data_preprocessor(packed_inputs, False) + out = detector.forward(**data, mode='tensor') + self.assertIsInstance(out, tuple) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_panoptic_two_stage_segmentor.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_panoptic_two_stage_segmentor.py new file mode 100644 index 0000000000000000000000000000000000000000..9234554f7b31f3c8d567b7396211a3589a2c0918 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_panoptic_two_stage_segmentor.py @@ -0,0 +1,93 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing._utils import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestTwoStagePanopticSegmentor(unittest.TestCase): + + def setUp(self): + register_all_modules() + + def _create_model_cfg(self): + cfg_file = 'panoptic_fpn/panoptic-fpn_r50_fpn_1x_coco.py' + model_cfg = get_detector_cfg(cfg_file) + model_cfg.backbone.depth = 18 + model_cfg.neck.in_channels = [64, 128, 256, 512] + model_cfg.backbone.init_cfg = None + return model_cfg + + def test_init(self): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + assert detector.backbone + assert detector.neck + assert detector.rpn_head + assert detector.roi_head + assert detector.roi_head.mask_head + assert detector.with_semantic_head + assert detector.with_panoptic_fusion_head + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_loss_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_predict_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_tensor_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, False) + out = detector.forward(**data, mode='tensor') + self.assertIsInstance(out, tuple) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_rpn.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_rpn.py new file mode 100644 index 0000000000000000000000000000000000000000..60f7492a96b8a0380ec7fe3e31f2e4c72f2d1237 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_rpn.py @@ -0,0 +1,112 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestRPN(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand(['rpn/rpn_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.bbox_head) + + # if rpn.num_classes > 1, force set rpn.num_classes = 1 + model.rpn_head.num_classes = 2 + detector = MODELS.build(model) + self.assertEqual(detector.bbox_head.num_classes, 1) + + @parameterized.expand([('rpn/rpn_r50_fpn_1x_coco.py', ('cpu', 'cuda'))]) + def test_rpn_forward_loss_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, True) + # Test forward train + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([('rpn/rpn_r50_fpn_1x_coco.py', ('cpu', 'cuda'))]) + def test_rpn_forward_predict_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([('rpn/rpn_r50_fpn_1x_coco.py', ('cpu', 'cuda'))]) + def test_rpn_forward_tensor_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + batch_results = detector.forward(**data, mode='tensor') + self.assertIsInstance(batch_results, tuple) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_semi_base.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_semi_base.py new file mode 100644 index 0000000000000000000000000000000000000000..7980fa6c32dfb022c0bb59ce280ee97646b55fff --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_semi_base.py @@ -0,0 +1,34 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +from mmengine.registry import MODELS +from parameterized import parameterized + +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + +register_all_modules() + + +class TestSemiBase(TestCase): + + @parameterized.expand([ + 'soft_teacher/' + 'soft-teacher_faster-rcnn_r50-caffe_fpn_180k_semi-0.1-coco.py', + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.detector.backbone.depth = 18 + model.detector.neck.in_channels = [64, 128, 256, 512] + model.detector.backbone.init_cfg = None + + model = MODELS.build(model) + self.assertTrue(model.teacher.backbone) + self.assertTrue(model.teacher.neck) + self.assertTrue(model.teacher.rpn_head) + self.assertTrue(model.teacher.roi_head) + self.assertTrue(model.student.backbone) + self.assertTrue(model.student.neck) + self.assertTrue(model.student.rpn_head) + self.assertTrue(model.student.roi_head) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_single_stage.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_single_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..22dbd1a98cb96c1b8edf9f1c2c34e131a8c9d4da --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_single_stage.py @@ -0,0 +1,126 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestSingleStageDetector(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand([ + 'retinanet/retinanet_r18_fpn_1x_coco.py', + 'centernet/centernet_r18_8xb16-crop512-140e_coco.py', + 'fsaf/fsaf_r50_fpn_1x_coco.py', + 'yolox/yolox_tiny_8xb8-300e_coco.py', + 'yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', + 'reppoints/reppoints-minmax_r50_fpn-gn_head-gn_1x_coco.py', + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.bbox_head) + + @parameterized.expand([ + ('retinanet/retinanet_r18_fpn_1x_coco.py', ('cpu', 'cuda')), + ('centernet/centernet_r18_8xb16-crop512-140e_coco.py', ('cpu', + 'cuda')), + ('yolox/yolox_tiny_8xb8-300e_coco.py', ('cpu', 'cuda')), + ('yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_single_stage_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + detector.init_weights() + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, True) + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + ('retinanet/retinanet_r18_fpn_1x_coco.py', ('cpu', 'cuda')), + ('centernet/centernet_r18_8xb16-crop512-140e_coco.py', ('cpu', + 'cuda')), + ('yolox/yolox_tiny_8xb8-300e_coco.py', ('cpu', 'cuda')), + ('yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_predict_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([ + ('retinanet/retinanet_r18_fpn_1x_coco.py', ('cpu', 'cuda')), + ('centernet/centernet_r18_8xb16-crop512-140e_coco.py', ('cpu', + 'cuda')), + ('yolox/yolox_tiny_8xb8-300e_coco.py', ('cpu', 'cuda')), + ('yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_tensor_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + batch_results = detector.forward(**data, mode='tensor') + self.assertIsInstance(batch_results, tuple) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_single_stage_instance_seg.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_single_stage_instance_seg.py new file mode 100644 index 0000000000000000000000000000000000000000..515303412412256802452906aed87e306947a891 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_single_stage_instance_seg.py @@ -0,0 +1,120 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestSingleStageInstanceSegmentor(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand([ + 'solo/solo_r50_fpn_1x_coco.py', + 'solov2/solov2_r50_fpn_1x_coco.py', + 'yolact/yolact_r50_1xb8-55e_coco.py', + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.mask_head) + if detector.with_bbox: + self.assertTrue(detector.bbox_head) + + @parameterized.expand([ + ('solo/solo_r50_fpn_1x_coco.py', ('cpu', 'cuda')), + ('solov2/solov2-light_r18_fpn_ms-3x_coco.py', ('cpu', 'cuda')), + ('yolact/yolact_r50_1xb8-55e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_loss_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + detector.init_weights() + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], with_mask=True) + data = detector.data_preprocessor(packed_inputs, True) + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + ('solo/decoupled-solo-light_r50_fpn_3x_coco.py', ('cpu', 'cuda')), + ('yolact/yolact_r50_1xb8-55e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_predict_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], with_mask=True) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([ + ('solo/solo_r50_fpn_1x_coco.py', ('cpu', 'cuda')), + ('solov2/solov2_r50_fpn_1x_coco.py', ('cpu', 'cuda')), + ('yolact/yolact_r50_1xb8-55e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_tensor_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + batch_results = detector.forward(**data, mode='tensor') + self.assertIsInstance(batch_results, tuple) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_two_stage.py b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_two_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..5609c0821dcff4ae1e9b33a00d24cc61b59ebc36 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_detectors/test_two_stage.py @@ -0,0 +1,236 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestTwoStageBBox(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand([ + 'faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py', + 'sparse_rcnn/sparse-rcnn_r50_fpn_1x_coco.py', + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.rpn_head) + self.assertTrue(detector.roi_head) + + # if rpn.num_classes > 1, force set rpn.num_classes = 1 + if hasattr(model.rpn_head, 'num_classes'): + model.rpn_head.num_classes = 2 + detector = MODELS.build(model) + self.assertEqual(detector.rpn_head.num_classes, 1) + + @parameterized.expand([ + 'faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py', + 'sparse_rcnn/sparse-rcnn_r50_fpn_1x_coco.py', + ]) + def test_two_stage_forward_loss_mode(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + 'faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py', + 'sparse_rcnn/sparse-rcnn_r50_fpn_1x_coco.py', + ]) + def test_two_stage_forward_predict_mode(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + # TODO: Awaiting refactoring + # @parameterized.expand([ + # 'faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', + # 'cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py', + # 'sparse_rcnn/sparse-rcnn_r50_fpn_1x_coco.py', + # ]) + # def test_two_stage_forward_tensor_mode(self, cfg_file): + # model = get_detector_cfg(cfg_file) + # # backbone convert to ResNet18 + # model.backbone.depth = 18 + # model.neck.in_channels = [64, 128, 256, 512] + # model.backbone.init_cfg = None + # + # from mmdet.models import build_detector + # detector = build_detector(model) + # + # if not torch.cuda.is_available(): + # return unittest.skip('test requires GPU and torch+cuda') + # detector = detector.cuda() + # + # packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + + # data = detector.data_preprocessor(packed_inputs, False) + + # out = detector.forward(**data, mode='tensor') + # self.assertIsInstance(out, tuple) + + +class TestTwoStageMask(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand([ + 'mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py', + 'queryinst/queryinst_r50_fpn_1x_coco.py' + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.rpn_head) + self.assertTrue(detector.roi_head) + self.assertTrue(detector.roi_head.mask_head) + + # if rpn.num_classes > 1, force set rpn.num_classes = 1 + if hasattr(model.rpn_head, 'num_classes'): + model.rpn_head.num_classes = 2 + detector = MODELS.build(model) + self.assertEqual(detector.rpn_head.num_classes, 1) + + @parameterized.expand([ + 'mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py', + 'queryinst/queryinst_r50_fpn_1x_coco.py' + ]) + def test_two_stage_forward_loss_mode(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], with_mask=True) + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + 'mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py', + 'queryinst/queryinst_r50_fpn_1x_coco.py' + ]) + def test_two_stage_forward_predict_mode(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 256, 256], [3, 255, 260]]) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + # TODO: Awaiting refactoring + # @parameterized.expand([ + # 'mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py', + # 'cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py', + # 'queryinst/queryinst_r50_fpn_1x_coco.py' + # ]) + # def test_two_stage_forward_tensor_mode(self, cfg_file): + # model = get_detector_cfg(cfg_file) + # # backbone convert to ResNet18 + # model.backbone.depth = 18 + # model.neck.in_channels = [64, 128, 256, 512] + # model.backbone.init_cfg = None + # + # from mmdet.models import build_detector + # detector = build_detector(model) + # + # if not torch.cuda.is_available(): + # return unittest.skip('test requires GPU and torch+cuda') + # detector = detector.cuda() + # + # packed_inputs = demo_mm_inputs( + # 2, [[3, 128, 128], [3, 125, 130]], with_mask=True) + # data = detector.data_preprocessor(packed_inputs, False) + # + # # out = detector.forward(**data, mode='tensor') + # # self.assertIsInstance(out, tuple) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/__init__.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/test_brick_wrappers.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_brick_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..3c59fcf79ba1d02ba377ab8ef3f8ef26ecd61ec4 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_brick_wrappers.py @@ -0,0 +1,93 @@ +from unittest.mock import patch + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from mmdet.models.layers import AdaptiveAvgPool2d, adaptive_avg_pool2d + +if torch.__version__ != 'parrots': + torch_version = '1.7' +else: + torch_version = 'parrots' + + +@patch('torch.__version__', torch_version) +def test_adaptive_avg_pool2d(): + # Test the empty batch dimension + # Test the two input conditions + x_empty = torch.randn(0, 3, 4, 5) + # 1. tuple[int, int] + wrapper_out = adaptive_avg_pool2d(x_empty, (2, 2)) + assert wrapper_out.shape == (0, 3, 2, 2) + # 2. int + wrapper_out = adaptive_avg_pool2d(x_empty, 2) + assert wrapper_out.shape == (0, 3, 2, 2) + + # wrapper op with 3-dim input + x_normal = torch.randn(3, 3, 4, 5) + wrapper_out = adaptive_avg_pool2d(x_normal, (2, 2)) + ref_out = F.adaptive_avg_pool2d(x_normal, (2, 2)) + assert wrapper_out.shape == (3, 3, 2, 2) + assert torch.equal(wrapper_out, ref_out) + + wrapper_out = adaptive_avg_pool2d(x_normal, 2) + ref_out = F.adaptive_avg_pool2d(x_normal, 2) + assert wrapper_out.shape == (3, 3, 2, 2) + assert torch.equal(wrapper_out, ref_out) + + +@patch('torch.__version__', torch_version) +def test_AdaptiveAvgPool2d(): + # Test the empty batch dimension + x_empty = torch.randn(0, 3, 4, 5) + # Test the four input conditions + # 1. tuple[int, int] + wrapper = AdaptiveAvgPool2d((2, 2)) + wrapper_out = wrapper(x_empty) + assert wrapper_out.shape == (0, 3, 2, 2) + + # 2. int + wrapper = AdaptiveAvgPool2d(2) + wrapper_out = wrapper(x_empty) + assert wrapper_out.shape == (0, 3, 2, 2) + + # 3. tuple[None, int] + wrapper = AdaptiveAvgPool2d((None, 2)) + wrapper_out = wrapper(x_empty) + assert wrapper_out.shape == (0, 3, 4, 2) + + # 3. tuple[int, None] + wrapper = AdaptiveAvgPool2d((2, None)) + wrapper_out = wrapper(x_empty) + assert wrapper_out.shape == (0, 3, 2, 5) + + # Test the normal batch dimension + x_normal = torch.randn(3, 3, 4, 5) + wrapper = AdaptiveAvgPool2d((2, 2)) + ref = nn.AdaptiveAvgPool2d((2, 2)) + wrapper_out = wrapper(x_normal) + ref_out = ref(x_normal) + assert wrapper_out.shape == (3, 3, 2, 2) + assert torch.equal(wrapper_out, ref_out) + + wrapper = AdaptiveAvgPool2d(2) + ref = nn.AdaptiveAvgPool2d(2) + wrapper_out = wrapper(x_normal) + ref_out = ref(x_normal) + assert wrapper_out.shape == (3, 3, 2, 2) + assert torch.equal(wrapper_out, ref_out) + + wrapper = AdaptiveAvgPool2d((None, 2)) + ref = nn.AdaptiveAvgPool2d((None, 2)) + wrapper_out = wrapper(x_normal) + ref_out = ref(x_normal) + assert wrapper_out.shape == (3, 3, 4, 2) + assert torch.equal(wrapper_out, ref_out) + + wrapper = AdaptiveAvgPool2d((2, None)) + ref = nn.AdaptiveAvgPool2d((2, None)) + wrapper_out = wrapper(x_normal) + ref_out = ref(x_normal) + assert wrapper_out.shape == (3, 3, 2, 5) + assert torch.equal(wrapper_out, ref_out) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/test_conv_upsample.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_conv_upsample.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc64d032a36731aad2c9870e565085cc46e7020 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_conv_upsample.py @@ -0,0 +1,24 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.layers import ConvUpsample + + +@pytest.mark.parametrize('num_layers', [0, 1, 2]) +def test_conv_upsample(num_layers): + num_upsample = num_layers if num_layers > 0 else 0 + num_layers = num_layers if num_layers > 0 else 1 + layer = ConvUpsample( + 10, + 5, + num_layers=num_layers, + num_upsample=num_upsample, + conv_cfg=None, + norm_cfg=None) + + size = 5 + x = torch.randn((1, 10, size, size)) + size = size * pow(2, num_upsample) + x = layer(x) + assert x.shape[-2:] == (size, size) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/test_ema.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_ema.py new file mode 100644 index 0000000000000000000000000000000000000000..5acf5460ce0a3f8273628db6a7755c0f73dc7c7f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_ema.py @@ -0,0 +1,94 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import itertools +import math +from unittest import TestCase + +import torch +import torch.nn as nn +from mmengine.testing import assert_allclose + +from mmdet.models.layers import ExpMomentumEMA + + +class TestEMA(TestCase): + + def test_exp_momentum_ema(self): + model = nn.Sequential(nn.Conv2d(1, 5, kernel_size=3), nn.Linear(5, 10)) + # Test invalid gamma + with self.assertRaisesRegex(AssertionError, + 'gamma must be greater than 0'): + ExpMomentumEMA(model, gamma=-1) + + # Test EMA + model = torch.nn.Sequential( + torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.Linear(5, 10)) + momentum = 0.1 + gamma = 4 + + ema_model = ExpMomentumEMA(model, momentum=momentum, gamma=gamma) + averaged_params = [ + torch.zeros_like(param) for param in model.parameters() + ] + n_updates = 10 + for i in range(n_updates): + updated_averaged_params = [] + for p, p_avg in zip(model.parameters(), averaged_params): + p.detach().add_(torch.randn_like(p)) + if i == 0: + updated_averaged_params.append(p.clone()) + else: + m = (1 - momentum) * math.exp(-(1 + i) / gamma) + momentum + updated_averaged_params.append( + (p_avg * (1 - m) + p * m).clone()) + ema_model.update_parameters(model) + averaged_params = updated_averaged_params + + for p_target, p_ema in zip(averaged_params, ema_model.parameters()): + assert_allclose(p_target, p_ema) + + def test_exp_momentum_ema_update_buffer(self): + model = nn.Sequential( + nn.Conv2d(1, 5, kernel_size=3), nn.BatchNorm2d(5, momentum=0.3), + nn.Linear(5, 10)) + # Test invalid gamma + with self.assertRaisesRegex(AssertionError, + 'gamma must be greater than 0'): + ExpMomentumEMA(model, gamma=-1) + + # Test EMA with momentum annealing. + momentum = 0.1 + gamma = 4 + + ema_model = ExpMomentumEMA( + model, gamma=gamma, momentum=momentum, update_buffers=True) + averaged_params = [ + torch.zeros_like(param) + for param in itertools.chain(model.parameters(), model.buffers()) + if param.size() != torch.Size([]) + ] + n_updates = 10 + for i in range(n_updates): + updated_averaged_params = [] + params = [ + param for param in itertools.chain(model.parameters(), + model.buffers()) + if param.size() != torch.Size([]) + ] + for p, p_avg in zip(params, averaged_params): + p.detach().add_(torch.randn_like(p)) + if i == 0: + updated_averaged_params.append(p.clone()) + else: + m = (1 - momentum) * math.exp(-(1 + i) / gamma) + momentum + updated_averaged_params.append( + (p_avg * (1 - m) + p * m).clone()) + ema_model.update_parameters(model) + averaged_params = updated_averaged_params + + ema_params = [ + param for param in itertools.chain(ema_model.module.parameters(), + ema_model.module.buffers()) + if param.size() != torch.Size([]) + ] + for p_target, p_ema in zip(averaged_params, ema_params): + assert_allclose(p_target, p_ema) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/test_inverted_residual.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_inverted_residual.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e9d6988a37aa5d5fa2333c9d5a6047baa5aa2f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_inverted_residual.py @@ -0,0 +1,76 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmcv.cnn import is_norm +from torch.nn.modules import GroupNorm + +from mmdet.models.layers import InvertedResidual, SELayer + + +def test_inverted_residual(): + + with pytest.raises(AssertionError): + # stride must be in [1, 2] + InvertedResidual(16, 16, 32, stride=3) + + with pytest.raises(AssertionError): + # se_cfg must be None or dict + InvertedResidual(16, 16, 32, se_cfg=list()) + + with pytest.raises(AssertionError): + # in_channeld and mid_channels must be the same if + # with_expand_conv is False + InvertedResidual(16, 16, 32, with_expand_conv=False) + + # Test InvertedResidual forward, stride=1 + block = InvertedResidual(16, 16, 32, stride=1) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert getattr(block, 'se', None) is None + assert block.with_res_shortcut + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward, stride=2 + block = InvertedResidual(16, 16, 32, stride=2) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert not block.with_res_shortcut + assert x_out.shape == torch.Size((1, 16, 28, 28)) + + # Test InvertedResidual forward with se layer + se_cfg = dict(channels=32) + block = InvertedResidual(16, 16, 32, stride=1, se_cfg=se_cfg) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert isinstance(block.se, SELayer) + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward, with_expand_conv=False + block = InvertedResidual(32, 16, 32, with_expand_conv=False) + x = torch.randn(1, 32, 56, 56) + x_out = block(x) + assert getattr(block, 'expand_conv', None) is None + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward with GroupNorm + block = InvertedResidual( + 16, 16, 32, norm_cfg=dict(type='GN', num_groups=2)) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + for m in block.modules(): + if is_norm(m): + assert isinstance(m, GroupNorm) + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward with HSigmoid + block = InvertedResidual(16, 16, 32, act_cfg=dict(type='HSigmoid')) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward with checkpoint + block = InvertedResidual(16, 16, 32, with_cp=True) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert block.with_cp + assert x_out.shape == torch.Size((1, 16, 56, 56)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/test_plugins.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..023ebe6d7fe9e566071a4238934da8ffbf30442d --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_plugins.py @@ -0,0 +1,171 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import pytest +import torch +from mmengine.config import ConfigDict + +from mmdet.models.layers import DropBlock +from mmdet.registry import MODELS +from mmdet.utils import register_all_modules + +register_all_modules() + + +def test_dropblock(): + feat = torch.rand(1, 1, 11, 11) + drop_prob = 1.0 + dropblock = DropBlock(drop_prob, block_size=11, warmup_iters=0) + out_feat = dropblock(feat) + assert (out_feat == 0).all() and out_feat.shape == feat.shape + drop_prob = 0.5 + dropblock = DropBlock(drop_prob, block_size=5, warmup_iters=0) + out_feat = dropblock(feat) + assert out_feat.shape == feat.shape + + # drop_prob must be (0,1] + with pytest.raises(AssertionError): + DropBlock(1.5, 3) + + # block_size cannot be an even number + with pytest.raises(AssertionError): + DropBlock(0.5, 2) + + # warmup_iters cannot be less than 0 + with pytest.raises(AssertionError): + DropBlock(0.5, 3, -1) + + +class TestPixelDecoder(unittest.TestCase): + + def test_forward(self): + base_channels = 64 + pixel_decoder_cfg = ConfigDict( + dict( + type='PixelDecoder', + in_channels=[base_channels * 2**i for i in range(4)], + feat_channels=base_channels, + out_channels=base_channels, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'))) + self = MODELS.build(pixel_decoder_cfg) + self.init_weights() + img_metas = [{}, {}] + feats = [ + torch.rand( + (2, base_channels * 2**i, 4 * 2**(3 - i), 5 * 2**(3 - i))) + for i in range(4) + ] + mask_feature, memory = self(feats, img_metas) + + assert (memory == feats[-1]).all() + assert mask_feature.shape == feats[0].shape + + +class TestTransformerEncoderPixelDecoder(unittest.TestCase): + + def test_forward(self): + base_channels = 64 + pixel_decoder_cfg = ConfigDict( + dict( + type='TransformerEncoderPixelDecoder', + in_channels=[base_channels * 2**i for i in range(4)], + feat_channels=base_channels, + out_channels=base_channels, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'), + encoder=dict( # DetrTransformerEncoder + num_layers=6, + layer_cfg=dict( # DetrTransformerEncoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=base_channels, + num_heads=8, + attn_drop=0.1, + proj_drop=0.1, + dropout_layer=None, + batch_first=True), + ffn_cfg=dict( + embed_dims=base_channels, + feedforward_channels=base_channels * 8, + num_fcs=2, + act_cfg=dict(type='ReLU', inplace=True), + ffn_drop=0.1, + dropout_layer=None, + add_identity=True), + norm_cfg=dict(type='LN'), + init_cfg=None), + init_cfg=None), + positional_encoding=dict( + num_feats=base_channels // 2, normalize=True))) + self = MODELS.build(pixel_decoder_cfg) + self.init_weights() + img_metas = [{ + 'batch_input_shape': (128, 160), + 'img_shape': (120, 160), + }, { + 'batch_input_shape': (128, 160), + 'img_shape': (125, 160), + }] + feats = [ + torch.rand( + (2, base_channels * 2**i, 4 * 2**(3 - i), 5 * 2**(3 - i))) + for i in range(4) + ] + mask_feature, memory = self(feats, img_metas) + + assert memory.shape[-2:] == feats[-1].shape[-2:] + assert mask_feature.shape == feats[0].shape + + +class TestMSDeformAttnPixelDecoder(unittest.TestCase): + + def test_forward(self): + base_channels = 64 + pixel_decoder_cfg = ConfigDict( + dict( + type='MSDeformAttnPixelDecoder', + in_channels=[base_channels * 2**i for i in range(4)], + strides=[4, 8, 16, 32], + feat_channels=base_channels, + out_channels=base_channels, + num_outs=3, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'), + encoder=dict( # DeformableDetrTransformerEncoder + num_layers=6, + layer_cfg=dict( # DeformableDetrTransformerEncoderLayer + self_attn_cfg=dict( # MultiScaleDeformableAttention + embed_dims=base_channels, + num_heads=8, + num_levels=3, + num_points=4, + im2col_step=64, + dropout=0.0, + batch_first=True, + norm_cfg=None, + init_cfg=None), + ffn_cfg=dict( + embed_dims=base_channels, + feedforward_channels=base_channels * 4, + num_fcs=2, + ffn_drop=0.0, + act_cfg=dict(type='ReLU', inplace=True))), + init_cfg=None), + positional_encoding=dict( + num_feats=base_channels // 2, normalize=True), + init_cfg=None)) + self = MODELS.build(pixel_decoder_cfg) + self.init_weights() + feats = [ + torch.rand( + (2, base_channels * 2**i, 4 * 2**(3 - i), 5 * 2**(3 - i))) + for i in range(4) + ] + mask_feature, multi_scale_features = self(feats) + + assert mask_feature.shape == feats[0].shape + assert len(multi_scale_features) == 3 + multi_scale_features = multi_scale_features[::-1] + for i in range(3): + assert multi_scale_features[i].shape[-2:] == feats[i + + 1].shape[-2:] diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/test_position_encoding.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_position_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..0d47287da7f0e1a5feddfcb7d0fbfbc2b9200136 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_position_encoding.py @@ -0,0 +1,39 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.layers import (LearnedPositionalEncoding, + SinePositionalEncoding) + + +def test_sine_positional_encoding(num_feats=16, batch_size=2): + # test invalid type of scale + with pytest.raises(AssertionError): + module = SinePositionalEncoding( + num_feats, scale=(3., ), normalize=True) + + module = SinePositionalEncoding(num_feats) + h, w = 10, 6 + mask = (torch.rand(batch_size, h, w) > 0.5).to(torch.int) + assert not module.normalize + out = module(mask) + assert out.shape == (batch_size, num_feats * 2, h, w) + + # set normalize + module = SinePositionalEncoding(num_feats, normalize=True) + assert module.normalize + out = module(mask) + assert out.shape == (batch_size, num_feats * 2, h, w) + + +def test_learned_positional_encoding(num_feats=16, + row_num_embed=10, + col_num_embed=10, + batch_size=2): + module = LearnedPositionalEncoding(num_feats, row_num_embed, col_num_embed) + assert module.row_embed.weight.shape == (row_num_embed, num_feats) + assert module.col_embed.weight.shape == (col_num_embed, num_feats) + h, w = 10, 6 + mask = torch.rand(batch_size, h, w) > 0.5 + out = module(mask) + assert out.shape == (batch_size, num_feats * 2, h, w) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/test_se_layer.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_se_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..2a19d4c3ae933868e58d776d0137eb0cc9016fc1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_se_layer.py @@ -0,0 +1,54 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +import torch.nn.functional as F +from mmengine.model import constant_init + +from mmdet.models.layers import DyReLU, SELayer + + +def test_se_layer(): + with pytest.raises(AssertionError): + # act_cfg sequence length must equal to 2 + SELayer(channels=32, act_cfg=(dict(type='ReLU'), )) + + with pytest.raises(AssertionError): + # act_cfg sequence must be a tuple of dict + SELayer(channels=32, act_cfg=[dict(type='ReLU'), dict(type='ReLU')]) + + # Test SELayer forward + layer = SELayer(channels=32) + layer.init_weights() + layer.train() + + x = torch.randn((1, 32, 10, 10)) + x_out = layer(x) + assert x_out.shape == torch.Size((1, 32, 10, 10)) + + +def test_dyrelu(): + with pytest.raises(AssertionError): + # act_cfg sequence length must equal to 2 + DyReLU(channels=32, act_cfg=(dict(type='ReLU'), )) + + with pytest.raises(AssertionError): + # act_cfg sequence must be a tuple of dict + DyReLU(channels=32, act_cfg=[dict(type='ReLU'), dict(type='ReLU')]) + + # Test DyReLU forward + layer = DyReLU(channels=32) + layer.init_weights() + layer.train() + x = torch.randn((1, 32, 10, 10)) + x_out = layer(x) + assert x_out.shape == torch.Size((1, 32, 10, 10)) + + # DyReLU should act as standard (static) ReLU + # when eliminating the effect of SE-like module + layer = DyReLU(channels=32) + constant_init(layer.conv2.conv, 0) + layer.train() + x = torch.randn((1, 32, 10, 10)) + x_out = layer(x) + relu_out = F.relu(x) + assert torch.equal(x_out, relu_out) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_layers/test_transformer.py b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..c261de622e7fbfa11c6619b1a1dcc80ca7c52c30 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_layers/test_transformer.py @@ -0,0 +1,504 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmengine.config import ConfigDict + +from mmdet.models.layers.transformer import (AdaptivePadding, + DetrTransformerDecoder, + DetrTransformerEncoder, + PatchEmbed, PatchMerging) + + +def test_adaptive_padding(): + + for padding in ('same', 'corner'): + kernel_size = 16 + stride = 16 + dilation = 1 + input = torch.rand(1, 1, 15, 17) + pool = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + out = pool(input) + # padding to divisible by 16 + assert (out.shape[2], out.shape[3]) == (16, 32) + input = torch.rand(1, 1, 16, 17) + out = pool(input) + # padding to divisible by 16 + assert (out.shape[2], out.shape[3]) == (16, 32) + + kernel_size = (2, 2) + stride = (2, 2) + dilation = (1, 1) + + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 11, 13) + out = adap_pad(input) + # padding to divisible by 2 + assert (out.shape[2], out.shape[3]) == (12, 14) + + kernel_size = (2, 2) + stride = (10, 10) + dilation = (1, 1) + + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 10, 13) + out = adap_pad(input) + # no padding + assert (out.shape[2], out.shape[3]) == (10, 13) + + kernel_size = (11, 11) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 11, 13) + out = adap_pad(input) + # all padding + assert (out.shape[2], out.shape[3]) == (21, 21) + + # test padding as kernel is (7,9) + input = torch.rand(1, 1, 11, 13) + stride = (3, 4) + kernel_size = (4, 5) + dilation = (2, 2) + # actually (7, 9) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + dilation_out = adap_pad(input) + assert (dilation_out.shape[2], dilation_out.shape[3]) == (16, 21) + kernel_size = (7, 9) + dilation = (1, 1) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + kernel79_out = adap_pad(input) + assert (kernel79_out.shape[2], kernel79_out.shape[3]) == (16, 21) + assert kernel79_out.shape == dilation_out.shape + + # assert only support "same" "corner" + with pytest.raises(AssertionError): + AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=1) + + +def test_patch_embed(): + B = 2 + H = 3 + W = 4 + C = 3 + embed_dims = 10 + kernel_size = 3 + stride = 1 + dummy_input = torch.rand(B, C, H, W) + patch_merge_1 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=1, + norm_cfg=None) + + x1, shape = patch_merge_1(dummy_input) + # test out shape + assert x1.shape == (2, 2, 10) + # test outsize is correct + assert shape == (1, 2) + # test L = out_h * out_w + assert shape[0] * shape[1] == x1.shape[1] + + B = 2 + H = 10 + W = 10 + C = 3 + embed_dims = 10 + kernel_size = 5 + stride = 2 + dummy_input = torch.rand(B, C, H, W) + # test dilation + patch_merge_2 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=None, + ) + + x2, shape = patch_merge_2(dummy_input) + # test out shape + assert x2.shape == (2, 1, 10) + # test outsize is correct + assert shape == (1, 1) + # test L = out_h * out_w + assert shape[0] * shape[1] == x2.shape[1] + + stride = 2 + input_size = (10, 10) + + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + x3, shape = patch_merge_3(dummy_input) + # test out shape + assert x3.shape == (2, 1, 10) + # test outsize is correct + assert shape == (1, 1) + # test L = out_h * out_w + assert shape[0] * shape[1] == x3.shape[1] + + # test the init_out_size with nn.Unfold + assert patch_merge_3.init_out_size[1] == (input_size[0] - 2 * 4 - + 1) // 2 + 1 + assert patch_merge_3.init_out_size[0] == (input_size[0] - 2 * 4 - + 1) // 2 + 1 + H = 11 + W = 12 + input_size = (H, W) + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + _, shape = patch_merge_3(dummy_input) + # when input_size equal to real input + # the out_size should be equal to `init_out_size` + assert shape == patch_merge_3.init_out_size + + input_size = (H, W) + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + _, shape = patch_merge_3(dummy_input) + # when input_size equal to real input + # the out_size should be equal to `init_out_size` + assert shape == patch_merge_3.init_out_size + + # test adap padding + for padding in ('same', 'corner'): + in_c = 2 + embed_dims = 3 + B = 2 + + # test stride is 1 + input_size = (5, 5) + kernel_size = (5, 5) + stride = (1, 1) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 25, 3) + assert out_size == (5, 5) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (5, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 1, 3) + assert out_size == (1, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (6, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 2, 3) + assert out_size == (2, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test different kernel_size with different stride + input_size = (6, 5) + kernel_size = (6, 2) + stride = (6, 2) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 3, 3) + assert out_size == (1, 3) + assert x_out.size(1) == out_size[0] * out_size[1] + + +def test_patch_merging(): + + # Test the model with int padding + in_c = 3 + out_c = 4 + kernel_size = 3 + stride = 3 + padding = 1 + dilation = 1 + bias = False + # test the case `pad_to_stride` is False + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + B, L, C = 1, 100, 3 + input_size = (10, 10) + x = torch.rand(B, L, C) + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (1, 16, 4) + assert out_size == (4, 4) + # assert out size is consistent with real output + assert x_out.size(1) == out_size[0] * out_size[1] + in_c = 4 + out_c = 5 + kernel_size = 6 + stride = 3 + padding = 2 + dilation = 2 + bias = False + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + B, L, C = 1, 100, 4 + input_size = (10, 10) + x = torch.rand(B, L, C) + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (1, 4, 5) + assert out_size == (2, 2) + # assert out size is consistent with real output + assert x_out.size(1) == out_size[0] * out_size[1] + + # Test with adaptive padding + for padding in ('same', 'corner'): + in_c = 2 + out_c = 3 + B = 2 + + # test stride is 1 + input_size = (5, 5) + kernel_size = (5, 5) + stride = (1, 1) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 25, 3) + assert out_size == (5, 5) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (5, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 1, 3) + assert out_size == (1, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (6, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 2, 3) + assert out_size == (2, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test different kernel_size with different stride + input_size = (6, 5) + kernel_size = (6, 2) + stride = (6, 2) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 3, 3) + assert out_size == (1, 3) + assert x_out.size(1) == out_size[0] * out_size[1] + + +def test_detr_transformer_encoder_decoder(): + config = ConfigDict( + num_layers=6, + layer_cfg=dict( # DetrTransformerDecoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.1), + cross_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.1), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + ffn_drop=0.1, + act_cfg=dict(type='ReLU', inplace=True)))) + assert len(DetrTransformerDecoder(**config).layers) == 6 + assert DetrTransformerDecoder(**config) + + config = ConfigDict( + dict( + num_layers=6, + layer_cfg=dict( # DetrTransformerEncoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.1), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + ffn_drop=0.1, + act_cfg=dict(type='ReLU', inplace=True))))) + assert len(DetrTransformerEncoder(**config).layers) == 6 + assert DetrTransformerEncoder(**config) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_losses/test_gaussian_focal_loss.py b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_gaussian_focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..5f26d6479076ec50f5514a4f4f256044131b91b2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_gaussian_focal_loss.py @@ -0,0 +1,38 @@ +import unittest + +import torch + +from mmdet.models.losses import GaussianFocalLoss + + +class TestGaussianFocalLoss(unittest.TestCase): + + def test_forward(self): + pred = torch.rand((10, 4)) + target = torch.rand((10, 4)) + gaussian_focal_loss = GaussianFocalLoss() + loss1 = gaussian_focal_loss(pred, target) + self.assertIsInstance(loss1, torch.Tensor) + + loss2 = gaussian_focal_loss(pred, target, avg_factor=0.5) + self.assertIsInstance(loss2, torch.Tensor) + + # test reduction + gaussian_focal_loss = GaussianFocalLoss(reduction='none') + loss = gaussian_focal_loss(pred, target) + self.assertTrue(loss.shape == (10, 4)) + + # test reduction_override + loss = gaussian_focal_loss(pred, target, reduction_override='mean') + self.assertTrue(loss.ndim == 0) + + # Only supports None, 'none', 'mean', 'sum' + with self.assertRaises(AssertionError): + gaussian_focal_loss(pred, target, reduction_override='max') + + # test pos_inds + pos_inds = (torch.rand(5) * 8).long() + pos_labels = (torch.rand(5) * 2).long() + gaussian_focal_loss = GaussianFocalLoss() + loss = gaussian_focal_loss(pred, target, pos_inds, pos_labels) + self.assertIsInstance(loss, torch.Tensor) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_losses/test_l2_loss.py b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_l2_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..2aa3e536c7b2477177b70045181f6f27635d96f8 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_l2_loss.py @@ -0,0 +1,21 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models import L2Loss + + +class TestL2Loss(TestCase): + + def test_l2_loss(self): + pred = torch.Tensor([[1, 1, 0, 0, 0, 0, 1]]) + target = torch.Tensor([[1, 1, 0, 0, 0, 0, 0]]) + + loss = L2Loss( + neg_pos_ub=2, + pos_margin=0, + neg_margin=0.1, + hard_mining=True, + loss_weight=1.0) + assert torch.allclose(loss(pred, target), torch.tensor(0.1350)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_losses/test_loss.py b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..bbf2f124b116522ee55626c740305fc6a731bc5f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_loss.py @@ -0,0 +1,303 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +import torch.nn.functional as F +from mmengine.utils import digit_version + +from mmdet.models.losses import (BalancedL1Loss, CrossEntropyLoss, DiceLoss, + DistributionFocalLoss, EQLV2Loss, FocalLoss, + GaussianFocalLoss, + KnowledgeDistillationKLDivLoss, L1Loss, + MarginL2Loss, MSELoss, QualityFocalLoss, + SeesawLoss, SmoothL1Loss, VarifocalLoss) +from mmdet.models.losses.ghm_loss import GHMC, GHMR +from mmdet.models.losses.iou_loss import (BoundedIoULoss, CIoULoss, DIoULoss, + EIoULoss, GIoULoss, IoULoss, + SIoULoss) + + +@pytest.mark.parametrize('loss_class', [ + IoULoss, BoundedIoULoss, GIoULoss, DIoULoss, CIoULoss, EIoULoss, SIoULoss +]) +def test_iou_type_loss_zeros_weight(loss_class): + pred = torch.rand((10, 4)) + target = torch.rand((10, 4)) + weight = torch.zeros(10) + + loss = loss_class()(pred, target, weight) + assert loss == 0. + + +@pytest.mark.parametrize('loss_class', [ + BalancedL1Loss, BoundedIoULoss, CIoULoss, CrossEntropyLoss, DIoULoss, + EIoULoss, SIoULoss, FocalLoss, DistributionFocalLoss, MSELoss, SeesawLoss, + GaussianFocalLoss, GIoULoss, QualityFocalLoss, IoULoss, L1Loss, + VarifocalLoss, GHMR, GHMC, SmoothL1Loss, KnowledgeDistillationKLDivLoss, + DiceLoss +]) +def test_loss_with_reduction_override(loss_class): + pred = torch.rand((10, 4)) + target = torch.rand((10, 4)), + weight = None + + with pytest.raises(AssertionError): + # only reduction_override from [None, 'none', 'mean', 'sum'] + # is not allowed + reduction_override = True + loss_class()( + pred, target, weight, reduction_override=reduction_override) + + +@pytest.mark.parametrize('loss_class', [QualityFocalLoss]) +@pytest.mark.parametrize('activated', [False, True]) +def test_QualityFocalLoss_Loss(loss_class, activated): + input_shape = (4, 5) + pred = torch.rand(input_shape) + label = torch.Tensor([0, 1, 2, 0]).long() + quality_label = torch.rand(input_shape[0]) + + original_loss = loss_class(activated=activated)(pred, + (label, quality_label)) + assert isinstance(original_loss, torch.Tensor) + + target = torch.nn.functional.one_hot(label, 5) + target = target * quality_label.reshape(input_shape[0], 1) + + new_loss = loss_class(activated=activated)(pred, target) + assert isinstance(new_loss, torch.Tensor) + assert new_loss == original_loss + + +@pytest.mark.parametrize('loss_class', [ + IoULoss, BoundedIoULoss, GIoULoss, DIoULoss, CIoULoss, EIoULoss, SIoULoss, + MSELoss, L1Loss, SmoothL1Loss, BalancedL1Loss, MarginL2Loss +]) +@pytest.mark.parametrize('input_shape', [(10, 4), (0, 4)]) +def test_regression_losses(loss_class, input_shape): + pred = torch.rand(input_shape) + target = torch.rand(input_shape) + weight = torch.rand(input_shape) + + # Test loss forward + loss = loss_class()(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with weight + loss = loss_class()(pred, target, weight) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class()(pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class()(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('loss_class', [CrossEntropyLoss]) +@pytest.mark.parametrize('input_shape', [(10, 5), (0, 5)]) +def test_classification_losses(loss_class, input_shape): + if input_shape[0] == 0 and digit_version( + torch.__version__) < digit_version('1.5.0'): + pytest.skip( + f'CELoss in PyTorch {torch.__version__} does not support empty' + f'tensor.') + + pred = torch.rand(input_shape) + target = torch.randint(0, 5, (input_shape[0], )) + + # Test loss forward + loss = loss_class()(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class()(pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class()(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('loss_class', [FocalLoss]) +@pytest.mark.parametrize('input_shape', [(10, 5), (3, 5, 40, 40)]) +def test_FocalLoss_loss(loss_class, input_shape): + pred = torch.rand(input_shape) + target = torch.randint(0, 5, (input_shape[0], )) + if len(input_shape) == 4: + B, N, W, H = input_shape + target = F.one_hot(torch.randint(0, 5, (B * W * H, )), + 5).reshape(B, W, H, N).permute(0, 3, 1, 2) + + # Test loss forward + loss = loss_class()(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class()(pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class()(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('loss_class', [GHMR]) +@pytest.mark.parametrize('input_shape', [(10, 4), (0, 4)]) +def test_GHMR_loss(loss_class, input_shape): + pred = torch.rand(input_shape) + target = torch.rand(input_shape) + weight = torch.rand(input_shape) + + # Test loss forward + loss = loss_class()(pred, target, weight) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('use_sigmoid', [True, False]) +@pytest.mark.parametrize('reduction', ['sum', 'mean', None]) +@pytest.mark.parametrize('avg_non_ignore', [True, False]) +def test_loss_with_ignore_index(use_sigmoid, reduction, avg_non_ignore): + # Test cross_entropy loss + loss_class = CrossEntropyLoss( + use_sigmoid=use_sigmoid, + use_mask=False, + ignore_index=255, + avg_non_ignore=avg_non_ignore) + pred = torch.rand((10, 5)) + target = torch.randint(0, 5, (10, )) + + ignored_indices = torch.randint(0, 10, (2, ), dtype=torch.long) + target[ignored_indices] = 255 + + # Test loss forward with default ignore + loss_with_ignore = loss_class(pred, target, reduction_override=reduction) + assert isinstance(loss_with_ignore, torch.Tensor) + + # Test loss forward with forward ignore + target[ignored_indices] = 255 + loss_with_forward_ignore = loss_class( + pred, target, ignore_index=255, reduction_override=reduction) + assert isinstance(loss_with_forward_ignore, torch.Tensor) + + # Verify correctness + if avg_non_ignore: + # manually remove the ignored elements + not_ignored_indices = (target != 255) + pred = pred[not_ignored_indices] + target = target[not_ignored_indices] + loss = loss_class(pred, target, reduction_override=reduction) + + assert torch.allclose(loss, loss_with_ignore) + assert torch.allclose(loss, loss_with_forward_ignore) + + # test ignore all target + pred = torch.rand((10, 5)) + target = torch.ones((10, ), dtype=torch.long) * 255 + loss = loss_class(pred, target, reduction_override=reduction) + assert loss == 0 + + +@pytest.mark.parametrize('naive_dice', [True, False]) +def test_dice_loss(naive_dice): + loss_class = DiceLoss + pred = torch.rand((10, 4, 4)) + target = torch.rand((10, 4, 4)) + weight = torch.rand((10)) + + # Test loss forward + loss = loss_class(naive_dice=naive_dice)(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with weight + loss = loss_class(naive_dice=naive_dice)(pred, target, weight) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class(naive_dice=naive_dice)( + pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class(naive_dice=naive_dice)(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class(naive_dice=naive_dice)( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class(naive_dice=naive_dice)( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with has_acted=False and use_sigmoid=False + with pytest.raises(NotImplementedError): + loss_class( + use_sigmoid=False, activate=True, naive_dice=naive_dice)(pred, + target) + + # Test loss forward with weight.ndim != loss.ndim + with pytest.raises(AssertionError): + weight = torch.rand((2, 8)) + loss_class(naive_dice=naive_dice)(pred, target, weight) + + # Test loss forward with len(weight) != len(pred) + with pytest.raises(AssertionError): + weight = torch.rand((8)) + loss_class(naive_dice=naive_dice)(pred, target, weight) + + +@pytest.mark.parametrize('loss_class', [EQLV2Loss]) +@pytest.mark.parametrize('reduction', ['mean']) +def test_eqlv2_loss(loss_class, reduction): + cls_score = torch.randn((1204, 1204)) + label = torch.randint(0, 2, (1204, )) + weight = None + + loss = loss_class()(cls_score, label, weight) + assert isinstance(loss, torch.Tensor) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_losses/test_multi_pos_cross_entropy_loss.py b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_multi_pos_cross_entropy_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f17c67ee6521d9d1260dfda24b5e4dd93f3c75 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_multi_pos_cross_entropy_loss.py @@ -0,0 +1,20 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models.losses import MultiPosCrossEntropyLoss + + +class TestMultiPosCrossEntropyLoss(TestCase): + + def test_mpce_loss(self): + costs = torch.tensor([[1, 0], [0, 1]]) + labels = torch.tensor([[1, 1], [0, 0]]) + + loss = MultiPosCrossEntropyLoss(reduction='mean', loss_weight=1.0) + assert torch.allclose(loss(costs, labels), torch.tensor(0.)) + + labels = torch.Tensor([[1, 0], [0, 1]]) + loss(costs, labels) + assert torch.allclose(loss(costs, labels), torch.tensor(0.31326)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_losses/test_triplet_loss.py b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_triplet_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..034419ab38f9eda0890d1abcc222e433fcb0db19 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_losses/test_triplet_loss.py @@ -0,0 +1,19 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models import TripletLoss + + +class TestTripletLoss(TestCase): + + def test_triplet_loss(self): + feature = torch.Tensor([[1, 1], [1, 1], [0, 0], [0, 0]]) + label = torch.Tensor([1, 1, 0, 0]) + + loss = TripletLoss(margin=0.3, loss_weight=1.0) + assert torch.allclose(loss(feature, label), torch.tensor(0.)) + + label = torch.Tensor([1, 0, 1, 0]) + assert torch.allclose(loss(feature, label), torch.tensor(1.7142)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_mot/test_byte_track.py b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_byte_track.py new file mode 100644 index 0000000000000000000000000000000000000000..a48548c7510adf3d8c1e36090f28b8dfbd461b7b --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_byte_track.py @@ -0,0 +1,100 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_track_inputs, get_detector_cfg + + +class TestByteTrack(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain' + '_test-mot17halfval.py', + ]) + def test_bytetrack_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.detector.neck.out_channels = 1 + model.detector.neck.num_csp_blocks = 1 + model.detector.bbox_head.in_channels = 1 + model.detector.bbox_head.feat_channels = 1 + model = MODELS.build(model) + assert model.detector + + @parameterized.expand([ + ('bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_bytetrack_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.num_classes = 10 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = model.data_preprocessor(packed_inputs, True) + losses = model.forward(**data, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ('bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_bytetrack_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_mot/test_deep_sort.py b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_deep_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..72dfeb43510a54ac337a0fcb840a36682b23c593 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_deep_sort.py @@ -0,0 +1,64 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestDeepSORT(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'deepsort/deepsort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model = MODELS.build(model) + assert model.detector + assert model.reid + assert model.tracker + + @parameterized.expand([ + ('deepsort/deepsort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_deepsort_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_deepsort_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_mot/test_oc_sort.py b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_oc_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf29513e00cb5756199b20d98c46fc3ab9bc89f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_oc_sort.py @@ -0,0 +1,100 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_track_inputs, get_detector_cfg + + +class TestByteTrack(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'ocsort/ocsort_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain' + '_test-mot17halfval.py', + ]) + def test_bytetrack_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.detector.neck.out_channels = 1 + model.detector.neck.num_csp_blocks = 1 + model.detector.bbox_head.in_channels = 1 + model.detector.bbox_head.feat_channels = 1 + model = MODELS.build(model) + assert model.detector + + @parameterized.expand([ + ('ocsort/ocsort_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_bytetrack_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.num_classes = 10 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = model.data_preprocessor(packed_inputs, True) + losses = model.forward(**data, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ('ocsort/ocsort_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_bytetrack_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_mot/test_qdtrack.py b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_qdtrack.py new file mode 100644 index 0000000000000000000000000000000000000000..714e022fdec71ecda49b662fcb0626ff1092eaff --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_qdtrack.py @@ -0,0 +1,94 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestQDTrack(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_' + 'test-mot17halfval.py', + ]) + def test_qdtrack_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + + model = MODELS.build(model) + assert model.detector + assert model.track_head + + @parameterized.expand([ + ('qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17' + 'halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_qdtrack_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_qdtrack_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=(3, 128, 128), + num_items=None) + out_data = model.data_preprocessor(packed_inputs, True) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + # Test forward + losses = model.forward(inputs, data_samples, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ('qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17' + 'halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_qdtrack_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, num_frames=1, image_shapes=(3, 128, 128)) + out_data = model.data_preprocessor(packed_inputs, False) + + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_mot/test_sort.py b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..ec15a6bdde25c0b756c86df0ec36cada9762f58a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_sort.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestDeepSORT(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'sort/sort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model = MODELS.build(model) + assert model.detector + assert model.tracker + + @parameterized.expand([ + ('sort/sort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_deepsort_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_deepsort_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_mot/test_strong_sort.py b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_strong_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d48a1dbf2f8040937b6efbf155ca7aae8d0ac9 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_mot/test_strong_sort.py @@ -0,0 +1,83 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestDeepSORT(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'strongsort/strongsort_yolox_x_8xb4-80e_crowdhuman' + '-mot17halftrain_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.detector.neck.out_channels = 1 + model.detector.neck.num_csp_blocks = 1 + model.detector.bbox_head.in_channels = 1 + model.detector.bbox_head.feat_channels = 1 + model.reid.backbone.depth = 18 + model.reid.head.fc_channels = 1 + model.reid.head.out_channels = 1 + model.reid.head.num_classes = 2 + model.cmc = None + model = MODELS.build(model) + assert model.detector + assert model.reid + assert model.tracker + + @parameterized.expand([ + ('strongsort/strongsort_yolox_x_8xb4-80e_crowdhuman' + '-mot17halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_strongsort_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_strongsort_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + _model.reid.backbone.depth = 18 + _model.reid.head.in_channels = 512 + _model.reid.head.fc_channels = 1 + _model.reid.head.out_channels = 1 + _model.reid.head.num_classes = 2 + _model.cmc = None + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_necks/test_ct_resnet_neck.py b/mmdet_code/SR-TOD/tests/test_models/test_necks/test_ct_resnet_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..acc5258f0d2beb07442fbc9c25af8814ad80229b --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_necks/test_ct_resnet_neck.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch + +from mmdet.models.necks import CTResNetNeck + + +class TestCTResNetNeck(unittest.TestCase): + + def test_init(self): + # num_filters/num_kernels must be same length + with self.assertRaises(AssertionError): + CTResNetNeck( + in_channels=10, + num_deconv_filters=(10, 10), + num_deconv_kernels=(4, )) + + ct_resnet_neck = CTResNetNeck( + in_channels=16, + num_deconv_filters=(8, 8), + num_deconv_kernels=(4, 4), + use_dcn=False) + ct_resnet_neck.init_weights() + + def test_forward(self): + in_channels = 16 + num_filters = (8, 8) + num_kernels = (4, 4) + feat = torch.rand(1, 16, 4, 4) + ct_resnet_neck = CTResNetNeck( + in_channels=in_channels, + num_deconv_filters=num_filters, + num_deconv_kernels=num_kernels, + use_dcn=False) + + # feat must be list or tuple + with self.assertRaises(AssertionError): + ct_resnet_neck(feat) + + out_feat = ct_resnet_neck([feat])[0] + self.assertEqual(out_feat.shape, (1, num_filters[-1], 16, 16)) + + if torch.cuda.is_available(): + # test dcn + ct_resnet_neck = CTResNetNeck( + in_channels=in_channels, + num_deconv_filters=num_filters, + num_deconv_kernels=num_kernels) + ct_resnet_neck = ct_resnet_neck.cuda() + feat = feat.cuda() + out_feat = ct_resnet_neck([feat])[0] + self.assertEqual(out_feat.shape, (1, num_filters[-1], 16, 16)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_necks/test_necks.py b/mmdet_code/SR-TOD/tests/test_models/test_necks/test_necks.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6256a6cace5ce4f4a387b66d4280bfb601fccd --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_necks/test_necks.py @@ -0,0 +1,651 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.necks import (FPG, FPN, FPN_CARAFE, NASFCOS_FPN, NASFPN, SSH, + YOLOXPAFPN, ChannelMapper, DilatedEncoder, + DyHead, SSDNeck, YOLOV3Neck) + + +def test_fpn(): + """Tests fpn.""" + s = 64 + in_channels = [8, 16, 32, 64] + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + out_channels = 8 + + # end_level=-1 is equal to end_level=3 + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=0, + end_level=-1, + num_outs=5) + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=0, + end_level=3, + num_outs=5) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + end_level=2, + num_outs=3) + + # `num_outs` is not equal to len(in_channels) - start_level + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + num_outs=2) + + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + end_level=4, + num_outs=2) + + # `num_outs` is not equal to end_level - start_level + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + end_level=3, + num_outs=1) + + # Invalid `add_extra_convs` option + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs='on_xxx', + num_outs=5) + + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=True, + num_outs=5) + + # FPN expects a multiple levels of features per image + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels)) + ] + outs = fpn_model(feats) + assert fpn_model.add_extra_convs == 'on_input' + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Tests for fpn with no extra convs (pooling is used instead) + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=False, + num_outs=5) + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + assert not fpn_model.add_extra_convs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Tests for fpn with lateral bns + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=True, + no_norm_on_lateral=False, + norm_cfg=dict(type='BN', requires_grad=True), + num_outs=5) + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + assert fpn_model.add_extra_convs == 'on_input' + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + bn_exist = False + for m in fpn_model.modules(): + if isinstance(m, _BatchNorm): + bn_exist = True + assert bn_exist + + # Bilinear upsample + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=True, + upsample_cfg=dict(mode='bilinear', align_corners=True), + num_outs=5) + fpn_model(feats) + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + assert fpn_model.add_extra_convs == 'on_input' + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Scale factor instead of fixed upsample size upsample + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=True, + upsample_cfg=dict(scale_factor=2), + num_outs=5) + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Extra convs source is 'inputs' + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + add_extra_convs='on_input', + start_level=1, + num_outs=5) + assert fpn_model.add_extra_convs == 'on_input' + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Extra convs source is 'laterals' + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + add_extra_convs='on_lateral', + start_level=1, + num_outs=5) + assert fpn_model.add_extra_convs == 'on_lateral' + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Extra convs source is 'outputs' + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + add_extra_convs='on_output', + start_level=1, + num_outs=5) + assert fpn_model.add_extra_convs == 'on_output' + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + +def test_channel_mapper(): + """Tests ChannelMapper.""" + s = 64 + in_channels = [8, 16, 32, 64] + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + out_channels = 8 + kernel_size = 3 + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels)) + ] + + # in_channels must be a list + with pytest.raises(AssertionError): + channel_mapper = ChannelMapper( + in_channels=10, out_channels=out_channels, kernel_size=kernel_size) + # the length of channel_mapper's inputs must be equal to the length of + # in_channels + with pytest.raises(AssertionError): + channel_mapper = ChannelMapper( + in_channels=in_channels[:-1], + out_channels=out_channels, + kernel_size=kernel_size) + channel_mapper(feats) + + channel_mapper = ChannelMapper( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size) + + outs = channel_mapper(feats) + assert len(outs) == len(feats) + for i in range(len(feats)): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + +def test_dilated_encoder(): + in_channels = 16 + out_channels = 32 + out_shape = 34 + dilated_encoder = DilatedEncoder(in_channels, out_channels, 16, 2, + [2, 4, 6, 8]) + feat = [torch.rand(1, in_channels, 34, 34)] + out_feat = dilated_encoder(feat)[0] + assert out_feat.shape == (1, out_channels, out_shape, out_shape) + + +def test_yolov3_neck(): + # num_scales, in_channels, out_channels must be same length + with pytest.raises(AssertionError): + YOLOV3Neck(num_scales=3, in_channels=[16, 8, 4], out_channels=[8, 4]) + + # len(feats) must equal to num_scales + with pytest.raises(AssertionError): + neck = YOLOV3Neck( + num_scales=3, in_channels=[16, 8, 4], out_channels=[8, 4, 2]) + feats = (torch.rand(1, 4, 16, 16), torch.rand(1, 8, 16, 16)) + neck(feats) + + # test normal channels + s = 32 + in_channels = [16, 8, 4] + out_channels = [8, 4, 2] + feat_sizes = [s // 2**i for i in range(len(in_channels) - 1, -1, -1)] + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels) - 1, -1, -1) + ] + neck = YOLOV3Neck( + num_scales=3, in_channels=in_channels, out_channels=out_channels) + outs = neck(feats) + + assert len(outs) == len(feats) + for i in range(len(outs)): + assert outs[i].shape == \ + (1, out_channels[i], feat_sizes[i], feat_sizes[i]) + + # test more flexible setting + s = 32 + in_channels = [32, 8, 16] + out_channels = [19, 21, 5] + feat_sizes = [s // 2**i for i in range(len(in_channels) - 1, -1, -1)] + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels) - 1, -1, -1) + ] + neck = YOLOV3Neck( + num_scales=3, in_channels=in_channels, out_channels=out_channels) + outs = neck(feats) + + assert len(outs) == len(feats) + for i in range(len(outs)): + assert outs[i].shape == \ + (1, out_channels[i], feat_sizes[i], feat_sizes[i]) + + +def test_ssd_neck(): + # level_strides/level_paddings must be same length + with pytest.raises(AssertionError): + SSDNeck( + in_channels=[8, 16], + out_channels=[8, 16, 32], + level_strides=[2], + level_paddings=[2, 1]) + + # length of out_channels must larger than in_channels + with pytest.raises(AssertionError): + SSDNeck( + in_channels=[8, 16], + out_channels=[8], + level_strides=[2], + level_paddings=[2]) + + # len(out_channels) - len(in_channels) must equal to len(level_strides) + with pytest.raises(AssertionError): + SSDNeck( + in_channels=[8, 16], + out_channels=[4, 16, 64], + level_strides=[2, 2], + level_paddings=[2, 2]) + + # in_channels must be same with out_channels[:len(in_channels)] + with pytest.raises(AssertionError): + SSDNeck( + in_channels=[8, 16], + out_channels=[4, 16, 64], + level_strides=[2], + level_paddings=[2]) + + ssd_neck = SSDNeck( + in_channels=[4], + out_channels=[4, 8, 16], + level_strides=[2, 1], + level_paddings=[1, 0]) + feats = (torch.rand(1, 4, 16, 16), ) + outs = ssd_neck(feats) + assert outs[0].shape == (1, 4, 16, 16) + assert outs[1].shape == (1, 8, 8, 8) + assert outs[2].shape == (1, 16, 6, 6) + + # test SSD-Lite Neck + ssd_neck = SSDNeck( + in_channels=[4, 8], + out_channels=[4, 8, 16], + level_strides=[1], + level_paddings=[1], + l2_norm_scale=None, + use_depthwise=True, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU6')) + assert not hasattr(ssd_neck, 'l2_norm') + + from mmcv.cnn.bricks import DepthwiseSeparableConvModule + assert isinstance(ssd_neck.extra_layers[0][-1], + DepthwiseSeparableConvModule) + + feats = (torch.rand(1, 4, 8, 8), torch.rand(1, 8, 8, 8)) + outs = ssd_neck(feats) + assert outs[0].shape == (1, 4, 8, 8) + assert outs[1].shape == (1, 8, 8, 8) + assert outs[2].shape == (1, 16, 8, 8) + + +def test_yolox_pafpn(): + s = 64 + in_channels = [8, 16, 32, 64] + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + out_channels = 24 + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels)) + ] + neck = YOLOXPAFPN(in_channels=in_channels, out_channels=out_channels) + outs = neck(feats) + assert len(outs) == len(feats) + for i in range(len(feats)): + assert outs[i].shape[1] == out_channels + assert outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # test depth-wise + neck = YOLOXPAFPN( + in_channels=in_channels, out_channels=out_channels, use_depthwise=True) + + from mmcv.cnn.bricks import DepthwiseSeparableConvModule + assert isinstance(neck.downsamples[0], DepthwiseSeparableConvModule) + + outs = neck(feats) + assert len(outs) == len(feats) + for i in range(len(feats)): + assert outs[i].shape[1] == out_channels + assert outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + +def test_dyhead(): + s = 64 + in_channels = 8 + out_channels = 16 + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + feats = [ + torch.rand(1, in_channels, feat_sizes[i], feat_sizes[i]) + for i in range(len(feat_sizes)) + ] + neck = DyHead( + in_channels=in_channels, out_channels=out_channels, num_blocks=3) + outs = neck(feats) + assert len(outs) == len(feats) + for i in range(len(outs)): + assert outs[i].shape[1] == out_channels + assert outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + feat = torch.rand(1, 8, 4, 4) + # input feat must be tuple or list + with pytest.raises(AssertionError): + neck(feat) + + +def test_fpg(): + # end_level=-1 is equal to end_level=3 + norm_cfg = dict(type='BN', requires_grad=True) + FPG(in_channels=[8, 16, 32, 64], + out_channels=8, + inter_channels=8, + num_outs=5, + add_extra_convs=True, + start_level=1, + end_level=-1, + stack_times=9, + paths=['bu'] * 9, + same_down_trans=None, + same_up_trans=dict( + type='conv', + kernel_size=3, + stride=2, + padding=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + across_lateral_trans=dict( + type='conv', + kernel_size=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + across_down_trans=dict( + type='interpolation_conv', + mode='nearest', + kernel_size=3, + norm_cfg=norm_cfg, + order=('act', 'conv', 'norm'), + inplace=False), + across_up_trans=None, + across_skip_trans=dict( + type='conv', + kernel_size=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + output_trans=dict( + type='last_conv', + kernel_size=3, + order=('act', 'conv', 'norm'), + inplace=False), + norm_cfg=norm_cfg, + skip_inds=[(0, 1, 2, 3), (0, 1, 2), (0, 1), (0, ), ()]) + FPG(in_channels=[8, 16, 32, 64], + out_channels=8, + inter_channels=8, + num_outs=5, + add_extra_convs=True, + start_level=1, + end_level=3, + stack_times=9, + paths=['bu'] * 9, + same_down_trans=None, + same_up_trans=dict( + type='conv', + kernel_size=3, + stride=2, + padding=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + across_lateral_trans=dict( + type='conv', + kernel_size=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + across_down_trans=dict( + type='interpolation_conv', + mode='nearest', + kernel_size=3, + norm_cfg=norm_cfg, + order=('act', 'conv', 'norm'), + inplace=False), + across_up_trans=None, + across_skip_trans=dict( + type='conv', + kernel_size=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + output_trans=dict( + type='last_conv', + kernel_size=3, + order=('act', 'conv', 'norm'), + inplace=False), + norm_cfg=norm_cfg, + skip_inds=[(0, 1, 2, 3), (0, 1, 2), (0, 1), (0, ), ()]) + + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + FPG(in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + paths=['bu'] * 9, + start_level=1, + end_level=4, + num_outs=2, + skip_inds=[(0, 1, 2, 3), (0, 1, 2), (0, 1), (0, ), ()]) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + FPG(in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + paths=['bu'] * 9, + start_level=1, + end_level=2, + num_outs=3, + skip_inds=[(0, 1, 2, 3), (0, 1, 2), (0, 1), (0, ), ()]) + + +def test_fpn_carafe(): + # end_level=-1 is equal to end_level=3 + FPN_CARAFE( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=0, + end_level=3, + num_outs=4) + FPN_CARAFE( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=0, + end_level=-1, + num_outs=4) + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + FPN_CARAFE( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=1, + end_level=4, + num_outs=2) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + FPN_CARAFE( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=1, + end_level=2, + num_outs=3) + + +def test_nas_fpn(): + # end_level=-1 is equal to end_level=3 + NASFPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + start_level=0, + end_level=3, + num_outs=4) + NASFPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + start_level=0, + end_level=-1, + num_outs=4) + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + NASFPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + start_level=1, + end_level=4, + num_outs=2) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + NASFPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + start_level=1, + end_level=2, + num_outs=3) + + +def test_nasfcos_fpn(): + # end_level=-1 is equal to end_level=3 + NASFCOS_FPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=0, + end_level=3, + num_outs=4) + NASFCOS_FPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=0, + end_level=-1, + num_outs=4) + + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + NASFCOS_FPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=1, + end_level=4, + num_outs=2) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + NASFCOS_FPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=1, + end_level=2, + num_outs=3) + + +def test_ssh_neck(): + """Tests ssh.""" + s = 64 + in_channels = [8, 16, 32, 64] + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + out_channels = [16, 32, 64, 128] + ssh_model = SSH( + num_scales=4, in_channels=in_channels, out_channels=out_channels) + + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels)) + ] + outs = ssh_model(feats) + assert len(outs) == len(feats) + for i in range(len(outs)): + assert outs[i].shape == \ + (1, out_channels[i], feat_sizes[i], feat_sizes[i]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_reid/test_base_reid.py b/mmdet_code/SR-TOD/tests/test_models/test_reid/test_base_reid.py new file mode 100644 index 0000000000000000000000000000000000000000..120cd402dbc68da83ef6721da94b90c9868cb2ec --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_reid/test_base_reid.py @@ -0,0 +1,46 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.structures import ReIDDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestBaseReID(TestCase): + + @classmethod + def setUpClass(cls) -> None: + register_all_modules() + + @parameterized.expand([ + 'reid/reid_r50_8xb32-6e_mot17train80_test-mot17val20.py', + ]) + def test_forward(self, cfg_file): + model_cfg = get_detector_cfg(cfg_file) + model = MODELS.build(model_cfg) + inputs = torch.rand(1, 4, 3, 256, 128) + data_samples = [ + ReIDDataSample().set_gt_label(label) for label in (0, 0, 1, 1) + ] + + # test mode='tensor' + feats = model(inputs, mode='tensor') + assert feats.shape == (4, 128) + + # test mode='loss' + losses = model(inputs, data_samples, mode='loss') + assert losses.keys() == {'triplet_loss', 'ce_loss', 'accuracy_top-1'} + assert losses['ce_loss'].item() > 0 + assert losses['triplet_loss'].item() > 0 + + # test mode='predict' + predictions = model(inputs, data_samples, mode='predict') + for pred in predictions: + assert isinstance(pred, ReIDDataSample) + assert isinstance(pred.pred_feature, torch.Tensor) + assert isinstance(pred.gt_label.label, torch.Tensor) + assert pred.pred_feature.shape == (128, ) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_reid/test_fc_module.py b/mmdet_code/SR-TOD/tests/test_models/test_reid/test_fc_module.py new file mode 100644 index 0000000000000000000000000000000000000000..1f998b76362f06170597c2d334df7166a3b11137 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_reid/test_fc_module.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models import FcModule + + +class TestFcModule(TestCase): + + def test_forward(self): + inputs = torch.rand(32, 128) + + # test + fc = FcModule( + in_channels=128, + out_channels=32, + ) + fc.init_weights() + outputs = fc(inputs) + assert outputs.shape == (32, 32) + + # test with norm + fc = FcModule( + in_channels=128, + out_channels=32, + norm_cfg=dict(type='BN1d'), + ) + outputs = fc(inputs) + assert outputs.shape == (32, 32) + + # test with norm and act + fc = FcModule( + in_channels=128, + out_channels=32, + norm_cfg=dict(type='BN1d'), + act_cfg=dict(type='ReLU'), + ) + outputs = fc(inputs) + assert outputs.shape == (32, 32) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_reid/test_gap.py b/mmdet_code/SR-TOD/tests/test_models/test_reid/test_gap.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b546b94b73c49c0407212583f2066fea2e0191 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_reid/test_gap.py @@ -0,0 +1,27 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models import GlobalAveragePooling + + +class TestGlobalAveragePooling(TestCase): + + def test_forward(self): + inputs = torch.rand(32, 128, 14, 14) + + # test AdaptiveAvgPool2d + neck = GlobalAveragePooling() + outputs = neck(inputs) + assert outputs.shape == (32, 128) + + # test kernel_size + neck = GlobalAveragePooling(kernel_size=7) + outputs = neck(inputs) + assert outputs.shape == (32, 128 * 2 * 2) + + # test kenel_size and stride + neck = GlobalAveragePooling(kernel_size=7, stride=2) + outputs = neck(inputs) + assert outputs.shape == (32, 128 * 4 * 4) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_reid/test_linear_reid_head.py b/mmdet_code/SR-TOD/tests/test_models/test_reid/test_linear_reid_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe582756873991f462f85070b4c38fa9ede8dab --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_reid/test_linear_reid_head.py @@ -0,0 +1,49 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS +from mmdet.structures import ReIDDataSample +from mmdet.utils import register_all_modules + + +class TestLinearReIDHead(TestCase): + + @classmethod + def setUpClass(cls) -> None: + register_all_modules() + head_cfg = dict( + type='LinearReIDHead', + num_fcs=1, + in_channels=128, + fc_channels=64, + out_channels=32, + num_classes=2, + loss_cls=dict(type='mmpretrain.CrossEntropyLoss', loss_weight=1.0), + loss_triplet=dict(type='TripletLoss', margin=0.3, loss_weight=1.0), + norm_cfg=dict(type='BN1d'), + act_cfg=dict(type='ReLU')) + cls.head = MODELS.build(head_cfg) + cls.inputs = (torch.rand(4, 128), torch.rand(4, 128)) + cls.data_samples = [ + ReIDDataSample().set_gt_label(label) for label in (0, 0, 1, 1) + ] + + def test_forward(self): + outputs = self.head(self.inputs) + assert outputs.shape == (4, 32) + + def test_loss(self): + losses = self.head.loss(self.inputs, self.data_samples) + assert losses.keys() == {'triplet_loss', 'ce_loss', 'accuracy_top-1'} + assert losses['ce_loss'].item() >= 0 + assert losses['triplet_loss'].item() >= 0 + + def test_predict(self): + predictions = self.head.predict(self.inputs, self.data_samples) + for pred in predictions: + assert isinstance(pred, ReIDDataSample) + assert isinstance(pred.pred_feature, torch.Tensor) + assert isinstance(pred.gt_label.label, torch.Tensor) + assert pred.pred_feature.shape == (32, ) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_bbox_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7003b0be348237be5fbc30c99ca3344e982e90d0 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_bbox_head.py @@ -0,0 +1,140 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.roi_heads.bbox_heads import (BBoxHead, Shared2FCBBoxHead, + Shared4Conv1FCBBoxHead) +from mmdet.models.task_modules.samplers import SamplingResult + + +class TestBboxHead(TestCase): + + def test_init(self): + # Shared2FCBBoxHead + bbox_head = Shared2FCBBoxHead( + in_channels=1, fc_out_channels=1, num_classes=4) + self.assertTrue(bbox_head.fc_cls) + self.assertTrue(bbox_head.fc_reg) + self.assertEqual(len(bbox_head.shared_fcs), 2) + + # Shared4Conv1FCBBoxHead + bbox_head = Shared4Conv1FCBBoxHead( + in_channels=1, fc_out_channels=1, num_classes=4) + self.assertTrue(bbox_head.fc_cls) + self.assertTrue(bbox_head.fc_reg) + self.assertEqual(len(bbox_head.shared_convs), 4) + self.assertEqual(len(bbox_head.shared_fcs), 1) + + def test_bbox_head_get_results(self): + num_classes = 6 + bbox_head = BBoxHead(reg_class_agnostic=True, num_classes=num_classes) + s = 128 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + + num_samples = 2 + rois = [torch.rand((num_samples, 5))] + cls_scores = [torch.rand((num_samples, num_classes + 1))] + bbox_preds = [torch.rand((num_samples, 4))] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertLessEqual(len(result_list[0]), num_samples * num_classes) + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + self.assertEqual(len(result_list[0].scores.shape), 1) + self.assertEqual(len(result_list[0].labels.shape), 1) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].bboxes.shape, bbox_preds[0].shape) + self.assertEqual(result_list[0].scores.shape, cls_scores[0].shape) + self.assertIsNone(result_list[0].get('label', None)) + + # num_samples is 0 + num_samples = 0 + rois = [torch.rand((num_samples, 5))] + cls_scores = [torch.rand((num_samples, num_classes + 1))] + bbox_preds = [torch.rand((num_samples, 4))] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertEqual(result_list[0].bboxes.shape, bbox_preds[0].shape) + self.assertIsNone(result_list[0].get('label', None)) + + def test_bbox_head_refine_bboxes(self): + num_classes = 6 + bbox_head = BBoxHead(reg_class_agnostic=True, num_classes=num_classes) + s = 128 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + sampling_results = [SamplingResult.random()] + num_samples = 20 + rois = torch.rand((num_samples, 4)) + roi_img_ids = torch.zeros(num_samples, 1) + rois = torch.cat((roi_img_ids, rois), dim=1) + cls_scores = torch.rand((num_samples, num_classes + 1)) + bbox_preds = torch.rand((num_samples, 4)) + labels = torch.randint(0, num_classes + 1, (num_samples, )).long() + bbox_targets = (labels, None, None, None) + bbox_results = dict( + rois=rois, + bbox_pred=bbox_preds, + cls_score=cls_scores, + bbox_targets=bbox_targets) + + bbox_list = bbox_head.refine_bboxes( + sampling_results=sampling_results, + bbox_results=bbox_results, + batch_img_metas=img_metas) + + self.assertGreaterEqual(num_samples, len(bbox_list[0])) + self.assertIsInstance(bbox_list[0], InstanceData) + self.assertEqual(bbox_list[0].bboxes.shape[1], 4) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_double_bbox_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_double_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..95aa02ee6bdc2bc2b5caeba40928fcab0dc6052f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_double_bbox_head.py @@ -0,0 +1,29 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads.bbox_heads import DoubleConvFCBBoxHead + + +class TestDoubleBboxHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + double_bbox_head = DoubleConvFCBBoxHead( + num_convs=4, + num_fcs=2, + in_channels=1, + conv_out_channels=4, + fc_out_channels=4) + double_bbox_head = double_bbox_head.to(device=device) + + num_samples = 4 + feats = torch.rand((num_samples, 1, 7, 7)).to(device) + double_bbox_head(x_cls=feats, x_reg=feats) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_multi_instance_bbox_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_multi_instance_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..04202a0732dd63a2203d15b3ea2f34d5f1c7bedc --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_multi_instance_bbox_head.py @@ -0,0 +1,118 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.roi_heads.bbox_heads import MultiInstanceBBoxHead + + +class TestMultiInstanceBBoxHead(TestCase): + + def test_init(self): + bbox_head = MultiInstanceBBoxHead( + num_instance=2, + with_refine=True, + num_shared_fcs=2, + in_channels=1, + fc_out_channels=1, + num_classes=4) + self.assertTrue(bbox_head.shared_fcs_ref) + self.assertTrue(bbox_head.fc_reg) + self.assertTrue(bbox_head.fc_cls) + self.assertEqual(len(bbox_head.shared_fcs), 2) + self.assertEqual(len(bbox_head.fc_reg), 2) + self.assertEqual(len(bbox_head.fc_cls), 2) + + def test_bbox_head_get_results(self): + num_classes = 1 + num_instance = 2 + bbox_head = MultiInstanceBBoxHead( + num_instance=num_instance, + num_shared_fcs=2, + reg_class_agnostic=True, + num_classes=num_classes) + s = 128 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + + num_samples = 2 + rois = [torch.rand((num_samples, 5))] + cls_scores = [] + bbox_preds = [] + for k in range(num_instance): + cls_scores.append(torch.rand((num_samples, num_classes + 1))) + bbox_preds.append(torch.rand((num_samples, 4))) + cls_scores = [torch.cat(cls_scores, dim=1)] + bbox_preds = [torch.cat(bbox_preds, dim=1)] + + # with nms + rcnn_test_cfg = ConfigDict( + nms=dict(type='nms', iou_threshold=0.5), + score_thr=0.01, + max_per_img=500) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertLessEqual( + len(result_list[0]), num_samples * num_instance * num_classes) + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + self.assertEqual(len(result_list[0].scores.shape), 1) + self.assertEqual(len(result_list[0].labels.shape), 1) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples * num_instance) + self.assertIsNone(result_list[0].get('label', None)) + + # num_samples is 0 + num_samples = 0 + rois = [torch.rand((num_samples, 5))] + cls_scores = [] + bbox_preds = [] + for k in range(num_instance): + cls_scores.append(torch.rand((num_samples, num_classes + 1))) + bbox_preds.append(torch.rand((num_samples, 4))) + cls_scores = [torch.cat(cls_scores, dim=1)] + bbox_preds = [torch.cat(bbox_preds, dim=1)] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0 * num_instance) + self.assertIsNone(result_list[0].get('label', None)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_sabl_bbox_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_sabl_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b796108c446d57353b639d000655eea98133abd1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_sabl_bbox_head.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.roi_heads.bbox_heads import SABLHead +from mmdet.models.task_modules.samplers import SamplingResult + + +class TestSABLBboxHead(TestCase): + + def test_init(self): + bbox_head = SABLHead( + cls_in_channels=1, + cls_out_channels=1, + reg_in_channels=1, + reg_offset_out_channels=1, + reg_cls_out_channels=1, + num_classes=4) + self.assertTrue(bbox_head.fc_cls) + self.assertTrue(hasattr(bbox_head, 'reg_cls_fcs')) + self.assertTrue(hasattr(bbox_head, 'reg_offset_fcs')) + self.assertFalse(hasattr(bbox_head, 'fc_reg')) + + def test_bbox_head_get_results(self): + num_classes = 6 + bbox_head = SABLHead(reg_class_agnostic=True, num_classes=num_classes) + s = 128 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + + num_samples = 2 + rois = [torch.rand((num_samples, 5))] + cls_scores = [torch.rand((num_samples, num_classes + 1))] + bbox_preds = [(torch.rand( + (num_samples, 28)), torch.rand((num_samples, 28)))] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertLessEqual(len(result_list[0]), num_samples * num_classes) + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + self.assertEqual(len(result_list[0].scores.shape), 1) + self.assertEqual(len(result_list[0].labels.shape), 1) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].scores.shape, cls_scores[0].shape) + self.assertIsNone(result_list[0].get('label', None)) + + # num_samples is 0 + num_samples = 0 + rois = [torch.rand((num_samples, 5))] + cls_scores = [torch.rand((num_samples, num_classes + 1))] + bbox_preds = [(torch.rand( + (num_samples, 28)), torch.rand((num_samples, 28)))] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertIsNone(result_list[0].get('label', None)) + + def test_bbox_head_refine_bboxes(self): + num_classes = 8 + bbox_head = SABLHead(reg_class_agnostic=True, num_classes=num_classes) + s = 20 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + sampling_results = [SamplingResult.random()] + num_samples = 20 + rois = torch.rand((num_samples, 4)) + roi_img_ids = torch.zeros(num_samples, 1) + rois = torch.cat((roi_img_ids, rois), dim=1) + cls_scores = torch.rand((num_samples, num_classes + 1)) + cls_preds = torch.rand((num_samples, 28)) + offset_preds = torch.rand((num_samples, 28)) + labels = torch.randint(0, num_classes + 1, (num_samples, )).long() + bbox_targets = (labels, None, None, None) + bbox_results = dict( + rois=rois, + bbox_pred=(cls_preds, offset_preds), + cls_score=cls_scores, + bbox_targets=bbox_targets) + + bbox_list = bbox_head.refine_bboxes( + sampling_results=sampling_results, + bbox_results=bbox_results, + batch_img_metas=img_metas) + + self.assertGreaterEqual(num_samples, len(bbox_list[0])) + self.assertIsInstance(bbox_list[0], InstanceData) + self.assertEqual(bbox_list[0].bboxes.shape[1], 4) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_scnet_bbox_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_scnet_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..eb74ab5770571e95c45bc5308528ed4b63f8e325 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_bbox_heads/test_scnet_bbox_head.py @@ -0,0 +1,22 @@ +import unittest + +import torch + +from mmdet.models.roi_heads.bbox_heads import SCNetBBoxHead + + +class TestSCNetBBoxHead(unittest.TestCase): + + def test_forward(self): + x = torch.rand((2, 1, 16, 16)) + bbox_head = SCNetBBoxHead( + num_shared_fcs=2, + in_channels=1, + roi_feat_size=16, + conv_out_channels=1, + fc_out_channels=256, + ) + results = bbox_head(x, return_shared_feat=False) + self.assertEqual(len(results), 2) + results = bbox_head(x, return_shared_feat=True) + self.assertEqual(len(results), 3) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_cascade_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_cascade_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5918b0067f1d540fce61edc59e15abcf2b90a4eb --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_cascade_roi_head.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads import StandardRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestCascadeRoIHead(TestCase): + + @parameterized.expand( + ['cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + """Test init standard RoI head.""" + # Normal Cascade Mask R-CNN RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + assert roi_head.with_bbox + assert roi_head.with_mask + + @parameterized.expand( + ['cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py']) + def test_cascade_roi_head_loss(self, cfg_file): + """Tests standard roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss_cls' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + elif 'loss_bbox' in name or 'loss_mask' in name: + self.assertEqual(value.sum(), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_dynamic_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_dynamic_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4b44de6991003890fe0d5dd24a42b02ae5f9f3 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_dynamic_roi_head.py @@ -0,0 +1,71 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestDynamicRoIHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'dynamic_rcnn/dynamic-rcnn_r50_fpn_1x_coco.py') + + def test_init(self): + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + + @parameterized.expand(['cpu', 'cuda']) + def test_dynamic_roi_head_loss(self, device): + """Tests trident roi head predict.""" + if not torch.cuda.is_available() and device == 'cuda': + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_bbox = out['loss_bbox'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_bbox.sum(), 0, 'box loss should be non-zero') + + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + empty_bbox_loss = out['loss_bbox'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_bbox_loss.sum(), 0, + 'there should be no box loss when there are no true boxes') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_grid_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_grid_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fc2988760c87247a49328578412d451b32e44527 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_grid_roi_head.py @@ -0,0 +1,121 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestGridRoIHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'grid_rcnn/grid-rcnn_r50_fpn_gn-head_2x_coco.py') + + def test_init(self): + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + + @parameterized.expand(['cpu', 'cuda']) + def test_grid_roi_head_loss(self, device): + """Tests trident roi head predict.""" + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_grid = out['loss_grid'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_grid.sum(), 0, 'grid loss should be non-zero') + + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertNotIn( + 'loss_grid', out, + 'grid loss should be passed when there are no true boxes') + + @parameterized.expand(['cpu', 'cuda']) + def test_grid_roi_head_predict(self, device): + """Tests trident roi head predict.""" + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + roi_head.predict(feats, proposals_list, batch_data_samples) + + @parameterized.expand(['cpu', 'cuda']) + def test_grid_roi_head_forward(self, device): + """Tests trident roi head forward.""" + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + roi_head.forward(feats, proposals_list) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_htc_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_htc_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..37bb92f5787d598571aa0189f2a7adbbc05e6963 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_htc_roi_head.py @@ -0,0 +1,114 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads import HybridTaskCascadeRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestHTCRoIHead(TestCase): + + @parameterized.expand(['htc/htc_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + """Test init htc RoI head.""" + # Normal HTC RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + assert roi_head.with_bbox + assert roi_head.with_mask + assert roi_head.with_semantic + + @parameterized.expand(['htc/htc_r50_fpn_1x_coco.py']) + def test_htc_roi_head_loss(self, cfg_file): + """Tests htc roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + with_semantic=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + with_semantic=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss_cls' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + elif 'loss_bbox' in name or 'loss_mask' in name: + self.assertEqual(value.sum(), 0) + + @parameterized.expand(['htc/htc_r50_fpn_1x_coco.py']) + def test_htc_roi_head_predict(self, cfg_file): + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + results = roi_head.predict( + feats, proposal_list, batch_data_samples, rescale=True) + self.assertEqual(results[0].masks.shape[-2:], (s, s)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_coarse_mask_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_coarse_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ffadc19ff2bb88007ad6be01ead0760dd7ee234f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_coarse_mask_head.py @@ -0,0 +1,41 @@ +import unittest + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads.mask_heads import CoarseMaskHead + + +class TestCoarseMaskHead(unittest.TestCase): + + def test_init(self): + with self.assertRaises(AssertionError): + CoarseMaskHead(num_fcs=0) + + with self.assertRaises(AssertionError): + CoarseMaskHead(downsample_factor=0.5) + + @parameterized.expand(['cpu', 'cuda']) + def test_forward(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + x = torch.rand((1, 32, 7, 7)).to(device) + mask_head = CoarseMaskHead( + downsample_factor=2, + in_channels=32, + conv_out_channels=32, + roi_feat_size=7).to(device) + mask_head.init_weights() + res = mask_head(x) + self.assertEqual(res.shape[-2:], (3, 3)) + + mask_head = CoarseMaskHead( + downsample_factor=1, + in_channels=32, + conv_out_channels=32, + roi_feat_size=7).to(device) + mask_head.init_weights() + res = mask_head(x) + self.assertEqual(res.shape[-2:], (7, 7)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_fcn_mask_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_fcn_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b4ee9362b1c588c705afa1a816d5da9fde2df6 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_fcn_mask_head.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet.models.roi_heads.mask_heads import FCNMaskHead + + +class TestFCNMaskHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_get_seg_masks(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + num_classes = 6 + mask_head = FCNMaskHead( + num_convs=1, + in_channels=1, + conv_out_channels=1, + num_classes=num_classes) + rcnn_test_cfg = ConfigDict( + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100, + mask_thr_binary=0.5) + s = 128 + img_metas = { + 'img_shape': (s, s, 3), + 'scale_factor': (1, 1), + 'ori_shape': (s, s, 3) + } + result = InstanceData(metainfo=img_metas) + + num_samples = 2 + mask_pred = [torch.rand((num_samples, num_classes, 14, 14)).to(device)] + result.bboxes = torch.rand((num_samples, 4)).to(device) + result.labels = torch.randint( + num_classes, (num_samples, ), dtype=torch.long).to(device) + mask_head.to(device=device) + result_list = mask_head.predict_by_feat( + mask_preds=tuple(mask_pred), + results_list=[result], + batch_img_metas=[img_metas], + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].masks.shape, (num_samples, s, s)) + + # test with activate_map, `mask_pred` has been activated before + num_samples = 2 + mask_pred = [torch.rand((num_samples, num_classes, 14, 14)).to(device)] + mask_pred = [m.sigmoid().detach() for m in mask_pred] + result.bboxes = torch.rand((num_samples, 4)).to(device) + result.labels = torch.randint( + num_classes, (num_samples, ), dtype=torch.long).to(device) + mask_head.to(device=device) + result_list = mask_head.predict_by_feat( + mask_preds=tuple(mask_pred), + results_list=[result], + batch_img_metas=[img_metas], + rcnn_test_cfg=rcnn_test_cfg, + activate_map=True) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].masks.shape, (num_samples, s, s)) + + # num_samples is 0 + num_samples = 0 + result = InstanceData(metainfo=img_metas) + mask_pred = [torch.rand((num_samples, num_classes, 14, 14)).to(device)] + result.bboxes = torch.zeros((num_samples, 4)).to(device) + result.labels = torch.zeros((num_samples, )).to(device) + result_list = mask_head.predict_by_feat( + mask_preds=tuple(mask_pred), + results_list=[result], + batch_img_metas=[img_metas], + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].masks.shape, (num_samples, s, s)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_feature_relay_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_feature_relay_head.py new file mode 100644 index 0000000000000000000000000000000000000000..4a182b842d9a4b84e7e064a2b2ace80d87d6661f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_feature_relay_head.py @@ -0,0 +1,26 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import FeatureRelayHead + + +class TestFeatureRelayHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + mask_head = FeatureRelayHead(in_channels=10, out_conv_channels=10) + + x = torch.rand((1, 10)) + results = mask_head(x) + self.assertIsInstance(results, Tensor) + x = torch.empty((0, 10)) + results = mask_head(x) + self.assertEqual(results, None) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_fused_semantic_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_fused_semantic_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7f912d797ebc7f8e8c8b85f058ddd2202d4f3d48 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_fused_semantic_head.py @@ -0,0 +1,33 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import FusedSemanticHead + + +class TestFusedSemanticHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + semantic_head = FusedSemanticHead( + num_ins=5, + fusion_level=1, + in_channels=4, + conv_out_channels=4, + num_classes=6) + feats = [ + torch.rand((1, 4, 32 // 2**(i + 1), 32 // 2**(i + 1))) + for i in range(5) + ] + mask_pred, x = semantic_head(feats) + labels = torch.randint(0, 6, (1, 1, 64, 64)) + loss = semantic_head.loss(mask_pred, labels) + self.assertIsInstance(loss, Tensor) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_global_context_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_global_context_head.py new file mode 100644 index 0000000000000000000000000000000000000000..32e850935011b1791ca9bdfb8e27c1b2afe34d6a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_global_context_head.py @@ -0,0 +1,30 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import GlobalContextHead + + +class TestGlobalContextHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + head = GlobalContextHead( + num_convs=1, in_channels=4, conv_out_channels=4, num_classes=10) + feats = [ + torch.rand((1, 4, 64 // 2**(i + 1), 64 // 2**(i + 1))) + for i in range(5) + ] + mc_pred, x = head(feats) + + labels = [torch.randint(0, 10, (10, ))] + loss = head.loss(mc_pred, labels) + self.assertIsInstance(loss, Tensor) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_grid_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_grid_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7a583cd4e61221ebf02ed9c1bf962851b7f31b08 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_grid_head.py @@ -0,0 +1,85 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet.models.roi_heads.mask_heads import GridHead +from mmdet.models.utils import unpack_gt_instances +from mmdet.testing import (demo_mm_inputs, demo_mm_proposals, + demo_mm_sampling_results) + + +class TestGridHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_grid_head_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + grid_head = GridHead() + grid_head.to(device=device) + + s = 256 + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + + train_cfg = ConfigDict(dict(pos_radius=1)) + + # prepare ground truth + (batch_gt_instances, batch_gt_instances_ignore, + _) = unpack_gt_instances(batch_data_samples) + sampling_results = demo_mm_sampling_results( + proposals_list=proposals_list, + batch_gt_instances=batch_gt_instances, + batch_gt_instances_ignore=batch_gt_instances_ignore) + + # prepare grid feats + pos_bboxes = torch.cat([res.pos_bboxes for res in sampling_results]) + grid_feats = torch.rand((pos_bboxes.size(0), 256, 14, 14)).to(device) + sample_idx = torch.arange(0, pos_bboxes.size(0)) + grid_pred = grid_head(grid_feats) + + grid_head.loss(grid_pred, sample_idx, sampling_results, train_cfg) + + @parameterized.expand(['cpu', 'cuda']) + def test_mask_iou_head_predict_by_feat(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + grid_head = GridHead() + grid_head.to(device=device) + + s = 128 + num_samples = 2 + num_classes = 4 + img_metas = { + 'img_shape': (s, s, 3), + 'scale_factor': (1, 1), + 'ori_shape': (s, s, 3) + } + results = InstanceData(metainfo=img_metas) + results.bboxes = torch.rand((num_samples, 4)).to(device) + results.scores = torch.rand((num_samples, )).to(device) + results.labels = torch.randint( + num_classes, (num_samples, ), dtype=torch.long).to(device) + + grid_feats = torch.rand((num_samples, 256, 14, 14)).to(device) + grid_preds = grid_head(grid_feats) + grid_head.predict_by_feat( + grid_preds=grid_preds, + results_list=[results], + batch_img_metas=[img_metas]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_htc_mask_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_htc_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6927e618da4a42451a355f44d8cbeaceae91329f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_htc_mask_head.py @@ -0,0 +1,46 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import HTCMaskHead + + +class TestHTCMaskHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + num_classes = 6 + mask_head = HTCMaskHead( + with_conv_res=True, + num_convs=1, + in_channels=1, + conv_out_channels=1, + num_classes=num_classes) + + x = torch.rand((1, 1, 10, 10)) + res_feat = torch.rand((1, 1, 10, 10)) + + with self.assertRaises(AssertionError): + mask_head(x, return_logits=False, return_feat=False) + + results = mask_head(x) + self.assertEqual(len(results), 2) + results = mask_head(x, res_feat=res_feat) + self.assertEqual(len(results), 2) + + results = mask_head(x, return_logits=False) + self.assertIsInstance(results, Tensor) + results = mask_head(x, return_feat=False) + self.assertIsInstance(results, Tensor) + + results = mask_head(x, res_feat=res_feat, return_logits=False) + self.assertIsInstance(results, Tensor) + results = mask_head(x, res_feat=res_feat, return_feat=False) + self.assertIsInstance(results, Tensor) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_maskiou_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_maskiou_head.py new file mode 100644 index 0000000000000000000000000000000000000000..548147861d5af5a1213629be462189cccf473de3 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_maskiou_head.py @@ -0,0 +1,100 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet.models.roi_heads.mask_heads import MaskIoUHead +from mmdet.models.utils import unpack_gt_instances +from mmdet.structures.mask import mask_target +from mmdet.testing import (demo_mm_inputs, demo_mm_proposals, + demo_mm_sampling_results) + + +class TestMaskIoUHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_mask_iou_head_loss_and_target(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + mask_iou_head = MaskIoUHead(num_classes=4) + mask_iou_head.to(device=device) + + s = 256 + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + train_cfg = ConfigDict(dict(mask_size=28, mask_thr_binary=0.5)) + + # prepare ground truth + (batch_gt_instances, batch_gt_instances_ignore, + _) = unpack_gt_instances(batch_data_samples) + sampling_results = demo_mm_sampling_results( + proposals_list=proposals_list, + batch_gt_instances=batch_gt_instances, + batch_gt_instances_ignore=batch_gt_instances_ignore) + + # prepare mask feats, pred and target + pos_proposals = [res.pos_priors for res in sampling_results] + pos_assigned_gt_inds = [ + res.pos_assigned_gt_inds for res in sampling_results + ] + gt_masks = [res.masks for res in batch_gt_instances] + mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, + gt_masks, train_cfg) + mask_feats = torch.rand((mask_targets.size(0), 256, 14, 14)).to(device) + mask_preds = torch.rand((mask_targets.size(0), 4, 28, 28)).to(device) + + pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results]) + pos_mask_pred = mask_preds[range(mask_preds.size(0)), pos_labels] + mask_iou_pred = mask_iou_head(mask_feats, pos_mask_pred) + pos_mask_iou_pred = mask_iou_pred[range(mask_iou_pred.size(0)), + pos_labels] + + mask_iou_head.loss_and_target(pos_mask_iou_pred, pos_mask_pred, + mask_targets, sampling_results, + batch_gt_instances, train_cfg) + + @parameterized.expand(['cpu', 'cuda']) + def test_mask_iou_head_predict_by_feat(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + mask_iou_head = MaskIoUHead(num_classes=4) + mask_iou_head.to(device=device) + + s = 128 + num_samples = 2 + num_classes = 4 + img_metas = { + 'img_shape': (s, s, 3), + 'scale_factor': (1, 1), + 'ori_shape': (s, s, 3) + } + results = InstanceData(metainfo=img_metas) + results.bboxes = torch.rand((num_samples, 4)).to(device) + results.scores = torch.rand((num_samples, )).to(device) + results.labels = torch.randint( + num_classes, (num_samples, ), dtype=torch.long).to(device) + + mask_feats = torch.rand((num_samples, 256, 14, 14)).to(device) + mask_preds = torch.rand((num_samples, num_classes, 28, 28)).to(device) + mask_iou_preds = mask_iou_head( + mask_feats, mask_preds[range(results.labels.size(0)), + results.labels]) + + mask_iou_head.predict_by_feat( + mask_iou_preds=[mask_iou_preds], results_list=[results]) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_mask_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..4df9dc59e9b3dd0db81d3926643e1f270b3780a2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_mask_head.py @@ -0,0 +1,29 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import SCNetMaskHead + + +class TestSCNetMaskHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + num_classes = 6 + mask_head = SCNetMaskHead( + conv_to_res=True, + num_convs=1, + in_channels=1, + conv_out_channels=1, + num_classes=num_classes) + + x = torch.rand((1, 1, 10, 10)) + results = mask_head(x) + self.assertIsInstance(results, Tensor) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_semantic_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_semantic_head.py new file mode 100644 index 0000000000000000000000000000000000000000..84f787bb7f4d62f87053bf97dfc1141ed11d344a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_semantic_head.py @@ -0,0 +1,33 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import SCNetSemanticHead + + +class TestSCNetSemanticHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + semantic_head = SCNetSemanticHead( + num_ins=5, + fusion_level=1, + in_channels=4, + conv_out_channels=4, + num_classes=6) + feats = [ + torch.rand((1, 4, 32 // 2**(i + 1), 32 // 2**(i + 1))) + for i in range(5) + ] + mask_pred, x = semantic_head(feats) + labels = torch.randint(0, 6, (1, 1, 64, 64)) + loss = semantic_head.loss(mask_pred, labels) + self.assertIsInstance(loss, Tensor) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_scoring_roI_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_scoring_roI_head.py new file mode 100644 index 0000000000000000000000000000000000000000..458eb302b00ab20d65052dd89bf57536b62015e9 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_mask_scoring_roI_head.py @@ -0,0 +1,124 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestMaskScoringRoiHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'ms_rcnn/ms-rcnn_r50_fpn_1x_coco.py') + + def test_init(self): + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + self.assertTrue(roi_head.with_mask) + self.assertTrue(roi_head.mask_iou_head) + + def test_mask_scoring_roi_head_loss(self): + """Tests trident roi head predict.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.cuda() + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_bbox = out['loss_bbox'] + loss_mask = out['loss_mask'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_bbox.sum(), 0, 'box loss should be non-zero') + self.assertGreater(loss_mask.sum(), 0, 'mask loss should be non-zero') + + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + empty_bbox_loss = out['loss_bbox'] + empty_mask_loss = out['loss_mask'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_bbox_loss.sum(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_mask_loss.sum(), 0, + 'there should be no mask loss when there are no true boxes') + + def test_mask_scoring_roi_head_predict(self): + """Tests trident roi head predict.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.cuda() + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + roi_head.predict(feats, proposals_list, batch_data_samples) + + def test_mask_scoring_roi_head_forward(self): + """Tests trident roi head forward.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.cuda() + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + + image_shapes = [(3, s, s)] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + roi_head.forward(feats, proposals_list) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_multi_instance_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_multi_instance_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..df7734c5a952cf99853dba21baa84d010b423446 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_multi_instance_roi_head.py @@ -0,0 +1,129 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import Config + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals +from mmdet.utils import register_all_modules + +register_all_modules() + + +def _fake_roi_head(): + """Set a fake roi head config.""" + + roi_head = Config( + dict( + type='MultiInstanceRoIHead', + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', + output_size=7, + sampling_ratio=-1, + aligned=True, + use_torchvision=True), + out_channels=256, + featmap_strides=[4, 8, 16, 32]), + bbox_head=dict( + type='MultiInstanceBBoxHead', + with_refine=False, + num_shared_fcs=2, + 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.], + target_stds=[0.1, 0.1, 0.2, 0.2]), + reg_class_agnostic=False, + loss_cls=dict( + type='CrossEntropyLoss', + loss_weight=1.0, + use_sigmoid=False, + reduction='none'), + loss_bbox=dict( + type='SmoothL1Loss', loss_weight=1.0, reduction='none')), + train_cfg=dict( + assigner=dict( + type='MultiInstanceAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.3, + match_low_quality=False, + ignore_iof_thr=-1), + sampler=dict( + type='MultiInsRandomSampler', + num=512, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + pos_weight=-1, + debug=False), + test_cfg=dict( + nms=dict(iou_threshold=0.5), score_thr=0.01, max_per_img=500))) + + return roi_head + + +class TestMultiInstanceRoIHead(TestCase): + + def test_init(self): + """Test init multi instance RoI head.""" + roi_head_cfg = _fake_roi_head() + roi_head = MODELS.build(roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + + def test_standard_roi_head_loss(self): + """Tests multi instance roi head loss when truth is empty and non- + empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + roi_head_cfg = _fake_roi_head() + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then emd loss should be nonzero for + # random inputs + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=False, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss = out['loss_rcnn_emd'] + self.assertGreater(loss.sum(), 0, 'loss should be non-zero') + + # When there is no truth, the emd loss should be zero. + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_loss = out['loss_rcnn_emd'] + self.assertEqual( + empty_loss.sum(), 0, + 'there should be no emd loss when there are no true boxes') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_pisa_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_pisa_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5820c3977c82207ee9f47cc5947b132281251f1c --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_pisa_roi_head.py @@ -0,0 +1,71 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestPISARoIHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'pisa/faster-rcnn_r50_fpn_pisa_1x_coco.py') + + def test_init(self): + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + + @parameterized.expand(['cpu', 'cuda']) + def test_pisa_roi_head(self, device): + """Tests trident roi head predict.""" + if not torch.cuda.is_available() and device == 'cuda': + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_bbox = out['loss_bbox'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_bbox.sum(), 0, 'box loss should be non-zero') + + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + empty_bbox_loss = out['loss_bbox'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_bbox_loss.sum(), 0, + 'there should be no box loss when there are no true boxes') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_point_rend_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_point_rend_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..dce8bf498eaf7d7fd4bae7b618973446c6b502c4 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_point_rend_roi_head.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads import PointRendRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestHTCRoIHead(TestCase): + + @parameterized.expand( + ['point_rend/point-rend_r50-caffe_fpn_ms-1x_coco.py']) + def test_init(self, cfg_file): + """Test init Point rend RoI head.""" + # Normal HTC RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + assert roi_head.with_bbox + assert roi_head.with_mask + + @parameterized.expand( + ['point_rend/point-rend_r50-caffe_fpn_ms-1x_coco.py']) + def test_point_rend_roi_head_loss(self, cfg_file): + """Tests htc roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [img_meta['img_shape'] for img_meta in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # Positive rois must not be empty + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + with self.assertRaises(AssertionError): + out = roi_head.loss(feats, proposal_list, batch_data_samples) + + @parameterized.expand( + ['point_rend/point-rend_r50-caffe_fpn_ms-1x_coco.py']) + def test_point_rend_roi_head_predict(self, cfg_file): + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + img_shape_list = [img_meta['img_shape'] for img_meta in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + results = roi_head.predict( + feats, proposal_list, batch_data_samples, rescale=True) + self.assertEqual(results[0].masks.shape[-2:], (s, s)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_roi_extractors/test_generic_roi_extractor.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_roi_extractors/test_generic_roi_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..c5637a4d8c93210b74b5febc1278a26d9a61a7bc --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_roi_extractors/test_generic_roi_extractor.py @@ -0,0 +1,101 @@ +import unittest + +import torch + +from mmdet.models.roi_heads.roi_extractors import GenericRoIExtractor + + +class TestGenericRoIExtractor(unittest.TestCase): + + def test_init(self): + with self.assertRaises(AssertionError): + GenericRoIExtractor( + aggregation='other', + roi_layer=dict( + type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16, + featmap_strides=[4, 8, 16, 32]) + + roi_extractor = GenericRoIExtractor( + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16, + featmap_strides=[4, 8, 16, 32]) + self.assertFalse(roi_extractor.with_pre) + self.assertFalse(roi_extractor.with_post) + + def test_forward(self): + # test with pre/post + cfg = dict( + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16, + featmap_strides=[4, 8, 16, 32], + pre_cfg=dict( + type='ConvModule', + in_channels=16, + out_channels=16, + kernel_size=5, + padding=2, + inplace=False), + post_cfg=dict( + type='ConvModule', + in_channels=16, + out_channels=16, + kernel_size=5, + padding=2, + inplace=False)) + roi_extractor = GenericRoIExtractor(**cfg) + + # empty rois + feats = ( + torch.rand((1, 16, 200, 336)), + torch.rand((1, 16, 100, 168)), + ) + rois = torch.empty((0, 5), dtype=torch.float32) + res = roi_extractor(feats, rois) + self.assertEqual(len(res), 0) + + # single scale feature + rois = torch.tensor([[0.0000, 587.8285, 52.1405, 886.2484, 341.5644]]) + feats = (torch.rand((1, 16, 200, 336)), ) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 16, 7, 7)) + + # multi-scale features + feats = ( + torch.rand((1, 16, 200, 336)), + torch.rand((1, 16, 100, 168)), + torch.rand((1, 16, 50, 84)), + torch.rand((1, 16, 25, 42)), + ) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 16, 7, 7)) + + # test w.o. pre/post concat + cfg = dict( + aggregation='concat', + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16 * 4, + featmap_strides=[4, 8, 16, 32]) + + roi_extractor = GenericRoIExtractor(**cfg) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 64, 7, 7)) + + # test concat channels number + cfg = dict( + aggregation='concat', + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=256 * 5, # 256*5 != 256*4 + featmap_strides=[4, 8, 16, 32]) + + roi_extractor = GenericRoIExtractor(**cfg) + + feats = ( + torch.rand((1, 256, 200, 336)), + torch.rand((1, 256, 100, 168)), + torch.rand((1, 256, 50, 84)), + torch.rand((1, 256, 25, 42)), + ) + # out_channels does not sum of feat channels + with self.assertRaises(AssertionError): + roi_extractor(feats, rois) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_roi_extractors/test_single_level_roi_extractor.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_roi_extractors/test_single_level_roi_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..a401197f107546b9b31982d2f01577b542934df0 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_roi_extractors/test_single_level_roi_extractor.py @@ -0,0 +1,39 @@ +import unittest + +import torch + +from mmdet.models.roi_heads.roi_extractors import SingleRoIExtractor + + +class TestSingleRoIExtractor(unittest.TestCase): + + def test_forward(self): + cfg = dict( + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16, + featmap_strides=[4, 8, 16, 32]) + roi_extractor = SingleRoIExtractor(**cfg) + + # empty rois + feats = (torch.rand((1, 16, 200, 336)), ) + rois = torch.empty((0, 5), dtype=torch.float32) + res = roi_extractor(feats, rois) + self.assertEqual(len(res), 0) + + # single scale feature + rois = torch.tensor([[0.0000, 587.8285, 52.1405, 886.2484, 341.5644]]) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 16, 7, 7)) + + # multi-scale features + feats = ( + torch.rand((1, 16, 200, 336)), + torch.rand((1, 16, 100, 168)), + torch.rand((1, 16, 50, 84)), + torch.rand((1, 16, 25, 42)), + ) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 16, 7, 7)) + + res = roi_extractor(feats, rois, roi_scale_factor=2.0) + self.assertEqual(res.shape, (1, 16, 7, 7)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_scnet_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_scnet_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9f14530ba7be05ae1cf3903402ff98055a25eb5a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_scnet_roi_head.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads import SCNetRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestSCNetRoIHead(TestCase): + + @parameterized.expand(['scnet/scnet_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + """Test init scnet RoI head.""" + # Normal Cascade Mask R-CNN RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + assert roi_head.with_bbox + assert roi_head.with_mask + assert roi_head.with_semantic + assert roi_head.with_feat_relay + assert roi_head.with_glbctx + + @parameterized.expand(['scnet/scnet_r50_fpn_1x_coco.py']) + def test_scnet_roi_head_loss(self, cfg_file): + """Tests htc roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + with_semantic=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + with_semantic=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss_cls' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + elif 'loss_bbox' in name or 'loss_mask' in name: + self.assertEqual(value.sum(), 0) + + @parameterized.expand(['scnet/scnet_r50_fpn_1x_coco.py']) + def test_scnet_roi_head_predict(self, cfg_file): + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + results = roi_head.predict( + feats, proposal_list, batch_data_samples, rescale=True) + self.assertEqual(results[0].masks.shape[-2:], (s, s)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_sparse_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_sparse_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1182786c0e0da52ac8e5efb294a8478be42dd470 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_sparse_roi_head.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +import torch.nn as nn +from parameterized import parameterized + +from mmdet.models.roi_heads import StandardRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestCascadeRoIHead(TestCase): + + @parameterized.expand(['queryinst/queryinst_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + """Test init standard RoI head.""" + # Normal Cascade Mask R-CNN RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head.init_weights() + assert roi_head.with_bbox + assert roi_head.with_mask + + @parameterized.expand(['queryinst/queryinst_r50_fpn_1x_coco.py']) + def test_cascade_roi_head_loss(self, cfg_file): + """Tests standard roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + # add import elements into proposal + init_proposal_features = nn.Embedding(100, 256).cuda().weight.clone() + for proposal in proposal_list: + proposal.features = init_proposal_features + proposal.imgs_whwh = feats[0].new_tensor([[s, s, s, + s]]).repeat(100, 1) + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + # add import elements into proposal + init_proposal_features = nn.Embedding(100, 256).cuda().weight.clone() + for proposal in proposal_list: + proposal.features = init_proposal_features + proposal.imgs_whwh = feats[0].new_tensor([[s, s, s, + s]]).repeat(100, 1) + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss_cls' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + elif 'loss_bbox' in name or 'loss_mask' in name: + self.assertEqual(value.sum(), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_standard_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_standard_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae95e284406bcf2f26b47d1b6b034c685395d7a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_standard_roi_head.py @@ -0,0 +1,206 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import Config +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals +from mmdet.utils import register_all_modules + +register_all_modules() + + +def _fake_roi_head(with_shared_head=False): + """Set a fake roi head config.""" + if not with_shared_head: + roi_head = Config( + dict( + type='StandardRoIHead', + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', output_size=7, sampling_ratio=0), + out_channels=1, + featmap_strides=[4, 8, 16, 32]), + bbox_head=dict( + type='Shared2FCBBoxHead', + in_channels=1, + fc_out_channels=1, + num_classes=4), + mask_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', output_size=14, sampling_ratio=0), + out_channels=1, + featmap_strides=[4, 8, 16, 32]), + mask_head=dict( + type='FCNMaskHead', + num_convs=1, + in_channels=1, + conv_out_channels=1, + num_classes=4), + train_cfg=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( + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100, + mask_thr_binary=0.5))) + else: + roi_head = Config( + dict( + type='StandardRoIHead', + shared_head=dict( + type='ResLayer', + depth=50, + stage=3, + stride=2, + dilation=1, + style='caffe', + norm_cfg=dict(type='BN', requires_grad=False), + norm_eval=True), + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', output_size=14, sampling_ratio=0), + out_channels=1, + featmap_strides=[16]), + bbox_head=dict( + type='BBoxHead', + with_avg_pool=True, + in_channels=2048, + roi_feat_size=7, + num_classes=4), + mask_roi_extractor=None, + mask_head=dict( + type='FCNMaskHead', + num_convs=0, + in_channels=2048, + conv_out_channels=1, + num_classes=4), + train_cfg=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), + mask_size=14, + pos_weight=-1, + debug=False), + test_cfg=dict( + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100, + mask_thr_binary=0.5))) + return roi_head + + +class TestStandardRoIHead(TestCase): + + def test_init(self): + """Test init standard RoI head.""" + # Normal Mask R-CNN RoI head + roi_head_cfg = _fake_roi_head() + roi_head = MODELS.build(roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + self.assertTrue(roi_head.with_mask) + + # Mask R-CNN RoI head with shared_head + roi_head_cfg = _fake_roi_head(with_shared_head=True) + roi_head = MODELS.build(roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + self.assertTrue(roi_head.with_mask) + self.assertTrue(roi_head.with_shared_head) + + @parameterized.expand([(False, ), (True, )]) + def test_standard_roi_head_loss(self, with_shared_head): + """Tests standard roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + roi_head_cfg = _fake_roi_head(with_shared_head=with_shared_head) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + if not with_shared_head: + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + else: + feats.append( + torch.rand(1, 1024, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_bbox = out['loss_bbox'] + loss_mask = out['loss_mask'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_bbox.sum(), 0, 'box loss should be non-zero') + self.assertGreater(loss_mask.sum(), 0, 'mask loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + empty_bbox_loss = out['loss_bbox'] + empty_mask_loss = out['loss_mask'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_bbox_loss.sum(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_mask_loss.sum(), 0, + 'there should be no mask loss when there are no true boxes') diff --git a/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_trident_roi_head.py b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_trident_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a173b01066cedf0b8915ce17ae22921d8b136827 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_roi_heads/test_trident_roi_head.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import unittest +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestTridentRoIHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'tridentnet/tridentnet_r50-caffe_1x_coco.py') + + def test_init(self): + + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + self.assertTrue(roi_head.with_shared_head) + + def test_trident_roi_head_predict(self): + """Tests trident roi head predict.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + + roi_head_cfg = copy.deepcopy(self.roi_head_cfg) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 1024, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + # When `test_branch_idx == 1` + roi_head.predict(feats, proposals_list, batch_data_samples) + # When `test_branch_idx == -1` + roi_head_cfg.test_branch_idx = -1 + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + roi_head.predict(feats, proposals_list, batch_data_samples) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_heuristic_fusion_head.py b/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_heuristic_fusion_head.py new file mode 100644 index 0000000000000000000000000000000000000000..89f3168c61f1437e9e173c447322a247b397ded8 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_heuristic_fusion_head.py @@ -0,0 +1,59 @@ +import unittest + +import torch +from mmengine.config import Config +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.evaluation import INSTANCE_OFFSET +from mmdet.models.seg_heads.panoptic_fusion_heads import HeuristicFusionHead + + +class TestHeuristicFusionHead(unittest.TestCase): + + def test_loss(self): + head = HeuristicFusionHead(num_things_classes=2, num_stuff_classes=2) + result = head.loss() + self.assertTrue(not head.with_loss) + self.assertDictEqual(result, dict()) + + def test_predict(self): + test_cfg = Config(dict(mask_overlap=0.5, stuff_area_limit=1)) + head = HeuristicFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + mask_results = InstanceData() + mask_results.bboxes = torch.tensor([[0, 0, 1, 1], [1, 1, 2, 2]]) + mask_results.labels = torch.tensor([0, 1]) + mask_results.scores = torch.tensor([0.8, 0.7]) + mask_results.masks = torch.tensor([[[1, 0], [0, 0]], [[0, 0], + [0, 1]]]).bool() + + seg_preds_list = [ + torch.tensor([[[0.2, 0.7], [0.3, 0.1]], [[0.2, 0.2], [0.6, 0.1]], + [[0.6, 0.1], [0.1, 0.8]]]) + ] + target_list = [ + torch.tensor([[0 + 1 * INSTANCE_OFFSET, 2], + [3, 1 + 2 * INSTANCE_OFFSET]]) + ] + results_list = head.predict([mask_results], seg_preds_list) + for target, result in zip(target_list, results_list): + assert_allclose(result.sem_seg[0], target) + + # test with no thing + head = HeuristicFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + mask_results = InstanceData() + mask_results.bboxes = torch.zeros((0, 4)) + mask_results.labels = torch.zeros((0, )).long() + mask_results.scores = torch.zeros((0, )) + mask_results.masks = torch.zeros((0, 2, 2), dtype=torch.bool) + seg_preds_list = [ + torch.tensor([[[0.2, 0.7], [0.3, 0.1]], [[0.2, 0.2], [0.6, 0.1]], + [[0.6, 0.1], [0.1, 0.8]]]) + ] + target_list = [torch.tensor([[4, 2], [3, 4]])] + + results_list = head.predict([mask_results], seg_preds_list) + for target, result in zip(target_list, results_list): + assert_allclose(result.sem_seg[0], target) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_maskformer_fusion_head.py b/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_maskformer_fusion_head.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0be936de61e36f6c28ae8b8c47770da5c1be1a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_maskformer_fusion_head.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch +from mmengine.config import Config + +from mmdet.models.seg_heads.panoptic_fusion_heads import MaskFormerFusionHead +from mmdet.structures import DetDataSample + + +class TestMaskFormerFusionHead(unittest.TestCase): + + def test_loss(self): + head = MaskFormerFusionHead(num_things_classes=2, num_stuff_classes=2) + result = head.loss() + self.assertTrue(not head.with_loss) + self.assertDictEqual(result, dict()) + + def test_predict(self): + mask_cls_results = torch.rand((2, 10, 5)) + mask_pred_results = torch.rand((2, 10, 32, 32)) + batch_data_samples = [ + DetDataSample( + metainfo={ + 'batch_input_shape': (32, 32), + 'img_shape': (32, 30), + 'ori_shape': (30, 30) + }), + DetDataSample( + metainfo={ + 'batch_input_shape': (32, 32), + 'img_shape': (32, 30), + 'ori_shape': (29, 30) + }) + ] + + # get panoptic and instance segmentation results + test_cfg = Config( + dict( + panoptic_on=True, + semantic_on=False, + instance_on=True, + max_per_image=10, + object_mask_thr=0.3, + iou_thr=0.3, + filter_low_score=False)) + head = MaskFormerFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + results = head.predict( + mask_cls_results, + mask_pred_results, + batch_data_samples, + rescale=False) + for i in range(len(results)): + self.assertEqual(results[i]['pan_results'].sem_seg.shape[-2:], + batch_data_samples[i].img_shape) + self.assertEqual(results[i]['ins_results'].masks.shape[-2:], + batch_data_samples[i].img_shape) + + results = head.predict( + mask_cls_results, + mask_pred_results, + batch_data_samples, + rescale=True) + for i in range(len(results)): + self.assertEqual(results[i]['pan_results'].sem_seg.shape[-2:], + batch_data_samples[i].ori_shape) + self.assertEqual(results[i]['ins_results'].masks.shape[-2:], + batch_data_samples[i].ori_shape) + + # get empty results + test_cfg = Config( + dict( + panoptic_on=False, + semantic_on=False, + instance_on=False, + max_per_image=10, + object_mask_thr=0.3, + iou_thr=0.3, + filter_low_score=False)) + head = MaskFormerFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + results = head.predict( + mask_cls_results, + mask_pred_results, + batch_data_samples, + rescale=True) + for i in range(len(results)): + self.assertEqual(results[i], dict()) + + # semantic segmentation is not supported + test_cfg = Config( + dict( + panoptic_on=False, + semantic_on=True, + instance_on=False, + max_per_image=10, + object_mask_thr=0.3, + iou_thr=0.3, + filter_low_score=False)) + head = MaskFormerFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + with self.assertRaises(AssertionError): + results = head.predict( + mask_cls_results, + mask_pred_results, + batch_data_samples, + rescale=True) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_panoptic_fpn_head.py b/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_panoptic_fpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f7471f246ea4cdaa7c5ccf949a2d3a9ab01fa49b --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_seg_heads/test_panoptic_fpn_head.py @@ -0,0 +1,70 @@ +import unittest + +import torch +from mmengine.structures import PixelData +from mmengine.testing import assert_allclose + +from mmdet.models.seg_heads import PanopticFPNHead +from mmdet.structures import DetDataSample + + +class TestPanopticFPNHead(unittest.TestCase): + + def test_init_weights(self): + head = PanopticFPNHead( + num_things_classes=2, + num_stuff_classes=2, + in_channels=32, + inner_channels=32) + head.init_weights() + assert_allclose(head.conv_logits.bias.data, + torch.zeros_like(head.conv_logits.bias.data)) + + def test_loss(self): + head = PanopticFPNHead( + num_things_classes=2, + num_stuff_classes=2, + in_channels=32, + inner_channels=32, + start_level=0, + end_level=1) + x = [torch.rand((2, 32, 8, 8)), torch.rand((2, 32, 4, 4))] + data_sample1 = DetDataSample() + data_sample1.gt_sem_seg = PixelData( + sem_seg=torch.randint(0, 4, (1, 7, 8))) + data_sample2 = DetDataSample() + data_sample2.gt_sem_seg = PixelData( + sem_seg=torch.randint(0, 4, (1, 7, 8))) + batch_data_samples = [data_sample1, data_sample2] + results = head.loss(x, batch_data_samples) + self.assertIsInstance(results, dict) + + def test_predict(self): + head = PanopticFPNHead( + num_things_classes=2, + num_stuff_classes=2, + in_channels=32, + inner_channels=32, + start_level=0, + end_level=1) + x = [torch.rand((2, 32, 8, 8)), torch.rand((2, 32, 4, 4))] + img_meta1 = { + 'batch_input_shape': (16, 16), + 'img_shape': (14, 14), + 'ori_shape': (12, 12), + } + img_meta2 = { + 'batch_input_shape': (16, 16), + 'img_shape': (16, 16), + 'ori_shape': (16, 16), + } + batch_img_metas = [img_meta1, img_meta2] + head.eval() + with torch.no_grad(): + seg_preds = head.predict(x, batch_img_metas, rescale=False) + self.assertTupleEqual(seg_preds[0].shape[-2:], (16, 16)) + self.assertTupleEqual(seg_preds[1].shape[-2:], (16, 16)) + + seg_preds = head.predict(x, batch_img_metas, rescale=True) + self.assertTupleEqual(seg_preds[0].shape[-2:], (12, 12)) + self.assertTupleEqual(seg_preds[1].shape[-2:], (16, 16)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/__init__.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_approx_max_iou_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_approx_max_iou_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9975b91d063dedf77273f7bd4b9acf8c8f517a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_approx_max_iou_assigner.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import ApproxMaxIoUAssigner + + +class TestApproxIoUAssigner(TestCase): + + def test_approx_iou_assigner(self): + assigner = ApproxMaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + bboxes = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData() + pred_instances.priors = bboxes + pred_instances.approxs = bboxes[:, None, :] + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([1, 0, 2, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_approx_iou_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + assigner = ApproxMaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + bboxes = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([]) + gt_labels = torch.LongTensor([]) + + pred_instances = InstanceData() + pred_instances.priors = bboxes + pred_instances.approxs = bboxes[:, None, :] + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_approx_iou_assigner_with_empty_boxes(self): + """Test corner case where an network might predict no boxes.""" + assigner = ApproxMaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + bboxes = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData() + pred_instances.priors = bboxes + pred_instances.approxs = bboxes[:, None, :] + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + self.assertEqual(len(assign_result.gt_inds), 0) + + def test_approx_iou_assigner_with_empty_boxes_and_gt(self): + """Test corner case where an network might predict no boxes and no + gt.""" + assigner = ApproxMaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + bboxes = torch.empty((0, 4)) + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.LongTensor([]) + + pred_instances = InstanceData() + pred_instances.priors = bboxes + pred_instances.approxs = bboxes[:, None, :] + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_atss_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_atss_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..8cce7e3bfc03c71182ecc6225396c4f167b60cd8 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_atss_assigner.py @@ -0,0 +1,147 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import ATSSAssigner + + +class TestATSSAssigner(TestCase): + + def test_atss_assigner(self): + atss_assigner = ATSSAssigner(topk=9) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_bboxes = [4] + + assign_result = atss_assigner.assign(pred_instances, num_level_bboxes, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + expected_gt_inds = torch.LongTensor([1, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_atss_assigner_with_ignore(self): + atss_assigner = ATSSAssigner(topk=9) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [30, 32, 40, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + num_level_bboxes = [4] + assign_result = atss_assigner.assign( + pred_instances, + num_level_bboxes, + gt_instances, + gt_instances_ignore=gt_instances_ignore) + + expected_gt_inds = torch.LongTensor([1, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_atss_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + atss_assigner = ATSSAssigner(topk=9) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_bboxes = [4] + assign_result = atss_assigner.assign(pred_instances, num_level_bboxes, + gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_atss_assigner_with_empty_boxes(self): + """Test corner case where a network might predict no boxes.""" + atss_assigner = ATSSAssigner(topk=9) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_bboxes = [0] + assign_result = atss_assigner.assign(pred_instances, num_level_bboxes, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_atss_assigner_with_empty_boxes_and_ignore(self): + """Test corner case where a network might predict no boxes and + ignore_iof_thr is on.""" + atss_assigner = ATSSAssigner(topk=9) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + num_level_bboxes = [0] + + assign_result = atss_assigner.assign( + pred_instances, + num_level_bboxes, + gt_instances, + gt_instances_ignore=gt_instances_ignore) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_atss_assigner_with_empty_boxes_and_gt(self): + """Test corner case where a network might predict no boxes and no + gt.""" + atss_assigner = ATSSAssigner(topk=9) + priors = torch.empty((0, 4)) + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.empty(0) + num_level_bboxes = [0] + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = atss_assigner.assign(pred_instances, num_level_bboxes, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_center_region_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_center_region_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..b98768fb3929e40f91d68410062f6888ad355251 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_center_region_assigner.py @@ -0,0 +1,149 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import CenterRegionAssigner + + +class TestCenterRegionAssigner(TestCase): + + def test_center_region_assigner(self): + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + + assign_result = center_region_assigner.assign(pred_instances, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + expected_gt_inds = torch.LongTensor([1, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + expected_shadowed_labels = torch.LongTensor([[2, 3]]) + shadowed_labels = assign_result.get_extra_property('shadowed_labels') + self.assertTrue(torch.all(shadowed_labels == expected_shadowed_labels)) + + def test_center_region_assigner_with_ignore(self): + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [30, 32, 40, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + assign_result = center_region_assigner.assign( + pred_instances, + gt_instances, + gt_instances_ignore=gt_instances_ignore) + + expected_gt_inds = torch.LongTensor([1, 0, 0, -1]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_center_region_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = center_region_assigner.assign(pred_instances, + gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_center_region_assigner_with_empty_boxes(self): + """Test corner case where a network might predict no boxes.""" + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = center_region_assigner.assign(pred_instances, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_center_region_assigner_with_empty_boxes_and_ignore(self): + """Test corner case where a network might predict no boxes and + ignore_iof_thr is on.""" + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + + assign_result = center_region_assigner.assign( + pred_instances, + gt_instances, + gt_instances_ignore=gt_instances_ignore) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_center_region_assigner_with_empty_boxes_and_gt(self): + """Test corner case where a network might predict no boxes and no + gt.""" + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.empty((0, 4)) + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = center_region_assigner.assign(pred_instances, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_dynamic_soft_label_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_dynamic_soft_label_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..233f6a1bc1d060e5281ca9f213193bc53110e28d --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_dynamic_soft_label_assigner.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import DynamicSoftLabelAssigner +from mmdet.structures.bbox import HorizontalBoxes + + +class TestDynamicSoftLabelAssigner(TestCase): + + def test_assign(self): + assigner = DynamicSoftLabelAssigner( + soft_center_radius=3.0, topk=1, iou_weight=3.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43], [4, 5, 6, 7]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43]]), + labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_no_valid_bboxes(self): + assigner = DynamicSoftLabelAssigner( + soft_center_radius=3.0, topk=1, iou_weight=3.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[123, 123, 143, 143], [114, 151, 161, 171]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [55, 55, 8, 8]])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[0, 0, 1, 1]]), labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_empty_gt(self): + assigner = DynamicSoftLabelAssigner( + soft_center_radius=3.0, topk=1, iou_weight=3.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[[30, 40, 50, 60]], [[4, 5, 6, 7]]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[0, 12, 23, 34], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=torch.empty(0, 4), labels=torch.empty(0)) + + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_box_type_input(self): + assigner = DynamicSoftLabelAssigner( + soft_center_radius=3.0, topk=1, iou_weight=3.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43], [4, 5, 6, 7]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=HorizontalBoxes(torch.Tensor([[23, 23, 43, 43]])), + labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_grid_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_grid_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4b1374be2e196315c051abd9904de6f995170e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_grid_assigner.py @@ -0,0 +1,81 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import GridAssigner + + +class TestGridAssigner(TestCase): + + def test_assign(self): + assigner = GridAssigner(pos_iou_thr=0.5, neg_iou_thr=0.3) + pred_instances = InstanceData( + priors=torch.Tensor([[23, 23, 43, 43], [4, 5, 6, 7]]), + responsible_flags=torch.BoolTensor([1, 1])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43]]), + labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + # invalid neg_iou_thr + with self.assertRaises(AssertionError): + assigner = GridAssigner( + pos_iou_thr=0.5, neg_iou_thr=[0.3, 0.1, 0.4]) + assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + # multi-neg_iou_thr + assigner = GridAssigner(pos_iou_thr=0.5, neg_iou_thr=(0.1, 0.3)) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([1, -1]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + # gt_max_assign_all=False + assigner = GridAssigner( + pos_iou_thr=0.5, neg_iou_thr=0.3, gt_max_assign_all=False) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + # large min_pos_iou + assigner = GridAssigner( + pos_iou_thr=0.5, neg_iou_thr=0.3, min_pos_iou=1) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_empty_gt(self): + assigner = GridAssigner(pos_iou_thr=0.5, neg_iou_thr=0.3) + pred_instances = InstanceData( + priors=torch.Tensor([[0, 12, 23, 34], [4, 5, 6, 7]]), + responsible_flags=torch.BoolTensor([1, 1])) + gt_instances = InstanceData( + bboxes=torch.empty(0, 4), labels=torch.empty(0)) + + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_empty_priors(self): + assigner = GridAssigner(pos_iou_thr=0.5, neg_iou_thr=0.3) + pred_instances = InstanceData( + priors=torch.Tensor(torch.empty(0, 4)), + responsible_flags=torch.empty(0)) + gt_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43]]), + labels=torch.LongTensor([0])) + + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_hungarian_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_hungarian_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..923d3b79f1a88cb2b217b47e3f46b1b5671be435 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_hungarian_assigner.py @@ -0,0 +1,148 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import HungarianAssigner + + +class TestHungarianAssigner(TestCase): + + def test_init(self): + with self.assertRaises(AssertionError): + HungarianAssigner([]) + + def test_hungarian_match_assigner(self): + assigner = HungarianAssigner([ + dict(type='ClassificationCost', weight=1.), + dict(type='BBoxL1Cost', weight=5.0), + dict(type='IoUCost', iou_mode='giou', weight=2.0) + ]) + + # test no gt bboxes + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)).float() + gt_instances.labels = torch.empty((0, )).long() + pred_instances = InstanceData() + pred_instances.scores = torch.rand((10, 81)) + pred_instances.bboxes = torch.rand((10, 4)) + img_meta = dict(img_shape=(10, 8)) + + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds == 0)) + self.assertTrue(torch.all(assign_result.labels == -1)) + + # test with gt bboxes + gt_instances.bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_instances.labels = torch.LongTensor([1, 20]) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + def test_bbox_match_cost(self): + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_instances.labels = torch.LongTensor([1, 20]) + pred_instances = InstanceData() + pred_instances.scores = torch.rand((10, 81)) + pred_instances.bboxes = torch.rand((10, 4)) + img_meta = dict(img_shape=(10, 8)) + + # test IoUCost + assigner = HungarianAssigner( + ConfigDict(dict(type='IoUCost', iou_mode='iou'))) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + # test BBoxL1Cost + assigner = HungarianAssigner(ConfigDict(dict(type='BBoxL1Cost'))) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + def test_cls_match_cost(self): + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_instances.labels = torch.LongTensor([1, 20]) + pred_instances = InstanceData() + pred_instances.scores = torch.rand((10, 81)) + pred_instances.bboxes = torch.rand((10, 4)) + img_meta = dict(img_shape=(10, 8)) + + # test FocalLossCost + assigner = HungarianAssigner(dict(type='FocalLossCost')) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + # test ClassificationCost + assigner = HungarianAssigner(dict(type='ClassificationCost')) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + def test_mask_match_cost(self): + gt_instances = InstanceData() + gt_instances.masks = torch.randint(0, 2, (2, 10, 10)).long() + gt_instances.labels = torch.LongTensor([1, 20]) + + pred_instances = InstanceData() + pred_instances.masks = torch.rand((4, 10, 10)) + pred_instances.scores = torch.rand((4, 25)) + img_meta = dict(img_shape=(10, 10)) + + # test DiceCost + assigner = HungarianAssigner(dict(type='DiceCost')) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.masks.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.masks.size(0)) + + # test CrossEntropyLossCost + assigner = HungarianAssigner(dict(type='CrossEntropyLossCost')) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.masks.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.masks.size(0)) + + # test FocalLossCost + assigner = HungarianAssigner( + dict(type='FocalLossCost', binary_input=True)) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.masks.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.masks.size(0)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_max_iou_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_max_iou_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..958933a784835116e495208ea5d0514bc3b58546 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_max_iou_assigner.py @@ -0,0 +1,162 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Tests the Assigner objects. + +CommandLine: + pytest tests/test_core/test_bbox/test_assigners/test_max_iou_assigner.py + xdoctest tests/test_core/test_bbox/test_assigners/test_max_iou_assigner.py zero +""" # noqa +import pytest +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import MaxIoUAssigner + + +@pytest.mark.parametrize('neg_iou_thr', [0.5, (0, 0.5)]) +def test_max_iou_assigner(neg_iou_thr): + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=neg_iou_thr, + ) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + + assign_result = self.assign(pred_instances, gt_instances) + assert len(assign_result.gt_inds) == 4 + assert len(assign_result.labels) == 4 + + expected_gt_inds = torch.LongTensor([1, 0, 2, 0]) + assert torch.all(assign_result.gt_inds == expected_gt_inds) + + +def test_max_iou_assigner_with_ignore(): + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ignore_iof_thr=0.5, + ignore_wrt_candidates=False, + ) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [30, 32, 40, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + assign_result = self.assign( + pred_instances, gt_instances, gt_instances_ignore=gt_instances_ignore) + + expected_gt_inds = torch.LongTensor([1, 0, 2, -1]) + assert torch.all(assign_result.gt_inds == expected_gt_inds) + + +def test_max_iou_assigner_with_empty_gt(): + """Test corner case where an image might have no true detections.""" + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = self.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + assert torch.all(assign_result.gt_inds == expected_gt_inds) + + +def test_max_iou_assigner_with_empty_priors(): + """Test corner case where a network might predict no boxes.""" + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + # Test with gt_labels + assign_result = self.assign(pred_instances, gt_instances) + assert len(assign_result.gt_inds) == 0 + assert tuple(assign_result.labels.shape) == (0, ) + + +def test_max_iou_assigner_with_empty_boxes_and_ignore(): + """Test corner case where a network might predict no boxes and + ignore_iof_thr is on.""" + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ignore_iof_thr=0.5, + ) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + + # Test with gt_labels + assign_result = self.assign( + pred_instances, gt_instances, gt_instances_ignore=gt_instances_ignore) + assert len(assign_result.gt_inds) == 0 + assert tuple(assign_result.labels.shape) == (0, ) + + +def test_max_iou_assigner_with_empty_priors_and_gt(): + """Test corner case where a network might predict no boxes and no gt.""" + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + priors = torch.empty(0, 4) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = self.assign(pred_instances, gt_instances) + assert len(assign_result.gt_inds) == 0 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_point_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_point_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1e38cf14c298ec17f038e00e7af9e36b4029bf --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_point_assigner.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import PointAssigner + + +class TestPointAssigner(unittest.TestCase): + + def test_point_assigner(self): + assigner = PointAssigner() + pred_instances = InstanceData() + pred_instances.priors = torch.FloatTensor([ + # [x, y, stride] + [0, 0, 1], + [10, 10, 1], + [5, 5, 1], + [32, 32, 1], + ]) + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_instances.labels = torch.LongTensor([0, 1]) + assign_result = assigner.assign(pred_instances, gt_instances) + expected_gt_inds = torch.LongTensor([1, 2, 1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_point_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + assigner = PointAssigner() + pred_instances = InstanceData() + pred_instances.priors = torch.FloatTensor([ + # [x, y, stride] + [0, 0, 1], + [10, 10, 1], + [5, 5, 1], + [32, 32, 1], + ]) + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([]) + gt_instances.labels = torch.LongTensor([]) + assign_result = assigner.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_point_assigner_with_empty_boxes_and_gt(self): + """Test corner case where an image might predict no points and no + gt.""" + assigner = PointAssigner() + pred_instances = InstanceData() + pred_instances.priors = torch.FloatTensor([]) + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([]) + gt_instances.labels = torch.LongTensor([]) + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_region_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_region_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..6a73b680333654a487a19cbfdd29b17ec0a24300 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_region_assigner.py @@ -0,0 +1,138 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import RegionAssigner + + +class TestRegionAssigner(TestCase): + + def setUp(self): + self.img_meta = ConfigDict(dict(img_shape=(256, 256))) + self.featmap_sizes = [(64, 64)] + self.anchor_scale = 10 + self.anchor_strides = [1] + + def test_region_assigner(self): + region_assigner = RegionAssigner(center_ratio=0.5, ignore_ratio=0.8) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + valid_flags = torch.BoolTensor([1, 1, 1, 1]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_anchors = [4] + + assign_result = region_assigner.assign( + pred_instances, gt_instances, self.img_meta, self.featmap_sizes, + num_level_anchors, self.anchor_scale, self.anchor_strides) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + expected_gt_inds = torch.LongTensor([1, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_region_assigner_with_ignore(self): + region_assigner = RegionAssigner(center_ratio=0.5) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [30, 32, 40, 42], + ]) + valid_flags = torch.BoolTensor([1, 1, 1, 1]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + num_level_anchors = [4] + with self.assertRaises(NotImplementedError): + region_assigner.assign( + pred_instances, + gt_instances, + self.img_meta, + self.featmap_sizes, + num_level_anchors, + self.anchor_scale, + self.anchor_strides, + gt_instances_ignore=gt_instances_ignore) + + def test_region_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + region_assigner = RegionAssigner(center_ratio=0.5) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + valid_flags = torch.BoolTensor([1, 1, 1, 1]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_anchors = [4] + assign_result = region_assigner.assign( + pred_instances, gt_instances, self.img_meta, self.featmap_sizes, + num_level_anchors, self.anchor_scale, self.anchor_strides) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_atss_assigner_with_empty_boxes(self): + """Test corner case where a network might predict no boxes.""" + region_assigner = RegionAssigner(center_ratio=0.5) + priors = torch.empty((0, 4)) + valid_flags = torch.BoolTensor([]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_anchors = [0] + assign_result = region_assigner.assign( + pred_instances, gt_instances, self.img_meta, self.featmap_sizes, + num_level_anchors, self.anchor_scale, self.anchor_strides) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_atss_assigner_with_empty_boxes_and_gt(self): + """Test corner case where a network might predict no boxes and no + gt.""" + region_assigner = RegionAssigner(center_ratio=0.5) + priors = torch.empty((0, 4)) + valid_flags = torch.BoolTensor([]) + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.empty(0) + num_level_anchors = [0] + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = region_assigner.assign( + pred_instances, gt_instances, self.img_meta, self.featmap_sizes, + num_level_anchors, self.anchor_scale, self.anchor_strides) + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_simota_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_simota_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..0517f75d23a73e68a9bbc8b34338357167f9276e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_simota_assigner.py @@ -0,0 +1,66 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import SimOTAAssigner + + +class TestSimOTAAssigner(TestCase): + + def test_assign(self): + assigner = SimOTAAssigner( + center_radius=2.5, + candidate_topk=1, + iou_weight=3.0, + cls_weight=1.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43], [4, 5, 6, 7]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43]]), + labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_no_valid_bboxes(self): + assigner = SimOTAAssigner( + center_radius=2.5, + candidate_topk=1, + iou_weight=3.0, + cls_weight=1.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[123, 123, 143, 143], [114, 151, 161, 171]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [55, 55, 8, 8]])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[0, 0, 1, 1]]), labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_empty_gt(self): + assigner = SimOTAAssigner( + center_radius=2.5, + candidate_topk=1, + iou_weight=3.0, + cls_weight=1.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[[30, 40, 50, 60]], [[4, 5, 6, 7]]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[0, 12, 23, 34], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=torch.empty(0, 4), labels=torch.empty(0)) + + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_task_aligned_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_task_aligned_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..9603b897f87b2f87bc0bce55f11e8adeefedd761 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_task_aligned_assigner.py @@ -0,0 +1,57 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import TaskAlignedAssigner + + +class TestTaskAlignedAssigner(TestCase): + + def test_task_aligned_assigner(self): + + with self.assertRaises(AssertionError): + TaskAlignedAssigner(topk=0) + + assigner = TaskAlignedAssigner(topk=13) + pred_score = torch.FloatTensor([[0.1, 0.2], [0.2, 0.3], [0.3, 0.4], + [0.4, 0.5]]) + pred_bbox = torch.FloatTensor([ + [1, 1, 12, 8], + [4, 4, 20, 20], + [1, 5, 15, 15], + [30, 5, 32, 42], + ]) + anchor = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([0, 1]) + pred_instances = InstanceData() + pred_instances.priors = anchor + pred_instances.bboxes = pred_bbox + pred_instances.scores = pred_score + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + # test empty gt + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0, 2).long() + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_task_uniform_assigner.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_task_uniform_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4fbca35c758ba3436cb6b4d05172bf26f211a9 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_assigners/test_task_uniform_assigner.py @@ -0,0 +1,93 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import UniformAssigner + + +class TestUniformAssigner(TestCase): + + def test_uniform_assigner(self): + assigner = UniformAssigner(0.15, 0.7, 1) + pred_bbox = torch.FloatTensor([ + [1, 1, 12, 8], + [4, 4, 20, 20], + [1, 5, 15, 15], + [30, 5, 32, 42], + ]) + anchor = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + pred_instances = InstanceData() + pred_instances.priors = anchor + pred_instances.decoder_priors = pred_bbox + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + expected_gt_inds = torch.LongTensor([-1, 0, 2, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_uniform_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + assigner = UniformAssigner(0.15, 0.7, 1) + pred_bbox = torch.FloatTensor([ + [1, 1, 12, 8], + [4, 4, 20, 20], + [1, 5, 15, 15], + [30, 5, 32, 42], + ]) + anchor = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + pred_instances = InstanceData() + pred_instances.priors = anchor + pred_instances.decoder_priors = pred_bbox + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_uniform_assigner_with_empty_boxes(self): + """Test corner case where a network might predict no boxes.""" + assigner = UniformAssigner(0.15, 0.7, 1) + pred_bbox = torch.empty((0, 4)) + anchor = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + pred_instances = InstanceData() + pred_instances.priors = anchor + pred_instances.decoder_priors = pred_bbox + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + + # Test with gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertEqual(tuple(assign_result.labels.shape), (0, )) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_coder/test_delta_xywh_bbox_coder.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_coder/test_delta_xywh_bbox_coder.py new file mode 100644 index 0000000000000000000000000000000000000000..087c6903f6b90d1de6e72ce2ed98f632cb88c6a3 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_coder/test_delta_xywh_bbox_coder.py @@ -0,0 +1,73 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.task_modules.coders import (DeltaXYWHBBoxCoder, + DeltaXYWHBBoxCoderForGLIP) + + +def test_delta_bbox_coder(): + coder = DeltaXYWHBBoxCoder() + + rois = torch.Tensor([[0., 0., 1., 1.], [0., 0., 1., 1.], [0., 0., 1., 1.], + [5., 5., 5., 5.]]) + deltas = torch.Tensor([[0., 0., 0., 0.], [1., 1., 1., 1.], + [0., 0., 2., -1.], [0.7, -1.9, -0.5, 0.3]]) + expected_decode_bboxes = torch.Tensor([[0.0000, 0.0000, 1.0000, 1.0000], + [0.1409, 0.1409, 2.8591, 2.8591], + [0.0000, 0.3161, 4.1945, 0.6839], + [5.0000, 5.0000, 5.0000, 5.0000]]) + + out = coder.decode(rois, deltas, max_shape=(32, 32)) + assert expected_decode_bboxes.allclose(out, atol=1e-04) + out = coder.decode(rois, deltas, max_shape=torch.Tensor((32, 32))) + assert expected_decode_bboxes.allclose(out, atol=1e-04) + + batch_rois = rois.unsqueeze(0).repeat(2, 1, 1) + batch_deltas = deltas.unsqueeze(0).repeat(2, 1, 1) + batch_out = coder.decode(batch_rois, batch_deltas, max_shape=(32, 32))[0] + assert out.allclose(batch_out) + batch_out = coder.decode( + batch_rois, batch_deltas, max_shape=[(32, 32), (32, 32)])[0] + assert out.allclose(batch_out) + + # test max_shape is not equal to batch + with pytest.raises(AssertionError): + coder.decode( + batch_rois, batch_deltas, max_shape=[(32, 32), (32, 32), (32, 32)]) + + rois = torch.zeros((0, 4)) + deltas = torch.zeros((0, 4)) + out = coder.decode(rois, deltas, max_shape=(32, 32)) + assert rois.shape == out.shape + + # test add_ctr_clamp + coder = DeltaXYWHBBoxCoder(add_ctr_clamp=True, ctr_clamp=2) + + rois = torch.Tensor([[0., 0., 6., 6.], [0., 0., 1., 1.], [0., 0., 1., 1.], + [5., 5., 5., 5.]]) + deltas = torch.Tensor([[1., 1., 2., 2.], [1., 1., 1., 1.], + [0., 0., 2., -1.], [0.7, -1.9, -0.5, 0.3]]) + expected_decode_bboxes = torch.Tensor([[0.0000, 0.0000, 27.1672, 27.1672], + [0.1409, 0.1409, 2.8591, 2.8591], + [0.0000, 0.3161, 4.1945, 0.6839], + [5.0000, 5.0000, 5.0000, 5.0000]]) + + out = coder.decode(rois, deltas, max_shape=(32, 32)) + assert expected_decode_bboxes.allclose(out, atol=1e-04) + + coder = DeltaXYWHBBoxCoderForGLIP() + + rois = torch.Tensor([[0., 0., 1., 1.], [0., 0., 1., 1.], [0., 0., 1., 1.], + [5., 5., 5., 5.]]) + deltas = torch.Tensor([[0., 0., 0., 0.], [1., 1., 1., 1.], + [0., 0., 2., -1.], [0.7, -1.9, -0.5, 0.3]]) + expected_decode_bboxes = torch.Tensor([[0.0000, 0.0000, 0.0000, 0.0000], + [0.1409, 0.1409, 1.8591, 1.8591], + [0.0000, 0.3161, 3.1945, 0.0000], + [5.0000, 5.0000, 4.0000, 4.0000]]) + + out = coder.decode(rois, deltas, max_shape=(32, 32)) + assert expected_decode_bboxes.allclose(out, atol=1e-04) + out = coder.decode(rois, deltas, max_shape=torch.Tensor((32, 32))) + assert expected_decode_bboxes.allclose(out, atol=1e-04) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_iou2d_calculator.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_iou2d_calculator.py new file mode 100644 index 0000000000000000000000000000000000000000..ce46e69174424f5827a11f7b5a459267eb992717 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_iou2d_calculator.py @@ -0,0 +1,134 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +import pytest +import torch + +from mmdet.evaluation import bbox_overlaps as recall_overlaps +from mmdet.models.task_modules import BboxOverlaps2D +from mmdet.structures.bbox import bbox_overlaps + + +def test_bbox_overlaps_2d(eps=1e-7): + + def _construct_bbox(num_bbox=None): + img_h = int(np.random.randint(3, 1000)) + img_w = int(np.random.randint(3, 1000)) + if num_bbox is None: + num_bbox = np.random.randint(1, 10) + x1y1 = torch.rand((num_bbox, 2)) + x2y2 = torch.max(torch.rand((num_bbox, 2)), x1y1) + bboxes = torch.cat((x1y1, x2y2), -1) + bboxes[:, 0::2] *= img_w + bboxes[:, 1::2] *= img_h + return bboxes, num_bbox + + # is_aligned is True, bboxes.size(-1) == 5 (include score) + self = BboxOverlaps2D() + bboxes1, num_bbox = _construct_bbox() + bboxes2, _ = _construct_bbox(num_bbox) + bboxes1 = torch.cat((bboxes1, torch.rand((num_bbox, 1))), 1) + bboxes2 = torch.cat((bboxes2, torch.rand((num_bbox, 1))), 1) + gious = self(bboxes1, bboxes2, 'giou', True) + assert gious.size() == (num_bbox, ), gious.size() + assert torch.all(gious >= -1) and torch.all(gious <= 1) + + # is_aligned is True, bboxes1.size(-2) == 0 + bboxes1 = torch.empty((0, 4)) + bboxes2 = torch.empty((0, 4)) + gious = self(bboxes1, bboxes2, 'giou', True) + assert gious.size() == (0, ), gious.size() + assert torch.all(gious == torch.empty((0, ))) + assert torch.all(gious >= -1) and torch.all(gious <= 1) + + # is_aligned is True, and bboxes.ndims > 2 + bboxes1, num_bbox = _construct_bbox() + bboxes2, _ = _construct_bbox(num_bbox) + bboxes1 = bboxes1.unsqueeze(0).repeat(2, 1, 1) + # test assertion when batch dim is not the same + with pytest.raises(AssertionError): + self(bboxes1, bboxes2.unsqueeze(0).repeat(3, 1, 1), 'giou', True) + bboxes2 = bboxes2.unsqueeze(0).repeat(2, 1, 1) + gious = self(bboxes1, bboxes2, 'giou', True) + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (2, num_bbox) + bboxes1 = bboxes1.unsqueeze(0).repeat(2, 1, 1, 1) + bboxes2 = bboxes2.unsqueeze(0).repeat(2, 1, 1, 1) + gious = self(bboxes1, bboxes2, 'giou', True) + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (2, 2, num_bbox) + + # is_aligned is False + bboxes1, num_bbox1 = _construct_bbox() + bboxes2, num_bbox2 = _construct_bbox() + gious = self(bboxes1, bboxes2, 'giou') + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (num_bbox1, num_bbox2) + + # is_aligned is False, and bboxes.ndims > 2 + bboxes1 = bboxes1.unsqueeze(0).repeat(2, 1, 1) + bboxes2 = bboxes2.unsqueeze(0).repeat(2, 1, 1) + gious = self(bboxes1, bboxes2, 'giou') + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (2, num_bbox1, num_bbox2) + bboxes1 = bboxes1.unsqueeze(0) + bboxes2 = bboxes2.unsqueeze(0) + gious = self(bboxes1, bboxes2, 'giou') + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (1, 2, num_bbox1, num_bbox2) + + # is_aligned is False, bboxes1.size(-2) == 0 + gious = self(torch.empty(1, 2, 0, 4), bboxes2, 'giou') + assert torch.all(gious == torch.empty(1, 2, 0, bboxes2.size(-2))) + assert torch.all(gious >= -1) and torch.all(gious <= 1) + + # test allclose between bbox_overlaps and the original official + # implementation. + bboxes1 = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [32, 32, 38, 42], + ]) + bboxes2 = torch.FloatTensor([ + [0, 0, 10, 20], + [0, 10, 10, 19], + [10, 10, 20, 20], + ]) + gious = bbox_overlaps(bboxes1, bboxes2, 'giou', is_aligned=True, eps=eps) + gious = gious.numpy().round(4) + # the gt is got with four decimal precision. + expected_gious = np.array([0.5000, -0.0500, -0.8214]) + assert np.allclose(gious, expected_gious, rtol=0, atol=eps) + + # test mode 'iof' + ious = bbox_overlaps(bboxes1, bboxes2, 'iof', is_aligned=True, eps=eps) + assert torch.all(ious >= -1) and torch.all(ious <= 1) + assert ious.size() == (bboxes1.size(0), ) + ious = bbox_overlaps(bboxes1, bboxes2, 'iof', eps=eps) + assert torch.all(ious >= -1) and torch.all(ious <= 1) + assert ious.size() == (bboxes1.size(0), bboxes2.size(0)) + + +def test_voc_recall_overlaps(): + + def _construct_bbox(num_bbox=None): + img_h = int(np.random.randint(3, 1000)) + img_w = int(np.random.randint(3, 1000)) + if num_bbox is None: + num_bbox = np.random.randint(1, 10) + x1y1 = torch.rand((num_bbox, 2)) + x2y2 = torch.max(torch.rand((num_bbox, 2)), x1y1) + bboxes = torch.cat((x1y1, x2y2), -1) + bboxes[:, 0::2] *= img_w + bboxes[:, 1::2] *= img_h + return bboxes.numpy(), num_bbox + + bboxes1, num_bbox = _construct_bbox() + bboxes2, _ = _construct_bbox(num_bbox) + ious = recall_overlaps( + bboxes1, bboxes2, 'iou', use_legacy_coordinate=False) + assert ious.shape == (num_bbox, num_bbox) + assert np.all(ious >= -1) and np.all(ious <= 1) + + ious = recall_overlaps(bboxes1, bboxes2, 'iou', use_legacy_coordinate=True) + assert ious.shape == (num_bbox, num_bbox) + assert np.all(ious >= -1) and np.all(ious <= 1) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_prior_generators/test_anchor_generator.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_prior_generators/test_anchor_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..db0b60717bcf7ba866c8ee2526b9108f04ee13dc --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_prior_generators/test_anchor_generator.py @@ -0,0 +1,771 @@ +# Copyright (c) OpenMMLab. All rights reserved. +""" +CommandLine: + pytest tests/test_utils/test_anchor.py + xdoctest tests/test_utils/test_anchor.py zero + +""" +import pytest +import torch + + +def test_standard_points_generator(): + from mmdet.models.task_modules import build_prior_generator + + # teat init + anchor_generator_cfg = dict( + type='MlvlPointGenerator', strides=[4, 8], offset=0) + anchor_generator = build_prior_generator(anchor_generator_cfg) + assert anchor_generator is not None + assert anchor_generator.num_base_priors == [1, 1] + # test_stride + from mmdet.models.task_modules.prior_generators import MlvlPointGenerator + + # Square strides + mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0) + mlvl_points_half_stride_generator = MlvlPointGenerator( + strides=[4, 10], offset=0.5) + assert mlvl_points.num_levels == 2 + + # assert self.num_levels == len(featmap_sizes) + with pytest.raises(AssertionError): + mlvl_points.grid_priors(featmap_sizes=[(2, 2)], device='cpu') + priors = mlvl_points.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], device='cpu') + priors_with_stride = mlvl_points.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], with_stride=True, device='cpu') + assert len(priors) == 2 + + # assert last dimension is (coord_x, coord_y, stride_w, stride_h). + assert priors_with_stride[0].size(1) == 4 + assert priors_with_stride[0][0][2] == 4 + assert priors_with_stride[0][0][3] == 4 + assert priors_with_stride[1][0][2] == 10 + assert priors_with_stride[1][0][3] == 10 + + stride_4_feat_2_2 = priors[0] + assert (stride_4_feat_2_2[1] - stride_4_feat_2_2[0]).sum() == 4 + assert stride_4_feat_2_2.size(0) == 4 + assert stride_4_feat_2_2.size(1) == 2 + + stride_10_feat_4_8 = priors[1] + assert (stride_10_feat_4_8[1] - stride_10_feat_4_8[0]).sum() == 10 + assert stride_10_feat_4_8.size(0) == 4 * 8 + assert stride_10_feat_4_8.size(1) == 2 + + # assert the offset of 0.5 * stride + priors_half_offset = mlvl_points_half_stride_generator.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], device='cpu') + + assert (priors_half_offset[0][0] - priors[0][0]).sum() == 4 * 0.5 * 2 + assert (priors_half_offset[1][0] - priors[1][0]).sum() == 10 * 0.5 * 2 + if torch.cuda.is_available(): + anchor_generator_cfg = dict( + type='MlvlPointGenerator', strides=[4, 8], offset=0) + anchor_generator = build_prior_generator(anchor_generator_cfg) + assert anchor_generator is not None + # Square strides + mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0) + mlvl_points_half_stride_generator = MlvlPointGenerator( + strides=[4, 10], offset=0.5) + assert mlvl_points.num_levels == 2 + + # assert self.num_levels == len(featmap_sizes) + with pytest.raises(AssertionError): + mlvl_points.grid_priors(featmap_sizes=[(2, 2)], device='cuda') + priors = mlvl_points.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], device='cuda') + priors_with_stride = mlvl_points.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], with_stride=True, device='cuda') + assert len(priors) == 2 + + # assert last dimension is (coord_x, coord_y, stride_w, stride_h). + assert priors_with_stride[0].size(1) == 4 + assert priors_with_stride[0][0][2] == 4 + assert priors_with_stride[0][0][3] == 4 + assert priors_with_stride[1][0][2] == 10 + assert priors_with_stride[1][0][3] == 10 + + stride_4_feat_2_2 = priors[0] + assert (stride_4_feat_2_2[1] - stride_4_feat_2_2[0]).sum() == 4 + assert stride_4_feat_2_2.size(0) == 4 + assert stride_4_feat_2_2.size(1) == 2 + + stride_10_feat_4_8 = priors[1] + assert (stride_10_feat_4_8[1] - stride_10_feat_4_8[0]).sum() == 10 + assert stride_10_feat_4_8.size(0) == 4 * 8 + assert stride_10_feat_4_8.size(1) == 2 + + # assert the offset of 0.5 * stride + priors_half_offset = mlvl_points_half_stride_generator.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], device='cuda') + + assert (priors_half_offset[0][0] - priors[0][0]).sum() == 4 * 0.5 * 2 + assert (priors_half_offset[1][0] - priors[1][0]).sum() == 10 * 0.5 * 2 + + +def test_sparse_prior(): + from mmdet.models.task_modules.prior_generators import MlvlPointGenerator + mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0) + prior_indexs = torch.Tensor([0, 2, 4, 5, 6, 9]).long() + + featmap_sizes = [(3, 5), (6, 4)] + grid_anchors = mlvl_points.grid_priors( + featmap_sizes=featmap_sizes, with_stride=False, device='cpu') + sparse_prior = mlvl_points.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[0], + level_idx=0, + device='cpu') + + assert not sparse_prior.is_cuda + assert (sparse_prior == grid_anchors[0][prior_indexs]).all() + sparse_prior = mlvl_points.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[1], + level_idx=1, + device='cpu') + assert (sparse_prior == grid_anchors[1][prior_indexs]).all() + + from mmdet.models.task_modules.prior_generators import AnchorGenerator + mlvl_anchors = AnchorGenerator( + strides=[16, 32], ratios=[1.], scales=[1.], base_sizes=[4, 8]) + prior_indexs = torch.Tensor([0, 2, 4, 5, 6, 9]).long() + + featmap_sizes = [(3, 5), (6, 4)] + grid_anchors = mlvl_anchors.grid_priors( + featmap_sizes=featmap_sizes, device='cpu') + sparse_prior = mlvl_anchors.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[0], + level_idx=0, + device='cpu') + assert (sparse_prior == grid_anchors[0][prior_indexs]).all() + sparse_prior = mlvl_anchors.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[1], + level_idx=1, + device='cpu') + assert (sparse_prior == grid_anchors[1][prior_indexs]).all() + + # for ssd + from mmdet.models.task_modules.prior_generators import SSDAnchorGenerator + featmap_sizes = [(38, 38), (19, 19), (10, 10)] + anchor_generator = SSDAnchorGenerator( + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32], + ratios=[[2], [2, 3], [2, 3]]) + ssd_anchors = anchor_generator.grid_anchors(featmap_sizes, device='cpu') + for i in range(len(featmap_sizes)): + sparse_ssd_anchors = anchor_generator.sparse_priors( + prior_idxs=prior_indexs, + level_idx=i, + featmap_size=featmap_sizes[i], + device='cpu') + assert (sparse_ssd_anchors == ssd_anchors[i][prior_indexs]).all() + + # for yolo + from mmdet.models.task_modules.prior_generators import YOLOAnchorGenerator + featmap_sizes = [(38, 38), (19, 19), (10, 10)] + anchor_generator = YOLOAnchorGenerator( + strides=[32, 16, 8], + base_sizes=[ + [(116, 90), (156, 198), (373, 326)], + [(30, 61), (62, 45), (59, 119)], + [(10, 13), (16, 30), (33, 23)], + ]) + yolo_anchors = anchor_generator.grid_anchors(featmap_sizes, device='cpu') + for i in range(len(featmap_sizes)): + sparse_yolo_anchors = anchor_generator.sparse_priors( + prior_idxs=prior_indexs, + level_idx=i, + featmap_size=featmap_sizes[i], + device='cpu') + assert (sparse_yolo_anchors == yolo_anchors[i][prior_indexs]).all() + + if torch.cuda.is_available(): + mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0) + prior_indexs = torch.Tensor([0, 3, 4, 5, 6, 7, 1, 2, 4, 5, 6, + 9]).long().cuda() + + featmap_sizes = [(6, 8), (6, 4)] + grid_anchors = mlvl_points.grid_priors( + featmap_sizes=featmap_sizes, with_stride=False, device='cuda') + sparse_prior = mlvl_points.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[0], + level_idx=0, + device='cuda') + assert (sparse_prior == grid_anchors[0][prior_indexs]).all() + sparse_prior = mlvl_points.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[1], + level_idx=1, + device='cuda') + assert (sparse_prior == grid_anchors[1][prior_indexs]).all() + assert sparse_prior.is_cuda + mlvl_anchors = AnchorGenerator( + strides=[16, 32], + ratios=[1., 2.5], + scales=[1., 5.], + base_sizes=[4, 8]) + prior_indexs = torch.Tensor([4, 5, 6, 7, 0, 2, 50, 4, 5, 6, + 9]).long().cuda() + + featmap_sizes = [(13, 5), (16, 4)] + grid_anchors = mlvl_anchors.grid_priors( + featmap_sizes=featmap_sizes, device='cuda') + sparse_prior = mlvl_anchors.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[0], + level_idx=0, + device='cuda') + assert (sparse_prior == grid_anchors[0][prior_indexs]).all() + sparse_prior = mlvl_anchors.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[1], + level_idx=1, + device='cuda') + assert (sparse_prior == grid_anchors[1][prior_indexs]).all() + + # for ssd + from mmdet.models.task_modules.prior_generators import \ + SSDAnchorGenerator + featmap_sizes = [(38, 38), (19, 19), (10, 10)] + anchor_generator = SSDAnchorGenerator( + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32], + ratios=[[2], [2, 3], [2, 3]]) + ssd_anchors = anchor_generator.grid_anchors( + featmap_sizes, device='cuda') + for i in range(len(featmap_sizes)): + sparse_ssd_anchors = anchor_generator.sparse_priors( + prior_idxs=prior_indexs, + level_idx=i, + featmap_size=featmap_sizes[i], + device='cuda') + assert (sparse_ssd_anchors == ssd_anchors[i][prior_indexs]).all() + + # for yolo + from mmdet.models.task_modules.prior_generators import \ + YOLOAnchorGenerator + featmap_sizes = [(38, 38), (19, 19), (10, 10)] + anchor_generator = YOLOAnchorGenerator( + strides=[32, 16, 8], + base_sizes=[ + [(116, 90), (156, 198), (373, 326)], + [(30, 61), (62, 45), (59, 119)], + [(10, 13), (16, 30), (33, 23)], + ]) + yolo_anchors = anchor_generator.grid_anchors( + featmap_sizes, device='cuda') + for i in range(len(featmap_sizes)): + sparse_yolo_anchors = anchor_generator.sparse_priors( + prior_idxs=prior_indexs, + level_idx=i, + featmap_size=featmap_sizes[i], + device='cuda') + assert (sparse_yolo_anchors == yolo_anchors[i][prior_indexs]).all() + + +def test_standard_anchor_generator(): + from mmdet.models.task_modules import build_anchor_generator + anchor_generator_cfg = dict( + type='AnchorGenerator', + scales=[8], + ratios=[0.5, 1.0, 2.0], + strides=[4, 8]) + + anchor_generator = build_anchor_generator(anchor_generator_cfg) + assert anchor_generator.num_base_priors == \ + anchor_generator.num_base_anchors + assert anchor_generator.num_base_priors == [3, 3] + assert anchor_generator is not None + + +def test_strides(): + from mmdet.models.task_modules.prior_generators import AnchorGenerator + + # Square strides + self = AnchorGenerator([10], [1.], [1.], [10]) + anchors = self.grid_anchors([(2, 2)], device='cpu') + + expected_anchors = torch.tensor([[-5., -5., 5., 5.], [5., -5., 15., 5.], + [-5., 5., 5., 15.], [5., 5., 15., 15.]]) + + assert torch.equal(anchors[0], expected_anchors) + + # Different strides in x and y direction + self = AnchorGenerator([(10, 20)], [1.], [1.], [10]) + anchors = self.grid_anchors([(2, 2)], device='cpu') + + expected_anchors = torch.tensor([[-5., -5., 5., 5.], [5., -5., 15., 5.], + [-5., 15., 5., 25.], [5., 15., 15., 25.]]) + + assert torch.equal(anchors[0], expected_anchors) + + +def test_ssd_anchor_generator(): + from mmdet.models.task_modules import build_anchor_generator + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + + # min_sizes max_sizes must set at the same time + with pytest.raises(AssertionError): + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + min_sizes=[48, 100, 150, 202, 253, 300], + max_sizes=None, + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + build_anchor_generator(anchor_generator_cfg) + + # length of min_sizes max_sizes must be the same + with pytest.raises(AssertionError): + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + min_sizes=[48, 100, 150, 202, 253, 300], + max_sizes=[100, 150, 202, 253], + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + build_anchor_generator(anchor_generator_cfg) + + # test setting anchor size manually + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + min_sizes=[48, 100, 150, 202, 253, 304], + max_sizes=[100, 150, 202, 253, 304, 320], + strides=[16, 32, 64, 107, 160, 320], + ratios=[[2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3]]) + + featmap_sizes = [(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)] + anchor_generator = build_anchor_generator(anchor_generator_cfg) + + expected_base_anchors = [ + torch.Tensor([[-16.0000, -16.0000, 32.0000, 32.0000], + [-26.6410, -26.6410, 42.6410, 42.6410], + [-25.9411, -8.9706, 41.9411, 24.9706], + [-8.9706, -25.9411, 24.9706, 41.9411], + [-33.5692, -5.8564, 49.5692, 21.8564], + [-5.8564, -33.5692, 21.8564, 49.5692]]), + torch.Tensor([[-34.0000, -34.0000, 66.0000, 66.0000], + [-45.2372, -45.2372, 77.2372, 77.2372], + [-54.7107, -19.3553, 86.7107, 51.3553], + [-19.3553, -54.7107, 51.3553, 86.7107], + [-70.6025, -12.8675, 102.6025, 44.8675], + [-12.8675, -70.6025, 44.8675, 102.6025]]), + torch.Tensor([[-43.0000, -43.0000, 107.0000, 107.0000], + [-55.0345, -55.0345, 119.0345, 119.0345], + [-74.0660, -21.0330, 138.0660, 85.0330], + [-21.0330, -74.0660, 85.0330, 138.0660], + [-97.9038, -11.3013, 161.9038, 75.3013], + [-11.3013, -97.9038, 75.3013, 161.9038]]), + torch.Tensor([[-47.5000, -47.5000, 154.5000, 154.5000], + [-59.5332, -59.5332, 166.5332, 166.5332], + [-89.3356, -17.9178, 196.3356, 124.9178], + [-17.9178, -89.3356, 124.9178, 196.3356], + [-121.4371, -4.8124, 228.4371, 111.8124], + [-4.8124, -121.4371, 111.8124, 228.4371]]), + torch.Tensor([[-46.5000, -46.5000, 206.5000, 206.5000], + [-58.6651, -58.6651, 218.6651, 218.6651], + [-98.8980, -9.4490, 258.8980, 169.4490], + [-9.4490, -98.8980, 169.4490, 258.8980], + [-139.1044, 6.9652, 299.1044, 153.0348], + [6.9652, -139.1044, 153.0348, 299.1044]]), + torch.Tensor([[8.0000, 8.0000, 312.0000, 312.0000], + [4.0513, 4.0513, 315.9487, 315.9487], + [-54.9605, 52.5198, 374.9604, 267.4802], + [52.5198, -54.9605, 267.4802, 374.9604], + [-103.2717, 72.2428, 423.2717, 247.7572], + [72.2428, -103.2717, 247.7572, 423.2717]]) + ] + + base_anchors = anchor_generator.base_anchors + for i, base_anchor in enumerate(base_anchors): + assert base_anchor.allclose(expected_base_anchors[i]) + + # check valid flags + expected_valid_pixels = [2400, 600, 150, 54, 24, 6] + multi_level_valid_flags = anchor_generator.valid_flags( + featmap_sizes, (320, 320), device) + for i, single_level_valid_flag in enumerate(multi_level_valid_flags): + assert single_level_valid_flag.sum() == expected_valid_pixels[i] + + # check number of base anchors for each level + assert anchor_generator.num_base_anchors == [6, 6, 6, 6, 6, 6] + + # check anchor generation + anchors = anchor_generator.grid_anchors(featmap_sizes, device) + assert len(anchors) == 6 + + # test vgg ssd anchor setting + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + + featmap_sizes = [(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)] + anchor_generator = build_anchor_generator(anchor_generator_cfg) + + # check base anchors + expected_base_anchors = [ + torch.Tensor([[-6.5000, -6.5000, 14.5000, 14.5000], + [-11.3704, -11.3704, 19.3704, 19.3704], + [-10.8492, -3.4246, 18.8492, 11.4246], + [-3.4246, -10.8492, 11.4246, 18.8492]]), + torch.Tensor([[-14.5000, -14.5000, 30.5000, 30.5000], + [-25.3729, -25.3729, 41.3729, 41.3729], + [-23.8198, -7.9099, 39.8198, 23.9099], + [-7.9099, -23.8198, 23.9099, 39.8198], + [-30.9711, -4.9904, 46.9711, 20.9904], + [-4.9904, -30.9711, 20.9904, 46.9711]]), + torch.Tensor([[-33.5000, -33.5000, 65.5000, 65.5000], + [-45.5366, -45.5366, 77.5366, 77.5366], + [-54.0036, -19.0018, 86.0036, 51.0018], + [-19.0018, -54.0036, 51.0018, 86.0036], + [-69.7365, -12.5788, 101.7365, 44.5788], + [-12.5788, -69.7365, 44.5788, 101.7365]]), + torch.Tensor([[-44.5000, -44.5000, 108.5000, 108.5000], + [-56.9817, -56.9817, 120.9817, 120.9817], + [-76.1873, -22.0937, 140.1873, 86.0937], + [-22.0937, -76.1873, 86.0937, 140.1873], + [-100.5019, -12.1673, 164.5019, 76.1673], + [-12.1673, -100.5019, 76.1673, 164.5019]]), + torch.Tensor([[-53.5000, -53.5000, 153.5000, 153.5000], + [-66.2185, -66.2185, 166.2185, 166.2185], + [-96.3711, -23.1855, 196.3711, 123.1855], + [-23.1855, -96.3711, 123.1855, 196.3711]]), + torch.Tensor([[19.5000, 19.5000, 280.5000, 280.5000], + [6.6342, 6.6342, 293.3658, 293.3658], + [-34.5549, 57.7226, 334.5549, 242.2774], + [57.7226, -34.5549, 242.2774, 334.5549]]), + ] + base_anchors = anchor_generator.base_anchors + for i, base_anchor in enumerate(base_anchors): + assert base_anchor.allclose(expected_base_anchors[i]) + + # check valid flags + expected_valid_pixels = [5776, 2166, 600, 150, 36, 4] + multi_level_valid_flags = anchor_generator.valid_flags( + featmap_sizes, (300, 300), device) + for i, single_level_valid_flag in enumerate(multi_level_valid_flags): + assert single_level_valid_flag.sum() == expected_valid_pixels[i] + + # check number of base anchors for each level + assert anchor_generator.num_base_anchors == [4, 6, 6, 6, 4, 4] + + # check anchor generation + anchors = anchor_generator.grid_anchors(featmap_sizes, device) + assert len(anchors) == 6 + + +def test_anchor_generator_with_tuples(): + from mmdet.models.task_modules import build_anchor_generator + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + + featmap_sizes = [(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)] + anchor_generator = build_anchor_generator(anchor_generator_cfg) + anchors = anchor_generator.grid_anchors(featmap_sizes, device) + + anchor_generator_cfg_tuples = dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[(8, 8), (16, 16), (32, 32), (64, 64), (100, 100), (300, 300)], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + + anchor_generator_tuples = build_anchor_generator( + anchor_generator_cfg_tuples) + anchors_tuples = anchor_generator_tuples.grid_anchors( + featmap_sizes, device) + for anchor, anchor_tuples in zip(anchors, anchors_tuples): + assert torch.equal(anchor, anchor_tuples) + + +def test_yolo_anchor_generator(): + from mmdet.models.task_modules import build_anchor_generator + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + + anchor_generator_cfg = dict( + type='YOLOAnchorGenerator', + strides=[32, 16, 8], + base_sizes=[ + [(116, 90), (156, 198), (373, 326)], + [(30, 61), (62, 45), (59, 119)], + [(10, 13), (16, 30), (33, 23)], + ]) + + featmap_sizes = [(14, 18), (28, 36), (56, 72)] + anchor_generator = build_anchor_generator(anchor_generator_cfg) + + # check base anchors + expected_base_anchors = [ + torch.Tensor([[-42.0000, -29.0000, 74.0000, 61.0000], + [-62.0000, -83.0000, 94.0000, 115.0000], + [-170.5000, -147.0000, 202.5000, 179.0000]]), + torch.Tensor([[-7.0000, -22.5000, 23.0000, 38.5000], + [-23.0000, -14.5000, 39.0000, 30.5000], + [-21.5000, -51.5000, 37.5000, 67.5000]]), + torch.Tensor([[-1.0000, -2.5000, 9.0000, 10.5000], + [-4.0000, -11.0000, 12.0000, 19.0000], + [-12.5000, -7.5000, 20.5000, 15.5000]]) + ] + base_anchors = anchor_generator.base_anchors + for i, base_anchor in enumerate(base_anchors): + assert base_anchor.allclose(expected_base_anchors[i]) + + # check number of base anchors for each level + assert anchor_generator.num_base_anchors == [3, 3, 3] + + # check anchor generation + anchors = anchor_generator.grid_anchors(featmap_sizes, device) + assert len(anchors) == 3 + + +def test_retina_anchor(): + from mmdet.registry import MODELS + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + + # head configs modified from + # configs/nas_fpn/retinanet_r50_fpn_crop640_50e.py + bbox_head = dict( + type='RetinaSepBNHead', + num_classes=4, + num_ins=5, + in_channels=4, + stacked_convs=1, + feat_channels=4, + anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0])) + + retina_head = MODELS.build(bbox_head) + assert retina_head.anchor_generator is not None + + # use the featmap sizes in NASFPN setting to test retina head + featmap_sizes = [(80, 80), (40, 40), (20, 20), (10, 10), (5, 5)] + # check base anchors + expected_base_anchors = [ + torch.Tensor([[-22.6274, -11.3137, 22.6274, 11.3137], + [-28.5088, -14.2544, 28.5088, 14.2544], + [-35.9188, -17.9594, 35.9188, 17.9594], + [-16.0000, -16.0000, 16.0000, 16.0000], + [-20.1587, -20.1587, 20.1587, 20.1587], + [-25.3984, -25.3984, 25.3984, 25.3984], + [-11.3137, -22.6274, 11.3137, 22.6274], + [-14.2544, -28.5088, 14.2544, 28.5088], + [-17.9594, -35.9188, 17.9594, 35.9188]]), + torch.Tensor([[-45.2548, -22.6274, 45.2548, 22.6274], + [-57.0175, -28.5088, 57.0175, 28.5088], + [-71.8376, -35.9188, 71.8376, 35.9188], + [-32.0000, -32.0000, 32.0000, 32.0000], + [-40.3175, -40.3175, 40.3175, 40.3175], + [-50.7968, -50.7968, 50.7968, 50.7968], + [-22.6274, -45.2548, 22.6274, 45.2548], + [-28.5088, -57.0175, 28.5088, 57.0175], + [-35.9188, -71.8376, 35.9188, 71.8376]]), + torch.Tensor([[-90.5097, -45.2548, 90.5097, 45.2548], + [-114.0350, -57.0175, 114.0350, 57.0175], + [-143.6751, -71.8376, 143.6751, 71.8376], + [-64.0000, -64.0000, 64.0000, 64.0000], + [-80.6349, -80.6349, 80.6349, 80.6349], + [-101.5937, -101.5937, 101.5937, 101.5937], + [-45.2548, -90.5097, 45.2548, 90.5097], + [-57.0175, -114.0350, 57.0175, 114.0350], + [-71.8376, -143.6751, 71.8376, 143.6751]]), + torch.Tensor([[-181.0193, -90.5097, 181.0193, 90.5097], + [-228.0701, -114.0350, 228.0701, 114.0350], + [-287.3503, -143.6751, 287.3503, 143.6751], + [-128.0000, -128.0000, 128.0000, 128.0000], + [-161.2699, -161.2699, 161.2699, 161.2699], + [-203.1873, -203.1873, 203.1873, 203.1873], + [-90.5097, -181.0193, 90.5097, 181.0193], + [-114.0350, -228.0701, 114.0350, 228.0701], + [-143.6751, -287.3503, 143.6751, 287.3503]]), + torch.Tensor([[-362.0387, -181.0193, 362.0387, 181.0193], + [-456.1401, -228.0701, 456.1401, 228.0701], + [-574.7006, -287.3503, 574.7006, 287.3503], + [-256.0000, -256.0000, 256.0000, 256.0000], + [-322.5398, -322.5398, 322.5398, 322.5398], + [-406.3747, -406.3747, 406.3747, 406.3747], + [-181.0193, -362.0387, 181.0193, 362.0387], + [-228.0701, -456.1401, 228.0701, 456.1401], + [-287.3503, -574.7006, 287.3503, 574.7006]]) + ] + base_anchors = retina_head.anchor_generator.base_anchors + for i, base_anchor in enumerate(base_anchors): + assert base_anchor.allclose(expected_base_anchors[i]) + + # check valid flags + expected_valid_pixels = [57600, 14400, 3600, 900, 225] + multi_level_valid_flags = retina_head.anchor_generator.valid_flags( + featmap_sizes, (640, 640), device) + for i, single_level_valid_flag in enumerate(multi_level_valid_flags): + assert single_level_valid_flag.sum() == expected_valid_pixels[i] + + # check number of base anchors for each level + assert retina_head.anchor_generator.num_base_anchors == [9, 9, 9, 9, 9] + + # check anchor generation + anchors = retina_head.anchor_generator.grid_anchors(featmap_sizes, device) + assert len(anchors) == 5 + + +def test_guided_anchor(): + from mmdet.registry import MODELS + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + # head configs modified from + # configs/guided_anchoring/ga-retinanet_r50_fpn_1x_coco.py + bbox_head = dict( + type='GARetinaHead', + num_classes=8, + in_channels=4, + stacked_convs=1, + feat_channels=4, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[4], + strides=[8, 16, 32, 64, 128])) + + ga_retina_head = MODELS.build(bbox_head) + assert ga_retina_head.approx_anchor_generator is not None + + # use the featmap sizes in NASFPN setting to test ga_retina_head + featmap_sizes = [(100, 152), (50, 76), (25, 38), (13, 19), (7, 10)] + # check base anchors + expected_approxs = [ + torch.Tensor([[-22.6274, -11.3137, 22.6274, 11.3137], + [-28.5088, -14.2544, 28.5088, 14.2544], + [-35.9188, -17.9594, 35.9188, 17.9594], + [-16.0000, -16.0000, 16.0000, 16.0000], + [-20.1587, -20.1587, 20.1587, 20.1587], + [-25.3984, -25.3984, 25.3984, 25.3984], + [-11.3137, -22.6274, 11.3137, 22.6274], + [-14.2544, -28.5088, 14.2544, 28.5088], + [-17.9594, -35.9188, 17.9594, 35.9188]]), + torch.Tensor([[-45.2548, -22.6274, 45.2548, 22.6274], + [-57.0175, -28.5088, 57.0175, 28.5088], + [-71.8376, -35.9188, 71.8376, 35.9188], + [-32.0000, -32.0000, 32.0000, 32.0000], + [-40.3175, -40.3175, 40.3175, 40.3175], + [-50.7968, -50.7968, 50.7968, 50.7968], + [-22.6274, -45.2548, 22.6274, 45.2548], + [-28.5088, -57.0175, 28.5088, 57.0175], + [-35.9188, -71.8376, 35.9188, 71.8376]]), + torch.Tensor([[-90.5097, -45.2548, 90.5097, 45.2548], + [-114.0350, -57.0175, 114.0350, 57.0175], + [-143.6751, -71.8376, 143.6751, 71.8376], + [-64.0000, -64.0000, 64.0000, 64.0000], + [-80.6349, -80.6349, 80.6349, 80.6349], + [-101.5937, -101.5937, 101.5937, 101.5937], + [-45.2548, -90.5097, 45.2548, 90.5097], + [-57.0175, -114.0350, 57.0175, 114.0350], + [-71.8376, -143.6751, 71.8376, 143.6751]]), + torch.Tensor([[-181.0193, -90.5097, 181.0193, 90.5097], + [-228.0701, -114.0350, 228.0701, 114.0350], + [-287.3503, -143.6751, 287.3503, 143.6751], + [-128.0000, -128.0000, 128.0000, 128.0000], + [-161.2699, -161.2699, 161.2699, 161.2699], + [-203.1873, -203.1873, 203.1873, 203.1873], + [-90.5097, -181.0193, 90.5097, 181.0193], + [-114.0350, -228.0701, 114.0350, 228.0701], + [-143.6751, -287.3503, 143.6751, 287.3503]]), + torch.Tensor([[-362.0387, -181.0193, 362.0387, 181.0193], + [-456.1401, -228.0701, 456.1401, 228.0701], + [-574.7006, -287.3503, 574.7006, 287.3503], + [-256.0000, -256.0000, 256.0000, 256.0000], + [-322.5398, -322.5398, 322.5398, 322.5398], + [-406.3747, -406.3747, 406.3747, 406.3747], + [-181.0193, -362.0387, 181.0193, 362.0387], + [-228.0701, -456.1401, 228.0701, 456.1401], + [-287.3503, -574.7006, 287.3503, 574.7006]]) + ] + approxs = ga_retina_head.approx_anchor_generator.base_anchors + for i, base_anchor in enumerate(approxs): + assert base_anchor.allclose(expected_approxs[i]) + + # check valid flags + expected_valid_pixels = [136800, 34200, 8550, 2223, 630] + multi_level_valid_flags = ga_retina_head.approx_anchor_generator \ + .valid_flags(featmap_sizes, (800, 1216), device) + for i, single_level_valid_flag in enumerate(multi_level_valid_flags): + assert single_level_valid_flag.sum() == expected_valid_pixels[i] + + # check number of base anchors for each level + assert ga_retina_head.approx_anchor_generator.num_base_anchors == [ + 9, 9, 9, 9, 9 + ] + + # check approx generation + squares = ga_retina_head.square_anchor_generator.grid_anchors( + featmap_sizes, device) + assert len(squares) == 5 + + expected_squares = [ + torch.Tensor([[-16., -16., 16., 16.]]), + torch.Tensor([[-32., -32., 32., 32]]), + torch.Tensor([[-64., -64., 64., 64.]]), + torch.Tensor([[-128., -128., 128., 128.]]), + torch.Tensor([[-256., -256., 256., 256.]]) + ] + squares = ga_retina_head.square_anchor_generator.base_anchors + for i, base_anchor in enumerate(squares): + assert base_anchor.allclose(expected_squares[i]) + + # square_anchor_generator does not check valid flags + # check number of base anchors for each level + assert (ga_retina_head.square_anchor_generator.num_base_anchors == [ + 1, 1, 1, 1, 1 + ]) + + # check square generation + anchors = ga_retina_head.square_anchor_generator.grid_anchors( + featmap_sizes, device) + assert len(anchors) == 5 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_samplers/test_pesudo_sampler.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_samplers/test_pesudo_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..cd428decc5ffaa735ad55f9c11b0cb24b25f76ca --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_samplers/test_pesudo_sampler.py @@ -0,0 +1 @@ +# TODO: follow up diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_aflink.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_aflink.py new file mode 100644 index 0000000000000000000000000000000000000000..51df13a2ab146c3057524326ab7313bfd12a319f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_aflink.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +from mmengine.registry import init_default_scope +from torch import nn + +from mmdet.registry import TASK_UTILS + + +class TestAppearanceFreeLink(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + cls.cfg = dict( + type='AppearanceFreeLink', + checkpoint='', + temporal_threshold=(0, 30), + spatial_threshold=75, + confidence_threshold=0.95, + ) + + def test_init(self): + aflink = TASK_UTILS.build(self.cfg) + assert aflink.temporal_threshold == (0, 30) + assert aflink.spatial_threshold == 75 + assert aflink.confidence_threshold == 0.95 + assert isinstance(aflink.model, nn.Module) + + def test_forward(self): + pred_track = np.random.randn(10, 7) + aflink = TASK_UTILS.build(self.cfg) + linked_track = aflink.forward(pred_track) + assert isinstance(linked_track, np.ndarray) + assert linked_track.shape == (10, 7) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_interpolation.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..413aa2c396bb2ab8275625813b59b51603ca5540 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_interpolation.py @@ -0,0 +1,39 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +from mmengine.registry import init_default_scope + +from mmdet.registry import TASK_UTILS + + +class TestInterpolateTracklets(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + cls.cfg = dict( + type='InterpolateTracklets', + min_num_frames=5, + max_num_frames=20, + use_gsi=True, + smooth_tau=10) + + def test_init(self): + interpolation = TASK_UTILS.build(self.cfg) + assert interpolation.min_num_frames == 5 + assert interpolation.max_num_frames == 20 + assert interpolation.use_gsi + assert interpolation.smooth_tau == 10 + + def test_forward(self): + pred_track = np.random.randn(5, 7) + + # set frame_id and target_id + pred_track[:, 0] = np.array([1, 2, 5, 6, 7]) + pred_track[:, 1] = 1 + + interpolation = TASK_UTILS.build(self.cfg) + linked_track = interpolation.forward(pred_track) + assert isinstance(linked_track, np.ndarray) + assert linked_track.shape == (5, 7) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_kalman_filter.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_kalman_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..a7344757e2f813ddc35f29a3605e87229999ea17 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_kalman_filter.py @@ -0,0 +1,37 @@ +from unittest import TestCase + +import numpy as np +from mmengine.registry import init_default_scope + +from mmdet.registry import TASK_UTILS + + +class TestKalmanFilter(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + motion = dict(type='KalmanFilter', ) + cls.kf = TASK_UTILS.build(motion) + + def test_init(self): + pred_det = np.random.randn(4) + mean, covariance = self.kf.initiate(pred_det) + assert len(mean) == 8 + assert covariance.shape == (8, 8) + + def test_predict(self): + mean = np.random.randn(8) + covariance = np.random.randn(8, 8) + mean, covariance = self.kf.predict(mean, covariance) + assert len(mean) == 8 + assert covariance.shape == (8, 8) + + def test_update(self): + mean = np.ones(8) + covariance = np.ones((8, 8)) + measurement = np.ones(4) + score = 0.1 + mean, covariance = self.kf.update(mean, covariance, measurement, score) + assert len(mean) == 8 + assert covariance.shape == (8, 8) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_similarity.py b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..8364ca503efeb583fdf4573efef86e6d0227310e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_task_modules/test_track/test_similarity.py @@ -0,0 +1,10 @@ +import torch + +from mmdet.models.task_modules import embed_similarity + + +def test_embed_similarity(): + """Test embed similarity.""" + embeds = torch.rand(2, 3) + similarity = embed_similarity(embeds, embeds) + assert similarity.shape == (2, 2) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_byte_tracker.py b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_byte_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..c26ec9703d97758fb61f0ba9742cefa534d81f3b --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_byte_tracker.py @@ -0,0 +1,65 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.testing import demo_track_inputs, random_boxes +from mmdet.utils import register_all_modules + + +class TestByteTracker(TestCase): + + @classmethod + def setUpClass(cls): + register_all_modules(init_default_scope=True) + cfg = dict( + type='ByteTracker', + motion=dict(type='KalmanFilter'), + obj_score_thrs=dict(high=0.6, low=0.1), + init_track_thr=0.7, + weight_iou_with_det_scores=True, + match_iou_thrs=dict(high=0.1, low=0.5, tentative=0.3), + num_tentatives=3, + num_frames_retain=30) + cls.tracker = MODELS.build(cfg) + cls.tracker.kf = TASK_UTILS.build(dict(type='KalmanFilter')) + cls.num_frames_retain = cfg['num_frames_retain'] + cls.num_objs = 30 + + def test_init(self): + bboxes = random_boxes(self.num_objs, 512) + labels = torch.zeros(self.num_objs) + scores = torch.ones(self.num_objs) + ids = torch.arange(self.num_objs) + self.tracker.update( + ids=ids, bboxes=bboxes, scores=scores, labels=labels, frame_ids=0) + + assert self.tracker.ids == list(ids) + assert self.tracker.memo_items == [ + 'ids', 'bboxes', 'scores', 'labels', 'frame_ids' + ] + + def test_track(self): + + with torch.no_grad(): + packed_inputs = demo_track_inputs(batch_size=1, num_frames=2) + track_data_sample = packed_inputs['data_samples'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.gt_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor( + scores) + + pred_track_instances = self.tracker.track( + data_sample=img_data_sample) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] diff --git a/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_masktrack_rcnn_tracker.py b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_masktrack_rcnn_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..38648d1e75bd618aba65128833e10345b50415b2 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_masktrack_rcnn_tracker.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg, random_boxes + + +class TestMaskTrackRCNNTracker(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + tracker_cfg = dict( + type='MaskTrackRCNNTracker', + match_weights=dict(det_score=1.0, iou=2.0, det_label=10.0), + num_frames_retain=20) + cls.tracker = MODELS.build(tracker_cfg) + cls.num_objs = 5 + + def test_get_match_score(self): + bboxes = random_boxes(self.num_objs, 64) + labels = torch.arange(self.num_objs) + scores = torch.arange(self.num_objs, dtype=torch.float32) + similarity_logits = torch.randn(self.num_objs, self.num_objs + 1) + + match_score = self.tracker.get_match_score(bboxes, labels, scores, + bboxes, labels, + similarity_logits) + assert match_score.size() == similarity_logits.size() + + @parameterized.expand([ + 'masktrack_rcnn/masktrack-rcnn_mask-rcnn_r50_fpn_8xb1-12e_youtubevis2019.py' # noqa: E501 + ]) + def test_track(self, cfg_file): + _model = get_detector_cfg(cfg_file) + # _scope_ will be popped after build + model = MODELS.build(_model) + + packed_inputs = demo_track_inputs( + batch_size=1, num_frames=2, with_mask=True) + track_data_sample = packed_inputs['data_samples'][0] + imgs = packed_inputs['inputs'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + single_image = imgs[frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.pred_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor(scores) + feats = [] + for i in range( + len(model.track_head.roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, 256 // (2**(i + 2)), + 256 // (2**(i + 2))).to(device='cpu')) + pred_track_instances = self.tracker.track( + model=model, + img=single_image, + feats=tuple(feats), + data_sample=img_data_sample) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + ids = pred_track_instances.instances_id + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] + assert bboxes.shape[0] == ids.shape[0] diff --git a/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_oc_sort_tracker.py b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_oc_sort_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..d24b801da30086cf29f62eed1b8574a036174abd --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_oc_sort_tracker.py @@ -0,0 +1,54 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.testing import demo_track_inputs +from mmdet.utils import register_all_modules + + +class TestByteTracker(TestCase): + + @classmethod + def setUpClass(cls): + register_all_modules(init_default_scope=True) + cfg = dict( + type='OCSORTTracker', + motion=dict(type='KalmanFilter'), + obj_score_thr=0.3, + init_track_thr=0.7, + weight_iou_with_det_scores=True, + match_iou_thr=0.3, + num_tentatives=3, + vel_consist_weight=0.2, + vel_delta_t=3, + num_frames_retain=30) + cls.tracker = MODELS.build(cfg) + cls.tracker.kf = TASK_UTILS.build(dict(type='KalmanFilter')) + cls.num_frames_retain = cfg['num_frames_retain'] + cls.num_objs = 30 + + def test_track(self): + + with torch.no_grad(): + packed_inputs = demo_track_inputs(batch_size=1, num_frames=2) + track_data_sample = packed_inputs['data_samples'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.gt_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor( + scores) + + pred_track_instances = self.tracker.track( + data_sample=img_data_sample) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] diff --git a/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_sort_tracker.py b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_sort_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..14562aa1069464c0986ba09ffa9187c62fbfc0d1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_sort_tracker.py @@ -0,0 +1,82 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import MagicMock + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.testing import demo_track_inputs, get_detector_cfg, random_boxes +from mmdet.utils import register_all_modules + + +class TestSORTTracker(TestCase): + + @classmethod + def setUpClass(cls): + register_all_modules(init_default_scope=True) + cls.num_objs = 30 + + @parameterized.expand([ + 'deepsort/deepsort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + cfg = get_detector_cfg(cfg_file) + tracker = MODELS.build(cfg['tracker']) + tracker.kf = TASK_UTILS.build(cfg['tracker']['motion']) + + bboxes = random_boxes(self.num_objs, 512) + labels = torch.zeros(self.num_objs) + scores = torch.ones(self.num_objs) + ids = torch.arange(self.num_objs) + tracker.update( + ids=ids, bboxes=bboxes, scores=scores, labels=labels, frame_ids=0) + + assert tracker.ids == list(ids) + assert tracker.memo_items == [ + 'ids', 'bboxes', 'scores', 'labels', 'frame_ids' + ] + + @parameterized.expand([ + 'deepsort/deepsort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py' + ]) + def test_track(self, cfg_file): + imgs = torch.rand((1, 2, 3, 128, 128)) + + cfg = get_detector_cfg(cfg_file) + tracker = MODELS.build(cfg['tracker']) + tracker.kf = TASK_UTILS.build(cfg['tracker']['motion']) + + model = MagicMock() + model.reid = MODELS.build(cfg['reid']) + + with torch.no_grad(): + packed_inputs = demo_track_inputs(batch_size=1, num_frames=2) + track_data_sample = packed_inputs['data_samples'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + single_img = imgs[:, frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.gt_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor( + scores) + + pred_track_instances = tracker.track( + model=model, + img=single_img, + feats=None, + data_sample=img_data_sample, + data_preprocessor=cfg['data_preprocessor']) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + ids = pred_track_instances.instances_id + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] + assert bboxes.shape[0] == ids.shape[0] diff --git a/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_strong_sort_tracker.py b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_strong_sort_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..adef04407bc8afc20ae210dcedd1c66912860b59 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_trackers/test_strong_sort_tracker.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import MagicMock + +import torch +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.testing import demo_track_inputs, get_detector_cfg, random_boxes + + +class TestStrongSORTTracker(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + cls.num_objs = 30 + + @parameterized.expand([ + 'strongsort/strongsort_yolox_x_8xb4-80e_crowdhuman-mot17halftrain' + '_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + cfg = get_detector_cfg(cfg_file) + tracker = MODELS.build(cfg['tracker']) + tracker.kf = TASK_UTILS.build(cfg['tracker']['motion']) + tracker.cmc = TASK_UTILS.build(cfg['cmc']) + + bboxes = random_boxes(self.num_objs, 512) + labels = torch.zeros(self.num_objs) + scores = torch.ones(self.num_objs) + ids = torch.arange(self.num_objs) + tracker.update( + ids=ids, bboxes=bboxes, scores=scores, labels=labels, frame_ids=0) + + assert tracker.ids == list(ids) + assert tracker.memo_items == [ + 'ids', 'bboxes', 'scores', 'labels', 'frame_ids' + ] + + @parameterized.expand([ + 'strongsort/strongsort_yolox_x_8xb4-80e_crowdhuman-mot17halftrain' + '_test-mot17halfval.py' + ]) + def test_track(self, cfg_file): + img = torch.rand((1, 3, 128, 128)) + + cfg = get_detector_cfg(cfg_file) + tracker = MODELS.build(cfg['tracker']) + tracker.kf = TASK_UTILS.build(cfg['tracker']['motion']) + + model = MagicMock() + model.reid = MODELS.build(cfg['reid']) + model.cmc = TASK_UTILS.build(cfg['cmc']) + + with torch.no_grad(): + packed_inputs = demo_track_inputs(batch_size=1, num_frames=2) + track_data_sample = packed_inputs['data_samples'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.gt_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor( + scores) + + pred_track_instances = tracker.track( + model=model, + img=img, + data_sample=img_data_sample, + data_preprocessor=cfg['data_preprocessor']) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] diff --git a/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_mask2former_track_head.py b/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_mask2former_track_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fa11c43f4bdb99c5283efe370cac7f9271372a55 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_mask2former_track_head.py @@ -0,0 +1,160 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config + +from mmdet.models.tracking_heads import Mask2FormerTrackHead +from mmdet.structures import DetDataSample, TrackDataSample +from mmdet.testing import demo_track_inputs + + +class TestMask2FormerHead(TestCase): + + @classmethod + def setUpClass(cls): + cls.config = Config( + dict( + in_channels=[256, 512, 1024, + 2048], # pass to pixel_decoder inside + strides=[4, 8, 16, 32], + feat_channels=256, + out_channels=256, + num_classes=40, + num_frames=2, + num_queries=100, + num_transformer_feat_level=3, + pixel_decoder=dict( + type='MSDeformAttnPixelDecoder', + num_outs=3, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'), + encoder=dict( + num_layers=6, + layer_cfg=dict( + self_attn_cfg=dict( + embed_dims=256, + num_heads=8, + num_levels=3, + num_points=4, + im2col_step=128, + dropout=0.0, + batch_first=True), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=1024, + num_fcs=2, + ffn_drop=0.0, + act_cfg=dict(type='ReLU', inplace=True)))), + positional_encoding=dict(num_feats=128, normalize=True)), + enforce_decoder_input_project=False, + positional_encoding=dict( + type='SinePositionalEncoding3D', + num_feats=128, + normalize=True), + transformer_decoder=dict( # Mask2FormerTransformerDecoder + return_intermediate=True, + num_layers=9, + layer_cfg=dict( # Mask2FormerTransformerDecoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.0, + batch_first=True), + cross_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.0, + batch_first=True), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + ffn_drop=0.0, + act_cfg=dict(type='ReLU', inplace=True))), + init_cfg=None), + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=2.0, + reduction='mean', + class_weight=[1.0] * 40 + [0.1]), + loss_mask=dict( + type='CrossEntropyLoss', + use_sigmoid=True, + reduction='mean', + loss_weight=5.0), + loss_dice=dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + reduction='mean', + naive_dice=True, + eps=1.0, + loss_weight=5.0), + train_cfg=dict( + num_points=12544, + oversample_ratio=3.0, + importance_sample_ratio=0.75, + assigner=dict( + type='mmdet.HungarianAssigner', + match_costs=[ + dict(type='mmdet.ClassificationCost', weight=2.0), + dict( + type='mmdet.CrossEntropyLossCost', + weight=5.0, + use_sigmoid=True), + dict( + type='mmdet.DiceCost', + weight=5.0, + pred_act=True, + eps=1.0) + ]), + sampler=dict(type='mmdet.MaskPseudoSampler')))) + + def test_mask2former_head_loss(self): + mask2former_head = Mask2FormerTrackHead(**self.config) + mask2former_head.init_weights() + s = 256 + feats = [ + torch.rand(2, 256 * (2**i), s // stride, s // stride) + for i, stride in enumerate([8, 16, 32, 64]) + ] + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=[(3, s, s)], + num_classes=2, + with_mask=True) + data_sample = packed_inputs['data_samples'][0] + loss = mask2former_head.loss(feats, [data_sample]) + # loss_cls, loss_mask and loss_dice + assert len(loss) == 30 + + def test_mask2former_head_predict(self): + mask2former_head = Mask2FormerTrackHead(**self.config) + mask2former_head.training = False + mask2former_head.init_weights() + s = 256 + # assume the video has 30 frames + feats = [ + torch.rand(30, 256 * (2**i), s // stride, s // stride) + for i, stride in enumerate([8, 16, 32, 64]) + ] + + img_metas = dict( + img_shape=(s, s), + ori_shape=(s, s), + scale_factor=(1, 1), + pad_shape=(s, s), + batch_input_shape=(s, s)) + + img_data_samples = [ + DetDataSample(metainfo=img_metas) for _ in range(30) + ] + data_sample = TrackDataSample() + data_sample.video_data_samples = img_data_samples + results = mask2former_head.predict(feats, data_sample) + + assert len(results) == 30 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_quasi_dense_embed_head.py b/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_quasi_dense_embed_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5012aa6adfeabcc4802cf67ebdf6359430ef8de9 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_quasi_dense_embed_head.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import mmengine +import torch +from mmengine.structures import InstanceData + +from mmdet.models.tracking_heads import QuasiDenseEmbedHead +from mmdet.registry import TASK_UTILS + + +def _dummy_bbox_sampling(rpn_results_list, batch_gt_instances): + """Create sample results that can be passed to Head.get_targets.""" + num_imgs = len(rpn_results_list) + feat = torch.rand(1, 1, 3, 3) + assign_config = dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.5, + ignore_iof_thr=-1) + sampler_config = dict( + type='CombinedSampler', + num=4, + pos_fraction=0.5, + neg_pos_ub=3, + add_gt_as_proposals=True, + pos_sampler=dict(type='InstanceBalancedPosSampler'), + neg_sampler=dict(type='RandomSampler')) + bbox_assigner = TASK_UTILS.build(assign_config) + bbox_sampler = TASK_UTILS.build(sampler_config) + + sampling_results = [] + for i in range(num_imgs): + assign_result = bbox_assigner.assign(rpn_results_list[i], + batch_gt_instances[i]) + sampling_result = bbox_sampler.sample( + assign_result, + rpn_results_list[i], + batch_gt_instances[i], + feats=feat) + sampling_results.append(sampling_result) + + return sampling_results + + +class TestQuasiDenseEmbedHead(TestCase): + + def test_quasi_dense_embed_head_loss(self): + cfg = mmengine.Config( + dict( + num_convs=4, + num_fcs=1, + embed_channels=256, + norm_cfg=dict(type='GN', num_groups=32), + loss_track=dict( + type='MultiPosCrossEntropyLoss', loss_weight=0.25), + loss_track_aux=dict( + type='MarginL2Loss', + neg_pos_ub=3, + pos_margin=0, + neg_margin=0.1, + hard_mining=True, + loss_weight=1.0))) + + embed_head = QuasiDenseEmbedHead(**cfg) + + key_feats = torch.rand(2, 256, 7, 7) + ref_feats = key_feats + rpn_results = InstanceData() + rpn_results.labels = torch.LongTensor([1, 2]) + rpn_results.priors = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874], + [23.6667, 23.8757, 238.6326, 151.8874]]) + rpn_results_list = [rpn_results] + + gt_instance = InstanceData() + gt_instance.labels = torch.LongTensor([1, 2]) + gt_instance.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874], + [23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instance.instances_id = torch.LongTensor([1, 2]) + batch_gt_instances = [gt_instance] + + sampling_results = _dummy_bbox_sampling(rpn_results_list, + batch_gt_instances) + gt_match_indices_list = [torch.Tensor([0, 1])] + loss_track = embed_head.loss(key_feats, ref_feats, sampling_results, + sampling_results, gt_match_indices_list) + assert loss_track['loss_track'] >= 0, 'track loss should be zero' + assert loss_track['loss_track_aux'] > 0, 'aux loss should be non-zero' + + def test_quasi_dense_embed_head_predict(self): + cfg = mmengine.Config( + dict( + num_convs=4, + num_fcs=1, + embed_channels=256, + norm_cfg=dict(type='GN', num_groups=32), + loss_track=dict( + type='MultiPosCrossEntropyLoss', loss_weight=0.25), + loss_track_aux=dict( + type='MarginL2Loss', + neg_pos_ub=3, + pos_margin=0, + neg_margin=0.1, + hard_mining=True, + loss_weight=1.0))) + + embed_head = QuasiDenseEmbedHead(**cfg) + + key_feats = torch.rand(2, 256, 7, 7) + track_feats = embed_head.predict(key_feats) + + assert isinstance(track_feats, torch.Tensor) + assert track_feats.size() == (2, 256) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_quasi_dense_track_head.py b/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_quasi_dense_track_head.py new file mode 100644 index 0000000000000000000000000000000000000000..dbce5a0ad1698a207f679ebf8a6cbfa4f37dead4 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_quasi_dense_track_head.py @@ -0,0 +1,104 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import init_default_scope +from mmengine.config import Config +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, random_boxes + + +def _fake_proposals(img_metas, proposal_len): + """Create a fake proposal list.""" + results = [] + for i in range(len(img_metas)): + result = InstanceData(metainfo=img_metas[i]) + proposal = random_boxes(proposal_len, 10).to(device='cpu') + result.bboxes = proposal + results.append(result) + return results + + +class TestQuasiDenseTrackHead(TestCase): + + def setUp(self): + init_default_scope('mmdet') + cfg = Config( + dict( + type='QuasiDenseTrackHead', + 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]), + embed_head=dict( + type='QuasiDenseEmbedHead', + num_convs=4, + num_fcs=1, + embed_channels=256, + norm_cfg=dict(type='GN', num_groups=32), + loss_track=dict( + type='MultiPosCrossEntropyLoss', loss_weight=0.25), + loss_track_aux=dict( + type='MarginL2Loss', + neg_pos_ub=3, + pos_margin=0, + neg_margin=0.1, + hard_mining=True, + loss_weight=1.0)), + loss_bbox=dict(type='L1Loss', loss_weight=1.0), + train_cfg=dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.5, + min_pos_iou=0.5, + match_low_quality=False, + ignore_iof_thr=-1), + sampler=dict( + type='CombinedSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=3, + add_gt_as_proposals=True, + pos_sampler=dict(type='InstanceBalancedPosSampler'), + neg_sampler=dict(type='RandomSampler'))))) + self.track_head = MODELS.build(cfg) + + def test_quasi_dense_track_head_loss(self): + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=[(3, 256, 256)]) + img_metas = [{ + 'img_shape': (256, 256, 3), + 'scale_factor': 1, + }] + proposal_list = _fake_proposals(img_metas, 10) + feats = [] + for i in range(len(self.track_head.roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, 256 // (2**(i + 2)), + 256 // (2**(i + 2))).to(device='cpu')) + key_feats = tuple(feats) + ref_feats = key_feats + loss_track = self.track_head.loss(key_feats, ref_feats, proposal_list, + proposal_list, + [packed_inputs['data_samples'][0]]) + assert loss_track['loss_track'] >= 0, 'track loss should be zero' + assert loss_track['loss_track_aux'] > 0, 'aux loss should be non-zero' + + def test_quasi_dense_track_head_predict(self): + feats = [] + for i in range(len(self.track_head.roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, 256 // (2**(i + 2)), + 256 // (2**(i + 2))).to(device='cpu')) + feats = tuple(feats) + track_feat = self.track_head.predict( + feats, [torch.Tensor([[10, 10, 20, 20]])]) + assert track_feat.size() == (1, 256) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_roi_embed_head.py b/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_roi_embed_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbecd158bc0b62528282555b58a0c7affc65350 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_tracking_heads/test_roi_embed_head.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import mmengine +import torch +from mmengine.structures import InstanceData + +from mmdet.models.tracking_heads import RoIEmbedHead +from mmdet.registry import TASK_UTILS + + +def _dummy_bbox_sampling(rpn_results_list, batch_gt_instances): + """Create sample results that can be passed to Head.get_targets.""" + num_imgs = len(rpn_results_list) + feat = torch.rand(1, 1, 3, 3) + assign_config = dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.5, + ignore_iof_thr=-1) + sampler_config = dict( + type='RandomSampler', + num=512, + pos_fraction=0.25, + neg_pos_ub=-1, + add_gt_as_proposals=False) + bbox_assigner = TASK_UTILS.build(assign_config) + bbox_sampler = TASK_UTILS.build(sampler_config) + + sampling_results = [] + for i in range(num_imgs): + assign_result = bbox_assigner.assign(rpn_results_list[i], + batch_gt_instances[i]) + sampling_result = bbox_sampler.sample( + assign_result, + rpn_results_list[i], + batch_gt_instances[i], + feats=feat) + sampling_results.append(sampling_result) + + return sampling_results + + +class TestRoIEmbedHead(TestCase): + + def test_roi_embed_head_loss(self): + """Test roi embed head loss when truth is non-empty.""" + cfg = mmengine.Config( + dict( + num_convs=2, + num_fcs=2, + roi_feat_size=7, + in_channels=16, + fc_out_channels=32)) + + embed_head = RoIEmbedHead(**cfg) + + x = torch.rand(1, 16, 7, 7) + ref_x = torch.rand(1, 16, 7, 7) + num_x_per_img = [1] + num_x_per_ref_img = [1] + x_split, ref_x_split = embed_head.forward(x, ref_x, num_x_per_img, + num_x_per_ref_img) + + gt_instance_ids = [torch.LongTensor([2])] + ref_gt_instance_ids = [torch.LongTensor([2])] + + rpn_results = InstanceData() + rpn_results.labels = torch.LongTensor([2]) + rpn_results.priors = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + rpn_results_list = [rpn_results] + + gt_instance = InstanceData() + gt_instance.labels = torch.LongTensor([2]) + gt_instance.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instance.instances_id = torch.LongTensor([2]) + batch_gt_instances = [gt_instance] + + sampling_results = _dummy_bbox_sampling(rpn_results_list, + batch_gt_instances) + + gt_losses = embed_head.loss_by_feat(x_split, ref_x_split, + sampling_results, gt_instance_ids, + ref_gt_instance_ids) + assert gt_losses['loss_match'] > 0, 'match loss should be non-zero' + assert gt_losses[ + 'match_accuracy'] >= 0, 'match accuracy should be non-zero or zero' + + def test_roi_embed_head_predict(self): + cfg = mmengine.Config( + dict( + num_convs=2, + num_fcs=2, + roi_feat_size=7, + in_channels=16, + fc_out_channels=32)) + + embed_head = RoIEmbedHead(**cfg) + + x = torch.rand(1, 16, 7, 7) + ref_x = torch.rand(1, 16, 7, 7) + similarity_logits = embed_head.predict(x, ref_x) + + assert isinstance(similarity_logits, list) + assert len(similarity_logits) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_tta/test_det_tta.py b/mmdet_code/SR-TOD/tests/test_models/test_tta/test_det_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..c94483c67eac5f2450c7cc5866c102aec72fa8e9 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_tta/test_det_tta.py @@ -0,0 +1,48 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import ConfigDict + +from mmdet.models import DetTTAModel +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDetTTAModel(TestCase): + + def setUp(self): + register_all_modules() + + def test_det_tta_model(self): + + detector_cfg = get_detector_cfg( + 'retinanet/retinanet_r18_fpn_1x_coco.py') + cfg = ConfigDict( + type='DetTTAModel', + module=detector_cfg, + tta_cfg=dict( + nms=dict(type='nms', iou_threshold=0.5), max_per_img=100)) + + model: DetTTAModel = MODELS.build(cfg) + + imgs = [] + data_samples = [] + directions = ['horizontal', 'vertical'] + for i in range(12): + flip_direction = directions[0] if i % 3 == 0 else directions[1] + imgs.append(torch.randn(1, 3, 100 + 10 * i, 100 + 10 * i)) + data_samples.append([ + DetDataSample( + metainfo=dict( + ori_shape=(100, 100), + img_shape=(100 + 10 * i, 100 + 10 * i), + scale_factor=((100 + 10 * i) / 100, + (100 + 10 * i) / 100), + flip=(i % 2 == 0), + flip_direction=flip_direction), ) + ]) + + model.test_step(dict(inputs=imgs, data_samples=data_samples)) diff --git a/mmdet_code/SR-TOD/tests/test_models/test_utils/test_misc.py b/mmdet_code/SR-TOD/tests/test_models/test_utils/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..2e54ff70f572b0212f607f8d9ee14ddaa5084400 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_utils/test_misc.py @@ -0,0 +1,110 @@ +import copy + +import pytest +import torch +from mmengine.structures import InstanceData + +from mmdet.models.utils import (empty_instances, filter_gt_instances, + rename_loss_dict, reweight_loss_dict, + unpack_gt_instances) +from mmdet.testing import demo_mm_inputs + + +def test_parse_gt_instance_info(): + packed_inputs = demo_mm_inputs()['data_samples'] + batch_gt_instances, batch_gt_instances_ignore, batch_img_metas \ + = unpack_gt_instances(packed_inputs) + assert len(batch_gt_instances) == len(packed_inputs) + assert len(batch_gt_instances_ignore) == len(packed_inputs) + assert len(batch_img_metas) == len(packed_inputs) + + +def test_process_empty_roi(): + batch_size = 2 + batch_img_metas = [{'ori_shape': (10, 12)}] * batch_size + device = torch.device('cpu') + + results_list = empty_instances(batch_img_metas, device, task_type='bbox') + assert len(results_list) == batch_size + for results in results_list: + assert isinstance(results, InstanceData) + assert len(results) == 0 + assert torch.allclose(results.bboxes, torch.zeros(0, 4, device=device)) + + results_list = empty_instances( + batch_img_metas, + device, + task_type='mask', + instance_results=results_list, + mask_thr_binary=0.5) + assert len(results_list) == batch_size + for results in results_list: + assert isinstance(results, InstanceData) + assert len(results) == 0 + assert results.masks.shape == (0, 10, 12) + + # batch_img_metas and instance_results length must be the same + with pytest.raises(AssertionError): + empty_instances( + batch_img_metas, + device, + task_type='mask', + instance_results=[results_list[0]] * 3) + + +def test_filter_gt_instances(): + packed_inputs = demo_mm_inputs()['data_samples'] + score_thr = 0.7 + with pytest.raises(AssertionError): + filter_gt_instances(packed_inputs, score_thr=score_thr) + + # filter no instances by score + for inputs in packed_inputs: + inputs.gt_instances.scores = torch.ones_like( + inputs.gt_instances.labels).float() + filtered_packed_inputs = filter_gt_instances( + copy.deepcopy(packed_inputs), score_thr=score_thr) + for filtered_inputs, inputs in zip(filtered_packed_inputs, packed_inputs): + assert len(filtered_inputs.gt_instances) == len(inputs.gt_instances) + + # filter all instances + for inputs in packed_inputs: + inputs.gt_instances.scores = torch.zeros_like( + inputs.gt_instances.labels).float() + filtered_packed_inputs = filter_gt_instances( + copy.deepcopy(packed_inputs), score_thr=score_thr) + for filtered_inputs in filtered_packed_inputs: + assert len(filtered_inputs.gt_instances) == 0 + + packed_inputs = demo_mm_inputs()['data_samples'] + # filter no instances by size + wh_thr = (0, 0) + filtered_packed_inputs = filter_gt_instances( + copy.deepcopy(packed_inputs), wh_thr=wh_thr) + for filtered_inputs, inputs in zip(filtered_packed_inputs, packed_inputs): + assert len(filtered_inputs.gt_instances) == len(inputs.gt_instances) + + # filter all instances by size + for inputs in packed_inputs: + img_shape = inputs.img_shape + wh_thr = (max(wh_thr[0], img_shape[0]), max(wh_thr[1], img_shape[1])) + filtered_packed_inputs = filter_gt_instances( + copy.deepcopy(packed_inputs), wh_thr=wh_thr) + for filtered_inputs in filtered_packed_inputs: + assert len(filtered_inputs.gt_instances) == 0 + + +def test_rename_loss_dict(): + prefix = 'sup_' + losses = {'cls_loss': torch.tensor(2.), 'reg_loss': torch.tensor(1.)} + sup_losses = rename_loss_dict(prefix, losses) + for name in losses.keys(): + assert sup_losses[prefix + name] == losses[name] + + +def test_reweight_loss_dict(): + weight = 4 + losses = {'cls_loss': torch.tensor(2.), 'reg_loss': torch.tensor(1.)} + weighted_losses = reweight_loss_dict(copy.deepcopy(losses), weight) + for name in losses.keys(): + assert weighted_losses[name] == losses[name] * weight diff --git a/mmdet_code/SR-TOD/tests/test_models/test_utils/test_model_misc.py b/mmdet_code/SR-TOD/tests/test_models/test_utils/test_model_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..93de33675141032a199261ddb6fdbc83bfe3ef2a --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_utils/test_model_misc.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +import torch +from torch.autograd import gradcheck + +from mmdet.models.utils import interpolate_as, sigmoid_geometric_mean + + +def test_interpolate_as(): + source = torch.rand((1, 5, 4, 4)) + target = torch.rand((1, 1, 16, 16)) + + # Test 4D source and target + result = interpolate_as(source, target) + assert result.shape == torch.Size((1, 5, 16, 16)) + + # Test 3D target + result = interpolate_as(source, target.squeeze(0)) + assert result.shape == torch.Size((1, 5, 16, 16)) + + # Test 3D source + result = interpolate_as(source.squeeze(0), target) + assert result.shape == torch.Size((5, 16, 16)) + + # Test type(target) == np.ndarray + target = np.random.rand(16, 16) + result = interpolate_as(source.squeeze(0), target) + assert result.shape == torch.Size((5, 16, 16)) + + +def test_sigmoid_geometric_mean(): + x = torch.randn(20, 20, dtype=torch.double, requires_grad=True) + y = torch.randn(20, 20, dtype=torch.double, requires_grad=True) + inputs = (x, y) + test = gradcheck(sigmoid_geometric_mean, inputs, eps=1e-6, atol=1e-4) + assert test diff --git a/mmdet_code/SR-TOD/tests/test_models/test_vis/test_mask2former.py b/mmdet_code/SR-TOD/tests/test_models/test_vis/test_mask2former.py new file mode 100644 index 0000000000000000000000000000000000000000..c8d3474e9ca7b0058e0b46d9cb36f35adebd1f53 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_vis/test_mask2former.py @@ -0,0 +1,96 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestMask2Former(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py', + ]) + def test_mask2former_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + + model = MODELS.build(model) + assert model.backbone + assert model.track_head + + @parameterized.expand([ + ('mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py', + ('cpu', 'cuda')), + ]) + def test_mask2former_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_mask2former_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=(3, 128, 128), + num_classes=2, + with_mask=True) + out_data = model.data_preprocessor(packed_inputs, True) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + losses = model.forward(inputs, data_samples, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ('mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py', + ('cpu', 'cuda')), + ]) + def test_mask2former_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_mask2former_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=1, + image_shapes=(3, 128, 128), + num_classes=2, + with_mask=True) + out_data = model.data_preprocessor(packed_inputs, False) + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_models/test_vis/test_masktrack_rcnn.py b/mmdet_code/SR-TOD/tests/test_models/test_vis/test_masktrack_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..fb94391f4d1dcf0c5b54fd2c5cb3f33ef9033360 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_models/test_vis/test_masktrack_rcnn.py @@ -0,0 +1,99 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestMaskTrackRCNN(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'masktrack_rcnn/masktrack-rcnn_mask-rcnn_r50_fpn_8xb1-12e_youtubevis2019.py', # noqa: E501 + ]) + def test_mask_track_rcnn_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + + model = MODELS.build(model) + assert model.detector + assert model.track_head + assert model.tracker + + @parameterized.expand([ + ( + 'masktrack_rcnn/masktrack-rcnn_mask-rcnn_r50_fpn_8xb1-12e_youtubevis2019.py', # noqa: E501 + ('cpu', 'cuda')), + ]) + def test_mask_track_rcnn_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_mask_track_rcnn_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=(3, 128, 128), + num_classes=2, + with_mask=True) + out_data = model.data_preprocessor(packed_inputs, True) + # Test forward + losses = model.forward(**out_data, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ( + 'masktrack_rcnn/masktrack-rcnn_mask-rcnn_r50_fpn_8xb1-12e_youtubevis2019.py', # noqa: E501 + ('cpu', 'cuda')), + ]) + def test_mask_track_rcnn_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_mask_track_rcnn_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=1, + image_shapes=(3, 128, 128), + num_classes=2, + with_mask=True) + out_data = model.data_preprocessor(packed_inputs, False) + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/SR-TOD/tests/test_structures/__init__.py b/mmdet_code/SR-TOD/tests/test_structures/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_bbox/__init__.py b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_base_boxes.py b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_base_boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..651eeefe12071177cdf335094fd4498ae4fb1390 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_base_boxes.py @@ -0,0 +1,276 @@ +from unittest import TestCase + +import numpy as np +import torch +from mmengine.testing import assert_allclose + +from .utils import ToyBaseBoxes + + +class TestBaseBoxes(TestCase): + + def test_init(self): + box_tensor = torch.rand((3, 4, 4)) + boxes = ToyBaseBoxes(box_tensor) + + boxes = ToyBaseBoxes(box_tensor, dtype=torch.float64) + self.assertEqual(boxes.tensor.dtype, torch.float64) + + if torch.cuda.is_available(): + boxes = ToyBaseBoxes(box_tensor, device='cuda') + self.assertTrue(boxes.tensor.is_cuda) + + with self.assertRaises(AssertionError): + box_tensor = torch.rand((4, )) + boxes = ToyBaseBoxes(box_tensor) + + with self.assertRaises(AssertionError): + box_tensor = torch.rand((3, 4, 3)) + boxes = ToyBaseBoxes(box_tensor) + + def test_getitem(self): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + + # test single dimension index + # int + new_boxes = boxes[0] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (4, 4)) + # list + new_boxes = boxes[[0, 2]] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (2, 4, 4)) + # slice + new_boxes = boxes[0:2] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (2, 4, 4)) + # torch.LongTensor + new_boxes = boxes[torch.LongTensor([0, 1])] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (2, 4, 4)) + # torch.BoolTensor + new_boxes = boxes[torch.BoolTensor([True, False, True])] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (2, 4, 4)) + with self.assertRaises(AssertionError): + index = torch.rand((2, 4, 4)) > 0 + new_boxes = boxes[index] + + # test multiple dimension index + # select single box + new_boxes = boxes[1, 2] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (1, 4)) + # select the last dimension + with self.assertRaises(AssertionError): + new_boxes = boxes[1, 2, 1] + # has Ellipsis + new_boxes = boxes[None, ...] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (1, 3, 4, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes[..., None] + + def test_setitem(self): + values = ToyBaseBoxes(torch.rand(3, 4, 4)) + tensor = torch.rand(3, 4, 4) + + # only support BaseBoxes type + with self.assertRaises(AssertionError): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[0:2] = tensor[0:2] + + # test single dimension index + # int + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[1] = values[1] + assert_allclose(boxes.tensor[1], values.tensor[1]) + # list + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[[1, 2]] = values[[1, 2]] + assert_allclose(boxes.tensor[[1, 2]], values.tensor[[1, 2]]) + # slice + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[0:2] = values[0:2] + assert_allclose(boxes.tensor[0:2], values.tensor[0:2]) + # torch.BoolTensor + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + index = torch.rand(3, 4) > 0.5 + boxes[index] = values[index] + assert_allclose(boxes.tensor[index], values.tensor[index]) + + # multiple dimension index + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[0:2, 0:2] = values[0:2, 0:2] + assert_allclose(boxes.tensor[0:2, 0:2], values.tensor[0:2, 0:2]) + # select single box + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[1, 1] = values[1, 1] + assert_allclose(boxes.tensor[1, 1], values.tensor[1, 1]) + # select the last dimension + with self.assertRaises(AssertionError): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[1, 1, 1] = values[1, 1, 1] + # has Ellipsis + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[0:2, ...] = values[0:2, ...] + assert_allclose(boxes.tensor[0:2, ...], values.tensor[0:2, ...]) + + def test_tensor_like_functions(self): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + # new_tensor + boxes.new_tensor([1, 2, 3]) + # new_full + boxes.new_full((3, 4), 0) + # new_empty + boxes.new_empty((3, 4)) + # new_ones + boxes.new_ones((3, 4)) + # new_zeros + boxes.new_zeros((3, 4)) + # size + self.assertEqual(boxes.size(0), 3) + self.assertEqual(tuple(boxes.size()), (3, 4, 4)) + # dim + self.assertEqual(boxes.dim(), 3) + # device + self.assertIsInstance(boxes.device, torch.device) + # dtype + self.assertIsInstance(boxes.dtype, torch.dtype) + # numpy + np_boxes = boxes.numpy() + self.assertIsInstance(np_boxes, np.ndarray) + self.assertTrue((np_boxes == np_boxes).all()) + # to + new_boxes = boxes.to(torch.uint8) + self.assertEqual(new_boxes.tensor.dtype, torch.uint8) + if torch.cuda.is_available(): + new_boxes = boxes.to(device='cuda') + self.assertTrue(new_boxes.tensor.is_cuda) + # cpu + if torch.cuda.is_available(): + new_boxes = boxes.to(device='cuda') + new_boxes = new_boxes.cpu() + self.assertFalse(new_boxes.tensor.is_cuda) + # cuda + if torch.cuda.is_available(): + new_boxes = boxes.cuda() + self.assertTrue(new_boxes.tensor.is_cuda) + # clone + boxes.clone() + # detach + boxes.detach() + # view + new_boxes = boxes.view(12, 4) + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + new_boxes = boxes.view(-1, 4) + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.view(-1) + # reshape + new_boxes = boxes.reshape(12, 4) + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + new_boxes = boxes.reshape(-1, 4) + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.reshape(-1) + # expand + new_boxes = boxes[None, ...].expand(4, -1, -1, -1) + self.assertEqual(tuple(new_boxes.size()), (4, 3, 4, 4)) + # repeat + new_boxes = boxes.repeat(2, 2, 1) + self.assertEqual(tuple(new_boxes.size()), (6, 8, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.repeat(2, 2, 2) + # transpose + new_boxes = boxes.transpose(0, 1) + self.assertEqual(tuple(new_boxes.size()), (4, 3, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.transpose(1, 2) + # permute + new_boxes = boxes.permute(1, 0, 2) + self.assertEqual(tuple(new_boxes.size()), (4, 3, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.permute(2, 1, 0) + # split + boxes_list = boxes.split(1, dim=0) + for box in boxes_list: + self.assertIsInstance(box, ToyBaseBoxes) + self.assertEqual(tuple(box.size()), (1, 4, 4)) + boxes_list = boxes.split([1, 2], dim=0) + with self.assertRaises(AssertionError): + boxes_list = boxes.split(1, dim=2) + # chunk + boxes_list = boxes.split(3, dim=1) + self.assertEqual(len(boxes_list), 2) + for box in boxes_list: + self.assertIsInstance(box, ToyBaseBoxes) + with self.assertRaises(AssertionError): + boxes_list = boxes.split(3, dim=2) + # unbind + boxes_list = boxes.unbind(dim=1) + self.assertEqual(len(boxes_list), 4) + for box in boxes_list: + self.assertIsInstance(box, ToyBaseBoxes) + self.assertEqual(tuple(box.size()), (3, 4)) + with self.assertRaises(AssertionError): + boxes_list = boxes.unbind(dim=2) + # flatten + new_boxes = boxes.flatten() + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.flatten(end_dim=2) + # squeeze + boxes = ToyBaseBoxes(torch.rand(1, 3, 1, 4, 4)) + new_boxes = boxes.squeeze() + self.assertEqual(tuple(new_boxes.size()), (3, 4, 4)) + new_boxes = boxes.squeeze(dim=2) + self.assertEqual(tuple(new_boxes.size()), (1, 3, 4, 4)) + # unsqueeze + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + new_boxes = boxes.unsqueeze(0) + self.assertEqual(tuple(new_boxes.size()), (1, 3, 4, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.unsqueeze(3) + # cat + with self.assertRaises(ValueError): + ToyBaseBoxes.cat([]) + box_list = [] + box_list.append(ToyBaseBoxes(torch.rand(3, 4, 4))) + box_list.append(ToyBaseBoxes(torch.rand(1, 4, 4))) + with self.assertRaises(AssertionError): + ToyBaseBoxes.cat(box_list, dim=2) + cat_boxes = ToyBaseBoxes.cat(box_list, dim=0) + self.assertIsInstance(cat_boxes, ToyBaseBoxes) + self.assertEqual((cat_boxes.size()), (4, 4, 4)) + # stack + with self.assertRaises(ValueError): + ToyBaseBoxes.stack([]) + box_list = [] + box_list.append(ToyBaseBoxes(torch.rand(3, 4, 4))) + box_list.append(ToyBaseBoxes(torch.rand(3, 4, 4))) + with self.assertRaises(AssertionError): + ToyBaseBoxes.stack(box_list, dim=3) + stack_boxes = ToyBaseBoxes.stack(box_list, dim=1) + self.assertIsInstance(stack_boxes, ToyBaseBoxes) + self.assertEqual((stack_boxes.size()), (3, 2, 4, 4)) + + def test_misc(self): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + # __len__ + self.assertEqual(len(boxes), 3) + # __repr__ + repr(boxes) + # fake_boxes + new_boxes = boxes.fake_boxes((3, 4, 4), 1) + self.assertEqual(tuple(new_boxes.size()), (3, 4, 4)) + self.assertEqual(boxes.dtype, new_boxes.dtype) + self.assertEqual(boxes.device, new_boxes.device) + self.assertTrue((new_boxes.tensor == 1).all()) + with self.assertRaises(AssertionError): + new_boxes = boxes.fake_boxes((3, 4, 1)) + new_boxes = boxes.fake_boxes((3, 4, 4), dtype=torch.uint8) + self.assertEqual(new_boxes.dtype, torch.uint8) + if torch.cuda.is_available(): + new_boxes = boxes.fake_boxes((3, 4, 4), device='cuda') + self.assertTrue(new_boxes.tensor.is_cuda) diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_box_type.py b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_box_type.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f58460743047b3568cd34878ce4b281d2d1c43 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_box_type.py @@ -0,0 +1,191 @@ +from unittest import TestCase +from unittest.mock import MagicMock + +import torch + +from mmdet.structures.bbox.box_type import (_box_type_to_name, box_converters, + box_types, convert_box_type, + get_box_type, register_box, + register_box_converter) +from .utils import ToyBaseBoxes + + +class TestBoxType(TestCase): + + def setUp(self): + self.box_types = box_types.copy() + self.box_converters = box_converters.copy() + self._box_type_to_name = _box_type_to_name.copy() + + def tearDown(self): + # Clear registered items + box_types.clear() + box_converters.clear() + _box_type_to_name.clear() + # Restore original items + box_types.update(self.box_types) + box_converters.update(self.box_converters) + _box_type_to_name.update(self._box_type_to_name) + + def test_register_box(self): + # test usage of decorator + @register_box('A') + class A(ToyBaseBoxes): + pass + + # test usage of normal function + class B(ToyBaseBoxes): + pass + + register_box('B', B) + + # register class without inheriting from BaseBoxes + with self.assertRaises(AssertionError): + + @register_box('C') + class C: + pass + + # test register registered class + with self.assertRaises(KeyError): + + @register_box('A') + class AA(ToyBaseBoxes): + pass + + with self.assertRaises(KeyError): + register_box('BB', B) + + @register_box('A', force=True) + class AAA(ToyBaseBoxes): + pass + + self.assertIs(box_types['a'], AAA) + self.assertEqual(_box_type_to_name[AAA], 'a') + register_box('BB', B, force=True) + self.assertIs(box_types['bb'], B) + self.assertEqual(_box_type_to_name[B], 'bb') + self.assertEqual(len(box_types), len(_box_type_to_name)) + + def test_register_box_converter(self): + + @register_box('A') + class A(ToyBaseBoxes): + pass + + @register_box('B') + class B(ToyBaseBoxes): + pass + + @register_box('C') + class C(ToyBaseBoxes): + pass + + # test usage of decorator + @register_box_converter('A', 'B') + def converter_A(bboxes): + return bboxes + + # test usage of normal function + def converter_B(bboxes): + return bboxes + + register_box_converter('B' + 'A', converter_B) + + # register uncallable object + with self.assertRaises(AssertionError): + register_box_converter('A', 'C', 'uncallable str') + + # test register unregistered bbox mode + with self.assertRaises(AssertionError): + + @register_box_converter('A', 'D') + def converter_C(bboxes): + return bboxes + + # test register registered converter + with self.assertRaises(KeyError): + + @register_box_converter('A', 'B') + def converter_D(bboxes): + return bboxes + + @register_box_converter('A', 'B', force=True) + def converter_E(bboxes): + return bboxes + + self.assertIs(box_converters['a2b'], converter_E) + + def test_get_box_type(self): + + @register_box('A') + class A(ToyBaseBoxes): + pass + + mode_name, mode_cls = get_box_type('A') + self.assertEqual(mode_name, 'a') + self.assertIs(mode_cls, A) + mode_name, mode_cls = get_box_type(A) + self.assertEqual(mode_name, 'a') + self.assertIs(mode_cls, A) + + # get unregistered mode + class B(ToyBaseBoxes): + pass + + with self.assertRaises(AssertionError): + mode_name, mode_cls = get_box_type('B') + with self.assertRaises(AssertionError): + mode_name, mode_cls = get_box_type(B) + + def test_convert_box_type(self): + + @register_box('A') + class A(ToyBaseBoxes): + pass + + @register_box('B') + class B(ToyBaseBoxes): + pass + + @register_box('C') + class C(ToyBaseBoxes): + pass + + converter = MagicMock() + converter.return_value = torch.rand(3, 4, 4) + register_box_converter('A', 'B', converter) + + bboxes_a = A(torch.rand(3, 4, 4)) + th_bboxes_a = bboxes_a.tensor + np_bboxes_a = th_bboxes_a.numpy() + + # test convert to mode + convert_box_type(bboxes_a, dst_type='B') + self.assertTrue(converter.called) + converted_bboxes = convert_box_type(bboxes_a, dst_type='A') + self.assertIs(converted_bboxes, bboxes_a) + # test convert to unregistered mode + with self.assertRaises(AssertionError): + convert_box_type(bboxes_a, dst_type='C') + + # test convert tensor and ndarray + # without specific src_type + with self.assertRaises(AssertionError): + convert_box_type(th_bboxes_a, dst_type='B') + with self.assertRaises(AssertionError): + convert_box_type(np_bboxes_a, dst_type='B') + # test np.ndarray + convert_box_type(np_bboxes_a, src_type='A', dst_type='B') + converted_bboxes = convert_box_type( + np_bboxes_a, src_type='A', dst_type='A') + self.assertIs(converted_bboxes, np_bboxes_a) + # test tensor + convert_box_type(th_bboxes_a, src_type='A', dst_type='B') + converted_bboxes = convert_box_type( + th_bboxes_a, src_type='A', dst_type='A') + self.assertIs(converted_bboxes, th_bboxes_a) + # test other type + with self.assertRaises(TypeError): + convert_box_type([[1, 2, 3, 4]], src_type='A', dst_type='B') diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_horizontal_boxes.py b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_horizontal_boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..1030e956def578cdf025d79f6a347994b5043c3e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/test_horizontal_boxes.py @@ -0,0 +1,187 @@ +import random +from math import sqrt +from unittest import TestCase + +import cv2 +import numpy as np +import torch +from mmengine.testing import assert_allclose + +from mmdet.structures.bbox import HorizontalBoxes +from mmdet.structures.mask import BitmapMasks, PolygonMasks + + +class TestHorizontalBoxes(TestCase): + + def test_init(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + th_boxes_cxcywh = torch.Tensor([15, 15, 10, 10]).reshape(1, 1, 4) + + boxes = HorizontalBoxes(th_boxes) + assert_allclose(boxes.tensor, th_boxes) + boxes = HorizontalBoxes(th_boxes, in_mode='xyxy') + assert_allclose(boxes.tensor, th_boxes) + boxes = HorizontalBoxes(th_boxes_cxcywh, in_mode='cxcywh') + assert_allclose(boxes.tensor, th_boxes) + with self.assertRaises(ValueError): + boxes = HorizontalBoxes(th_boxes, in_mode='invalid') + + def test_cxcywh(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + th_boxes_cxcywh = torch.Tensor([15, 15, 10, 10]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + + assert_allclose( + HorizontalBoxes.xyxy_to_cxcywh(th_boxes), th_boxes_cxcywh) + assert_allclose(th_boxes, + HorizontalBoxes.cxcywh_to_xyxy(th_boxes_cxcywh)) + assert_allclose(boxes.cxcywh, th_boxes_cxcywh) + + def test_propoerty(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + + # Centers + centers = torch.Tensor([15, 15]).reshape(1, 1, 2) + assert_allclose(boxes.centers, centers) + # Areas + areas = torch.Tensor([100]).reshape(1, 1) + assert_allclose(boxes.areas, areas) + # widths + widths = torch.Tensor([10]).reshape(1, 1) + assert_allclose(boxes.widths, widths) + # heights + heights = torch.Tensor([10]).reshape(1, 1) + assert_allclose(boxes.heights, heights) + + def test_flip(self): + img_shape = [50, 85] + # horizontal flip + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + flipped_boxes_th = torch.Tensor([65, 10, 75, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.flip_(img_shape, direction='horizontal') + assert_allclose(boxes.tensor, flipped_boxes_th) + # vertical flip + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + flipped_boxes_th = torch.Tensor([10, 30, 20, 40]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.flip_(img_shape, direction='vertical') + assert_allclose(boxes.tensor, flipped_boxes_th) + # diagonal flip + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + flipped_boxes_th = torch.Tensor([65, 30, 75, 40]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.flip_(img_shape, direction='diagonal') + assert_allclose(boxes.tensor, flipped_boxes_th) + + def test_translate(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.translate_([23, 46]) + translated_boxes_th = torch.Tensor([33, 56, 43, 66]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, translated_boxes_th) + + def test_clip(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + img_shape = [13, 14] + boxes = HorizontalBoxes(th_boxes) + boxes.clip_(img_shape) + cliped_boxes_th = torch.Tensor([10, 10, 14, 13]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, cliped_boxes_th) + + def test_rotate(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + center = (15, 15) + angle = -45 + boxes = HorizontalBoxes(th_boxes) + boxes.rotate_(center, angle) + rotated_boxes_th = torch.Tensor([ + 15 - 5 * sqrt(2), 15 - 5 * sqrt(2), 15 + 5 * sqrt(2), + 15 + 5 * sqrt(2) + ]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, rotated_boxes_th) + + def test_project(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes1 = HorizontalBoxes(th_boxes) + boxes2 = boxes1.clone() + + matrix = np.zeros((3, 3), dtype=np.float32) + center = [random.random() * 80, random.random() * 80] + angle = random.random() * 180 + matrix[:2, :3] = cv2.getRotationMatrix2D(center, angle, 1) + x_translate = random.random() * 40 + y_translate = random.random() * 40 + matrix[0, 2] = matrix[0, 2] + x_translate + matrix[1, 2] = matrix[1, 2] + y_translate + scale_factor = random.random() * 2 + matrix[2, 2] = 1 / scale_factor + boxes1.project_(matrix) + + boxes2.rotate_(center, -angle) + boxes2.translate_([x_translate, y_translate]) + boxes2.rescale_([scale_factor, scale_factor]) + assert_allclose(boxes1.tensor, boxes2.tensor) + # test empty boxes + empty_boxes = HorizontalBoxes(torch.zeros((0, 4))) + empty_boxes.project_(matrix) + + def test_rescale(self): + scale_factor = [0.4, 0.8] + # rescale + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.rescale_(scale_factor) + rescaled_boxes_th = torch.Tensor([4, 8, 8, 16]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, rescaled_boxes_th) + + def test_resize(self): + scale_factor = [0.4, 0.8] + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.resize_(scale_factor) + resized_boxes_th = torch.Tensor([13, 11, 17, 19]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, resized_boxes_th) + + def test_is_inside(self): + th_boxes = torch.Tensor([[10, 10, 20, 20], [-5, -5, 15, 15], + [45, 45, 55, 55]]).reshape(1, 3, 4) + img_shape = [30, 30] + boxes = HorizontalBoxes(th_boxes) + + index = boxes.is_inside(img_shape) + index_th = torch.BoolTensor([True, True, False]).reshape(1, 3) + assert_allclose(index, index_th) + + def test_find_inside_points(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 4) + boxes = HorizontalBoxes(th_boxes) + points = torch.Tensor([[0, 0], [0, 15], [15, 0], [15, 15]]) + index = boxes.find_inside_points(points) + index_th = torch.BoolTensor([False, False, False, True]).reshape(4, 1) + assert_allclose(index, index_th) + # is_aligned + boxes = boxes.expand(4, 4) + index = boxes.find_inside_points(points, is_aligned=True) + index_th = torch.BoolTensor([False, False, False, True]) + assert_allclose(index, index_th) + + def test_from_instance_masks(self): + bitmap_masks = BitmapMasks.random() + boxes = HorizontalBoxes.from_instance_masks(bitmap_masks) + self.assertIsInstance(boxes, HorizontalBoxes) + self.assertEqual(len(boxes), len(bitmap_masks)) + polygon_masks = PolygonMasks.random() + boxes = HorizontalBoxes.from_instance_masks(polygon_masks) + self.assertIsInstance(boxes, HorizontalBoxes) + self.assertEqual(len(boxes), len(bitmap_masks)) + # zero length masks + bitmap_masks = BitmapMasks.random(num_masks=0) + boxes = HorizontalBoxes.from_instance_masks(bitmap_masks) + self.assertIsInstance(boxes, HorizontalBoxes) + self.assertEqual(len(boxes), 0) + polygon_masks = PolygonMasks.random(num_masks=0) + boxes = HorizontalBoxes.from_instance_masks(polygon_masks) + self.assertIsInstance(boxes, HorizontalBoxes) + self.assertEqual(len(boxes), 0) diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_bbox/utils.py b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0d15414bd990ac50197c7bf96b779a685fa24203 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_structures/test_bbox/utils.py @@ -0,0 +1,55 @@ +from mmdet.structures.bbox import BaseBoxes + + +class ToyBaseBoxes(BaseBoxes): + + box_dim = 4 + + @property + def centers(self): + pass + + @property + def areas(self): + pass + + @property + def widths(self): + pass + + @property + def heights(self): + pass + + def flip_(self, img_shape, direction='horizontal'): + pass + + def translate_(self, distances): + pass + + def clip_(self, img_shape): + pass + + def rotate_(self, center, angle): + pass + + def project_(self, homography_matrix): + pass + + def rescale_(self, scale_factor): + pass + + def resize_(self, scale_factor): + pass + + def is_inside(self, img_shape): + pass + + def find_inside_points(self, points, is_aligned=False): + pass + + def overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6): + pass + + def from_instance_masks(masks): + pass diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_det_data_sample.py b/mmdet_code/SR-TOD/tests/test_structures/test_det_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc7bdb90ddbed9ae017cd5bc845e3b3d1734e8f --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_structures/test_det_data_sample.py @@ -0,0 +1,166 @@ +from unittest import TestCase + +import numpy as np +import pytest +import torch +from mmengine.structures import InstanceData, PixelData + +from mmdet.structures import DetDataSample + + +def _equal(a, b): + if isinstance(a, (torch.Tensor, np.ndarray)): + return (a == b).all() + else: + return a == b + + +class TestDetDataSample(TestCase): + + def test_init(self): + meta_info = dict( + img_size=[256, 256], + scale_factor=np.array([1.5, 1.5]), + img_shape=torch.rand(4)) + + det_data_sample = DetDataSample(metainfo=meta_info) + assert 'img_size' in det_data_sample + assert det_data_sample.img_size == [256, 256] + assert det_data_sample.get('img_size') == [256, 256] + + def test_setter(self): + det_data_sample = DetDataSample() + # test gt_instances + gt_instances_data = dict( + bboxes=torch.rand(4, 4), + labels=torch.rand(4), + masks=np.random.rand(4, 2, 2)) + gt_instances = InstanceData(**gt_instances_data) + det_data_sample.gt_instances = gt_instances + assert 'gt_instances' in det_data_sample + assert _equal(det_data_sample.gt_instances.bboxes, + gt_instances_data['bboxes']) + assert _equal(det_data_sample.gt_instances.labels, + gt_instances_data['labels']) + assert _equal(det_data_sample.gt_instances.masks, + gt_instances_data['masks']) + + # test pred_instances + pred_instances_data = dict( + bboxes=torch.rand(2, 4), + labels=torch.rand(2), + masks=np.random.rand(2, 2, 2)) + pred_instances = InstanceData(**pred_instances_data) + det_data_sample.pred_instances = pred_instances + assert 'pred_instances' in det_data_sample + assert _equal(det_data_sample.pred_instances.bboxes, + pred_instances_data['bboxes']) + assert _equal(det_data_sample.pred_instances.labels, + pred_instances_data['labels']) + assert _equal(det_data_sample.pred_instances.masks, + pred_instances_data['masks']) + + # test pred_track_instances + pred_track_instances_data = dict( + bboxes=torch.rand(2, 4), + labels=torch.rand(2), + masks=np.random.rand(2, 2, 2)) + pred_instances = InstanceData(**pred_track_instances_data) + det_data_sample.pred_instances = pred_instances + assert 'pred_instances' in det_data_sample + assert _equal(det_data_sample.pred_instances.bboxes, + pred_track_instances_data['bboxes']) + assert _equal(det_data_sample.pred_instances.labels, + pred_track_instances_data['labels']) + assert _equal(det_data_sample.pred_instances.masks, + pred_track_instances_data['masks']) + + # test proposals + proposals_data = dict(bboxes=torch.rand(4, 4), labels=torch.rand(4)) + proposals = InstanceData(**proposals_data) + det_data_sample.proposals = proposals + assert 'proposals' in det_data_sample + assert _equal(det_data_sample.proposals.bboxes, + proposals_data['bboxes']) + assert _equal(det_data_sample.proposals.labels, + proposals_data['labels']) + + # test ignored_instances + ignored_instances_data = dict( + bboxes=torch.rand(4, 4), labels=torch.rand(4)) + ignored_instances = InstanceData(**ignored_instances_data) + det_data_sample.ignored_instances = ignored_instances + assert 'ignored_instances' in det_data_sample + assert _equal(det_data_sample.ignored_instances.bboxes, + ignored_instances_data['bboxes']) + assert _equal(det_data_sample.ignored_instances.labels, + ignored_instances_data['labels']) + + # test gt_panoptic_seg + gt_panoptic_seg_data = dict(panoptic_seg=torch.rand(5, 4)) + gt_panoptic_seg = PixelData(**gt_panoptic_seg_data) + det_data_sample.gt_panoptic_seg = gt_panoptic_seg + assert 'gt_panoptic_seg' in det_data_sample + assert _equal(det_data_sample.gt_panoptic_seg.panoptic_seg, + gt_panoptic_seg_data['panoptic_seg']) + + # test pred_panoptic_seg + pred_panoptic_seg_data = dict(panoptic_seg=torch.rand(5, 4)) + pred_panoptic_seg = PixelData(**pred_panoptic_seg_data) + det_data_sample.pred_panoptic_seg = pred_panoptic_seg + assert 'pred_panoptic_seg' in det_data_sample + assert _equal(det_data_sample.pred_panoptic_seg.panoptic_seg, + pred_panoptic_seg_data['panoptic_seg']) + + # test gt_sem_seg + gt_segm_seg_data = dict(segm_seg=torch.rand(5, 4, 2)) + gt_segm_seg = PixelData(**gt_segm_seg_data) + det_data_sample.gt_segm_seg = gt_segm_seg + assert 'gt_segm_seg' in det_data_sample + assert _equal(det_data_sample.gt_segm_seg.segm_seg, + gt_segm_seg_data['segm_seg']) + + # test pred_segm_seg + pred_segm_seg_data = dict(segm_seg=torch.rand(5, 4, 2)) + pred_segm_seg = PixelData(**pred_segm_seg_data) + det_data_sample.pred_segm_seg = pred_segm_seg + assert 'pred_segm_seg' in det_data_sample + assert _equal(det_data_sample.pred_segm_seg.segm_seg, + pred_segm_seg_data['segm_seg']) + + # test type error + with pytest.raises(AssertionError): + det_data_sample.pred_instances = torch.rand(2, 4) + + with pytest.raises(AssertionError): + det_data_sample.pred_panoptic_seg = torch.rand(2, 4) + + with pytest.raises(AssertionError): + det_data_sample.pred_sem_seg = torch.rand(2, 4) + + def test_deleter(self): + gt_instances_data = dict( + bboxes=torch.rand(4, 4), + labels=torch.rand(4), + masks=np.random.rand(4, 2, 2)) + + det_data_sample = DetDataSample() + gt_instances = InstanceData(data=gt_instances_data) + det_data_sample.gt_instances = gt_instances + assert 'gt_instances' in det_data_sample + del det_data_sample.gt_instances + assert 'gt_instances' not in det_data_sample + + pred_panoptic_seg_data = torch.rand(5, 4) + pred_panoptic_seg = PixelData(data=pred_panoptic_seg_data) + det_data_sample.pred_panoptic_seg = pred_panoptic_seg + assert 'pred_panoptic_seg' in det_data_sample + del det_data_sample.pred_panoptic_seg + assert 'pred_panoptic_seg' not in det_data_sample + + pred_segm_seg_data = dict(segm_seg=torch.rand(5, 4, 2)) + pred_segm_seg = PixelData(**pred_segm_seg_data) + det_data_sample.pred_segm_seg = pred_segm_seg + assert 'pred_segm_seg' in det_data_sample + del det_data_sample.pred_segm_seg + assert 'pred_segm_seg' not in det_data_sample diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_mask/test_mask_structures.py b/mmdet_code/SR-TOD/tests/test_structures/test_mask/test_mask_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..051db7f1319f8146e5bf64f788c327381065e36d --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_structures/test_mask/test_mask_structures.py @@ -0,0 +1,73 @@ +from unittest import TestCase + +import numpy as np +from mmengine.testing import assert_allclose + +from mmdet.structures.mask import BitmapMasks, PolygonMasks + + +class TestMaskStructures(TestCase): + + def test_bitmap_translate_same_size(self): + mask_array = np.zeros((5, 10, 10), dtype=np.uint8) + mask_array[:, 0:5, 0:5] = 1 + mask_target = np.zeros((5, 10, 10), dtype=np.uint8) + mask_target[:, 0:5, 5:10] = 1 + + mask = BitmapMasks(mask_array, 10, 10) + mask = mask.translate((10, 10), 5) + assert mask.masks.shape == (5, 10, 10) + assert_allclose(mask_target, mask.masks) + + def test_bitmap_translate_diff_size(self): + # test out shape larger + mask_array = np.zeros((5, 10, 10), dtype=np.uint8) + mask_array[:, 0:5, 0:5] = 1 + + mask_target = np.zeros((5, 20, 20), dtype=np.uint8) + mask_target[:, 0:5, 5:10] = 1 + mask = BitmapMasks(mask_array, 10, 10) + mask = mask.translate((20, 20), 5) + assert mask.masks.shape == (5, 20, 20) + assert_allclose(mask_target, mask.masks) + + # test out shape smaller + mask_array = np.zeros((5, 10, 10), dtype=np.uint8) + mask_array[:, 0:5, 0:5] = 1 + + mask_target = np.zeros((5, 20, 8), dtype=np.uint8) + mask_target[:, 0:5, 5:] = 1 + mask = BitmapMasks(mask_array, 10, 10) + mask = mask.translate((20, 8), 5) + assert mask.masks.shape == (5, 20, 8) + assert_allclose(mask_target, mask.masks) + + def test_bitmap_cat(self): + # test invalid inputs + with self.assertRaises(AssertionError): + BitmapMasks.cat(BitmapMasks.random(4)) + with self.assertRaises(ValueError): + BitmapMasks.cat([]) + with self.assertRaises(AssertionError): + BitmapMasks.cat([BitmapMasks.random(2), PolygonMasks.random(3)]) + + masks = [BitmapMasks.random(num_masks=3) for _ in range(5)] + cat_mask = BitmapMasks.cat(masks) + assert len(cat_mask) == 3 * 5 + for i, m in enumerate(masks): + assert_allclose(m.masks, cat_mask.masks[i * 3:(i + 1) * 3]) + + def test_polygon_cat(self): + # test invalid inputs + with self.assertRaises(AssertionError): + PolygonMasks.cat(PolygonMasks.random(4)) + with self.assertRaises(ValueError): + PolygonMasks.cat([]) + with self.assertRaises(AssertionError): + PolygonMasks.cat([BitmapMasks.random(2), PolygonMasks.random(3)]) + + masks = [PolygonMasks.random(num_masks=3) for _ in range(5)] + cat_mask = PolygonMasks.cat(masks) + assert len(cat_mask) == 3 * 5 + for i, m in enumerate(masks): + assert_allclose(m.masks, cat_mask.masks[i * 3:(i + 1) * 3]) diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_reid_data_sample.py b/mmdet_code/SR-TOD/tests/test_structures/test_reid_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..d9f2ebb2f86df9bace88b3e78f963d42d1796580 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_structures/test_reid_data_sample.py @@ -0,0 +1,129 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine.structures import LabelData + +from mmdet.structures import ReIDDataSample + + +def _equal(a, b): + if isinstance(a, (torch.Tensor, np.ndarray)): + return (a == b).all() + else: + return a == b + + +class TestReIDDataSample(TestCase): + + def test_init(self): + img_shape = (256, 128) + ori_shape = (64, 64) + num_classes = 5 + meta_info = dict( + img_shape=img_shape, ori_shape=ori_shape, num_classes=num_classes) + data_sample = ReIDDataSample(metainfo=meta_info) + self.assertIn('img_shape', data_sample) + self.assertIn('ori_shape', data_sample) + self.assertIn('num_classes', data_sample) + self.assertTrue(_equal(data_sample.get('img_shape'), img_shape)) + self.assertTrue(_equal(data_sample.get('ori_shape'), ori_shape)) + self.assertTrue(_equal(data_sample.get('num_classes'), num_classes)) + + def test_set_gt_label(self): + data_sample = ReIDDataSample(metainfo=dict(num_classes=5)) + method = getattr(data_sample, 'set_' + 'gt_label') + + # Test number + method(1) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.LongTensor) + + # Test tensor with single number + method(torch.tensor(2)) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.LongTensor) + + # Test array with single number + method(np.array(3)) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.LongTensor) + + # Test tensor + _label = torch.tensor([1, 2, 3]) + method(_label) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.Tensor) + self.assertTrue(_equal(label.label, _label)) + + # Test array + _label = np.array([1, 2, 3]) + method(_label) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.Tensor) + self.assertTrue(_equal(label.label, torch.from_numpy(_label))) + + # Test Sequence + _label = [1, 2, 3.] + method(_label) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.Tensor) + self.assertTrue(_equal(label.label, torch.tensor(_label))) + + # Test set num_classes + self.assertEqual(label.num_classes, 5) + + # Test unavailable type + with self.assertRaisesRegex(TypeError, " is not"): + method('hi') + + def test_set_gt_score(self): + data_sample = ReIDDataSample(metainfo={'num_classes': 5}) + method = getattr(data_sample, 'set_' + 'gt_score') + + # Test set + score = [0.1, 0.1, 0.6, 0.1, 0.1] + method(torch.tensor(score)) + sample_gt_label = getattr(data_sample, 'gt_label') + self.assertIn('score', sample_gt_label) + torch.testing.assert_allclose(sample_gt_label.score, score) + self.assertEqual(sample_gt_label.num_classes, 5) + + # Test set again + score = [0.2, 0.1, 0.5, 0.1, 0.1] + method(torch.tensor(score)) + torch.testing.assert_allclose(sample_gt_label.score, score) + + # Test invalid type + with self.assertRaisesRegex(AssertionError, 'be a torch.Tensor'): + method(score) + + # Test invalid dims + with self.assertRaisesRegex(AssertionError, 'but got 2'): + method(torch.tensor([score])) + + # Test invalid num_classes + with self.assertRaisesRegex(AssertionError, r'length of value \(6\)'): + method(torch.tensor(score + [0.1])) + + # Test auto inter num_classes + data_sample = ReIDDataSample() + method = getattr(data_sample, 'set_gt_score') + method(torch.tensor(score)) + sample_gt_label = getattr(data_sample, 'gt_label') + self.assertEqual(sample_gt_label.num_classes, len(score)) + + def test_del_gt_label(self): + data_sample = ReIDDataSample() + self.assertNotIn('gt_label', data_sample) + data_sample.set_gt_label(1) + self.assertIn('gt_label', data_sample) + del data_sample.gt_label + self.assertNotIn('gt_label', data_sample) diff --git a/mmdet_code/SR-TOD/tests/test_structures/test_track_data_sample.py b/mmdet_code/SR-TOD/tests/test_structures/test_track_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..c926707a7ddc87f31aca0a31d55c8e8759722b2e --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_structures/test_track_data_sample.py @@ -0,0 +1,47 @@ +from unittest import TestCase + +import pytest + +from mmdet.structures import DetDataSample, TrackDataSample + + +class TestDetDataSample(TestCase): + + def test_init(self): + track_data_sample = TrackDataSample( + metainfo=dict(key_frames_inds=[0], ref_frames_inds=[1])) + + assert 'key_frames_inds' in track_data_sample.metainfo and \ + 'ref_frames_inds' in track_data_sample.metainfo + assert track_data_sample.key_frames_inds == [0] + assert track_data_sample.ref_frames_inds == [1] + with pytest.raises(AssertionError): + track_data_sample.get_key_frames() + with pytest.raises(AssertionError): + track_data_sample.get_ref_frames() + + def test_setter(self): + det_data_sample_1 = DetDataSample( + metainfo=dict(scale_factor=(1.5, 1.5))) + det_data_sample_2 = DetDataSample(metainfo=dict(scale_factor=(2., 2.))) + track_data_sample = TrackDataSample( + metainfo=dict(key_frames_inds=[0], ref_frames_inds=[1])) + track_data_sample.video_data_samples = [ + det_data_sample_1, det_data_sample_2 + ] + + assert track_data_sample.get_key_frames()[0].scale_factor == (1.5, 1.5) + assert track_data_sample.get_ref_frames()[0].scale_factor == (2., 2.) + + def test_deleter(self): + det_data_sample_1 = DetDataSample( + metainfo=dict(scale_factor=(1.5, 1.5))) + det_data_sample_2 = DetDataSample(metainfo=dict(scale_factor=(2., 2.))) + track_data_sample = TrackDataSample( + metainfo=dict(key_frames_inds=[0], ref_frames_inds=[1])) + track_data_sample.video_data_samples = [ + det_data_sample_1, det_data_sample_2 + ] + assert 'video_data_samples' in track_data_sample + del track_data_sample.video_data_samples + assert 'video_data_samples' not in track_data_sample diff --git a/mmdet_code/SR-TOD/tests/test_utils/test_benchmark.py b/mmdet_code/SR-TOD/tests/test_utils/test_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..939a7eca4e5e340e905287c2289ab769c6d946a1 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_utils/test_benchmark.py @@ -0,0 +1,309 @@ +import copy +import os +import tempfile +import unittest + +import torch +from mmengine import Config, MMLogger +from mmengine.dataset import Compose +from mmengine.model import BaseModel +from torch.utils.data import Dataset + +from mmdet.registry import DATASETS, MODELS +from mmdet.utils import register_all_modules +from mmdet.utils.benchmark import (DataLoaderBenchmark, DatasetBenchmark, + InferenceBenchmark) + + +@MODELS.register_module() +class ToyDetector(BaseModel): + + def __init__(self, *args, **kwargs): + super().__init__() + + def forward(self, *args, **kwargs): + pass + + +@DATASETS.register_module() +class ToyDataset(Dataset): + METAINFO = dict() # type: ignore + data = torch.randn(12, 2) + label = torch.ones(12) + + def __init__(self): + self.pipeline = Compose([lambda x: x]) + + def __len__(self): + return self.data.size(0) + + def get_data_info(self, index): + return dict(inputs=self.data[index], data_sample=self.label[index]) + + def __getitem__(self, index): + return dict(inputs=self.data[index], data_sample=self.label[index]) + + +@DATASETS.register_module() +class ToyFullInitDataset(Dataset): + METAINFO = dict() # type: ignore + data = torch.randn(12, 2) + label = torch.ones(12) + + def __init__(self): + self.pipeline = Compose([lambda x: x]) + + def __len__(self): + return self.data.size(0) + + def get_data_info(self, index): + return dict(inputs=self.data[index], data_sample=self.label[index]) + + def full_init(self): + pass + + def __getitem__(self, index): + return dict(inputs=self.data[index], data_sample=self.label[index]) + + +class TestInferenceBenchmark(unittest.TestCase): + + def setUp(self) -> None: + register_all_modules() + + self.cfg = Config( + dict( + model=dict(type='ToyDetector'), + test_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=1), + env_cfg=dict(dist_cfg=dict(backend='nccl')))) + self.max_iter = 10 + self.log_interval = 5 + + @unittest.skipIf(not torch.cuda.is_available(), + 'test requires GPU and torch+cuda') + def test_init_and_run(self): + checkpoint_path = os.path.join(tempfile.gettempdir(), 'checkpoint.pth') + torch.save(ToyDetector().state_dict(), checkpoint_path) + + cfg = copy.deepcopy(self.cfg) + inference_benchmark = InferenceBenchmark(cfg, checkpoint_path, False, + False, self.max_iter, + self.log_interval) + results = inference_benchmark.run() + + self.assertTrue(isinstance(results, dict)) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 1) + self.assertTrue(inference_benchmark.data_loader.num_workers == 0) + self.assertTrue(inference_benchmark.data_loader.batch_size == 1) + + results = inference_benchmark.run(1) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 1) + self.assertTrue(inference_benchmark.data_loader.num_workers == 0) + self.assertTrue(inference_benchmark.data_loader.batch_size == 1) + + # test repeat + results = inference_benchmark.run(3) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 3) + + # test cudnn_benchmark + cfg = copy.deepcopy(self.cfg) + cfg.env_cfg.cudnn_benchmark = True + inference_benchmark = InferenceBenchmark(cfg, checkpoint_path, False, + False, self.max_iter, + self.log_interval) + inference_benchmark.run(1) + + # test mp_cfg + cfg = copy.deepcopy(self.cfg) + cfg.env_cfg.cudnn_benchmark = True + cfg.env_cfg.mp_cfg = { + 'mp_start_method': 'fork', + 'opencv_num_threads': 1 + } + inference_benchmark = InferenceBenchmark(cfg, checkpoint_path, False, + False, self.max_iter, + self.log_interval) + inference_benchmark.run(1) + + # test fp16 + cfg = copy.deepcopy(self.cfg) + cfg.fp16 = True + inference_benchmark = InferenceBenchmark(cfg, checkpoint_path, False, + False, self.max_iter, + self.log_interval) + inference_benchmark.run(1) + + # test logger + logger = MMLogger.get_instance( + 'mmdet', log_file='temp.log', log_level='INFO') + inference_benchmark = InferenceBenchmark( + cfg, + checkpoint_path, + False, + False, + self.max_iter, + self.log_interval, + logger=logger) + inference_benchmark.run(1) + self.assertTrue(os.path.exists('temp.log')) + + os.remove(checkpoint_path) + os.remove('temp.log') + + +class TestDataLoaderBenchmark(unittest.TestCase): + + def setUp(self) -> None: + register_all_modules() + + self.cfg = Config( + dict( + model=dict(type='ToyDetector'), + train_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=2, + num_workers=1), + val_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=1, + num_workers=2), + test_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=1), + env_cfg=dict(dist_cfg=dict(backend='nccl')))) + self.max_iter = 5 + self.log_interval = 1 + self.num_warmup = 1 + + def test_init_and_run(self): + cfg = copy.deepcopy(self.cfg) + dataloader_benchmark = DataLoaderBenchmark(cfg, False, 'train', + self.max_iter, + self.log_interval, + self.num_warmup) + results = dataloader_benchmark.run(1) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 1) + self.assertTrue(dataloader_benchmark.data_loader.num_workers == 1) + self.assertTrue(dataloader_benchmark.data_loader.batch_size == 2) + + # test repeat + results = dataloader_benchmark.run(3) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 3) + + # test dataset_type input parameters error + with self.assertRaises(AssertionError): + DataLoaderBenchmark(cfg, False, 'training', self.max_iter, + self.log_interval, self.num_warmup) + + dataloader_benchmark = DataLoaderBenchmark(cfg, False, 'val', + self.max_iter, + self.log_interval, + self.num_warmup) + self.assertTrue(dataloader_benchmark.data_loader.num_workers == 2) + self.assertTrue(dataloader_benchmark.data_loader.batch_size == 1) + + dataloader_benchmark = DataLoaderBenchmark(cfg, False, 'test', + self.max_iter, + self.log_interval, + self.num_warmup) + self.assertTrue(dataloader_benchmark.data_loader.num_workers == 1) + self.assertTrue(dataloader_benchmark.data_loader.batch_size == 3) + + # test mp_cfg + cfg = copy.deepcopy(self.cfg) + cfg.env_cfg.mp_cfg = { + 'mp_start_method': 'fork', + 'opencv_num_threads': 1 + } + dataloader_benchmark = DataLoaderBenchmark(cfg, False, 'train', + self.max_iter, + self.log_interval, + self.num_warmup) + dataloader_benchmark.run(1) + + +class TestDatasetBenchmark(unittest.TestCase): + + def setUp(self) -> None: + register_all_modules() + + self.cfg = Config( + dict( + model=dict(type='ToyDetector'), + train_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=2, + num_workers=1), + val_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=1, + num_workers=2), + test_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=1))) + self.max_iter = 5 + self.log_interval = 1 + self.num_warmup = 1 + + def test_init_and_run(self): + cfg = copy.deepcopy(self.cfg) + dataset_benchmark = DatasetBenchmark(cfg, 'train', self.max_iter, + self.log_interval, + self.num_warmup) + results = dataset_benchmark.run(1) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 1) + + # test repeat + results = dataset_benchmark.run(3) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 3) + + # test test dataset + dataset_benchmark = DatasetBenchmark(cfg, 'test', self.max_iter, + self.log_interval, + self.num_warmup) + dataset_benchmark.run(1) + + # test val dataset + dataset_benchmark = DatasetBenchmark(cfg, 'val', self.max_iter, + self.log_interval, + self.num_warmup) + dataset_benchmark.run(1) + + # test dataset_type input parameters error + with self.assertRaises(AssertionError): + DatasetBenchmark(cfg, 'training', self.max_iter, self.log_interval, + self.num_warmup) + + # test full_init + cfg = copy.deepcopy(self.cfg) + cfg.test_dataloader.dataset = dict(type='ToyFullInitDataset') + dataset_benchmark = DatasetBenchmark(cfg, 'train', self.max_iter, + self.log_interval, + self.num_warmup) + dataset_benchmark.run(1) diff --git a/mmdet_code/SR-TOD/tests/test_utils/test_memory.py b/mmdet_code/SR-TOD/tests/test_utils/test_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..840601c114cc22bb7350ba8be91c7f23cedc4d61 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_utils/test_memory.py @@ -0,0 +1,98 @@ +import numpy as np +import pytest +import torch + +from mmdet.utils import AvoidOOM +from mmdet.utils.memory import cast_tensor_type + + +def test_avoidoom(): + tensor = torch.from_numpy(np.random.random((20, 20))) + if torch.cuda.is_available(): + tensor = tensor.cuda() + # get default result + default_result = torch.mm(tensor, tensor.transpose(1, 0)) + + # when not occurred OOM error + AvoidCudaOOM = AvoidOOM() + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert default_result.device == result.device and \ + default_result.dtype == result.dtype and \ + torch.equal(default_result, result) + + # calculate with fp16 and convert back to source type + AvoidCudaOOM = AvoidOOM(test=True) + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert default_result.device == result.device and \ + default_result.dtype == result.dtype and \ + torch.allclose(default_result, result, 1e-3) + + # calculate on cpu and convert back to source device + AvoidCudaOOM = AvoidOOM(test=True) + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert result.dtype == default_result.dtype and \ + result.device == default_result.device and \ + torch.allclose(default_result, result) + + # do not calculate on cpu and the outputs will be same as input + AvoidCudaOOM = AvoidOOM(test=True, to_cpu=False) + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert result.dtype == default_result.dtype and \ + result.device == default_result.device + + else: + default_result = torch.mm(tensor, tensor.transpose(1, 0)) + AvoidCudaOOM = AvoidOOM() + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert default_result.device == result.device and \ + default_result.dtype == result.dtype and \ + torch.equal(default_result, result) + + +def test_cast_tensor_type(): + inputs = torch.rand(10) + if torch.cuda.is_available(): + inputs = inputs.cuda() + with pytest.raises(AssertionError): + cast_tensor_type(inputs, src_type=None, dst_type=None) + # input is a float + out = cast_tensor_type(10., dst_type=torch.half) + assert out == 10. and isinstance(out, float) + # convert Tensor to fp16 and re-convert to fp32 + fp16_out = cast_tensor_type(inputs, dst_type=torch.half) + assert fp16_out.dtype == torch.half + fp32_out = cast_tensor_type(fp16_out, dst_type=torch.float32) + assert fp32_out.dtype == torch.float32 + + # input is a list + list_input = [inputs, inputs] + list_outs = cast_tensor_type(list_input, dst_type=torch.half) + assert len(list_outs) == len(list_input) and \ + isinstance(list_outs, list) + for out in list_outs: + assert out.dtype == torch.half + # input is a dict + dict_input = {'test1': inputs, 'test2': inputs} + dict_outs = cast_tensor_type(dict_input, dst_type=torch.half) + assert len(dict_outs) == len(dict_input) and \ + isinstance(dict_outs, dict) + + # convert the input tensor to CPU and re-convert to GPU + if torch.cuda.is_available(): + cpu_device = torch.empty(0).device + gpu_device = inputs.device + cpu_out = cast_tensor_type(inputs, dst_type=cpu_device) + assert cpu_out.device == cpu_device + + gpu_out = cast_tensor_type(inputs, dst_type=gpu_device) + assert gpu_out.device == gpu_device diff --git a/mmdet_code/SR-TOD/tests/test_utils/test_replace_cfg_vals.py b/mmdet_code/SR-TOD/tests/test_utils/test_replace_cfg_vals.py new file mode 100644 index 0000000000000000000000000000000000000000..de039f95eee41cbc69aec15c397fd9acd5cbf948 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_utils/test_replace_cfg_vals.py @@ -0,0 +1,83 @@ +import os.path as osp +import tempfile +from copy import deepcopy + +import pytest +from mmengine.config import Config + +from mmdet.utils import replace_cfg_vals + + +def test_replace_cfg_vals(): + temp_file = tempfile.NamedTemporaryFile() + cfg_path = f'{temp_file.name}.py' + with open(cfg_path, 'w') as f: + f.write('configs') + + ori_cfg_dict = dict() + ori_cfg_dict['cfg_name'] = osp.basename(temp_file.name) + ori_cfg_dict['work_dir'] = 'work_dirs/${cfg_name}/${percent}/${fold}' + ori_cfg_dict['percent'] = 5 + ori_cfg_dict['fold'] = 1 + ori_cfg_dict['model_wrapper'] = dict( + type='SoftTeacher', detector='${model}') + ori_cfg_dict['model'] = dict( + type='FasterRCNN', + backbone=dict(type='ResNet'), + neck=dict(type='FPN'), + rpn_head=dict(type='RPNHead'), + roi_head=dict(type='StandardRoIHead'), + train_cfg=dict( + rpn=dict( + assigner=dict(type='MaxIoUAssigner'), + sampler=dict(type='RandomSampler'), + ), + rpn_proposal=dict(nms=dict(type='nms', iou_threshold=0.7)), + rcnn=dict( + assigner=dict(type='MaxIoUAssigner'), + sampler=dict(type='RandomSampler'), + ), + ), + test_cfg=dict( + rpn=dict(nms=dict(type='nms', iou_threshold=0.7)), + rcnn=dict(nms=dict(type='nms', iou_threshold=0.5)), + ), + ) + ori_cfg_dict['iou_threshold'] = dict( + rpn_proposal_nms='${model.train_cfg.rpn_proposal.nms.iou_threshold}', + test_rpn_nms='${model.test_cfg.rpn.nms.iou_threshold}', + test_rcnn_nms='${model.test_cfg.rcnn.nms.iou_threshold}', + ) + + ori_cfg_dict['str'] = 'Hello, world!' + ori_cfg_dict['dict'] = {'Hello': 'world!'} + ori_cfg_dict['list'] = [ + 'Hello, world!', + ] + ori_cfg_dict['tuple'] = ('Hello, world!', ) + ori_cfg_dict['test_str'] = 'xxx${str}xxx' + + ori_cfg = Config(ori_cfg_dict, filename=cfg_path) + updated_cfg = replace_cfg_vals(deepcopy(ori_cfg)) + + assert updated_cfg.work_dir \ + == f'work_dirs/{osp.basename(temp_file.name)}/5/1' + assert updated_cfg.model.detector == ori_cfg.model + assert updated_cfg.iou_threshold.rpn_proposal_nms \ + == ori_cfg.model.train_cfg.rpn_proposal.nms.iou_threshold + assert updated_cfg.test_str == 'xxxHello, world!xxx' + ori_cfg_dict['test_dict'] = 'xxx${dict}xxx' + ori_cfg_dict['test_list'] = 'xxx${list}xxx' + ori_cfg_dict['test_tuple'] = 'xxx${tuple}xxx' + with pytest.raises(AssertionError): + cfg = deepcopy(ori_cfg) + cfg['test_dict'] = 'xxx${dict}xxx' + updated_cfg = replace_cfg_vals(cfg) + with pytest.raises(AssertionError): + cfg = deepcopy(ori_cfg) + cfg['test_list'] = 'xxx${list}xxx' + updated_cfg = replace_cfg_vals(cfg) + with pytest.raises(AssertionError): + cfg = deepcopy(ori_cfg) + cfg['test_tuple'] = 'xxx${tuple}xxx' + updated_cfg = replace_cfg_vals(cfg) diff --git a/mmdet_code/SR-TOD/tests/test_utils/test_setup_env.py b/mmdet_code/SR-TOD/tests/test_utils/test_setup_env.py new file mode 100644 index 0000000000000000000000000000000000000000..34c37161c3f3657c9ac6977c66d439193c42b173 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_utils/test_setup_env.py @@ -0,0 +1,38 @@ +import datetime +import sys +from unittest import TestCase + +from mmengine import DefaultScope + +from mmdet.utils import register_all_modules + + +class TestSetupEnv(TestCase): + + def test_register_all_modules(self): + from mmdet.registry import DATASETS + + # not init default scope + sys.modules.pop('mmdet.datasets', None) + sys.modules.pop('mmdet.datasets.coco', None) + DATASETS._module_dict.pop('CocoDataset', None) + self.assertFalse('CocoDataset' in DATASETS.module_dict) + register_all_modules(init_default_scope=False) + self.assertTrue('CocoDataset' in DATASETS.module_dict) + + # init default scope + sys.modules.pop('mmdet.datasets') + sys.modules.pop('mmdet.datasets.coco') + DATASETS._module_dict.pop('CocoDataset', None) + self.assertFalse('CocoDataset' in DATASETS.module_dict) + register_all_modules(init_default_scope=True) + self.assertTrue('CocoDataset' in DATASETS.module_dict) + self.assertEqual(DefaultScope.get_current_instance().scope_name, + 'mmdet') + + # init default scope when another scope is init + name = f'test-{datetime.datetime.now()}' + DefaultScope.get_instance(name, scope_name='test') + with self.assertWarnsRegex( + Warning, 'The current default scope "test" is not "mmdet"'): + register_all_modules(init_default_scope=True) diff --git a/mmdet_code/SR-TOD/tests/test_visualization/test_local_visualizer.py b/mmdet_code/SR-TOD/tests/test_visualization/test_local_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..b745adf74fc252a9fd67c44040769b52aa489247 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_visualization/test_local_visualizer.py @@ -0,0 +1,199 @@ +import os +from unittest import TestCase + +import cv2 +import numpy as np +import torch +from mmengine.structures import InstanceData, PixelData + +from mmdet.evaluation import INSTANCE_OFFSET +from mmdet.structures import DetDataSample +from mmdet.visualization import DetLocalVisualizer, TrackLocalVisualizer + + +def _rand_bboxes(num_boxes, h, w): + cx, cy, bw, bh = torch.rand(num_boxes, 4).T + + tl_x = ((cx * w) - (w * bw / 2)).clamp(0, w) + tl_y = ((cy * h) - (h * bh / 2)).clamp(0, h) + br_x = ((cx * w) + (w * bw / 2)).clamp(0, w) + br_y = ((cy * h) + (h * bh / 2)).clamp(0, h) + + bboxes = torch.stack([tl_x, tl_y, br_x, br_y], dim=0).T + return bboxes + + +def _create_panoptic_data(num_boxes, h, w): + sem_seg = np.zeros((h, w), dtype=np.int64) + 2 + bboxes = _rand_bboxes(num_boxes, h, w).int() + labels = torch.randint(2, (num_boxes, )) + for i in range(num_boxes): + x, y, w, h = bboxes[i] + sem_seg[y:y + h, x:x + w] = (i + 1) * INSTANCE_OFFSET + labels[i] + + return sem_seg[None] + + +class TestDetLocalVisualizer(TestCase): + + def test_add_datasample(self): + h = 12 + w = 10 + num_class = 3 + num_bboxes = 5 + out_file = 'out_file.jpg' + + image = np.random.randint(0, 256, size=(h, w, 3)).astype('uint8') + + # test gt_instances + gt_instances = InstanceData() + gt_instances.bboxes = _rand_bboxes(num_bboxes, h, w) + gt_instances.labels = torch.randint(0, num_class, (num_bboxes, )) + det_data_sample = DetDataSample() + det_data_sample.gt_instances = gt_instances + + det_local_visualizer = DetLocalVisualizer() + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, draw_pred=False) + + # test out_file + det_local_visualizer.add_datasample( + 'image', + image, + det_data_sample, + draw_pred=False, + out_file=out_file) + assert os.path.exists(out_file) + drawn_img = cv2.imread(out_file) + assert drawn_img.shape == (h, w, 3) + os.remove(out_file) + + # test gt_instances and pred_instances + pred_instances = InstanceData() + pred_instances.bboxes = _rand_bboxes(num_bboxes, h, w) + pred_instances.labels = torch.randint(0, num_class, (num_bboxes, )) + pred_instances.scores = torch.rand((num_bboxes, )) + det_data_sample.pred_instances = pred_instances + + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, out_file=out_file) + self._assert_image_and_shape(out_file, (h, w * 2, 3)) + + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, draw_gt=False, out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) + + det_local_visualizer.add_datasample( + 'image', + image, + det_data_sample, + draw_pred=False, + out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) + + # test gt_panoptic_seg and pred_panoptic_seg + det_local_visualizer.dataset_meta = dict(classes=('1', '2')) + gt_sem_seg = _create_panoptic_data(num_bboxes, h, w) + panoptic_seg = PixelData(sem_seg=gt_sem_seg) + + det_data_sample = DetDataSample() + det_data_sample.gt_panoptic_seg = panoptic_seg + + pred_sem_seg = _create_panoptic_data(num_bboxes, h, w) + panoptic_seg = PixelData(sem_seg=pred_sem_seg) + det_data_sample.pred_panoptic_seg = panoptic_seg + + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, out_file=out_file) + self._assert_image_and_shape(out_file, (h, w * 2, 3)) + + # class information must be provided + det_local_visualizer.dataset_meta = {} + with self.assertRaises(AssertionError): + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, out_file=out_file) + + def _assert_image_and_shape(self, out_file, out_shape): + assert os.path.exists(out_file) + drawn_img = cv2.imread(out_file) + assert drawn_img.shape == out_shape + os.remove(out_file) + + +class TestTrackLocalVisualizer(TestCase): + + @staticmethod + def _get_gt_instances(): + bboxes = np.array([[912, 484, 1009, 593], [1338, 418, 1505, 797]]) + masks = np.zeros((2, 1080, 1920), dtype=np.bool_) + for i, bbox in enumerate(bboxes): + masks[i, bbox[1]:bbox[3], bbox[0]:bbox[2]] = True + instances_data = dict( + bboxes=torch.tensor(bboxes), + masks=masks, + instances_id=torch.tensor([1, 2]), + labels=torch.tensor([0, 1])) + instances = InstanceData(**instances_data) + return instances + + @staticmethod + def _get_pred_instances(): + instances_data = dict( + bboxes=torch.tensor([[900, 500, 1000, 600], [1300, 400, 1500, + 800]]), + instances_id=torch.tensor([1, 2]), + labels=torch.tensor([0, 1]), + scores=torch.tensor([0.955, 0.876])) + instances = InstanceData(**instances_data) + return instances + + @staticmethod + def _assert_image_and_shape(out_file, out_shape): + assert os.path.exists(out_file) + drawn_img = cv2.imread(out_file) + assert drawn_img.shape == out_shape + os.remove(out_file) + + def test_add_datasample(self): + out_file = 'out_file.jpg' + h, w = 1080, 1920 + image = np.random.randint(0, 256, size=(h, w, 3)).astype('uint8') + gt_instances = self._get_gt_instances() + pred_instances = self._get_pred_instances() + image_data_sample = DetDataSample() + image_data_sample.gt_instances = gt_instances + image_data_sample.pred_track_instances = pred_instances + + track_local_visualizer = TrackLocalVisualizer(alpha=0.2) + track_local_visualizer.dataset_meta = dict( + classes=['pedestrian', 'vehicle']) + + # test gt_instances + track_local_visualizer.add_datasample('image', image, + image_data_sample, None) + + # test out_file + track_local_visualizer.add_datasample( + 'image', image, image_data_sample, None, out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) + + # test gt_instances and pred_instances + track_local_visualizer.add_datasample( + 'image', image, image_data_sample, out_file=out_file) + self._assert_image_and_shape(out_file, (h, 2 * w, 3)) + + track_local_visualizer.add_datasample( + 'image', + image, + image_data_sample, + draw_gt=False, + out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) + + track_local_visualizer.add_datasample( + 'image', + image, + image_data_sample, + draw_pred=False, + out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) diff --git a/mmdet_code/SR-TOD/tests/test_visualization/test_palette.py b/mmdet_code/SR-TOD/tests/test_visualization/test_palette.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1fd65e9827f625adc4dda8599238b6a627cfd5 --- /dev/null +++ b/mmdet_code/SR-TOD/tests/test_visualization/test_palette.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np + +from mmdet.datasets import CocoDataset +from mmdet.visualization import get_palette, jitter_color, palette_val + + +def test_palette(): + assert palette_val([(1, 2, 3)])[0] == (1 / 255, 2 / 255, 3 / 255) + + # test list + palette = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] + palette_ = get_palette(palette, 3) + for color, color_ in zip(palette, palette_): + assert color == color_ + + # test tuple + palette = get_palette((1, 2, 3), 3) + assert len(palette) == 3 + for color in palette: + assert color == (1, 2, 3) + + # test color str + palette = get_palette('red', 3) + assert len(palette) == 3 + for color in palette: + assert color == (255, 0, 0) + + # test dataset str + palette = get_palette('coco', len(CocoDataset.METAINFO['classes'])) + assert len(palette) == len(CocoDataset.METAINFO['classes']) + assert palette[0] == (220, 20, 60) + + # TODO: Awaiting refactoring + # palette = get_palette('coco', len(CocoPanopticDataset.METAINFO['CLASSES'])) # noqa + # assert len(palette) == len(CocoPanopticDataset.METAINFO['CLASSES']) + # assert palette[-1] == (250, 141, 255) + # palette = get_palette('voc', len(VOCDataset.METAINFO['CLASSES'])) + # assert len(palette) == len(VOCDataset.METAINFO['CLASSES']) + # assert palette[0] == (106, 0, 228) + # palette = get_palette('citys', len(CityscapesDataset.METAINFO['CLASSES'])) # noqa + # assert len(palette) == len(CityscapesDataset.METAINFO['CLASSES']) + # assert palette[0] == (220, 20, 60) + + # test random + palette1 = get_palette('random', 3) + palette2 = get_palette(None, 3) + for color1, color2 in zip(palette1, palette2): + assert isinstance(color1, tuple) + assert isinstance(color2, tuple) + assert color1 == color2 + + +def test_jitter_color(): + color = tuple(np.random.randint(0, 255, 3, np.uint8)) + jittered_color = jitter_color(color) + for c in jittered_color: + assert 0 <= c <= 255 diff --git a/mmdet_code/__pycache__/train_all_levir_baseline.cpython-313.pyc b/mmdet_code/__pycache__/train_all_levir_baseline.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eff74583caabef3b375ed361b422bf60d1caf49 Binary files /dev/null and b/mmdet_code/__pycache__/train_all_levir_baseline.cpython-313.pyc differ diff --git a/mmdet_code/__pycache__/train_all_levir_baseline.cpython-314.pyc b/mmdet_code/__pycache__/train_all_levir_baseline.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b5dbea2283b6e272d1a0ad131be2ce4be0bade3 Binary files /dev/null and b/mmdet_code/__pycache__/train_all_levir_baseline.cpython-314.pyc differ diff --git a/mmdet_code/__pycache__/train_all_mmdet.cpython-313.pyc b/mmdet_code/__pycache__/train_all_mmdet.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39630987378cca657b3c8ae91216c129651dd238 Binary files /dev/null and b/mmdet_code/__pycache__/train_all_mmdet.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/.github/CODE_OF_CONDUCT.md b/mmdet_code/mmdetection/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..92afad1c5ab5d5781115dee45c131d3751d3cd31 --- /dev/null +++ b/mmdet_code/mmdetection/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or + advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic + address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at chenkaidev@gmail.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq + +[homepage]: https://www.contributor-covenant.org diff --git a/mmdet_code/mmdetection/.github/CONTRIBUTING.md b/mmdet_code/mmdetection/.github/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..c6696262b4a1469314c1bf76b36e4e24519aeec9 --- /dev/null +++ b/mmdet_code/mmdetection/.github/CONTRIBUTING.md @@ -0,0 +1 @@ +We appreciate all contributions to improve MMDetection. Please refer to [CONTRIBUTING.md](https://github.com/open-mmlab/mmcv/blob/master/CONTRIBUTING.md) in MMCV for more details about the contributing guideline. diff --git a/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/config.yml b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..56bbd88fddfd7a1ceb50a1cb406e80318a8d0370 --- /dev/null +++ b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,9 @@ +blank_issues_enabled: false + +contact_links: + - name: Common Issues + url: https://mmdetection.readthedocs.io/en/latest/faq.html + about: Check if your issue already has solutions + - name: MMDetection Documentation + url: https://mmdetection.readthedocs.io/en/latest/ + about: Check if your question is answered in docs diff --git a/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/error-report.md b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/error-report.md new file mode 100644 index 0000000000000000000000000000000000000000..9dbd3ff165bec349f4813e8a6b50c009e95345e7 --- /dev/null +++ b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/error-report.md @@ -0,0 +1,46 @@ +--- +name: Error report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' +--- + +Thanks for your error report and we appreciate it a lot. + +**Checklist** + +1. I have searched related issues but cannot get the expected help. +2. I have read the [FAQ documentation](https://mmdetection.readthedocs.io/en/latest/faq.html) but cannot get the expected help. +3. The bug has not been fixed in the latest version. + +**Describe the bug** +A clear and concise description of what the bug is. + +**Reproduction** + +1. What command or script did you run? + +```none +A placeholder for the command. +``` + +2. Did you make any modifications on the code or config? Did you understand what you have modified? +3. What dataset did you use? + +**Environment** + +1. Please run `python mmdet/utils/collect_env.py` to collect necessary environment information and paste it here. +2. You may add addition that may be helpful for locating the problem, such as + - How you installed PyTorch \[e.g., pip, conda, source\] + - Other environment variables that may be related (such as `$PATH`, `$LD_LIBRARY_PATH`, `$PYTHONPATH`, etc.) + +**Error traceback** +If applicable, paste the error trackback here. + +```none +A placeholder for trackback. +``` + +**Bug fix** +If you have already identified the reason, you can provide the information here. If you are willing to create a PR to fix it, please also leave a comment here and that would be much appreciated! diff --git a/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/feature_request.md b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..7bf92e8c912df6839eb755715c181f5fc7244f36 --- /dev/null +++ b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' +--- + +**Describe the feature** + +**Motivation** +A clear and concise description of the motivation of the feature. +Ex1. It is inconvenient when \[....\]. +Ex2. There is a recent paper \[....\], which is very helpful for \[....\]. + +**Related resources** +If there is an official code release or third-party implementations, please also provide the information here, which would be very helpful. + +**Additional context** +Add any other context or screenshots about the feature request here. +If you would like to implement the feature and create a PR, please leave a comment here and that would be much appreciated. diff --git a/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/general_questions.md b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/general_questions.md new file mode 100644 index 0000000000000000000000000000000000000000..f02dd63a8095c65ca6a46172d8c739c6cde3e5f0 --- /dev/null +++ b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/general_questions.md @@ -0,0 +1,7 @@ +--- +name: General questions +about: Ask general questions to get help +title: '' +labels: '' +assignees: '' +--- diff --git a/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/reimplementation_questions.md b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/reimplementation_questions.md new file mode 100644 index 0000000000000000000000000000000000000000..83607ac34028bec7312e2f163777da77a0da192f --- /dev/null +++ b/mmdet_code/mmdetection/.github/ISSUE_TEMPLATE/reimplementation_questions.md @@ -0,0 +1,67 @@ +--- +name: Reimplementation Questions +about: Ask about questions during model reimplementation +title: '' +labels: reimplementation +assignees: '' +--- + +**Notice** + +There are several common situations in the reimplementation issues as below + +1. Reimplement a model in the model zoo using the provided configs +2. Reimplement a model in the model zoo on other dataset (e.g., custom datasets) +3. Reimplement a custom model but all the components are implemented in MMDetection +4. Reimplement a custom model with new modules implemented by yourself + +There are several things to do for different cases as below. + +- For case 1 & 3, please follow the steps in the following sections thus we could help to quick identify the issue. +- For case 2 & 4, please understand that we are not able to do much help here because we usually do not know the full code and the users should be responsible to the code they write. +- One suggestion for case 2 & 4 is that the users should first check whether the bug lies in the self-implemented code or the original code. For example, users can first make sure that the same model runs well on supported datasets. If you still need help, please describe what you have done and what you obtain in the issue, and follow the steps in the following sections and try as clear as possible so that we can better help you. + +**Checklist** + +1. I have searched related issues but cannot get the expected help. +2. The issue has not been fixed in the latest version. + +**Describe the issue** + +A clear and concise description of what the problem you meet and what have you done. + +**Reproduction** + +1. What command or script did you run? + +```none +A placeholder for the command. +``` + +2. What config dir you run? + +```none +A placeholder for the config. +``` + +3. Did you make any modifications on the code or config? Did you understand what you have modified? +4. What dataset did you use? + +**Environment** + +1. Please run `python mmdet/utils/collect_env.py` to collect necessary environment information and paste it here. +2. You may add addition that may be helpful for locating the problem, such as + 1. How you installed PyTorch \[e.g., pip, conda, source\] + 2. Other environment variables that may be related (such as `$PATH`, `$LD_LIBRARY_PATH`, `$PYTHONPATH`, etc.) + +**Results** + +If applicable, paste the related results here, e.g., what you expect and what you get. + +```none +A placeholder for results comparison +``` + +**Issue fix** + +If you have already identified the reason, you can provide the information here. If you are willing to create a PR to fix it, please also leave a comment here and that would be much appreciated! diff --git a/mmdet_code/mmdetection/.github/pull_request_template.md b/mmdet_code/mmdetection/.github/pull_request_template.md new file mode 100644 index 0000000000000000000000000000000000000000..7a9f0d901f45d977a29e5030fb2c67993026ae3d --- /dev/null +++ b/mmdet_code/mmdetection/.github/pull_request_template.md @@ -0,0 +1,25 @@ +Thanks for your contribution and we appreciate it a lot. The following instructions would make your pull request more healthy and more easily get feedback. If you do not understand some items, don't worry, just make the pull request and seek help from maintainers. + +## Motivation + +Please describe the motivation of this PR and the goal you want to achieve through this PR. + +## Modification + +Please briefly describe what modification is made in this PR. + +## BC-breaking (Optional) + +Does the modification introduce changes that break the backward-compatibility of the downstream repos? +If so, please describe how it breaks the compatibility and how the downstream projects should modify their code to keep compatibility with this PR. + +## Use cases (Optional) + +If this PR introduces a new feature, it is better to list some use cases here, and update the documentation. + +## Checklist + +1. Pre-commit or other linting tools are used to fix the potential lint issues. +2. The modification is covered by complete unit tests. If not, please add more unit test to ensure the correctness. +3. If the modification has potential influence on downstream projects, this PR should be tested with downstream projects, like MMDet or MMPreTrain. +4. The documentation has been modified accordingly, like docstring or example tutorials. diff --git a/mmdet_code/mmdetection/.github/workflows/deploy.yml b/mmdet_code/mmdetection/.github/workflows/deploy.yml new file mode 100644 index 0000000000000000000000000000000000000000..f575061468b98978caa067c970ad853efc0cfa21 --- /dev/null +++ b/mmdet_code/mmdetection/.github/workflows/deploy.yml @@ -0,0 +1,28 @@ +name: deploy + +on: push + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-n-publish: + runs-on: ubuntu-latest + if: startsWith(github.event.ref, 'refs/tags') + steps: + - uses: actions/checkout@v2 + - name: Set up Python 3.7 + uses: actions/setup-python@v2 + with: + python-version: 3.7 + - name: Install torch + run: pip install torch + - name: Install wheel + run: pip install wheel + - name: Build MMDetection + run: python setup.py sdist bdist_wheel + - name: Publish distribution to PyPI + run: | + pip install twine + twine upload dist/* -u __token__ -p ${{ secrets.pypi_password }} diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_instance.py b/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..57f657aa67f34830515f410425eccc96cb065af4 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_instance.py @@ -0,0 +1,53 @@ +# dataset settings +dataset_type = 'ADE20KInstanceDataset' +data_root = 'data/ADEChallengeData2016/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/ADEChallengeData2016/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2560, 640), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='ade20k_instance_val.json', + data_prefix=dict(img='images/validation'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'ade20k_instance_val.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_panoptic.py b/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..7be5ddd7f0732193f4f92bc49e52493602928162 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_panoptic.py @@ -0,0 +1,38 @@ +# dataset settings +dataset_type = 'ADE20KPanopticDataset' +data_root = 'data/ADEChallengeData2016/' + +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2560, 640), keep_ratio=True), + dict(type='LoadPanopticAnnotations', backend_args=backend_args), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=0, + persistent_workers=False, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='ade20k_panoptic_val.json', + data_prefix=dict(img='images/validation/', seg='ade20k_panoptic_val/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoPanopticMetric', + ann_file=data_root + 'ade20k_panoptic_val.json', + seg_prefix=data_root + 'ade20k_panoptic_val/', + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_semantic.py b/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..522a775704182ededaa36f318cd1eb185784918f --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/ade20k_semantic.py @@ -0,0 +1,48 @@ +dataset_type = 'ADE20KSegDataset' +data_root = 'data/ADEChallengeData2016/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/ADEChallengeData2016/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2048, 512), keep_ratio=True), + dict( + type='LoadAnnotations', + with_bbox=False, + with_mask=False, + with_seg=True, + reduce_zero_label=True), + dict( + type='PackDetInputs', meta_keys=('img_path', 'ori_shape', 'img_shape')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='images/validation', + seg_map_path='annotations/validation'), + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +val_evaluator = dict(type='SemSegMetric', iou_metrics=['mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/cityscapes_detection.py b/mmdet_code/mmdetection/configs/_base_/datasets/cityscapes_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..caeba6bfcd26d8954fc9d499446e93323e372959 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/cityscapes_detection.py @@ -0,0 +1,84 @@ +# dataset settings +dataset_type = 'CityscapesDataset' +data_root = 'data/cityscapes/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/segmentation/cityscapes/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/segmentation/', +# 'data/': 's3://openmmlab/datasets/segmentation/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomResize', + scale=[(2048, 800), (2048, 1024)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2048, 1024), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=8, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instancesonly_filtered_gtFine_train.json', + data_prefix=dict(img='leftImg8bit/train/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instancesonly_filtered_gtFine_val.json', + data_prefix=dict(img='leftImg8bit/val/'), + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instancesonly_filtered_gtFine_val.json', + metric='bbox', + backend_args=backend_args) + +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/cityscapes_instance.py b/mmdet_code/mmdetection/configs/_base_/datasets/cityscapes_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..136403136c67a6726662832b66f56701ff5aba8a --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/cityscapes_instance.py @@ -0,0 +1,113 @@ +# dataset settings +dataset_type = 'CityscapesDataset' +data_root = 'data/cityscapes/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/segmentation/cityscapes/' + +# Method 2: Use backend_args, file_client_args in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/segmentation/', +# 'data/': 's3://openmmlab/datasets/segmentation/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', + scale=[(2048, 800), (2048, 1024)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(2048, 1024), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=8, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instancesonly_filtered_gtFine_train.json', + data_prefix=dict(img='leftImg8bit/train/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instancesonly_filtered_gtFine_val.json', + data_prefix=dict(img='leftImg8bit/val/'), + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = [ + dict( + type='CocoMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + metric=['bbox', 'segm'], + backend_args=backend_args), + dict( + type='CityScapesMetric', + seg_prefix=data_root + 'gtFine/val', + outfile_prefix='./work_dirs/cityscapes_metric/instance', + backend_args=backend_args) +] + +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file='annotations/instancesonly_filtered_gtFine_test.json', +# data_prefix=dict(img='leftImg8bit/test/'), +# test_mode=True, +# filter_cfg=dict(filter_empty_gt=True, min_size=32), +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CityScapesMetric', +# format_only=True, +# outfile_prefix='./work_dirs/cityscapes_metric/test') diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/coco_caption.py b/mmdet_code/mmdetection/configs/_base_/datasets/coco_caption.py new file mode 100644 index 0000000000000000000000000000000000000000..a1bd898313927e4fca336dfa10f05e78b9fb7162 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/coco_caption.py @@ -0,0 +1,60 @@ +# data settings + +dataset_type = 'CocoCaptionDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +test_pipeline = [ + dict( + type='LoadImageFromFile', + imdecode_backend='pillow', + backend_args=backend_args), + dict( + type='Resize', + scale=(224, 224), + interpolation='bicubic', + backend='pillow'), + dict(type='PackInputs', meta_keys=['image_id']), +] + +# ann_file download from +# train dataset: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_train.json # noqa +# val dataset: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val.json # noqa +# test dataset: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test.json # noqa +# val evaluator: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val_gt.json # noqa +# test evaluator: https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test_gt.json # noqa +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/coco_karpathy_val.json', + pipeline=test_pipeline, + )) + +val_evaluator = dict( + type='COCOCaptionMetric', + ann_file=data_root + 'annotations/coco_karpathy_val_gt.json', +) + +# # If you want standard test, please manually configure the test dataset +test_dataloader = val_dataloader +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/coco_detection.py b/mmdet_code/mmdetection/configs/_base_/datasets/coco_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf8dfad9476b1d7b7a4e8c3e2832f115a1ea7f2 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/coco_detection.py @@ -0,0 +1,95 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoMetric', +# metric='bbox', +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_detection/test') diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/coco_instance.py b/mmdet_code/mmdetection/configs/_base_/datasets/coco_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..e91cb354038db4df3b990b307a5da9d77f341a88 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/coco_instance.py @@ -0,0 +1,95 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoMetric', +# metric=['bbox', 'segm'], +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_instance/test') diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/coco_instance_semantic.py b/mmdet_code/mmdetection/configs/_base_/datasets/coco_instance_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..cc961863306690c056e564b542d518c0ebfbb7e2 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/coco_instance_semantic.py @@ -0,0 +1,78 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict( + type='LoadAnnotations', with_bbox=True, with_mask=True, with_seg=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict( + type='LoadAnnotations', with_bbox=True, with_mask=True, with_seg=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/', seg='stuffthingmaps/train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/coco_panoptic.py b/mmdet_code/mmdetection/configs/_base_/datasets/coco_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..0b95b619e68ed531d361bbd11a2382852c13446e --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/coco_panoptic.py @@ -0,0 +1,94 @@ +# dataset settings +dataset_type = 'CocoPanopticDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadPanopticAnnotations', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadPanopticAnnotations', backend_args=backend_args), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/panoptic_train2017.json', + data_prefix=dict( + img='train2017/', seg='annotations/panoptic_train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/panoptic_val2017.json', + data_prefix=dict(img='val2017/', seg='annotations/panoptic_val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoPanopticMetric', + ann_file=data_root + 'annotations/panoptic_val2017.json', + seg_prefix=data_root + 'annotations/panoptic_val2017/', + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=1, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type='DefaultSampler', shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file='annotations/panoptic_image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type='CocoPanopticMetric', +# format_only=True, +# ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_panoptic/test') diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/coco_semantic.py b/mmdet_code/mmdetection/configs/_base_/datasets/coco_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..944bbbaeaeb6f10f0946bd1fc828bb01ea6c1fc3 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/coco_semantic.py @@ -0,0 +1,78 @@ +# dataset settings +dataset_type = 'CocoSegDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict( + type='LoadAnnotations', + with_bbox=False, + with_label=False, + with_seg=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_bbox=False, + with_label=False, + with_seg=True), + dict( + type='PackDetInputs', + meta_keys=('img_path', 'ori_shape', 'img_shape', 'scale_factor')) +] + +# For stuffthingmaps_semseg, please refer to +# `docs/en/user_guides/dataset_prepare.md` +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='train2017/', + seg_map_path='stuffthingmaps_semseg/train2017/'), + pipeline=train_pipeline)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='val2017/', + seg_map_path='stuffthingmaps_semseg/val2017/'), + pipeline=test_pipeline)) + +test_dataloader = val_dataloader + +val_evaluator = dict(type='SemSegMetric', iou_metrics=['mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/deepfashion.py b/mmdet_code/mmdetection/configs/_base_/datasets/deepfashion.py new file mode 100644 index 0000000000000000000000000000000000000000..a93dc7152f7a2e28ab726c79f9398a1034b7b4a1 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/deepfashion.py @@ -0,0 +1,95 @@ +# dataset settings +dataset_type = 'DeepFashionDataset' +data_root = 'data/DeepFashion/In-shop/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='Resize', scale=(750, 1101), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(750, 1101), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=2, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='Anno/segmentation/DeepFashion_segmentation_train.json', + data_prefix=dict(img='Img/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='Anno/segmentation/DeepFashion_segmentation_query.json', + data_prefix=dict(img='Img/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='Anno/segmentation/DeepFashion_segmentation_gallery.json', + data_prefix=dict(img='Img/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + + 'Anno/segmentation/DeepFashion_segmentation_query.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = dict( + type='CocoMetric', + ann_file=data_root + + 'Anno/segmentation/DeepFashion_segmentation_gallery.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/dsdl.py b/mmdet_code/mmdetection/configs/_base_/datasets/dsdl.py new file mode 100644 index 0000000000000000000000000000000000000000..1f19e5e498b18a404f3c4e6419316b5f9981e811 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/dsdl.py @@ -0,0 +1,62 @@ +dataset_type = 'DSDLDetDataset' +data_root = 'path to dataset folder' +train_ann = 'path to train yaml file' +val_ann = 'path to val yaml file' + +backend_args = None +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': "s3://open_data/", +# 'data/': "s3://open_data/" +# })) + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'instances')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=train_ann, + filter_cfg=dict(filter_empty_gt=True, min_size=32, bbox_min_size=32), + pipeline=train_pipeline)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=val_ann, + test_mode=True, + pipeline=test_pipeline)) + +test_dataloader = val_dataloader + +val_evaluator = dict(type='CocoMetric', metric='bbox') +# val_evaluator = dict(type='VOCMetric', metric='mAP', eval_mode='11points') +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/isaid_instance.py b/mmdet_code/mmdetection/configs/_base_/datasets/isaid_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..09ddcab02bdd52374d5093d446abb0e34751f7a3 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/isaid_instance.py @@ -0,0 +1,59 @@ +# dataset settings +dataset_type = 'iSAIDDataset' +data_root = 'data/iSAID/' +backend_args = None + +# Please see `projects/iSAID/README.md` for data preparation +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='Resize', scale=(800, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(800, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='train/instancesonly_filtered_train.json', + data_prefix=dict(img='train/images/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='val/instancesonly_filtered_val.json', + data_prefix=dict(img='val/images/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'val/instancesonly_filtered_val.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/lvis_v0.5_instance.py b/mmdet_code/mmdetection/configs/_base_/datasets/lvis_v0.5_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ca44efb6d31aae5f6426a1c8b89d2e9be2104f --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/lvis_v0.5_instance.py @@ -0,0 +1,79 @@ +# dataset settings +dataset_type = 'LVISV05Dataset' +data_root = 'data/lvis_v0.5/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/lvis_v0.5/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomChoiceResize', + scales=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='ClassBalancedDataset', + oversample_thr=1e-3, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/lvis_v0.5_train.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/lvis_v0.5_val.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='LVISMetric', + ann_file=data_root + 'annotations/lvis_v0.5_val.json', + metric=['bbox', 'segm'], + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/lvis_v1_instance.py b/mmdet_code/mmdetection/configs/_base_/datasets/lvis_v1_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..0413f370a2b635362a60c20881769064bac9a603 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/lvis_v1_instance.py @@ -0,0 +1,22 @@ +# dataset settings +_base_ = 'lvis_v0.5_instance.py' +dataset_type = 'LVISV1Dataset' +data_root = 'data/lvis_v1/' + +train_dataloader = dict( + dataset=dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/lvis_v1_train.json', + data_prefix=dict(img='')))) +val_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/lvis_v1_val.json', + data_prefix=dict(img=''))) +test_dataloader = val_dataloader + +val_evaluator = dict(ann_file=data_root + 'annotations/lvis_v1_val.json') +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge.py b/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge.py new file mode 100644 index 0000000000000000000000000000000000000000..ce2828ef70a34c123792d252bf992f423049d065 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge.py @@ -0,0 +1,90 @@ +# dataset settings +dataset_type = 'MOTChallengeDataset' +data_root = 'data/MOT17/' +img_scale = (1088, 1088) + +backend_args = None +# data pipeline +train_pipeline = [ + dict( + type='UniformRefFrameSample', + num_ref_imgs=1, + frame_range=10, + filter_key_img=True), + dict( + type='TransformBroadcaster', + share_random_params=True, + transforms=[ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadTrackAnnotations'), + dict( + type='RandomResize', + scale=img_scale, + ratio_range=(0.8, 1.2), + keep_ratio=True, + clip_object_border=False), + dict(type='PhotoMetricDistortion') + ]), + dict( + type='TransformBroadcaster', + # different cropped positions for different frames + share_random_params=False, + transforms=[ + dict( + type='RandomCrop', crop_size=img_scale, bbox_clip_border=False) + ]), + dict( + type='TransformBroadcaster', + share_random_params=True, + transforms=[ + dict(type='RandomFlip', prob=0.5), + ]), + dict(type='PackTrackInputs') +] + +test_pipeline = [ + dict( + type='TransformBroadcaster', + transforms=[ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=img_scale, keep_ratio=True), + dict(type='LoadTrackAnnotations') + ]), + dict(type='PackTrackInputs') +] + +# dataloader +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='TrackImgSampler'), # image-based sampling + dataset=dict( + type=dataset_type, + data_root=data_root, + visibility_thr=-1, + ann_file='annotations/half-train_cocoformat.json', + data_prefix=dict(img_path='train'), + metainfo=dict(classes=('pedestrian', )), + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + # Now we support two ways to test, image_based and video_based + # if you want to use video_based sampling, you can use as follows + # sampler=dict(type='DefaultSampler', shuffle=False, round_up=False), + sampler=dict(type='TrackImgSampler'), # image-based sampling + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/half-val_cocoformat.json', + data_prefix=dict(img_path='train'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# evaluator +val_evaluator = dict( + type='MOTChallengeMetric', metric=['HOTA', 'CLEAR', 'Identity']) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge_det.py b/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge_det.py new file mode 100644 index 0000000000000000000000000000000000000000..a988572c3837eb2a8a6bf7b9eca06f3d82abdfda --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge_det.py @@ -0,0 +1,66 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/MOT17/' + +backend_args = None +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args, to_float32=True), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomResize', + scale=(1088, 1088), + ratio_range=(0.8, 1.2), + keep_ratio=True, + clip_object_border=False), + dict(type='PhotoMetricDistortion'), + dict(type='RandomCrop', crop_size=(1088, 1088), bbox_clip_border=False), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1088, 1088), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/half-train_cocoformat.json', + data_prefix=dict(img='train/'), + metainfo=dict(classes=('pedestrian', )), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/half-val_cocoformat.json', + data_prefix=dict(img='train/'), + metainfo=dict(classes=('pedestrian', )), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/half-val_cocoformat.json', + metric='bbox', + format_only=False) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge_reid.py b/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge_reid.py new file mode 100644 index 0000000000000000000000000000000000000000..57a95b531f3591e60daaabc5eea6f11c7424215b --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/mot_challenge_reid.py @@ -0,0 +1,61 @@ +# dataset settings +dataset_type = 'ReIDDataset' +data_root = 'data/MOT17/' + +backend_args = None +# data pipeline +train_pipeline = [ + dict( + type='TransformBroadcaster', + share_random_params=False, + transforms=[ + dict( + type='LoadImageFromFile', + backend_args=backend_args, + to_float32=True), + dict( + type='Resize', + scale=(128, 256), + keep_ratio=False, + clip_object_border=False), + dict(type='RandomFlip', prob=0.5, direction='horizontal'), + ]), + dict(type='PackReIDInputs', meta_keys=('flip', 'flip_direction')) +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args, to_float32=True), + dict(type='Resize', scale=(128, 256), keep_ratio=False), + dict(type='PackReIDInputs') +] + +# dataloader +train_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + dataset=dict( + type=dataset_type, + data_root=data_root, + triplet_sampler=dict(num_ids=8, ins_per_id=4), + data_prefix=dict(img_path='reid/imgs'), + ann_file='reid/meta/train_80.txt', + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + triplet_sampler=None, + data_prefix=dict(img_path='reid/imgs'), + ann_file='reid/meta/val_20.txt', + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# evaluator +val_evaluator = dict(type='ReIDMetrics', metric=['mAP', 'CMC']) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/objects365v1_detection.py b/mmdet_code/mmdetection/configs/_base_/datasets/objects365v1_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..ee398698608543e13188452a816283e9a2563390 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/objects365v1_detection.py @@ -0,0 +1,74 @@ +# dataset settings +dataset_type = 'Objects365V1Dataset' +data_root = 'data/Objects365/Obj365_v1/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/objects365_train.json', + data_prefix=dict(img='train/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/objects365_val.json', + data_prefix=dict(img='val/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/objects365_val.json', + metric='bbox', + sort_categories=True, + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/objects365v2_detection.py b/mmdet_code/mmdetection/configs/_base_/datasets/objects365v2_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..b25a7ba901befa8d61e3cdae8a7c68fb8a9c5aef --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/objects365v2_detection.py @@ -0,0 +1,73 @@ +# dataset settings +dataset_type = 'Objects365V2Dataset' +data_root = 'data/Objects365/Obj365_v2/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/zhiyuan_objv2_train.json', + data_prefix=dict(img='train/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/zhiyuan_objv2_val.json', + data_prefix=dict(img='val/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/zhiyuan_objv2_val.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/openimages_detection.py b/mmdet_code/mmdetection/configs/_base_/datasets/openimages_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..129661b405c70d3e2d0d2c4741e3a59333dd960c --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/openimages_detection.py @@ -0,0 +1,81 @@ +# dataset settings +dataset_type = 'OpenImagesDataset' +data_root = 'data/OpenImages/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1024, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1024, 800), keep_ratio=True), + # avoid bboxes being resized + dict(type='LoadAnnotations', with_bbox=True), + # TODO: find a better way to collect image_level_labels + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'instances', 'image_level_labels')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=0, # workers_per_gpu > 0 may occur out of memory + persistent_workers=False, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/oidv6-train-annotations-bbox.csv', + data_prefix=dict(img='OpenImages/train/'), + label_file='annotations/class-descriptions-boxable.csv', + hierarchy_file='annotations/bbox_labels_600_hierarchy.json', + meta_file='annotations/train-image-metas.pkl', + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=0, + persistent_workers=False, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/validation-annotations-bbox.csv', + data_prefix=dict(img='OpenImages/validation/'), + label_file='annotations/class-descriptions-boxable.csv', + hierarchy_file='annotations/bbox_labels_600_hierarchy.json', + meta_file='annotations/validation-image-metas.pkl', + image_level_ann_file='annotations/validation-' + 'annotations-human-imagelabels-boxable.csv', + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='OpenImagesMetric', + iou_thrs=0.5, + ioa_thrs=0.5, + use_group_of=True, + get_supercategory=True) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/refcoco+.py b/mmdet_code/mmdetection/configs/_base_/datasets/refcoco+.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0278ddf6c30fda6e4fb42aed1cb1b9a55109ec --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/refcoco+.py @@ -0,0 +1,55 @@ +# dataset settings +dataset_type = 'RefCocoDataset' +data_root = 'data/coco/' + +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_mask=True, + with_bbox=False, + with_seg=False, + with_label=False), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'gt_masks', 'text')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcoco+/instances.json', + split_file='refcoco+/refs(unc).p', + split='val', + text_mode='select_first', + pipeline=test_pipeline)) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcoco+/instances.json', + split_file='refcoco+/refs(unc).p', + split='testA', # or 'testB' + text_mode='select_first', + pipeline=test_pipeline)) + +val_evaluator = dict(type='RefSegMetric', metric=['cIoU', 'mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/refcoco.py b/mmdet_code/mmdetection/configs/_base_/datasets/refcoco.py new file mode 100644 index 0000000000000000000000000000000000000000..7b6caefa9a4bbfabdb49689588821f99d882a80f --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/refcoco.py @@ -0,0 +1,55 @@ +# dataset settings +dataset_type = 'RefCocoDataset' +data_root = 'data/coco/' + +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_mask=True, + with_bbox=False, + with_seg=False, + with_label=False), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'gt_masks', 'text')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcoco/instances.json', + split_file='refcoco/refs(unc).p', + split='val', + text_mode='select_first', + pipeline=test_pipeline)) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcoco/instances.json', + split_file='refcoco/refs(unc).p', + split='testA', # or 'testB' + text_mode='select_first', + pipeline=test_pipeline)) + +val_evaluator = dict(type='RefSegMetric', metric=['cIoU', 'mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/refcocog.py b/mmdet_code/mmdetection/configs/_base_/datasets/refcocog.py new file mode 100644 index 0000000000000000000000000000000000000000..19dbeef1cde79fcb2aa80bb9936a60cc30089963 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/refcocog.py @@ -0,0 +1,55 @@ +# dataset settings +dataset_type = 'RefCocoDataset' +data_root = 'data/coco/' + +backend_args = None + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_mask=True, + with_bbox=False, + with_seg=False, + with_label=False), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'gt_masks', 'text')) +] + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcocog/instances.json', + split_file='refcocog/refs(umd).p', + split='val', + text_mode='select_first', + pipeline=test_pipeline)) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path='train2014/'), + ann_file='refcocog/instances.json', + split_file='refcocog/refs(umd).p', + split='test', + text_mode='select_first', + pipeline=test_pipeline)) + +val_evaluator = dict(type='RefSegMetric', metric=['cIoU', 'mIoU']) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/semi_coco_detection.py b/mmdet_code/mmdetection/configs/_base_/datasets/semi_coco_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..694f25f841e06dbb59a699dfe13c18e34dbdce9f --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/semi_coco_detection.py @@ -0,0 +1,178 @@ +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +color_space = [ + [dict(type='ColorTransform')], + [dict(type='AutoContrast')], + [dict(type='Equalize')], + [dict(type='Sharpness')], + [dict(type='Posterize')], + [dict(type='Solarize')], + [dict(type='Color')], + [dict(type='Contrast')], + [dict(type='Brightness')], +] + +geometric = [ + [dict(type='Rotate')], + [dict(type='ShearX')], + [dict(type='ShearY')], + [dict(type='TranslateX')], + [dict(type='TranslateY')], +] + +scale = [(1333, 400), (1333, 1200)] + +branch_field = ['sup', 'unsup_teacher', 'unsup_student'] +# pipeline used to augment labeled data, +# which will be sent to student model for supervised training. +sup_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict( + type='MultiBranch', + branch_field=branch_field, + sup=dict(type='PackDetInputs')) +] + +# pipeline used to augment unlabeled data weakly, +# which will be sent to teacher model for predicting pseudo instances. +weak_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data strongly, +# which will be sent to student model for unsupervised training. +strong_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomOrder', + transforms=[ + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='RandAugment', aug_space=geometric, aug_num=1), + ]), + dict(type='RandomErasing', n_patches=(1, 5), ratio=(0, 0.2)), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data into different views +unsup_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadEmptyAnnotations'), + dict( + type='MultiBranch', + branch_field=branch_field, + unsup_teacher=weak_pipeline, + unsup_student=strong_pipeline, + ) +] + +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +batch_size = 5 +num_workers = 5 +# There are two common semi-supervised learning settings on the coco dataset: +# (1) Divide the train2017 into labeled and unlabeled datasets +# by a fixed percentage, such as 1%, 2%, 5% and 10%. +# The format of labeled_ann_file and unlabeled_ann_file are +# instances_train2017.{fold}@{percent}.json, and +# instances_train2017.{fold}@{percent}-unlabeled.json +# `fold` is used for cross-validation, and `percent` represents +# the proportion of labeled data in the train2017. +# (2) Choose the train2017 as the labeled dataset +# and unlabeled2017 as the unlabeled dataset. +# The labeled_ann_file and unlabeled_ann_file are +# instances_train2017.json and image_info_unlabeled2017.json +# We use this configuration by default. +labeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=sup_pipeline, + backend_args=backend_args) + +unlabeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_unlabeled2017.json', + data_prefix=dict(img='unlabeled2017/'), + filter_cfg=dict(filter_empty_gt=False), + pipeline=unsup_pipeline, + backend_args=backend_args) + +train_dataloader = dict( + batch_size=batch_size, + num_workers=num_workers, + persistent_workers=True, + sampler=dict( + type='GroupMultiSourceSampler', + batch_size=batch_size, + source_ratio=[1, 4]), + dataset=dict( + type='ConcatDataset', datasets=[labeled_dataset, unlabeled_dataset])) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/v3det.py b/mmdet_code/mmdetection/configs/_base_/datasets/v3det.py new file mode 100644 index 0000000000000000000000000000000000000000..38ccbf864b6248192dfbf4abaf4858b5f93d45e8 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/v3det.py @@ -0,0 +1,69 @@ +# dataset settings +dataset_type = 'V3DetDataset' +data_root = 'data/V3Det/' + +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomChoiceResize', + scales=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='ClassBalancedDataset', + oversample_thr=1e-3, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/v3det_2023_v1_train.json', + data_prefix=dict(img=''), + filter_cfg=dict(filter_empty_gt=True, min_size=4), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/v3det_2023_v1_val.json', + data_prefix=dict(img=''), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/v3det_2023_v1_val.json', + metric='bbox', + format_only=False, + backend_args=backend_args, + use_mp_eval=True, + proposal_nums=[300]) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/voc0712.py b/mmdet_code/mmdetection/configs/_base_/datasets/voc0712.py new file mode 100644 index 0000000000000000000000000000000000000000..47f5e6563b7f47dd6cfec02248d4c8decd32afe4 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/voc0712.py @@ -0,0 +1,92 @@ +# dataset settings +dataset_type = 'VOCDataset' +data_root = 'data/VOCdevkit/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically Infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/segmentation/VOCdevkit/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/segmentation/', +# 'data/': 's3://openmmlab/datasets/segmentation/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1000, 600), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1000, 600), keep_ratio=True), + # avoid bboxes being resized + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=3, + dataset=dict( + type='ConcatDataset', + # VOCDataset will add different `dataset_type` in dataset.metainfo, + # which will get error if using ConcatDataset. Adding + # `ignore_keys` can avoid this error. + ignore_keys=['dataset_type'], + datasets=[ + dict( + type=dataset_type, + data_root=data_root, + ann_file='VOC2007/ImageSets/Main/trainval.txt', + data_prefix=dict(sub_data_root='VOC2007/'), + filter_cfg=dict( + filter_empty_gt=True, min_size=32, bbox_min_size=32), + pipeline=train_pipeline, + backend_args=backend_args), + dict( + type=dataset_type, + data_root=data_root, + ann_file='VOC2012/ImageSets/Main/trainval.txt', + data_prefix=dict(sub_data_root='VOC2012/'), + filter_cfg=dict( + filter_empty_gt=True, min_size=32, bbox_min_size=32), + pipeline=train_pipeline, + backend_args=backend_args) + ]))) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='VOC2007/ImageSets/Main/test.txt', + data_prefix=dict(sub_data_root='VOC2007/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +# Pascal VOC2007 uses `11points` as default evaluate mode, while PASCAL +# VOC2012 defaults to use 'area'. +val_evaluator = dict(type='VOCMetric', metric='mAP', eval_mode='11points') +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/wider_face.py b/mmdet_code/mmdetection/configs/_base_/datasets/wider_face.py new file mode 100644 index 0000000000000000000000000000000000000000..7042bc46e877ed899969730325143307e15adf64 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/wider_face.py @@ -0,0 +1,73 @@ +# dataset settings +dataset_type = 'WIDERFaceDataset' +data_root = 'data/WIDERFace/' +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/cityscapes/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +img_scale = (640, 640) # VGA resolution + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=img_scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=img_scale, keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='train.txt', + data_prefix=dict(img='WIDER_train'), + filter_cfg=dict(filter_empty_gt=True, bbox_min_size=17, min_size=32), + pipeline=train_pipeline)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='val.txt', + data_prefix=dict(img='WIDER_val'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +val_evaluator = dict( + # TODO: support WiderFace-Evaluation for easy, medium, hard cases + type='VOCMetric', + metric='mAP', + eval_mode='11points') +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/configs/_base_/datasets/youtube_vis.py b/mmdet_code/mmdetection/configs/_base_/datasets/youtube_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..ece07cc3879e512082e302c2e3f76108c57a0234 --- /dev/null +++ b/mmdet_code/mmdetection/configs/_base_/datasets/youtube_vis.py @@ -0,0 +1,66 @@ +dataset_type = 'YouTubeVISDataset' +data_root = 'data/youtube_vis_2019/' +dataset_version = data_root[-5:-1] # 2019 or 2021 + +backend_args = None + +# dataset settings +train_pipeline = [ + dict( + type='UniformRefFrameSample', + num_ref_imgs=1, + frame_range=100, + filter_key_img=True), + dict( + type='TransformBroadcaster', + share_random_params=True, + transforms=[ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadTrackAnnotations', with_mask=True), + dict(type='Resize', scale=(640, 360), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + ]), + dict(type='PackTrackInputs') +] + +test_pipeline = [ + dict( + type='TransformBroadcaster', + transforms=[ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(640, 360), keep_ratio=True), + dict(type='LoadTrackAnnotations', with_mask=True), + ]), + dict(type='PackTrackInputs') +] + +# dataloader +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + # sampler=dict(type='TrackImgSampler'), # image-based sampling + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='TrackAspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + dataset_version=dataset_version, + ann_file='annotations/youtube_vis_2019_train.json', + data_prefix=dict(img_path='train/JPEGImages'), + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False, round_up=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + dataset_version=dataset_version, + ann_file='annotations/youtube_vis_2019_valid.json', + data_prefix=dict(img_path='valid/JPEGImages'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader diff --git a/mmdet_code/mmdetection/configs/dala/__pycache__/cascade-rcnn_r50_fpn_dala_1x_coco.cpython-313.pyc b/mmdet_code/mmdetection/configs/dala/__pycache__/cascade-rcnn_r50_fpn_dala_1x_coco.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9a488492ffa1f2cba3876528db88df6e64a819f Binary files /dev/null and b/mmdet_code/mmdetection/configs/dala/__pycache__/cascade-rcnn_r50_fpn_dala_1x_coco.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/configs/dala/__pycache__/faster-rcnn_r50_fpn_dala_1x_coco.cpython-313.pyc b/mmdet_code/mmdetection/configs/dala/__pycache__/faster-rcnn_r50_fpn_dala_1x_coco.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aedddec36347264bef1ec043e4ee966ac9416647 Binary files /dev/null and b/mmdet_code/mmdetection/configs/dala/__pycache__/faster-rcnn_r50_fpn_dala_1x_coco.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/configs/dala/__pycache__/fcos_r50-caffe_fpn_dala_1x_coco.cpython-313.pyc b/mmdet_code/mmdetection/configs/dala/__pycache__/fcos_r50-caffe_fpn_dala_1x_coco.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..479f6cae375ecd54d38e8118cfff0e847035784a Binary files /dev/null and b/mmdet_code/mmdetection/configs/dala/__pycache__/fcos_r50-caffe_fpn_dala_1x_coco.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/configs/dala/__pycache__/retinanet_r50_fpn_dala_1x_coco.cpython-313.pyc b/mmdet_code/mmdetection/configs/dala/__pycache__/retinanet_r50_fpn_dala_1x_coco.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31b565f7bc951375657190204b4cacaa0bf2f12e Binary files /dev/null and b/mmdet_code/mmdetection/configs/dala/__pycache__/retinanet_r50_fpn_dala_1x_coco.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/docs/en/Makefile b/mmdet_code/mmdetection/docs/en/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d4bb2cbb9eddb1bb1b4f366623044af8e4830919 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/mmdet_code/mmdetection/docs/en/_static/css/readthedocs.css b/mmdet_code/mmdetection/docs/en/_static/css/readthedocs.css new file mode 100644 index 0000000000000000000000000000000000000000..57ed0ad084827ae75f5c58d3799ff5cfa6e40600 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/_static/css/readthedocs.css @@ -0,0 +1,6 @@ +.header-logo { + background-image: url("../image/mmdet-logo.png"); + background-size: 156px 40px; + height: 40px; + width: 156px; +} diff --git a/mmdet_code/mmdetection/docs/en/_static/image/mmdet-logo.png b/mmdet_code/mmdetection/docs/en/_static/image/mmdet-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..da0b5a3f01ba8ba79c63189e09b4689f3fe25472 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/_static/image/mmdet-logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3cbc8783587b4c1edd6300c8026007514b8fee8298d2a7cfa48a53936f47610 +size 32181 diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/conventions.md b/mmdet_code/mmdetection/docs/en/advanced_guides/conventions.md new file mode 100644 index 0000000000000000000000000000000000000000..da159ac699f741d07bf89c15bee5a79740a2315c --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/conventions.md @@ -0,0 +1,111 @@ +# Conventions + +Please check the following conventions if you would like to modify MMDetection as your own project. + +## About the order of image shape + +In OpenMMLab 2.0, to be consistent with the input argument of OpenCV, the argument about image shape in the data transformation pipeline is always in the `(width, height)` order. On the contrary, for computation convenience, the order of the field going through the data pipeline and the model is `(height, width)`. Specifically, in the results processed by each data transform pipeline, the fields and their value meaning is as below: + +- img_shape: (height, width) +- ori_shape: (height, width) +- pad_shape: (height, width) +- batch_input_shape: (height, width) + +As an example, the initialization arguments of `Mosaic` are as below: + +```python +@TRANSFORMS.register_module() +class Mosaic(BaseTransform): + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + center_ratio_range: Tuple[float, float] = (0.5, 1.5), + bbox_clip_border: bool = True, + pad_val: float = 114.0, + prob: float = 1.0) -> None: + ... + + # img_scale order should be (width, height) + self.img_scale = img_scale + + def transform(self, results: dict) -> dict: + ... + + results['img'] = mosaic_img + # (height, width) + results['img_shape'] = mosaic_img.shape[:2] +``` + +## Loss + +In MMDetection, a `dict` containing losses and metrics will be returned by `model(**data)`. + +For example, in bbox head, + +```python +class BBoxHead(nn.Module): + ... + def loss(self, ...): + losses = dict() + # classification loss + losses['loss_cls'] = self.loss_cls(...) + # classification accuracy + losses['acc'] = accuracy(...) + # bbox regression loss + losses['loss_bbox'] = self.loss_bbox(...) + return losses +``` + +`bbox_head.loss()` will be called during model forward. +The returned dict contains `'loss_bbox'`, `'loss_cls'`, `'acc'` . +Only `'loss_bbox'`, `'loss_cls'` will be used during back propagation, +`'acc'` will only be used as a metric to monitor training process. + +By default, only values whose keys contain `'loss'` will be back propagated. +This behavior could be changed by modifying `BaseDetector.train_step()`. + +## Empty Proposals + +In MMDetection, We have added special handling and unit test for empty proposals of two-stage. We need to deal with the empty proposals of the entire batch and single image at the same time. For example, in CascadeRoIHead, + +```python +# simple_test method +... +# There is no proposal in the whole batch +if rois.shape[0] == 0: + bbox_results = [[ + np.zeros((0, 5), dtype=np.float32) + for _ in range(self.bbox_head[-1].num_classes) + ]] * num_imgs + if self.with_mask: + mask_classes = self.mask_head[-1].num_classes + segm_results = [[[] for _ in range(mask_classes)] + for _ in range(num_imgs)] + results = list(zip(bbox_results, segm_results)) + else: + results = bbox_results + return results +... + +# There is no proposal in the single image +for i in range(self.num_stages): + ... + if i < self.num_stages - 1: + for j in range(num_imgs): + # Handle empty proposal + if rois[j].shape[0] > 0: + bbox_label = cls_score[j][:, :-1].argmax(dim=1) + refine_roi = self.bbox_head[i].regress_by_class( + rois[j], bbox_label, bbox_pred[j], img_metas[j]) + refine_roi_list.append(refine_roi) +``` + +If you have customized `RoIHead`, you can refer to the above method to deal with empty proposals. + +## Coco Panoptic Dataset + +In MMDetection, we have supported COCO Panoptic dataset. We clarify a few conventions about the implementation of `CocoPanopticDataset` here. + +1. For mmdet\<=2.16.0, the range of foreground and background labels in semantic segmentation are different from the default setting of MMDetection. The label `0` stands for `VOID` label and the category labels start from `1`. + Since mmdet=2.17.0, the category labels of semantic segmentation start from `0` and label `255` stands for `VOID` for consistency with labels of bounding boxes. + To achieve that, the `Pad` pipeline supports setting the padding value for `seg`. +2. In the evaluation, the panoptic result is a map with the same shape as the original image. Each value in the result map has the format of `instance_id * INSTANCE_OFFSET + category_id`. diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/customize_dataset.md b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_dataset.md new file mode 100644 index 0000000000000000000000000000000000000000..3d63d12c61a436563f7318e766089b6ce48dda79 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_dataset.md @@ -0,0 +1,433 @@ +# Customize Datasets + +## Support new data format + +To support a new data format, you can either convert them to existing formats (COCO format or PASCAL format) or directly convert them to the middle format. You could also choose to convert them offline (before training by a script) or online (implement a new dataset and do the conversion at training). In MMDetection, we recommend to convert the data into COCO formats and do the conversion offline, thus you only need to modify the config's data annotation paths and classes after the conversion of your data. + +### Reorganize new data formats to existing format + +The simplest way is to convert your dataset to existing dataset formats (COCO or PASCAL VOC). + +The annotation JSON files in COCO format has the following necessary keys: + +```python +'images': [ + { + 'file_name': 'COCO_val2014_000000001268.jpg', + 'height': 427, + 'width': 640, + 'id': 1268 + }, + ... +], + +'annotations': [ + { + 'segmentation': [[192.81, + 247.09, + ... + 219.03, + 249.06]], # If you have mask labels, and it is in polygon XY point coordinate format, you need to ensure that at least 3 point coordinates are included. Otherwise, it is an invalid polygon. + 'area': 1035.749, + 'iscrowd': 0, + 'image_id': 1268, + 'bbox': [192.81, 224.8, 74.73, 33.43], + 'category_id': 16, + 'id': 42986 + }, + ... +], + +'categories': [ + {'id': 0, 'name': 'car'}, + ] +``` + +There are three necessary keys in the JSON file: + +- `images`: contains a list of images with their information like `file_name`, `height`, `width`, and `id`. +- `annotations`: contains the list of instance annotations. +- `categories`: contains the list of categories names and their ID. + +After the data pre-processing, there are two steps for users to train the customized new dataset with existing format (e.g. COCO format): + +1. Modify the config file for using the customized dataset. +2. Check the annotations of the customized dataset. + +Here we give an example to show the above two steps, which uses a customized dataset of 5 classes with COCO format to train an existing Cascade Mask R-CNN R50-FPN detector. + +#### 1. Modify the config file for using the customized dataset + +There are two aspects involved in the modification of config file: + +1. The `data` field. Specifically, you need to explicitly add the `metainfo=dict(classes=classes)` fields in `train_dataloader.dataset`, `val_dataloader.dataset` and `test_dataloader.dataset` and `classes` must be a tuple type. +2. The `num_classes` field in the `model` part. Explicitly over-write all the `num_classes` from default value (e.g. 80 in COCO) to your classes number. + +In `configs/my_custom_config.py`: + +```python + +# the new config inherits the base configs to highlight the necessary modification +_base_ = './cascade_mask_rcnn_r50_fpn_1x_coco.py' + +# 1. dataset settings +dataset_type = 'CocoDataset' +classes = ('a', 'b', 'c', 'd', 'e') +data_root='path/to/your/' + +train_dataloader = dict( + batch_size=2, + num_workers=2, + dataset=dict( + type=dataset_type, + # explicitly add your class names to the field `metainfo` + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='train/annotation_data', + data_prefix=dict(img='train/image_data') + ) + ) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + dataset=dict( + type=dataset_type, + test_mode=True, + # explicitly add your class names to the field `metainfo` + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='val/annotation_data', + data_prefix=dict(img='val/image_data') + ) + ) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + dataset=dict( + type=dataset_type, + test_mode=True, + # explicitly add your class names to the field `metainfo` + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='test/annotation_data', + data_prefix=dict(img='test/image_data') + ) + ) + +# 2. model settings + +# explicitly over-write all the `num_classes` field from default 80 to 5. +model = dict( + roi_head=dict( + bbox_head=[ + dict( + type='Shared2FCBBoxHead', + # explicitly over-write all the `num_classes` field from default 80 to 5. + num_classes=5), + dict( + type='Shared2FCBBoxHead', + # explicitly over-write all the `num_classes` field from default 80 to 5. + num_classes=5), + dict( + type='Shared2FCBBoxHead', + # explicitly over-write all the `num_classes` field from default 80 to 5. + num_classes=5)], + # explicitly over-write all the `num_classes` field from default 80 to 5. + mask_head=dict(num_classes=5))) +``` + +#### 2. Check the annotations of the customized dataset + +Assuming your customized dataset is COCO format, make sure you have the correct annotations in the customized dataset: + +1. The length for `categories` field in annotations should exactly equal the tuple length of `classes` fields in your config, meaning the number of classes (e.g. 5 in this example). +2. The `classes` fields in your config file should have exactly the same elements and the same order with the `name` in `categories` of annotations. MMDetection automatically maps the uncontinuous `id` in `categories` to the continuous label indices, so the string order of `name` in `categories` field affects the order of label indices. Meanwhile, the string order of `classes` in config affects the label text during visualization of predicted bounding boxes. +3. The `category_id` in `annotations` field should be valid, i.e., all values in `category_id` should belong to `id` in `categories`. + +Here is a valid example of annotations: + +```python + +'annotations': [ + { + 'segmentation': [[192.81, + 247.09, + ... + 219.03, + 249.06]], # if you have mask labels + 'area': 1035.749, + 'iscrowd': 0, + 'image_id': 1268, + 'bbox': [192.81, 224.8, 74.73, 33.43], + 'category_id': 16, + 'id': 42986 + }, + ... +], + +# MMDetection automatically maps the uncontinuous `id` to the continuous label indices. +'categories': [ + {'id': 1, 'name': 'a'}, {'id': 3, 'name': 'b'}, {'id': 4, 'name': 'c'}, {'id': 16, 'name': 'd'}, {'id': 17, 'name': 'e'}, + ] +``` + +We use this way to support CityScapes dataset. The script is in [cityscapes.py](../../../tools/dataset_converters/cityscapes.py) and we also provide the finetuning [configs](../../../configs/cityscapes). + +**Note** + +1. For instance segmentation datasets, **MMDetection only supports evaluating mask AP of dataset in COCO format for now**. +2. It is recommended to convert the data offline before training, thus you can still use `CocoDataset` and only need to modify the path of annotations and the training classes. + +### Reorganize new data format to middle format + +It is also fine if you do not want to convert the annotation format to COCO or PASCAL format. +Actually, we define a simple annotation format in MMEninge's [BaseDataset](https://github.com/open-mmlab/mmengine/blob/main/mmengine/dataset/base_dataset.py#L116) and all existing datasets are +processed to be compatible with it, either online or offline. + +The annotation of the dataset must be in `json` or `yaml`, `yml` or `pickle`, `pkl` format; the dictionary stored in the annotation file must contain two fields `metainfo` and `data_list`. The `metainfo` is a dictionary, which contains the metadata of the dataset, such as class information; `data_list` is a list, each element in the list is a dictionary, the dictionary defines the raw data of one image, and each raw data contains a or several training/testing samples. + +Here is an example. + +```python +{ + 'metainfo': + { + 'classes': ('person', 'bicycle', 'car', 'motorcycle'), + ... + }, + 'data_list': + [ + { + "img_path": "xxx/xxx_1.jpg", + "height": 604, + "width": 640, + "instances": + [ + { + "bbox": [0, 0, 10, 20], + "bbox_label": 1, + "ignore_flag": 0 + }, + { + "bbox": [10, 10, 110, 120], + "bbox_label": 2, + "ignore_flag": 0 + } + ] + }, + { + "img_path": "xxx/xxx_2.jpg", + "height": 320, + "width": 460, + "instances": + [ + { + "bbox": [10, 0, 20, 20], + "bbox_label": 3, + "ignore_flag": 1, + } + ] + }, + ... + ] +} +``` + +Some datasets may provide annotations like crowd/difficult/ignored bboxes, we use `ignore_flag`to cover them. + +After obtaining the above standard data annotation format, you can directly use [BaseDetDataset](../../../mmdet/datasets/base_det_dataset.py#L13) of MMDetection in the configuration , without conversion. + +### An example of customized dataset + +Assume the annotation is in a new format in text files. +The bounding boxes annotations are stored in text file `annotation.txt` as the following + +``` +# +000001.jpg +1280 720 +2 +10 20 40 60 1 +20 40 50 60 2 +# +000002.jpg +1280 720 +3 +50 20 40 60 2 +20 40 30 45 2 +30 40 50 60 3 +``` + +We can create a new dataset in `mmdet/datasets/my_dataset.py` to load the data. + +```python +import mmengine + +from mmdet.base_det_dataset import BaseDetDataset +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class MyDataset(BaseDetDataset): + + METAINFO = { + 'classes': ('person', 'bicycle', 'car', 'motorcycle'), + 'palette': [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230)] + } + + def load_data_list(self, ann_file): + ann_list = mmengine.list_from_file(ann_file) + + data_infos = [] + for i, ann_line in enumerate(ann_list): + if ann_line != '#': + continue + + img_shape = ann_list[i + 2].split(' ') + width = int(img_shape[0]) + height = int(img_shape[1]) + bbox_number = int(ann_list[i + 3]) + + instances = [] + for anns in ann_list[i + 4:i + 4 + bbox_number]: + instance = {} + instance['bbox'] = [float(ann) for ann in anns.split(' ')[:4]] + instance['bbox_label']=int(anns[4]) + instances.append(instance) + + data_infos.append( + dict( + img_path=ann_list[i + 1], + img_id=i, + width=width, + height=height, + instances=instances + )) + + return data_infos +``` + +Then in the config, to use `MyDataset` you can modify the config as the following + +```python +dataset_A_train = dict( + type='MyDataset', + ann_file = 'image_list.txt', + pipeline=train_pipeline +) +``` + +## Customize datasets by dataset wrappers + +MMEngine also supports many dataset wrappers to mix the dataset or modify the dataset distribution for training. +Currently it supports to three dataset wrappers as below: + +- `RepeatDataset`: simply repeat the whole dataset. +- `ClassBalancedDataset`: repeat dataset in a class balanced manner. +- `ConcatDataset`: concat datasets. + +For detailed usage, see [MMEngine Dataset Wrapper](#TODO). + +## Modify Dataset Classes + +With existing dataset types, we can modify the metainfo of them to train subset of the annotations. +For example, if you want to train only three classes of the current dataset, +you can modify the classes of dataset. +The dataset will filter out the ground truth boxes of other classes automatically. + +```python +classes = ('person', 'bicycle', 'car') +train_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +val_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +test_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +``` + +**Note**: + +- Before MMDetection v2.5.0, the dataset will filter out the empty GT images automatically if the classes are set and there is no way to disable that through config. This is an undesirable behavior and introduces confusion because if the classes are not set, the dataset only filter the empty GT images when `filter_empty_gt=True` and `test_mode=False`. After MMDetection v2.5.0, we decouple the image filtering process and the classes modification, i.e., the dataset will only filter empty GT images when `filter_cfg=dict(filter_empty_gt=True)` and `test_mode=False`, no matter whether the classes are set. Thus, setting the classes only influences the annotations of classes used for training and users could decide whether to filter empty GT images by themselves. +- When directly using `BaseDataset` in MMEngine or `BaseDetDataset` in MMDetection, users cannot filter images without GT by modifying the configuration, but it can be solved in an offline way. +- Please remember to modify the `num_classes` in the head when specifying `classes` in dataset. We implemented [NumClassCheckHook](../../../mmdet/engine/hooks/num_class_check_hook.py) to check whether the numbers are consistent since v2.9.0(after PR#4508). + +## COCO Panoptic Dataset + +Now we support COCO Panoptic Dataset, the format of panoptic annotations is different from COCO format. +Both the foreground and the background will exist in the annotation file. +The annotation json files in COCO Panoptic format has the following necessary keys: + +```python +'images': [ + { + 'file_name': '000000001268.jpg', + 'height': 427, + 'width': 640, + 'id': 1268 + }, + ... +] + +'annotations': [ + { + 'filename': '000000001268.jpg', + 'image_id': 1268, + 'segments_info': [ + { + 'id':8345037, # One-to-one correspondence with the id in the annotation map. + 'category_id': 51, + 'iscrowd': 0, + 'bbox': (x1, y1, w, h), # The bbox of the background is the outer rectangle of its mask. + 'area': 24315 + }, + ... + ] + }, + ... +] + +'categories': [ # including both foreground categories and background categories + {'id': 0, 'name': 'person'}, + ... + ] +``` + +Moreover, the `seg` must be set to the path of the panoptic annotation images. + +```python +dataset_type = 'CocoPanopticDataset' +data_root='path/to/your/' + +train_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='train/image_data/', seg='train/panoptic/image_annotation_data/') + ) +) +val_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='val/image_data/', seg='val/panoptic/image_annotation_data/') + ) +) +test_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='test/image_data/', seg='test/panoptic/image_annotation_data/') + ) +) +``` diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/customize_losses.md b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_losses.md new file mode 100644 index 0000000000000000000000000000000000000000..3120dc01ffe4b11e75eb1e43632cbbfe6f1b05c8 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_losses.md @@ -0,0 +1,126 @@ +# Customize Losses + +MMDetection provides users with different loss functions. But the default configuration may be not applicable for different datasets or models, so users may want to modify a specific loss to adapt the new situation. + +This tutorial first elaborate the computation pipeline of losses, then give some instructions about how to modify each step. The modification can be categorized as tweaking and weighting. + +## Computation pipeline of a loss + +Given the input prediction and target, as well as the weights, a loss function maps the input tensor to the final loss scalar. The mapping can be divided into five steps: + +1. Set the sampling method to sample positive and negative samples. + +2. Get **element-wise** or **sample-wise** loss by the loss kernel function. + +3. Weighting the loss with a weight tensor **element-wisely**. + +4. Reduce the loss tensor to a **scalar**. + +5. Weighting the loss with a **scalar**. + +## Set sampling method (step 1) + +For some loss functions, sampling strategies are needed to avoid imbalance between positive and negative samples. + +For example, when using `CrossEntropyLoss` in RPN head, we need to set `RandomSampler` in `train_cfg` + +```python +train_cfg=dict( + rpn=dict( + sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False)) +``` + +For some other losses which have positive and negative sample balance mechanism such as Focal Loss, GHMC, and QualityFocalLoss, the sampler is no more necessary. + +## Tweaking loss + +Tweaking a loss is more related with step 2, 4, 5, and most modifications can be specified in the config. +Here we take [Focal Loss (FL)](../../../mmdet/models/losses/focal_loss.py) as an example. +The following code sniper are the construction method and config of FL respectively, they are actually one to one correspondence. + +```python +@LOSSES.register_module() +class FocalLoss(nn.Module): + + def __init__(self, + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + reduction='mean', + loss_weight=1.0): +``` + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0) +``` + +### Tweaking hyper-parameters (step 2) + +`gamma` and `beta` are two hyper-parameters in the Focal Loss. Say if we want to change the value of `gamma` to be 1.5 and `alpha` to be 0.5, then we can specify them in the config as follows: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=1.5, + alpha=0.5, + loss_weight=1.0) +``` + +### Tweaking the way of reduction (step 3) + +The default way of reduction is `mean` for FL. Say if we want to change the reduction from `mean` to `sum`, we can specify it in the config as follows: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0, + reduction='sum') +``` + +### Tweaking loss weight (step 5) + +The loss weight here is a scalar which controls the weight of different losses in multi-task learning, e.g. classification loss and regression loss. Say if we want to change to loss weight of classification loss to be 0.5, we can specify it in the config as follows: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=0.5) +``` + +## Weighting loss (step 3) + +Weighting loss means we re-weight the loss element-wisely. To be more specific, we multiply the loss tensor with a weight tensor which has the same shape. As a result, different entries of the loss can be scaled differently, and so called element-wisely. +The loss weight varies across different models and highly context related, but overall there are two kinds of loss weights, `label_weights` for classification loss and `bbox_weights` for bbox regression loss. You can find them in the `get_target` method of the corresponding head. Here we take [ATSSHead](../../../mmdet/models/dense_heads/atss_head.py#L322) as an example, which inherit [AnchorHead](../../../mmdet/models/dense_heads/anchor_head.py) but overwrite its `get_targets` method which yields different `label_weights` and `bbox_weights`. + +``` +class ATSSHead(AnchorHead): + + ... + + def get_targets(self, + anchor_list, + valid_flag_list, + gt_bboxes_list, + img_metas, + gt_bboxes_ignore_list=None, + gt_labels_list=None, + label_channels=1, + unmap_outputs=True): +``` diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/customize_models.md b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_models.md new file mode 100644 index 0000000000000000000000000000000000000000..1779aeb1aa1f347fa27cd71bf214dc0b298f6b43 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_models.md @@ -0,0 +1,412 @@ +# Customize Models + +We basically categorize model components into 5 types. + +- backbone: usually an FCN network to extract feature maps, e.g., ResNet, MobileNet. +- neck: the component between backbones and heads, e.g., FPN, PAFPN. +- head: the component for specific tasks, e.g., bbox prediction and mask prediction. +- roi extractor: the part for extracting RoI features from feature maps, e.g., RoI Align. +- loss: the component in head for calculating losses, e.g., FocalLoss, L1Loss, and GHMLoss. + +## Develop new components + +### Add a new backbone + +Here we show how to develop new components with an example of MobileNet. + +#### 1. Define a new backbone (e.g. MobileNet) + +Create a new file `mmdet/models/backbones/mobilenet.py`. + +```python +import torch.nn as nn + +from mmdet.registry import MODELS + + +@MODELS.register_module() +class MobileNet(nn.Module): + + def __init__(self, arg1, arg2): + pass + + def forward(self, x): # should return a tuple + pass +``` + +#### 2. Import the module + +You can either add the following line to `mmdet/models/backbones/__init__.py` + +```python +from .mobilenet import MobileNet +``` + +or alternatively add + +```python +custom_imports = dict( + imports=['mmdet.models.backbones.mobilenet'], + allow_failed_imports=False) +``` + +to the config file to avoid modifying the original code. + +#### 3. Use the backbone in your config file + +```python +model = dict( + ... + backbone=dict( + type='MobileNet', + arg1=xxx, + arg2=xxx), + ... +``` + +### Add new necks + +#### 1. Define a neck (e.g. PAFPN) + +Create a new file `mmdet/models/necks/pafpn.py`. + +```python +import torch.nn as nn + +from mmdet.registry import MODELS + +@MODELS.register_module() +class PAFPN(nn.Module): + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False): + pass + + def forward(self, inputs): + # implementation is ignored + pass +``` + +#### 2. Import the module + +You can either add the following line to `mmdet/models/necks/__init__.py`, + +```python +from .pafpn import PAFPN +``` + +or alternatively add + +```python +custom_imports = dict( + imports=['mmdet.models.necks.pafpn'], + allow_failed_imports=False) +``` + +to the config file and avoid modifying the original code. + +#### 3. Modify the config file + +```python +neck=dict( + type='PAFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5) +``` + +### Add new heads + +Here we show how to develop a new head with the example of [Double Head R-CNN](https://arxiv.org/abs/1904.06493) as the following. + +First, add a new bbox head in `mmdet/models/roi_heads/bbox_heads/double_bbox_head.py`. +Double Head R-CNN implements a new bbox head for object detection. +To implement a bbox head, basically we need to implement three functions of the new module as the following. + +```python +from typing import Tuple + +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule, ModuleList +from torch import Tensor + +from mmdet.models.backbones.resnet import Bottleneck +from mmdet.registry import MODELS +from mmdet.utils import ConfigType, MultiConfig, OptConfigType, OptMultiConfig +from .bbox_head import BBoxHead + +@MODELS.register_module() +class DoubleConvFCBBoxHead(BBoxHead): + r"""Bbox head used in Double-Head R-CNN + + .. code-block:: none + + /-> cls + /-> shared convs -> + \-> reg + roi features + /-> cls + \-> shared fc -> + \-> reg + """ # noqa: W605 + + def __init__(self, + num_convs: int = 0, + num_fcs: int = 0, + conv_out_channels: int = 1024, + fc_out_channels: int = 1024, + conv_cfg: OptConfigType = None, + norm_cfg: ConfigType = dict(type='BN'), + init_cfg: MultiConfig = dict( + type='Normal', + override=[ + dict(type='Normal', name='fc_cls', std=0.01), + dict(type='Normal', name='fc_reg', std=0.001), + dict( + type='Xavier', + name='fc_branch', + distribution='uniform') + ]), + **kwargs) -> None: + kwargs.setdefault('with_avg_pool', True) + super().__init__(init_cfg=init_cfg, **kwargs) + + def forward(self, x_cls: Tensor, x_reg: Tensor) -> Tuple[Tensor]: + +``` + +Second, implement a new RoI Head if it is necessary. We plan to inherit the new `DoubleHeadRoIHead` from `StandardRoIHead`. We can find that a `StandardRoIHead` already implements the following functions. + +```python +from typing import List, Optional, Tuple + +import torch +from torch import Tensor + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.structures import DetDataSample +from mmdet.structures.bbox import bbox2roi +from mmdet.utils import ConfigType, InstanceList +from ..task_modules.samplers import SamplingResult +from ..utils import empty_instances, unpack_gt_instances +from .base_roi_head import BaseRoIHead + + +@MODELS.register_module() +class StandardRoIHead(BaseRoIHead): + """Simplest base roi head including one bbox head and one mask head.""" + + def init_assigner_sampler(self) -> None: + + def init_bbox_head(self, bbox_roi_extractor: ConfigType, + bbox_head: ConfigType) -> None: + + def init_mask_head(self, mask_roi_extractor: ConfigType, + mask_head: ConfigType) -> None: + + def forward(self, x: Tuple[Tensor], + rpn_results_list: InstanceList) -> tuple: + + def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, + batch_data_samples: List[DetDataSample]) -> dict: + + def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict: + + def bbox_loss(self, x: Tuple[Tensor], + sampling_results: List[SamplingResult]) -> dict: + + def mask_loss(self, x: Tuple[Tensor], + sampling_results: List[SamplingResult], bbox_feats: Tensor, + batch_gt_instances: InstanceList) -> dict: + + def _mask_forward(self, + x: Tuple[Tensor], + rois: Tensor = None, + pos_inds: Optional[Tensor] = None, + bbox_feats: Optional[Tensor] = None) -> dict: + + def predict_bbox(self, + x: Tuple[Tensor], + batch_img_metas: List[dict], + rpn_results_list: InstanceList, + rcnn_test_cfg: ConfigType, + rescale: bool = False) -> InstanceList: + + def predict_mask(self, + x: Tuple[Tensor], + batch_img_metas: List[dict], + results_list: InstanceList, + rescale: bool = False) -> InstanceList: + +``` + +Double Head's modification is mainly in the `bbox_forward` logic, and it inherits other logics from the `StandardRoIHead`. In the `mmdet/models/roi_heads/double_roi_head.py`, we implement the new RoI Head as the following: + +```python +from typing import Tuple + +from torch import Tensor + +from mmdet.registry import MODELS +from .standard_roi_head import StandardRoIHead + + +@MODELS.register_module() +class DoubleHeadRoIHead(StandardRoIHead): + """RoI head for `Double Head RCNN `_. + + Args: + reg_roi_scale_factor (float): The scale factor to extend the rois + used to extract the regression features. + """ + + def __init__(self, reg_roi_scale_factor: float, **kwargs): + super().__init__(**kwargs) + self.reg_roi_scale_factor = reg_roi_scale_factor + + def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict: + """Box head forward function used in both training and testing. + + Args: + x (tuple[Tensor]): List of multi-level img features. + rois (Tensor): RoIs with the shape (n, 5) where the first + column indicates batch id of each RoI. + + Returns: + dict[str, Tensor]: Usually returns a dictionary with keys: + + - `cls_score` (Tensor): Classification scores. + - `bbox_pred` (Tensor): Box energies / deltas. + - `bbox_feats` (Tensor): Extract bbox RoI features. + """ + bbox_cls_feats = self.bbox_roi_extractor( + x[:self.bbox_roi_extractor.num_inputs], rois) + bbox_reg_feats = self.bbox_roi_extractor( + x[:self.bbox_roi_extractor.num_inputs], + rois, + roi_scale_factor=self.reg_roi_scale_factor) + if self.with_shared_head: + bbox_cls_feats = self.shared_head(bbox_cls_feats) + bbox_reg_feats = self.shared_head(bbox_reg_feats) + cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats) + + bbox_results = dict( + cls_score=cls_score, + bbox_pred=bbox_pred, + bbox_feats=bbox_cls_feats) + return bbox_results +``` + +Last, the users need to add the module in +`mmdet/models/bbox_heads/__init__.py` and `mmdet/models/roi_heads/__init__.py` thus the corresponding registry could find and load them. + +Alternatively, the users can add + +```python +custom_imports=dict( + imports=['mmdet.models.roi_heads.double_roi_head', 'mmdet.models.roi_heads.bbox_heads.double_bbox_head']) +``` + +to the config file and achieve the same goal. + +The config file of Double Head R-CNN is as the following + +```python +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + roi_head=dict( + type='DoubleHeadRoIHead', + reg_roi_scale_factor=1.3, + bbox_head=dict( + _delete_=True, + type='DoubleConvFCBBoxHead', + num_convs=4, + num_fcs=2, + in_channels=256, + conv_out_channels=1024, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=80, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[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=2.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=2.0)))) + +``` + +Since MMDetection 2.0, the config system supports to inherit configs such that the users can focus on the modification. +The Double Head R-CNN mainly uses a new `DoubleHeadRoIHead` and a new `DoubleConvFCBBoxHead `, the arguments are set according to the `__init__` function of each module. + +### Add new loss + +Assume you want to add a new loss as `MyLoss`, for bounding box regression. +To add a new loss function, the users need implement it in `mmdet/models/losses/my_loss.py`. +The decorator `weighted_loss` enable the loss to be weighted for each element. + +```python +import torch +import torch.nn as nn + +from mmdet.registry import MODELS +from .utils import weighted_loss + +@weighted_loss +def my_loss(pred, target): + assert pred.size() == target.size() and target.numel() > 0 + loss = torch.abs(pred - target) + return loss + +@MODELS.register_module() +class MyLoss(nn.Module): + + def __init__(self, reduction='mean', loss_weight=1.0): + super(MyLoss, self).__init__() + self.reduction = reduction + self.loss_weight = loss_weight + + def forward(self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None): + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + loss_bbox = self.loss_weight * my_loss( + pred, target, weight, reduction=reduction, avg_factor=avg_factor) + return loss_bbox +``` + +Then the users need to add it in the `mmdet/models/losses/__init__.py`. + +```python +from .my_loss import MyLoss, my_loss + +``` + +Alternatively, you can add + +```python +custom_imports=dict( + imports=['mmdet.models.losses.my_loss']) +``` + +to the config file and achieve the same goal. + +To use it, modify the `loss_xxx` field. +Since MyLoss is for regression, you need to modify the `loss_bbox` field in the head. + +```python +loss_bbox=dict(type='MyLoss', loss_weight=1.0)) +``` diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/customize_runtime.md b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_runtime.md new file mode 100644 index 0000000000000000000000000000000000000000..e6ce740a492b9e655536fc06aa365cd5421c81c2 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_runtime.md @@ -0,0 +1,391 @@ +# Customize Runtime Settings + +## Customize optimization settings + +Optimization related configuration is now all managed by `optim_wrapper` which usually has three fields: `optimizer`, `paramwise_cfg`, `clip_grad`, refer to [OptimWrapper](https://mmengine.readthedocs.io/en/latest/tutorials/optim_wrapper.md) for more detail. See the example below, where `Adamw` is used as an `optimizer`, the learning rate of the backbone is reduced by a factor of 10, and gradient clipping is added. + +```python +optim_wrapper = dict( + type='OptimWrapper', + # optimizer + optimizer=dict( + type='AdamW', + lr=0.0001, + weight_decay=0.05, + eps=1e-8, + betas=(0.9, 0.999)), + + # Parameter-level learning rate and weight decay settings + paramwise_cfg=dict( + custom_keys={ + 'backbone': dict(lr_mult=0.1, decay_mult=1.0), + }, + norm_decay_mult=0.0), + + # gradient clipping + clip_grad=dict(max_norm=0.01, norm_type=2)) +``` + +### Customize optimizer supported by Pytorch + +We already support to use all the optimizers implemented by PyTorch, and the only modification is to change the `optimizer` field in `optim_wrapper` field of config files. For example, if you want to use `ADAM` (note that the performance could drop a lot), the modification could be as the following. + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='Adam', lr=0.0003, weight_decay=0.0001)) +``` + +To modify the learning rate of the model, the users only need to modify the `lr` in `optimizer`. The users can directly set arguments following the [API doc](https://pytorch.org/docs/stable/optim.html?highlight=optim#module-torch.optim) of PyTorch. + +### Customize self-implemented optimizer + +#### 1. Define a new optimizer + +A customized optimizer could be defined as following. + +Assume you want to add a optimizer named `MyOptimizer`, which has arguments `a`, `b`, and `c`. +You need to create a new directory named `mmdet/engine/optimizers`. And then implement the new optimizer in a file, e.g., in `mmdet/engine/optimizers/my_optimizer.py`: + +```python +from mmdet.registry import OPTIMIZERS +from torch.optim import Optimizer + + +@OPTIMIZERS.register_module() +class MyOptimizer(Optimizer): + + def __init__(self, a, b, c) + +``` + +#### 2. Add the optimizer to registry + +To find the above module defined above, this module should be imported into the main namespace at first. There are two options to achieve it. + +- Modify `mmdet/engine/optimizers/__init__.py` to import it. + + The newly defined module should be imported in `mmdet/engine/optimizers/__init__.py` so that the registry will find the new module and add it: + +```python +from .my_optimizer import MyOptimizer +``` + +- Use `custom_imports` in the config to manually import it + +```python +custom_imports = dict(imports=['mmdet.engine.optimizers.my_optimizer'], allow_failed_imports=False) +``` + +The module `mmdet.engine.optimizers.my_optimizer` will be imported at the beginning of the program and the class `MyOptimizer` is then automatically registered. +Note that only the package containing the class `MyOptimizer` should be imported. +`mmdet.engine.optimizers.my_optimizer.MyOptimizer` **cannot** be imported directly. + +Actually users can use a totally different file directory structure using this importing method, as long as the module root can be located in `PYTHONPATH`. + +#### 3. Specify the optimizer in the config file + +Then you can use `MyOptimizer` in `optimizer` field in `optim_wrapper` field of config files. In the configs, the optimizers are defined by the field `optimizer` like the following: + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) +``` + +To use your own optimizer, the field can be changed to + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='MyOptimizer', a=a_value, b=b_value, c=c_value)) +``` + +### Customize optimizer wrapper constructor + +Some models may have some parameter-specific settings for optimization, e.g. weight decay for BatchNorm layers. +The users can do those fine-grained parameter tuning through customizing optimizer wrapper constructor. + +```python +from mmengine.optim import DefaultOptiWrapperConstructor + +from mmdet.registry import OPTIM_WRAPPER_CONSTRUCTORS +from .my_optimizer import MyOptimizer + + +@OPTIM_WRAPPER_CONSTRUCTORS.register_module() +class MyOptimizerWrapperConstructor(DefaultOptimWrapperConstructor): + + def __init__(self, + optim_wrapper_cfg: dict, + paramwise_cfg: Optional[dict] = None): + + def __call__(self, model: nn.Module) -> OptimWrapper: + + return optim_wrapper + +``` + +The default optimizer wrapper constructor is implemented [here](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/optimizer/default_constructor.py#L18), which could also serve as a template for the new optimizer wrapper constructor. + +### Additional settings + +Tricks not implemented by the optimizer should be implemented through optimizer wrapper constructor (e.g., set parameter-wise learning rates) or hooks. We list some common settings that could stabilize the training or accelerate the training. Feel free to create PR, issue for more settings. + +- __Use gradient clip to stabilize training__: + Some models need gradient clip to clip the gradients to stabilize the training process. An example is as below: + + ```python + optim_wrapper = dict( + _delete_=True, clip_grad=dict(max_norm=35, norm_type=2)) + ``` + + If your config inherits the base config which already sets the `optim_wrapper`, you might need `_delete_=True` to override the unnecessary settings. See the [config documentation](../user_guides/config.md) for more details. + +- __Use momentum schedule to accelerate model convergence__: + We support momentum scheduler to modify model's momentum according to learning rate, which could make the model converge in a faster way. + Momentum scheduler is usually used with LR scheduler, for example, the following config is used in [3D detection](https://github.com/open-mmlab/mmdetection3d/blob/dev-1.x/configs/_base_/schedules/cyclic-20e.py) to accelerate convergence. + For more details, please refer to the implementation of [CosineAnnealingLR](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py#L43) and [CosineAnnealingMomentum](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/momentum_scheduler.py#L71). + + ```python + param_scheduler = [ + # learning rate scheduler + # During the first 8 epochs, learning rate increases from 0 to lr * 10 + # during the next 12 epochs, learning rate decreases from lr * 10 to lr * 1e-4 + dict( + type='CosineAnnealingLR', + T_max=8, + eta_min=lr * 10, + begin=0, + end=8, + by_epoch=True, + convert_to_iter_based=True), + dict( + type='CosineAnnealingLR', + T_max=12, + eta_min=lr * 1e-4, + begin=8, + end=20, + by_epoch=True, + convert_to_iter_based=True), + # momentum scheduler + # During the first 8 epochs, momentum increases from 0 to 0.85 / 0.95 + # during the next 12 epochs, momentum increases from 0.85 / 0.95 to 1 + dict( + type='CosineAnnealingMomentum', + T_max=8, + eta_min=0.85 / 0.95, + begin=0, + end=8, + by_epoch=True, + convert_to_iter_based=True), + dict( + type='CosineAnnealingMomentum', + T_max=12, + eta_min=1, + begin=8, + end=20, + by_epoch=True, + convert_to_iter_based=True) + ] + ``` + +## Customize training schedules + +By default we use step learning rate with 1x schedule, this calls [MultiStepLR](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py#L139) in MMEngine. +We support many other learning rate schedule [here](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py), such as `CosineAnnealingLR` and `PolyLR` schedule. Here are some examples + +- Poly schedule: + + ```python + param_scheduler = [ + dict( + type='PolyLR', + power=0.9, + eta_min=1e-4, + begin=0, + end=8, + by_epoch=True)] + ``` + +- ConsineAnnealing schedule: + + ```python + param_scheduler = [ + dict( + type='CosineAnnealingLR', + T_max=8, + eta_min=lr * 1e-5, + begin=0, + end=8, + by_epoch=True)] + + ``` + +## Customize train loop + +By default, `EpochBasedTrainLoop` is used in `train_cfg` and validation is done after every train epoch, as follows. + +```python +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_begin=1, val_interval=1) +``` + +Actually, both [`IterBasedTrainLoop`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py#L183%5D) and [`EpochBasedTrainLoop`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py#L18) support dynamical interval, see the following example. + +```python +# Before 365001th iteration, we do evaluation every 5000 iterations. +# After 365000th iteration, we do evaluation every 368750 iterations, +# which means that we do evaluation at the end of training. + +interval = 5000 +max_iters = 368750 +dynamic_intervals = [(max_iters // interval * interval + 1, max_iters)] +train_cfg = dict( + type='IterBasedTrainLoop', + max_iters=max_iters, + val_interval=interval, + dynamic_intervals=dynamic_intervals) +``` + +## Customize hooks + +### Customize self-implemented hooks + +#### 1. Implement a new hook + +MMEngine provides many useful [hooks](https://mmengine.readthedocs.io/en/latest/tutorials/hooks.html), but there are some occasions when the users might need to implement a new hook. MMDetection supports customized hooks in training in v3.0 . Thus the users could implement a hook directly in mmdet or their mmdet-based codebases and use the hook by only modifying the config in training. +Here we give an example of creating a new hook in mmdet and using it in training. + +```python +from mmengine.hooks import Hook +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class MyHook(Hook): + + def __init__(self, a, b): + + def before_run(self, runner) -> None: + + def after_run(self, runner) -> None: + + def before_train(self, runner) -> None: + + def after_train(self, runner) -> None: + + def before_train_epoch(self, runner) -> None: + + def after_train_epoch(self, runner) -> None: + + def before_train_iter(self, + runner, + batch_idx: int, + data_batch: DATA_BATCH = None) -> None: + + def after_train_iter(self, + runner, + batch_idx: int, + data_batch: DATA_BATCH = None, + outputs: Optional[dict] = None) -> None: +``` + +Depending on the functionality of the hook, the users need to specify what the hook will do at each stage of the training in `before_run`, `after_run`, `before_train`, `after_train` , `before_train_epoch`, `after_train_epoch`, `before_train_iter`, and `after_train_iter`. There are more points where hooks can be inserted, refer to [base hook class](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/hook.py#L9) for more detail. + +#### 2. Register the new hook + +Then we need to make `MyHook` imported. Assuming the file is in `mmdet/engine/hooks/my_hook.py` there are two ways to do that: + +- Modify `mmdet/engine/hooks/__init__.py` to import it. + + The newly defined module should be imported in `mmdet/engine/hooks/__init__.py` so that the registry will find the new module and add it: + +```python +from .my_hook import MyHook +``` + +- Use `custom_imports` in the config to manually import it + +```python +custom_imports = dict(imports=['mmdet.engine.hooks.my_hook'], allow_failed_imports=False) +``` + +#### 3. Modify the config + +```python +custom_hooks = [ + dict(type='MyHook', a=a_value, b=b_value) +] +``` + +You can also set the priority of the hook by adding key `priority` to `'NORMAL'` or `'HIGHEST'` as below + +```python +custom_hooks = [ + dict(type='MyHook', a=a_value, b=b_value, priority='NORMAL') +] +``` + +By default the hook's priority is set as `NORMAL` during registration. + +### Use hooks implemented in MMDetection + +If the hook is already implemented in MMDectection, you can directly modify the config to use the hook as below + +#### Example: `NumClassCheckHook` + +We implement a customized hook named [NumClassCheckHook](../../../mmdet/engine/hooks/num_class_check_hook.py) to check whether the `num_classes` in head matches the length of `classes` in the metainfo of `dataset`. + +We set it in [default_runtime.py](../../../configs/_base_/default_runtime.py). + +```python +custom_hooks = [dict(type='NumClassCheckHook')] +``` + +### Modify default runtime hooks + +There are some common hooks that are registered through `default_hooks`, they are + +- `IterTimerHook`: A hook that logs 'data_time' for loading data and 'time' for a model train step. +- `LoggerHook`: A hook that Collect logs from different components of `Runner` and write them to terminal, JSON file, tensorboard and wandb .etc. +- `ParamSchedulerHook`: A hook to update some hyper-parameters in optimizer, e.g., learning rate and momentum. +- `CheckpointHook`: A hook that saves checkpoints periodically. +- `DistSamplerSeedHook`: A hook that sets the seed for sampler and batch_sampler. +- `DetVisualizationHook`: A hook used to visualize validation and testing process prediction results. + +`IterTimerHook`, `ParamSchedulerHook` and `DistSamplerSeedHook` are simple and no need to be modified usually, so here we reveals how what we can do with `LoggerHook`, `CheckpointHook` and `DetVisualizationHook`. + +#### CheckpointHook + +Except saving checkpoints periodically, [`CheckpointHook`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py#L19) provides other options such as `max_keep_ckpts`, `save_optimizer` and etc. The users could set `max_keep_ckpts` to only save small number of checkpoints or decide whether to store state dict of optimizer by `save_optimizer`. More details of the arguments are [here](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py#L19) + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + interval=1, + max_keep_ckpts=3, + save_optimizer=True)) +``` + +#### LoggerHook + +The `LoggerHook` enables to set intervals. And the detail usages can be found in the [docstring](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/logger_hook.py#L18). + +```python +default_hooks = dict(logger=dict(type='LoggerHook', interval=50)) +``` + +#### DetVisualizationHook + +`DetVisualizationHook` use `DetLocalVisualizer` to visualize prediction results, and `DetLocalVisualizer` current supports different backends, e.g., `TensorboardVisBackend` and `WandbVisBackend` (see [docstring](https://github.com/open-mmlab/mmengine/blob/main/mmengine/visualization/vis_backend.py) for more detail). The users could add multi backbends to do visualization, as follows. + +```python +default_hooks = dict( + visualization=dict(type='DetVisualizationHook', draw=True)) + +vis_backends = [dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +``` diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/customize_transforms.md b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_transforms.md new file mode 100644 index 0000000000000000000000000000000000000000..5fe84e9f7c9fdac45db6210e2be9176b53e74536 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/customize_transforms.md @@ -0,0 +1,49 @@ +# Customize Data Pipelines + +1. Write a new transform in a file, e.g., in `my_pipeline.py`. It takes a dict as input and returns a dict. + + ```python + import random + from mmcv.transforms import BaseTransform + from mmdet.registry import TRANSFORMS + + + @TRANSFORMS.register_module() + class MyTransform(BaseTransform): + """Add your transform + + Args: + p (float): Probability of shifts. Default 0.5. + """ + + def __init__(self, prob=0.5): + self.prob = prob + + def transform(self, results): + if random.random() > self.prob: + results['dummy'] = True + return results + ``` + +2. Import and use the pipeline in your config file. + Make sure the import is relative to where your train script is located. + + ```python + custom_imports = dict(imports=['path.to.my_pipeline'], allow_failed_imports=False) + + train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='MyTransform', prob=0.2), + dict(type='PackDetInputs') + ] + ``` + +3. Visualize the output of your transforms pipeline + + To visualize the output of your transforms pipeline, `tools/misc/browse_dataset.py` + can help the user to browse a detection dataset (both images and bounding box annotations) + visually, or save the image to a designated directory. More details can refer to + [visualization documentation](../user_guides/visualization.md) diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/data_flow.md b/mmdet_code/mmdetection/docs/en/advanced_guides/data_flow.md new file mode 100644 index 0000000000000000000000000000000000000000..59e7ca329422c749a7f07b52e891a42cb5e0ae81 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/data_flow.md @@ -0,0 +1 @@ +# Data Flow diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/datasets.md b/mmdet_code/mmdetection/docs/en/advanced_guides/datasets.md new file mode 100644 index 0000000000000000000000000000000000000000..157ea3aad83c802540cb7a1c7a914592ef6d8ab7 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/datasets.md @@ -0,0 +1 @@ +# Datasets diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/engine.md b/mmdet_code/mmdetection/docs/en/advanced_guides/engine.md new file mode 100644 index 0000000000000000000000000000000000000000..eaa55b0c8c47f49fce4a2e827cc58af5212c3433 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/engine.md @@ -0,0 +1 @@ +# Engine diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/evaluation.md b/mmdet_code/mmdetection/docs/en/advanced_guides/evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..b394c7690c4c67638ff6cf79becf0e139e1e7b1c --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/evaluation.md @@ -0,0 +1 @@ +# Evaluation diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/how_to.md b/mmdet_code/mmdetection/docs/en/advanced_guides/how_to.md new file mode 100644 index 0000000000000000000000000000000000000000..7eb41ceeb7a99a8539457689138b6f21273bd402 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/how_to.md @@ -0,0 +1,222 @@ +This tutorial collects answers to any `How to xxx with MMDetection`. Feel free to update this doc if you meet new questions about `How to` and find the answers! + +# Use backbone network through MMPretrain + +The model registry in MMDet, MMPreTrain, MMSeg all inherit from the root registry in MMEngine. This allows these repositories to directly use the modules already implemented by each other. Therefore, users can use backbone networks from MMPretrain in MMDetection without implementing a network that already exists in MMPretrain. + +## Use backbone network implemented in MMPretrain + +Suppose you want to use `MobileNetV3-small` as the backbone network of `RetinaNet`, the example config is as the following. + +```python +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict(imports=['mmpretrain.models'], allow_failed_imports=False) +pretrained = 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v3/convert/mobilenet_v3_small-8427ecf0.pth' +model = dict( + backbone=dict( + _delete_=True, # Delete the backbone field in _base_ + type='mmpretrain.MobileNetV3', # Using MobileNetV3 from mmpretrain + arch='small', + out_indices=(3, 8, 11), # Modify out_indices + init_cfg=dict( + type='Pretrained', + checkpoint=pretrained, + prefix='backbone.')), # The pre-trained weights of backbone network in mmpretrain have prefix='backbone.'. The prefix in the keys will be removed so that these weights can be normally loaded. + # Modify in_channels + neck=dict(in_channels=[24, 48, 96], start_level=0)) +``` + +## Use backbone network in TIMM through MMPretrain + +MMPretrain also provides a wrapper for the PyTorch Image Models (timm) backbone network, users can directly use the backbone network in timm through MMPretrain. Suppose you want to use [EfficientNet-B1](../../../configs/timm_example/retinanet_timm-efficientnet-b1_fpn_1x_coco.py) as the backbone network of RetinaNet, the example config is as the following. + +```python +# https://github.com/open-mmlab/mmdetection/blob/main/configs/timm_example/retinanet_timm-efficientnet-b1_fpn_1x_coco.py + +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict(imports=['mmpretrain.models'], allow_failed_imports=False) +model = dict( + backbone=dict( + _delete_=True, # Delete the backbone field in _base_ + type='mmpretrain.TIMMBackbone', # Using timm from mmpretrain + model_name='efficientnet_b1', + features_only=True, + pretrained=True, + out_indices=(1, 2, 3, 4)), # Modify out_indices + neck=dict(in_channels=[24, 40, 112, 320])) # Modify in_channels + +optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) +``` + +`type='mmpretrain.TIMMBackbone'` means use the `TIMMBackbone` class from MMPretrain in MMDetection, and the model used is `EfficientNet-B1`, where `mmpretrain` means the MMPretrain repo and `TIMMBackbone` means the TIMMBackbone wrapper implemented in MMPretrain. + +For the principle of the Hierarchy Registry, please refer to the [MMEngine document](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/config.md). For how to use other backbones in MMPretrain, you can refer to the [MMPretrain document](https://mmpretrain.readthedocs.io/en/latest/user_guides/config.html). + +# Use Mosaic augmentation + +If you want to use `Mosaic` in training, please make sure that you use `MultiImageMixDataset` at the same time. Taking the 'Faster R-CNN' algorithm as an example, you should modify the values of `train_pipeline` and `train_dataset` in the config as below: + +```python +# Open configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py directly and add the following fields +data_root = 'data/coco/' +dataset_type = 'CocoDataset' +img_scale=(1333, 800) + +train_pipeline = [ + dict(type='Mosaic', img_scale=img_scale, pad_val=114.0), + dict( + type='RandomAffine', + scaling_ratio_range=(0.1, 2), + border=(-img_scale[0] // 2, -img_scale[1] // 2)), # The image will be enlarged by 4 times after Mosaic processing,so we use affine transformation to restore the image size. + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +train_dataset = dict( + _delete_ = True, # remove unnecessary Settings + type='MultiImageMixDataset', + dataset=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=[ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True) + ], + filter_empty_gt=False, + ), + pipeline=train_pipeline + ) + +data = dict( + train=train_dataset + ) +``` + +# Unfreeze backbone network after freezing the backbone in the config + +If you have freezed the backbone network in the config and want to unfreeze it after some epoches, you can write a hook function to do it. Taking the Faster R-CNN with the resnet backbone as an example, you can freeze one stage of the backbone network and add a `custom_hooks` in the config as below: + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +model = dict( + # freeze one stage of the backbone network. + backbone=dict(frozen_stages=1), +) +custom_hooks = [dict(type="UnfreezeBackboneEpochBasedHook", unfreeze_epoch=1)] +``` + +Meanwhile write the hook class `UnfreezeBackboneEpochBasedHook` in `mmdet/core/hook/unfreeze_backbone_epoch_based_hook.py` + +```python +from mmengine.model import is_model_wrapper +from mmengine.hooks import Hook +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class UnfreezeBackboneEpochBasedHook(Hook): + """Unfreeze backbone network Hook. + + Args: + unfreeze_epoch (int): The epoch unfreezing the backbone network. + """ + + def __init__(self, unfreeze_epoch=1): + self.unfreeze_epoch = unfreeze_epoch + + def before_train_epoch(self, runner): + # Unfreeze the backbone network. + # Only valid for resnet. + if runner.epoch == self.unfreeze_epoch: + model = runner.model + if is_model_wrapper(model): + model = model.module + backbone = model.backbone + if backbone.frozen_stages >= 0: + if backbone.deep_stem: + backbone.stem.train() + for param in backbone.stem.parameters(): + param.requires_grad = True + else: + backbone.norm1.train() + for m in [backbone.conv1, backbone.norm1]: + for param in m.parameters(): + param.requires_grad = True + + for i in range(1, backbone.frozen_stages + 1): + m = getattr(backbone, f'layer{i}') + m.train() + for param in m.parameters(): + param.requires_grad = True +``` + +# Get the channels of a new backbone + +If you want to get the channels of a new backbone, you can build this backbone alone and input a pseudo image to get each stage output. + +Take `ResNet` as an example: + +```python +from mmdet.models import ResNet +import torch +self = ResNet(depth=18) +self.eval() +inputs = torch.rand(1, 3, 32, 32) +level_outputs = self.forward(inputs) +for level_out in level_outputs: + print(tuple(level_out.shape)) + +``` + +Output of the above script is as below: + +```python +(1, 64, 8, 8) +(1, 128, 4, 4) +(1, 256, 2, 2) +(1, 512, 1, 1) +``` + +Users can get the channels of the new backbone by Replacing the `ResNet(depth=18)` in this script with their customized backbone. + +# Use Detectron2 Model in MMDetection + +Users can use Detectron2Wrapper to run Detectron2's model in MMDetection. We provide examples of [Faster R-CNN](../../../configs/misc/d2_faster-rcnn_r50-caffe_fpn_ms-90k_coco.py), +[Mask R-CNN](../../../configs/misc/d2_mask-rcnn_r50-caffe_fpn_ms-90k_coco.py), and [RetinaNet](../../../configs/misc/d2_retinanet_r50-caffe_fpn_ms-90k_coco.py) in MMDetection. + +The algorithm components in config file should be the same as those of in Detectron2. During setup, we will first initialize the default settings, which can be found in [Detectron2](https://github.com/facebookresearch/detectron2/blob/main/detectron2/config/defaults.py). +Then, the settings in config file will overwrite the default settings and the model will be built with these settings. +The input data will first convert to Detectron2's type and feed into Detectron2's model. +During inference the results calculate from Detectron2's model will reconvert back to the MMDetection's type. + +## Use Detectron2's pre-trained weights + +The weight initialization in `Detectron2Wrapper` will not use the logic of MMDetection. Users can set `model.d2_detector.weights=xxx` to load pre-trained weights. +For example, we can use `model.d2_detector.weights='detectron2://ImageNetPretrained/MSRA/R-50.pkl'` to load the pre-trained ResNet-50 or use +`model.d2_detector.weights='detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/137260431/model_final_a54504.pkl'` to load the pre-trained Mask R-CNN weights proposed in Detectron2. + +**Note:** Detectron2's pretrained model cannot be loaded directly by using `load_from`, it should be first converted via `tools/model_converters/detectron2_to_mmdet.py` + +For inference of released detectron2 checkpoints, users should first use `tools/model_converters/detectron2_to_mmdet.py` to convert Detectron2 checkpoint to MMDetection. + +```shell +python tools/model_converters/detectron2_to_mmdet.py ${Detectron2 ckpt path} ${MMDetectron ckpt path} +``` diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/index.rst b/mmdet_code/mmdetection/docs/en/advanced_guides/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..20d8177498222efbc568a14a5f6e691a2a360a90 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/index.rst @@ -0,0 +1,34 @@ +Basic Concepts +*************** + +.. toctree:: + :maxdepth: 1 + + data_flow.md + structures.md + models.md + datasets.md + transforms.md + evaluation.md + engine.md + conventions.md + +Component Customization +************************ + +.. toctree:: + :maxdepth: 1 + + customize_models.md + customize_losses.md + customize_dataset.md + customize_transforms.md + customize_runtime.md + +How to +************************ + +.. toctree:: + :maxdepth: 1 + + how_to.md diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/models.md b/mmdet_code/mmdetection/docs/en/advanced_guides/models.md new file mode 100644 index 0000000000000000000000000000000000000000..91361720ebfffda1ff30f500879c18dafe084dc9 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/models.md @@ -0,0 +1 @@ +# Models diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/structures.md b/mmdet_code/mmdetection/docs/en/advanced_guides/structures.md new file mode 100644 index 0000000000000000000000000000000000000000..985286177db39812a8d39c77d365d7aade4ae08f --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/structures.md @@ -0,0 +1 @@ +# Structures diff --git a/mmdet_code/mmdetection/docs/en/advanced_guides/transforms.md b/mmdet_code/mmdetection/docs/en/advanced_guides/transforms.md new file mode 100644 index 0000000000000000000000000000000000000000..4db036ae5c2433df3dfdf6a704827aaa13cad667 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/advanced_guides/transforms.md @@ -0,0 +1,42 @@ +# Data Transforms (Need to update) + +## Design of Data transforms pipeline + +Following typical conventions, we use `Dataset` and `DataLoader` for data loading +with multiple workers. `Dataset` returns a dict of data items corresponding +the arguments of models' forward method. + +The data transforms pipeline and the dataset is decomposed. Usually a dataset +defines how to process the annotations and a data transforms pipeline defines all the steps to prepare a data dict. +A pipeline consists of a sequence of data transforms. Each operation takes a dict as input and also output a dict for the next transform. + +We present a classical pipeline in the following figure. The blue blocks are pipeline operations. With the pipeline going on, each operator can add new keys (marked as green) to the result dict or update the existing keys (marked as orange). +![pipeline figure](../../../resources/data_pipeline.png) + +Here is a pipeline example for Faster R-CNN. + +```python +train_pipeline = [ # Training data processing pipeline + dict(type='LoadImageFromFile', backend_args=backend_args), # First pipeline to load images from file path + dict( + type='LoadAnnotations', # Second pipeline to load annotations for current image + with_bbox=True), # Whether to use bounding box, True for detection + dict( + type='Resize', # Pipeline that resize the images and their annotations + scale=(1333, 800), # The largest scale of image + keep_ratio=True # Whether to keep the ratio between height and width + ), + dict( + type='RandomFlip', # Augmentation pipeline that flip the images and their annotations + prob=0.5), # The probability to flip + dict(type='PackDetInputs') # Pipeline that formats the annotation data and decides which keys in the data should be packed into data_samples +] +test_pipeline = [ # Testing data processing pipeline + dict(type='LoadImageFromFile', backend_args=backend_args), # First pipeline to load images from file path + dict(type='Resize', scale=(1333, 800), keep_ratio=True), # Pipeline that resize the images + dict( + type='PackDetInputs', # Pipeline that formats the annotation data and decides which keys in the data should be packed into data_samples + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +``` diff --git a/mmdet_code/mmdetection/docs/en/api.rst b/mmdet_code/mmdetection/docs/en/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..1b1273219e8ac7af1a9e2e27a3f80d6a18c630e5 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/api.rst @@ -0,0 +1,161 @@ +mmdet.apis +-------------- +.. automodule:: mmdet.apis + :members: + +mmdet.datasets +-------------- + +datasets +^^^^^^^^^^ +.. automodule:: mmdet.datasets + :members: + +api_wrappers +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.datasets.api_wrappers + :members: + +samplers +^^^^^^^^^^ +.. automodule:: mmdet.datasets.samplers + :members: + +transforms +^^^^^^^^^^^^ +.. automodule:: mmdet.datasets.transforms + :members: + +mmdet.engine +-------------- + +hooks +^^^^^^^^^^ +.. automodule:: mmdet.engine.hooks + :members: + +optimizers +^^^^^^^^^^^^^^^ +.. automodule:: mmdet.engine.optimizers + :members: + +runner +^^^^^^^^^^ +.. automodule:: mmdet.engine.runner + :members: + +schedulers +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.engine.schedulers + :members: + +mmdet.evaluation +-------------------- + +functional +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.evaluation.functional + :members: + +metrics +^^^^^^^^^^ +.. automodule:: mmdet.evaluation.metrics + :members: + + +mmdet.models +-------------- + +backbones +^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.backbones + :members: + +data_preprocessors +^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.data_preprocessors + :members: + +dense_heads +^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.dense_heads + :members: + +detectors +^^^^^^^^^^ +.. automodule:: mmdet.models.detectors + :members: + +layers +^^^^^^^^^^ +.. automodule:: mmdet.models.layers + :members: + +losses +^^^^^^^^^^ +.. automodule:: mmdet.models.losses + :members: + +necks +^^^^^^^^^^^^ +.. automodule:: mmdet.models.necks + :members: + +roi_heads +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.roi_heads + :members: + +seg_heads +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.seg_heads + :members: + +task_modules +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.task_modules + :members: + +test_time_augs +^^^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.test_time_augs + :members: + +utils +^^^^^^^^^^ +.. automodule:: mmdet.models.utils + :members: + + +mmdet.structures +-------------------- + +structures +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.structures + :members: + +bbox +^^^^^^^^^^ +.. automodule:: mmdet.structures.bbox + :members: + +mask +^^^^^^^^^^ +.. automodule:: mmdet.structures.mask + :members: + +mmdet.testing +---------------- +.. automodule:: mmdet.testing + :members: + +mmdet.visualization +-------------------- +.. automodule:: mmdet.visualization + :members: + +mmdet.utils +-------------- +.. automodule:: mmdet.utils + :members: diff --git a/mmdet_code/mmdetection/docs/en/conf.py b/mmdet_code/mmdetection/docs/en/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..d2beaf1e5c1ca9708d3556476ee3a5073dfdfc5b --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/conf.py @@ -0,0 +1,116 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/main/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import subprocess +import sys + +import pytorch_sphinx_theme + +sys.path.insert(0, os.path.abspath('../..')) + +# -- Project information ----------------------------------------------------- + +project = 'MMDetection' +copyright = '2018-2021, OpenMMLab' +author = 'MMDetection Authors' +version_file = '../../mmdet/version.py' + + +def get_version(): + with open(version_file, 'r') as f: + exec(compile(f.read(), version_file, 'exec')) + return locals()['__version__'] + + +# The full version, including alpha/beta/rc tags +release = get_version() + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.napoleon', + 'sphinx.ext.viewcode', + 'myst_parser', + 'sphinx_markdown_tables', + 'sphinx_copybutton', +] + +myst_enable_extensions = ['colon_fence'] +myst_heading_anchors = 3 + +autodoc_mock_imports = [ + 'matplotlib', 'pycocotools', 'terminaltables', 'mmdet.version', 'mmcv.ops' +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +source_suffix = { + '.rst': 'restructuredtext', + '.md': 'markdown', +} + +# The main toctree document. +master_doc = 'index' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +# html_theme = 'sphinx_rtd_theme' +html_theme = 'pytorch_sphinx_theme' +html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()] + +html_theme_options = { + 'menu': [ + { + 'name': 'GitHub', + 'url': 'https://github.com/open-mmlab/mmdetection' + }, + ], + # Specify the language of shared menu + 'menu_lang': + 'en' +} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] +html_css_files = ['css/readthedocs.css'] + +# -- Extension configuration ------------------------------------------------- +# Ignore >>> when copying code +copybutton_prompt_text = r'>>> |\.\.\. ' +copybutton_prompt_is_regexp = True + + +def builder_inited_handler(app): + subprocess.run(['./stat.py']) + + +def setup(app): + app.connect('builder-inited', builder_inited_handler) diff --git a/mmdet_code/mmdetection/docs/en/dataset_zoo.md b/mmdet_code/mmdetection/docs/en/dataset_zoo.md new file mode 100644 index 0000000000000000000000000000000000000000..c35cc220bc001f20f02421ac892efe9e6bb7c925 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/dataset_zoo.md @@ -0,0 +1 @@ +# Dataset Zoo diff --git a/mmdet_code/mmdetection/docs/en/get_started.md b/mmdet_code/mmdetection/docs/en/get_started.md new file mode 100644 index 0000000000000000000000000000000000000000..f65878b610b97364bb2cfcf63350f42fd583c702 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/get_started.md @@ -0,0 +1,297 @@ +# GET STARTED + +## Prerequisites + +In this section, we demonstrate how to prepare an environment with PyTorch. + +MMDetection works on Linux, Windows, and macOS. It requires Python 3.7+, CUDA 9.2+, and PyTorch 1.8+. + +```{note} +If you are experienced with PyTorch and have already installed it, just skip this part and jump to the [next section](#installation). Otherwise, you can follow these steps for the preparation. +``` + +**Step 0.** Download and install Miniconda from the [official website](https://docs.conda.io/en/latest/miniconda.html). + +**Step 1.** Create a conda environment and activate it. + +```shell +conda create --name openmmlab python=3.8 -y +conda activate openmmlab +``` + +**Step 2.** Install PyTorch following [official instructions](https://pytorch.org/get-started/locally/), e.g. + +On GPU platforms: + +```shell +conda install pytorch torchvision -c pytorch +``` + +On CPU platforms: + +```shell +conda install pytorch torchvision cpuonly -c pytorch +``` + +## Installation + +We recommend that users follow our best practices to install MMDetection. However, the whole process is highly customizable. See [Customize Installation](#customize-installation) section for more information. + +### Best Practices + +**Step 0.** Install [MMEngine](https://github.com/open-mmlab/mmengine) and [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim). + +```shell +pip install -U openmim +mim install mmengine +mim install "mmcv>=2.0.0" +``` + +**Note:** In MMCV-v2.x, `mmcv-full` is rename to `mmcv`, if you want to install `mmcv` without CUDA ops, you can use `mim install "mmcv-lite>=2.0.0rc1"` to install the lite version. + +**Step 1.** Install MMDetection. + +Case a: If you develop and run mmdet directly, install it from source: + +```shell +git clone https://github.com/open-mmlab/mmdetection.git +cd mmdetection +pip install -v -e . +# "-v" means verbose, or more output +# "-e" means installing a project in editable mode, +# thus any local modifications made to the code will take effect without reinstallation. +``` + +Case b: If you use mmdet as a dependency or third-party package, install it with MIM: + +```shell +mim install mmdet +``` + +## Verify the installation + +To verify whether MMDetection is installed correctly, we provide some sample codes to run an inference demo. + +**Step 1.** We need to download config and checkpoint files. + +```shell +mim download mmdet --config rtmdet_tiny_8xb32-300e_coco --dest . +``` + +The downloading will take several seconds or more, depending on your network environment. When it is done, you will find two files `rtmdet_tiny_8xb32-300e_coco.py` and `rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth` in your current folder. + +**Step 2.** Verify the inference demo. + +Case a: If you install MMDetection from source, just run the following command. + +```shell +python demo/image_demo.py demo/demo.jpg rtmdet_tiny_8xb32-300e_coco.py --weights rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --device cpu +``` + +You will see a new image `demo.jpg` on your `./outputs/vis` folder, where bounding boxes are plotted on cars, benches, etc. + +Case b: If you install MMDetection with MIM, open your python interpreter and copy&paste the following codes. + +```python +from mmdet.apis import init_detector, inference_detector + +config_file = 'rtmdet_tiny_8xb32-300e_coco.py' +checkpoint_file = 'rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth' +model = init_detector(config_file, checkpoint_file, device='cpu') # or device='cuda:0' +inference_detector(model, 'demo/demo.jpg') +``` + +You will see a list of `DetDataSample`, and the predictions are in the `pred_instance`, indicating the detected bounding boxes, labels, and scores. + +## Tracking Installation + +We recommend that users follow our best practices to install MMDetection for tracking task. + +### Best Practices + +**Step 0.** Install [MMEngine](https://github.com/open-mmlab/mmengine) and [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim). + +```shell +pip install -U openmim +mim install mmengine +mim install "mmcv>=2.0.0" +``` + +**Step 1.** Install MMDetection. + +Case a: If you develop and run mmdet directly, install it from source: + +```shell +git clone https://github.com/open-mmlab/mmdetection.git +cd mmdetection +pip install -v -e . -r requirements/tracking.txt +# "-v" means verbose, or more output +# "-e" means installing a project in editable mode, +# thus any local modifications made to the code will take effect without reinstallation. +``` + +Case b: If you use mmdet as a dependency or third-party package, install it with MIM: + +```shell +mim install mmdet[tracking] +``` + +**Step 2.** Install TrackEval. + +```shell +pip install git+https://github.com/JonathonLuiten/TrackEval.git +``` + +## Verify the installation + +To verify whether MMDetection is installed correctly, we provide some sample codes to run an inference demo. + +**Step 1.** We need to download config and checkpoint files. + +```shell +mim download mmdet --config bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval --dest . +``` + +The downloading will take several seconds or more, depending on your network environment. When it is done, you will find two files `bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py` and `bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500-1985c9f0.pth` in your current folder. + +**Step 2.** Verify the inference demo. + +Case a: If you install MMDetection from source, just run the following command. + +```shell +python demo/mot_demo.py demo/demo_mot.mp4 bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py --checkpoint bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500-1985c9f0.pth --out mot.mp4 +``` + +You will see a new video `mot.mp4` on your folder, where bounding boxes are plotted on person. + +Case b: If you install MMDetection with MIM, open your python interpreter and demo/mot_demo.py, then run it like Case a. + +### Customize Installation + +#### CUDA versions + +When installing PyTorch, you need to specify the version of CUDA. If you are not clear on which to choose, follow our recommendations: + +- For Ampere-based NVIDIA GPUs, such as GeForce 30 series and NVIDIA A100, CUDA 11 is a must. +- For older NVIDIA GPUs, CUDA 11 is backward compatible, but CUDA 10.2 offers better compatibility and is more lightweight. + +Please make sure the GPU driver satisfies the minimum version requirements. See [this table](https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cuda-major-component-versions__table-cuda-toolkit-driver-versions) for more information. + +```{note} +Installing CUDA runtime libraries is enough if you follow our best practices, because no CUDA code will be compiled locally. However, if you hope to compile MMCV from source or develop other CUDA operators, you need to install the complete CUDA toolkit from NVIDIA's [website](https://developer.nvidia.com/cuda-downloads), and its version should match the CUDA version of PyTorch. i.e., the specified version of cudatoolkit in the `conda install` command. +``` + +#### Install MMEngine without MIM + +To install MMEngine with pip instead of MIM, please follow [MMEngine installation guides](https://mmengine.readthedocs.io/en/latest/get_started/installation.html). + +For example, you can install MMEngine by the following command. + +```shell +pip install mmengine +``` + +#### Install MMCV without MIM + +MMCV contains C++ and CUDA extensions, thus depending on PyTorch in a complex way. MIM solves such dependencies automatically and makes the installation easier. However, it is not a must. + +To install MMCV with pip instead of MIM, please follow [MMCV installation guides](https://mmcv.readthedocs.io/en/2.x/get_started/installation.html). This requires manually specifying a find-url based on the PyTorch version and its CUDA version. + +For example, the following command installs MMCV built for PyTorch 1.12.x and CUDA 11.6. + +```shell +pip install "mmcv>=2.0.0" -f https://download.openmmlab.com/mmcv/dist/cu116/torch1.12.0/index.html +``` + +#### Install on CPU-only platforms + +MMDetection can be built for CPU-only environments. In CPU mode you can train (requires MMCV version >= 2.0.0rc1), test, or infer a model. + +However, some functionalities are gone in this mode: + +- Deformable Convolution +- Modulated Deformable Convolution +- ROI pooling +- Deformable ROI pooling +- CARAFE +- SyncBatchNorm +- CrissCrossAttention +- MaskedConv2d +- Temporal Interlace Shift +- nms_cuda +- sigmoid_focal_loss_cuda +- bbox_overlaps + +If you try to train/test/infer a model containing the above ops, an error will be raised. +The following table lists affected algorithms. + +| Operator | Model | +| :-----------------------------------------------------: | :--------------------------------------------------------------------------------------: | +| Deformable Convolution/Modulated Deformable Convolution | DCN, Guided Anchoring, RepPoints, CentripetalNet, VFNet, CascadeRPN, NAS-FCOS, DetectoRS | +| MaskedConv2d | Guided Anchoring | +| CARAFE | CARAFE | +| SyncBatchNorm | ResNeSt | + +#### Install on Google Colab + +[Google Colab](https://colab.research.google.com/) usually has PyTorch installed, +thus we only need to install MMEngine, MMCV, and MMDetection with the following commands. + +**Step 1.** Install [MMEngine](https://github.com/open-mmlab/mmengine) and [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim). + +```shell +!pip3 install openmim +!mim install mmengine +!mim install "mmcv>=2.0.0,<2.1.0" +``` + +**Step 2.** Install MMDetection from the source. + +```shell +!git clone https://github.com/open-mmlab/mmdetection.git +%cd mmdetection +!pip install -e . +``` + +**Step 3.** Verification. + +```python +import mmdet +print(mmdet.__version__) +# Example output: 3.0.0, or an another version. +``` + +```{note} +Within Jupyter, the exclamation mark `!` is used to call external executables and `%cd` is a [magic command](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-cd) to change the current working directory of Python. +``` + +#### Use MMDetection with Docker + +We provide a [Dockerfile](../../docker/Dockerfile) to build an image. Ensure that your [docker version](https://docs.docker.com/engine/install/) >=19.03. + +```shell +# build an image with PyTorch 1.9, CUDA 11.1 +# If you prefer other versions, just modified the Dockerfile +docker build -t mmdetection docker/ +``` + +Run it with + +```shell +docker run --gpus all --shm-size=8g -it -v {DATA_DIR}:/mmdetection/data mmdetection +``` + +### Troubleshooting + +If you have some issues during the installation, please first view the [FAQ](notes/faq.md) page. +You may [open an issue](https://github.com/open-mmlab/mmdetection/issues/new/choose) on GitHub if no solution is found. + +### Use Multiple Versions of MMDetection in Development + +Training and testing scripts have already been modified in `PYTHONPATH` in order to make sure the scripts are using their own versions of MMDetection. + +To install the default version of MMDetection in your environment, you can exclude the follow code in the relative scripts: + +```shell +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH +``` diff --git a/mmdet_code/mmdetection/docs/en/index.rst b/mmdet_code/mmdetection/docs/en/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..32c5952a4ae438b491a7408f61b9d833e54f1b68 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/index.rst @@ -0,0 +1,63 @@ +Welcome to MMDetection's documentation! +======================================= + +.. toctree:: + :maxdepth: 1 + :caption: Get Started + + overview.md + get_started.md + +.. toctree:: + :maxdepth: 2 + :caption: User Guides + + user_guides/index.rst + +.. toctree:: + :maxdepth: 2 + :caption: Advanced Guides + + advanced_guides/index.rst + +.. toctree:: + :maxdepth: 1 + :caption: Migration + + migration/migration.md + +.. toctree:: + :maxdepth: 1 + :caption: API Reference + + api.rst + +.. toctree:: + :maxdepth: 1 + :caption: Model Zoo + + model_zoo.md + +.. toctree:: + :maxdepth: 1 + :caption: Notes + + notes/contribution_guide.md + notes/projects.md + notes/changelog.md + notes/changelog_v2.x.md + notes/faq.md + notes/compatibility.md + +.. toctree:: + :caption: Switch Language + + switch_language.md + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`search` diff --git a/mmdet_code/mmdetection/docs/en/make.bat b/mmdet_code/mmdetection/docs/en/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..922152e96a04a242e6fc40f124261d74890617d8 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/mmdet_code/mmdetection/docs/en/migration.md b/mmdet_code/mmdetection/docs/en/migration.md new file mode 100644 index 0000000000000000000000000000000000000000..689e8d24e45c578b273836d48697610cf63f7115 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/migration.md @@ -0,0 +1 @@ +# Migration diff --git a/mmdet_code/mmdetection/docs/en/migration/api_and_registry_migration.md b/mmdet_code/mmdetection/docs/en/migration/api_and_registry_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..72bfd3aec8e34136acf16c2313c1eecad9cfb461 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/migration/api_and_registry_migration.md @@ -0,0 +1 @@ +# Migrate API and Registry from MMDetection 2.x to 3.x diff --git a/mmdet_code/mmdetection/docs/en/migration/config_migration.md b/mmdet_code/mmdetection/docs/en/migration/config_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..1177fa9faad623df03d8df816077e83914570cb9 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/migration/config_migration.md @@ -0,0 +1,819 @@ +# Migrate Configuration File from MMDetection 2.x to 3.x + +The configuration file of MMDetection 3.x has undergone significant changes in comparison to the 2.x version. This document explains how to migrate 2.x configuration files to 3.x. + +In the previous tutorial [Learn about Configs](../user_guides/config.md), we used Mask R-CNN as an example to introduce the configuration file structure of MMDetection 3.x. Here, we will follow the same structure to demonstrate how to migrate 2.x configuration files to 3.x. + +## Model Configuration + +There have been no major changes to the model configuration in 3.x compared to 2.x. For the model's backbone, neck, head, as well as train_cfg and test_cfg, the parameters remain the same as in version 2.x. + +On the other hand, we have added the `DataPreprocessor` module in MMDetection 3.x. The configuration for the `DataPreprocessor` module is located in `model.data_preprocessor`. It is used to preprocess the input data, such as normalizing input images and padding images of different sizes into batches, and loading images from memory to VRAM. This configuration replaces the `Normalize` and `Pad` modules in `train_pipeline` and `test_pipeline` of the earlier version. + + + + + + + + + +
2.x Config + +```python +# Image normalization parameters +img_norm_cfg = dict( + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True) +pipeline=[ + ..., + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), # Padding the image to multiples of 32 + ... +] +``` + +
3.x Config + +```python +model = dict( + data_preprocessor=dict( + type='DetDataPreprocessor', + # Image normalization parameters + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + # Image padding parameters + pad_mask=True, # In instance segmentation, the mask needs to be padded + pad_size_divisor=32) # Padding the image to multiples of 32 +) + +``` + +
+ +## Dataset and Evaluator Configuration + +The dataset and evaluator configurations have undergone major changes compared to version 2.x. We will introduce how to migrate from version 2.x to version 3.x from three aspects: Dataloader and Dataset, Data transform pipeline, and Evaluator configuration. + +### Dataloader and Dataset Configuration + +In the new version, we set the data loading settings consistent with PyTorch's official DataLoader, +making it easier for users to understand and get started with. +We put the data loading settings for training, validation, and testing separately in `train_dataloader`, `val_dataloader`, and `test_dataloader`. +Users can set different parameters for these dataloaders. +The input parameters are basically the same as those required by [PyTorch DataLoader](https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader). + +This way, we put the unconfigurable parameters in version 2.x, such as `sampler`, `batch_sampler`, and `persistent_workers`, in the configuration file, so that users can set dataloader parameters more flexibly. + +Users can set the dataset configuration through `train_dataloader.dataset`, `val_dataloader.dataset`, and `test_dataloader.dataset`, which correspond to `data.train`, `data.val`, and `data.test` in version 2.x. + + + + + + + + + +
2.x Config + +```python +data = dict( + samples_per_gpu=2, + workers_per_gpu=2, + train=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=train_pipeline), + val=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline), + test=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline)) +``` + +
3.x Config + +```python +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, # Avoid recreating subprocesses after each iteration + sampler=dict(type='DefaultSampler', shuffle=True), # Default sampler, supports both distributed and non-distributed training + batch_sampler=dict(type='AspectRatioBatchSampler'), # Default batch_sampler, used to ensure that images in the batch have similar aspect ratios, so as to better utilize graphics memory + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline)) +# In version 3.x, validation and test dataloaders can be configured independently +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader # The configuration of the testing dataloader is the same as that of the validation dataloader, which is omitted here + +``` + +
+ +### Data Transform Pipeline Configuration + +As mentioned earlier, we have separated the normalization and padding configurations for images from the `train_pipeline` and `test_pipeline`, and have placed them in `model.data_preprocessor` instead. Hence, in the 3.x version of the pipeline, we no longer require the `Normalize` and `Pad` transforms. + +At the same time, we have also refactored the transform responsible for packing the data format, and have merged the `Collect` and `DefaultFormatBundle` transforms into `PackDetInputs`. This transform is responsible for packing the data from the data pipeline into the input format of the model. For more details on the input format conversion, please refer to the [data flow documentation](../advanced_guides/data_flow.md). + +Below, we will use the `train_pipeline` of Mask R-CNN as an example, to demonstrate how to migrate from the 2.x configuration to the 3.x configuration: + + + + + + + + + +
2.x Config + +```python +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=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', flip_ratio=0.5), + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='DefaultFormatBundle'), + dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), +] +``` + +
3.x Config + +```python +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +``` + +
+ +For the `test_pipeline`, apart from removing the `Normalize` and `Pad` transforms, we have also separated the data augmentation for testing (TTA) from the normal testing process, and have removed `MultiScaleFlipAug`. For more information on how to use the new TTA version, please refer to the [TTA documentation](../advanced_guides/tta.md). + +Below, we will again use the `test_pipeline` of Mask R-CNN as an example, to demonstrate how to migrate from the 2.x configuration to the 3.x configuration: + + + + + + + + + +
2.x Config + +```python +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', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='ImageToTensor', keys=['img']), + dict(type='Collect', keys=['img']), + ]) +] +``` + +
3.x Config + +```python +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +``` + +
+ +In addition, we have also refactored some data augmentation transforms. The following table lists the mapping between the transforms used in the 2.x version and the 3.x version: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name2.x Config3.x Config
Resize + +```python +dict(type='Resize', + img_scale=(1333, 800), + keep_ratio=True) +``` + + + +```python +dict(type='Resize', + scale=(1333, 800), + keep_ratio=True) +``` + +
RandomResize + +```python +dict( + type='Resize', + img_scale=[ + (1333, 640), (1333, 800)], + multiscale_mode='range', + keep_ratio=True) +``` + + + +```python +dict( + type='RandomResize', + scale=[ + (1333, 640), (1333, 800)], + keep_ratio=True) +``` + +
RandomChoiceResize + +```python +dict( + type='Resize', + img_scale=[ + (1333, 640), (1333, 672), + (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + multiscale_mode='value', + keep_ratio=True) +``` + + + +```python +dict( + type='RandomChoiceResize', + scales=[ + (1333, 640), (1333, 672), + (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True) +``` + +
RandomFlip + +```python +dict(type='RandomFlip', flip_ratio=0.5) +``` + + + +```python +dict(type='RandomFlip', prob=0.5) +``` + +
+ +### 评测器配置 + +In version 3.x, model accuracy evaluation is no longer tied to the dataset, but is instead accomplished through the use of an Evaluator. +The Evaluator configuration is divided into two parts: `val_evaluator` and `test_evaluator`. The `val_evaluator` is used for validation dataset evaluation, while the `test_evaluator` is used for testing dataset evaluation. +This corresponds to the `evaluation` field in version 2.x. + +The following table shows the corresponding relationship between Evaluators in version 2.x and 3.x. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Metric Name2.x Config3.x Config
COCO + +```python +data = dict( + val=dict( + type='CocoDataset', + ann_file=data_root + 'annotations/instances_val2017.json')) +evaluation = dict(metric=['bbox', 'segm']) +``` + + + +```python +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False) +``` + +
Pascal VOC + +```python +data = dict( + val=dict( + type=dataset_type, + ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt')) +evaluation = dict(metric='mAP') +``` + + + +```python +val_evaluator = dict( + type='VOCMetric', + metric='mAP', + eval_mode='11points') +``` + +
OpenImages + +```python +data = dict( + val=dict( + type='OpenImagesDataset', + ann_file=data_root + 'annotations/validation-annotations-bbox.csv', + img_prefix=data_root + 'OpenImages/validation/', + label_file=data_root + 'annotations/class-descriptions-boxable.csv', + hierarchy_file=data_root + + 'annotations/bbox_labels_600_hierarchy.json', + meta_file=data_root + 'annotations/validation-image-metas.pkl', + image_level_ann_file=data_root + + 'annotations/validation-annotations-human-imagelabels-boxable.csv')) +evaluation = dict(interval=1, metric='mAP') +``` + + + +```python +val_evaluator = dict( + type='OpenImagesMetric', + iou_thrs=0.5, + ioa_thrs=0.5, + use_group_of=True, + get_supercategory=True) +``` + +
CityScapes + +```python +data = dict( + val=dict( + type='CityScapesDataset', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + img_prefix=data_root + 'leftImg8bit/val/', + pipeline=test_pipeline)) +evaluation = dict(metric=['bbox', 'segm']) +``` + + + +```python +val_evaluator = [ + dict( + type='CocoMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + metric=['bbox', 'segm']), + dict( + type='CityScapesMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + seg_prefix=data_root + '/gtFine/val', + outfile_prefix='./work_dirs/cityscapes_metric/instance') +] +``` + +
+ +## Configuration for Training and Testing + + + + + + + + + +
2.x Config + +```python +runner = dict( + type='EpochBasedRunner', # Type of training loop + max_epochs=12) # Maximum number of training epochs +evaluation = dict(interval=2) # Interval for evaluation, check the performance every 2 epochs +``` + +
3.x Config + +```python +train_cfg = dict( + type='EpochBasedTrainLoop', # Type of training loop, please refer to https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py + max_epochs=12, # Maximum number of training epochs + val_interval=2) # Interval for validation, check the performance every 2 epochs +val_cfg = dict(type='ValLoop') # Type of validation loop +test_cfg = dict(type='TestLoop') # Type of testing loop +``` + +
+ +## Optimization Configuration + +The configuration for optimizer and gradient clipping is moved to the `optim_wrapper` field. +The following table shows the correspondences for optimizer configuration between 2.x version and 3.x version: + + + + + + + + + +
2.x Config + +```python +optimizer = dict( + type='SGD', # Optimizer: Stochastic Gradient Descent + lr=0.02, # Base learning rate + momentum=0.9, # SGD with momentum + weight_decay=0.0001) # Weight decay +optimizer_config = dict(grad_clip=None) # Configuration for gradient clipping, set to None to disable +``` + +
3.x Config + +```python +optim_wrapper = dict( # Configuration for the optimizer wrapper + type='OptimWrapper', # Type of optimizer wrapper, you can switch to AmpOptimWrapper to enable mixed precision training + optimizer=dict( # Optimizer configuration, supports various PyTorch optimizers, please refer to https://pytorch.org/docs/stable/optim.html#algorithms + type='SGD', # SGD + lr=0.02, # Base learning rate + momentum=0.9, # SGD with momentum + weight_decay=0.0001), # Weight decay + clip_grad=None, # Configuration for gradient clipping, set to None to disable. For usage, please see https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html + ) +``` + +
+ +The configuration for learning rate is also moved from the `lr_config` field to the `param_scheduler` field. The `param_scheduler` configuration is more similar to PyTorch's learning rate scheduler and more flexible. The following table shows the correspondences for learning rate configuration between 2.x version and 3.x version: + + + + + + + + + +
2.x Config + +```python +lr_config = dict( + policy='step', # Use multi-step learning rate strategy during training + warmup='linear', # Use linear learning rate warmup + warmup_iters=500, # End warmup at iteration 500 + warmup_ratio=0.001, # Coefficient for learning rate warmup + step=[8, 11], # Learning rate decay at which epochs + gamma=0.1) # Learning rate decay coefficient + +``` + +
3.x Config + +```python +param_scheduler = [ + dict( + type='LinearLR', # Use linear learning rate warmup + start_factor=0.001, # Coefficient for learning rate warmup + by_epoch=False, # Update the learning rate during warmup at each iteration + begin=0, # Starting from the first iteration + end=500), # End at the 500th iteration + dict( + type='MultiStepLR', # Use multi-step learning rate strategy during training + by_epoch=True, # Update the learning rate at each epoch + begin=0, # Starting from the first epoch + end=12, # Ending at the 12th epoch + milestones=[8, 11], # Learning rate decay at which epochs + gamma=0.1) # Learning rate decay coefficient +] + +``` + +
+ +For information on how to migrate other learning rate adjustment policies, please refer to the [learning rate migration document of MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/migration/param_scheduler.html). + +## Migration of Other Configurations + +### Configuration for Saving Checkpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Function2.x Config3.x Config
Set Save Interval + +```python +checkpoint_config = dict( + interval=1) +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + interval=1)) +``` + +
Save Best Model + +```python +evaluation = dict( + save_best='auto') +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + save_best='auto')) +``` + +
Keep Latest Model + +```python +checkpoint_config = dict( + max_keep_ckpts=3) +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + max_keep_ckpts=3)) +``` + +
+ +### Logging Configuration + +In MMDetection 3.x, the logging and visualization of the log are carried out respectively by the logger and visualizer in MMEngine. The following table shows the comparison between the configuration of printing logs and visualizing logs in MMDetection 2.x and 3.x. + + + + + + + + + + + + + + + + + + + + + + + + +
Function2.x Config3.x Config
Set Log Printing Interval + +```python +log_config = dict(interval=50) +``` + + + +```python +default_hooks = dict( + logger=dict(type='LoggerHook', interval=50)) +# Optional: set moving average window size +log_processor = dict( + type='LogProcessor', window_size=50) +``` + +
Use TensorBoard or WandB to visualize logs + +```python +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook'), + dict(type='MMDetWandbHook', + init_kwargs={ + 'project': 'mmdetection', + 'group': 'maskrcnn-r50-fpn-1x-coco' + }, + interval=50, + log_checkpoint=True, + log_checkpoint_metadata=True, + num_eval_images=100) + ]) +``` + + + +```python +vis_backends = [ + dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend'), + dict(type='WandbVisBackend', + init_kwargs={ + 'project': 'mmdetection', + 'group': 'maskrcnn-r50-fpn-1x-coco' + }) +] +visualizer = dict( + type='DetLocalVisualizer', + vis_backends=vis_backends, + name='visualizer') +``` + +
+ +For visualization-related tutorials, please refer to [Visualization Tutorial](../user_guides/visualization.md) of MMDetection. + +### Runtime Configuration + +The runtime configuration fields in version 3.x have been adjusted, and the specific correspondence is as follows: + + + + + + + + + + + + + + + + +
2.x Config3.x Config
+ +```python +cudnn_benchmark = False +opencv_num_threads = 0 +mp_start_method = 'fork' +dist_params = dict(backend='nccl') +log_level = 'INFO' +load_from = None +resume_from = None + + +``` + + + +```python +env_cfg = dict( + cudnn_benchmark=False, + mp_cfg=dict(mp_start_method='fork', + opencv_num_threads=0), + dist_cfg=dict(backend='nccl')) +log_level = 'INFO' +load_from = None +resume = False +``` + +
diff --git a/mmdet_code/mmdetection/docs/en/migration/dataset_migration.md b/mmdet_code/mmdetection/docs/en/migration/dataset_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..75d093298e0e751203614d8c5008bc774ebfd93e --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/migration/dataset_migration.md @@ -0,0 +1 @@ +# Migrate dataset from MMDetection 2.x to 3.x diff --git a/mmdet_code/mmdetection/docs/en/migration/migration.md b/mmdet_code/mmdetection/docs/en/migration/migration.md new file mode 100644 index 0000000000000000000000000000000000000000..ec6a2f891b15182b033d34e95c9710d701478e21 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/migration/migration.md @@ -0,0 +1,12 @@ +# Migrating from MMDetection 2.x to 3.x + +MMDetection 3.x is a significant update that includes many changes to API and configuration files. This document aims to help users migrate from MMDetection 2.x to 3.x. +We divided the migration guide into the following sections: + +- [Configuration file migration](./config_migration.md) +- [API and Registry migration](./api_and_registry_migration.md) +- [Dataset migration](./dataset_migration.md) +- [Model migration](./model_migration.md) +- [Frequently Asked Questions](./migration_faq.md) + +If you encounter any problems during the migration process, feel free to raise an issue. We also welcome contributions to this document. diff --git a/mmdet_code/mmdetection/docs/en/migration/migration_faq.md b/mmdet_code/mmdetection/docs/en/migration/migration_faq.md new file mode 100644 index 0000000000000000000000000000000000000000..a6e3c356c275a9306532d41ac1cb552b714a463a --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/migration/migration_faq.md @@ -0,0 +1 @@ +# Migration FAQ diff --git a/mmdet_code/mmdetection/docs/en/migration/model_migration.md b/mmdet_code/mmdetection/docs/en/migration/model_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..04e280879fca1b251f5e32e0d3eafae58af5dab1 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/migration/model_migration.md @@ -0,0 +1 @@ +# Migrate models from MMDetection 2.x to 3.x diff --git a/mmdet_code/mmdetection/docs/en/model_zoo.md b/mmdet_code/mmdetection/docs/en/model_zoo.md new file mode 100644 index 0000000000000000000000000000000000000000..15dd7b2fb5b2f890de78d036746b3c8371f0ddf3 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/model_zoo.md @@ -0,0 +1,358 @@ +# Benchmark and Model Zoo + +## Mirror sites + +We only use aliyun to maintain the model zoo since MMDetection V2.0. The model zoo of V1.x has been deprecated. + +## Common settings + +- All models were trained on `coco_2017_train`, and tested on the `coco_2017_val`. +- We use distributed training. +- All pytorch-style pretrained backbones on ImageNet are from PyTorch model zoo, caffe-style pretrained backbones are converted from the newly released model from detectron2. +- For fair comparison with other codebases, we report the GPU memory as the maximum value of `torch.cuda.max_memory_allocated()` for all 8 GPUs. Note that this value is usually less than what `nvidia-smi` shows. +- We report the inference time as the total time of network forwarding and post-processing, excluding the data loading time. Results are obtained with the script [benchmark.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/benchmark.py) which computes the average time on 2000 images. + +## ImageNet Pretrained Models + +It is common to initialize from backbone models pre-trained on ImageNet classification task. All pre-trained model links can be found at [open_mmlab](https://github.com/open-mmlab/mmcv/blob/master/mmcv/model_zoo/open_mmlab.json). According to `img_norm_cfg` and source of weight, we can divide all the ImageNet pre-trained model weights into some cases: + +- TorchVision: Corresponding to torchvision weight, including ResNet50, ResNet101. The `img_norm_cfg` is `dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)`. +- Pycls: Corresponding to [pycls](https://github.com/facebookresearch/pycls) weight, including RegNetX. The `img_norm_cfg` is `dict( mean=[103.530, 116.280, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False)`. +- MSRA styles: Corresponding to [MSRA](https://github.com/KaimingHe/deep-residual-networks) weights, including ResNet50_Caffe and ResNet101_Caffe. The `img_norm_cfg` is `dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)`. +- Caffe2 styles: Currently only contains ResNext101_32x8d. The `img_norm_cfg` is `dict(mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395], to_rgb=False)`. +- Other styles: E.g SSD which corresponds to `img_norm_cfg` is `dict(mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True)` and YOLOv3 which corresponds to `img_norm_cfg` is `dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True)`. + +The detailed table of the commonly used backbone models in MMDetection is listed below : + +| model | source | link | description | +| ---------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| ResNet50 | TorchVision | [torchvision's ResNet-50](https://download.pytorch.org/models/resnet50-19c8e357.pth) | From [torchvision's ResNet-50](https://download.pytorch.org/models/resnet50-19c8e357.pth). | +| ResNet101 | TorchVision | [torchvision's ResNet-101](https://download.pytorch.org/models/resnet101-5d3b4d8f.pth) | From [torchvision's ResNet-101](https://download.pytorch.org/models/resnet101-5d3b4d8f.pth). | +| RegNetX | Pycls | [RegNetX_3.2gf](https://download.openmmlab.com/pretrain/third_party/regnetx_3.2gf-c2599b0f.pth), [RegNetX_800mf](https://download.openmmlab.com/pretrain/third_party/regnetx_800mf-1f4be4c7.pth). etc. | From [pycls](https://github.com/facebookresearch/pycls). | +| ResNet50_Caffe | MSRA | [MSRA's ResNet-50](https://download.openmmlab.com/pretrain/third_party/resnet50_caffe-788b5fa3.pth) | Converted copy of [Detectron2's R-50.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-50.pkl) model. The original weight comes from [MSRA's original ResNet-50](https://github.com/KaimingHe/deep-residual-networks). | +| ResNet101_Caffe | MSRA | [MSRA's ResNet-101](https://download.openmmlab.com/pretrain/third_party/resnet101_caffe-3ad79236.pth) | Converted copy of [Detectron2's R-101.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-101.pkl) model. The original weight comes from [MSRA's original ResNet-101](https://github.com/KaimingHe/deep-residual-networks). | +| ResNext101_32x8d | Caffe2 | [Caffe2 ResNext101_32x8d](https://download.openmmlab.com/pretrain/third_party/resnext101_32x8d-1516f1aa.pth) | Converted copy of [Detectron2's X-101-32x8d.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/FAIR/X-101-32x8d.pkl) model. The ResNeXt-101-32x8d model trained with Caffe2 at FB. | + +## Baselines + +### RPN + +Please refer to [RPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/rpn) for details. + +### Faster R-CNN + +Please refer to [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn) for details. + +### Mask R-CNN + +Please refer to [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn) for details. + +### Fast R-CNN (with pre-computed proposals) + +Please refer to [Fast R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/fast_rcnn) for details. + +### RetinaNet + +Please refer to [RetinaNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/retinanet) for details. + +### Cascade R-CNN and Cascade Mask R-CNN + +Please refer to [Cascade R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/cascade_rcnn) for details. + +### Hybrid Task Cascade (HTC) + +Please refer to [HTC](https://github.com/open-mmlab/mmdetection/blob/main/configs/htc) for details. + +### SSD + +Please refer to [SSD](https://github.com/open-mmlab/mmdetection/blob/main/configs/ssd) for details. + +### Group Normalization (GN) + +Please refer to [Group Normalization](https://github.com/open-mmlab/mmdetection/blob/main/configs/gn) for details. + +### Weight Standardization + +Please refer to [Weight Standardization](https://github.com/open-mmlab/mmdetection/blob/main/configs/gn+ws) for details. + +### Deformable Convolution v2 + +Please refer to [Deformable Convolutional Networks](https://github.com/open-mmlab/mmdetection/blob/main/configs/dcn) for details. + +### CARAFE: Content-Aware ReAssembly of FEatures + +Please refer to [CARAFE](https://github.com/open-mmlab/mmdetection/blob/main/configs/carafe) for details. + +### Instaboost + +Please refer to [Instaboost](https://github.com/open-mmlab/mmdetection/blob/main/configs/instaboost) for details. + +### Libra R-CNN + +Please refer to [Libra R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/libra_rcnn) for details. + +### Guided Anchoring + +Please refer to [Guided Anchoring](https://github.com/open-mmlab/mmdetection/blob/main/configs/guided_anchoring) for details. + +### FCOS + +Please refer to [FCOS](https://github.com/open-mmlab/mmdetection/blob/main/configs/fcos) for details. + +### FoveaBox + +Please refer to [FoveaBox](https://github.com/open-mmlab/mmdetection/blob/main/configs/foveabox) for details. + +### RepPoints + +Please refer to [RepPoints](https://github.com/open-mmlab/mmdetection/blob/main/configs/reppoints) for details. + +### FreeAnchor + +Please refer to [FreeAnchor](https://github.com/open-mmlab/mmdetection/blob/main/configs/free_anchor) for details. + +### Grid R-CNN (plus) + +Please refer to [Grid R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/grid_rcnn) for details. + +### GHM + +Please refer to [GHM](https://github.com/open-mmlab/mmdetection/blob/main/configs/ghm) for details. + +### GCNet + +Please refer to [GCNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/gcnet) for details. + +### HRNet + +Please refer to [HRNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/hrnet) for details. + +### Mask Scoring R-CNN + +Please refer to [Mask Scoring R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/ms_rcnn) for details. + +### Train from Scratch + +Please refer to [Rethinking ImageNet Pre-training](https://github.com/open-mmlab/mmdetection/blob/main/configs/scratch) for details. + +### NAS-FPN + +Please refer to [NAS-FPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/nas_fpn) for details. + +### ATSS + +Please refer to [ATSS](https://github.com/open-mmlab/mmdetection/blob/main/configs/atss) for details. + +### FSAF + +Please refer to [FSAF](https://github.com/open-mmlab/mmdetection/blob/main/configs/fsaf) for details. + +### RegNetX + +Please refer to [RegNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/regnet) for details. + +### Res2Net + +Please refer to [Res2Net](https://github.com/open-mmlab/mmdetection/blob/main/configs/res2net) for details. + +### GRoIE + +Please refer to [GRoIE](https://github.com/open-mmlab/mmdetection/blob/main/configs/groie) for details. + +### Dynamic R-CNN + +Please refer to [Dynamic R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/dynamic_rcnn) for details. + +### PointRend + +Please refer to [PointRend](https://github.com/open-mmlab/mmdetection/blob/main/configs/point_rend) for details. + +### DetectoRS + +Please refer to [DetectoRS](https://github.com/open-mmlab/mmdetection/blob/main/configs/detectors) for details. + +### Generalized Focal Loss + +Please refer to [Generalized Focal Loss](https://github.com/open-mmlab/mmdetection/blob/main/configs/gfl) for details. + +### CornerNet + +Please refer to [CornerNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/cornernet) for details. + +### YOLOv3 + +Please refer to [YOLOv3](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolo) for details. + +### PAA + +Please refer to [PAA](https://github.com/open-mmlab/mmdetection/blob/main/configs/paa) for details. + +### SABL + +Please refer to [SABL](https://github.com/open-mmlab/mmdetection/blob/main/configs/sabl) for details. + +### CentripetalNet + +Please refer to [CentripetalNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/centripetalnet) for details. + +### ResNeSt + +Please refer to [ResNeSt](https://github.com/open-mmlab/mmdetection/blob/main/configs/resnest) for details. + +### DETR + +Please refer to [DETR](https://github.com/open-mmlab/mmdetection/blob/main/configs/detr) for details. + +### Deformable DETR + +Please refer to [Deformable DETR](https://github.com/open-mmlab/mmdetection/blob/main/configs/deformable_detr) for details. + +### AutoAssign + +Please refer to [AutoAssign](https://github.com/open-mmlab/mmdetection/blob/main/configs/autoassign) for details. + +### YOLOF + +Please refer to [YOLOF](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolof) for details. + +### Seesaw Loss + +Please refer to [Seesaw Loss](https://github.com/open-mmlab/mmdetection/blob/main/configs/seesaw_loss) for details. + +### CenterNet + +Please refer to [CenterNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/centernet) for details. + +### YOLOX + +Please refer to [YOLOX](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolox) for details. + +### PVT + +Please refer to [PVT](https://github.com/open-mmlab/mmdetection/blob/main/configs/pvt) for details. + +### SOLO + +Please refer to [SOLO](https://github.com/open-mmlab/mmdetection/blob/main/configs/solo) for details. + +### QueryInst + +Please refer to [QueryInst](https://github.com/open-mmlab/mmdetection/blob/main/configs/queryinst) for details. + +### PanopticFPN + +Please refer to [PanopticFPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/panoptic_fpn) for details. + +### MaskFormer + +Please refer to [MaskFormer](https://github.com/open-mmlab/mmdetection/blob/main/configs/maskformer) for details. + +### DyHead + +Please refer to [DyHead](https://github.com/open-mmlab/mmdetection/blob/main/configs/dyhead) for details. + +### Mask2Former + +Please refer to [Mask2Former](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask2former) for details. + +### Efficientnet + +Please refer to [Efficientnet](https://github.com/open-mmlab/mmdetection/blob/main/configs/efficientnet) for details. + +### Other datasets + +We also benchmark some methods on [PASCAL VOC](https://github.com/open-mmlab/mmdetection/blob/main/configs/pascal_voc), [Cityscapes](https://github.com/open-mmlab/mmdetection/blob/main/configs/cityscapes), [OpenImages](https://github.com/open-mmlab/mmdetection/blob/main/configs/openimages) and [WIDER FACE](https://github.com/open-mmlab/mmdetection/blob/main/configs/wider_face). + +### Pre-trained Models + +We also train [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn) and [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn) using ResNet-50 and [RegNetX-3.2G](https://github.com/open-mmlab/mmdetection/blob/main/configs/regnet) with multi-scale training and longer schedules. These models serve as strong pre-trained models for downstream tasks for convenience. + +## Speed benchmark + +### Training Speed benchmark + +We provide [analyze_logs.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/analyze_logs.py) to get average time of iteration in training. You can find examples in [Log Analysis](https://mmdetection.readthedocs.io/en/latest/useful_tools.html#log-analysis). + +We compare the training speed of Mask R-CNN with some other popular frameworks (The data is copied from [detectron2](https://github.com/facebookresearch/detectron2/blob/main/docs/notes/benchmarks.md/)). +For mmdetection, we benchmark with [mask-rcnn_r50-caffe_fpn_poly-1x_coco_v1.py](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn/mask-rcnn_r50-caffe_fpn_poly-1x_coco_v1.py), which should have the same setting with [mask_rcnn_R_50_FPN_noaug_1x.yaml](https://github.com/facebookresearch/detectron2/blob/main/configs/Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x.yaml) of detectron2. +We also provide the [checkpoint](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug_compare_20200518-10127928.pth) and [training log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug_20200518_105755.log.json) for reference. The throughput is computed as the average throughput in iterations 100-500 to skip GPU warmup time. + +| Implementation | Throughput (img/s) | +| -------------------------------------------------------------------------------------- | ------------------ | +| [Detectron2](https://github.com/facebookresearch/detectron2) | 62 | +| [MMDetection](https://github.com/open-mmlab/mmdetection) | 61 | +| [maskrcnn-benchmark](https://github.com/facebookresearch/maskrcnn-benchmark/) | 53 | +| [tensorpack](https://github.com/tensorpack/tensorpack/tree/master/examples/FasterRCNN) | 50 | +| [simpledet](https://github.com/TuSimple/simpledet/) | 39 | +| [Detectron](https://github.com/facebookresearch/Detectron) | 19 | +| [matterport/Mask_RCNN](https://github.com/matterport/Mask_RCNN/) | 14 | + +### Inference Speed Benchmark + +We provide [benchmark.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/benchmark.py) to benchmark the inference latency. +The script benchmarkes the model with 2000 images and calculates the average time ignoring first 5 times. You can change the output log interval (defaults: 50) by setting `LOG-INTERVAL`. + +```shell +python tools/benchmark.py ${CONFIG} ${CHECKPOINT} [--log-interval $[LOG-INTERVAL]] [--fuse-conv-bn] +``` + +The latency of all models in our model zoo is benchmarked without setting `fuse-conv-bn`, you can get a lower latency by setting it. + +## Comparison with Detectron2 + +We compare mmdetection with [Detectron2](https://github.com/facebookresearch/detectron2.git) in terms of speed and performance. +We use the commit id [185c27e](https://github.com/facebookresearch/detectron2/tree/185c27e4b4d2d4c68b5627b3765420c6d7f5a659)(30/4/2020) of detectron. +For fair comparison, we install and run both frameworks on the same machine. + +### Hardware + +- 8 NVIDIA Tesla V100 (32G) GPUs +- Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz + +### Software environment + +- Python 3.7 +- PyTorch 1.4 +- CUDA 10.1 +- CUDNN 7.6.03 +- NCCL 2.4.08 + +### Performance + +| Type | Lr schd | Detectron2 | mmdetection | Download | +| ------------------------------------------------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_ms-1x_coco.py) | 1x | [37.9](https://github.com/facebookresearch/detectron2/blob/main/configs/COCO-Detection/faster_rcnn_R_50_FPN_1x.yaml) | 38.0 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco-5324cff8.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco_20200429_234554.log.json) | +| [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_coco.py) | 1x | [38.6 & 35.2](https://github.com/facebookresearch/detectron2/blob/main/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml) | 38.8 & 35.4 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco-dbecf295.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco_20200430_054239.log.json) | +| [Retinanet](https://github.com/open-mmlab/mmdetection/blob/main/configs/retinanet/retinanet_r50-caffe_fpn_ms-1x_coco.py) | 1x | [36.5](https://github.com/facebookresearch/detectron2/blob/master/configs/COCO-Detection/retinanet_R_50_FPN_1x.yaml) | 37.0 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/retinanet_r50_caffe_fpn_mstrain_1x_coco/retinanet_r50_caffe_fpn_mstrain_1x_coco-586977a0.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/retinanet_r50_caffe_fpn_mstrain_1x_coco/retinanet_r50_caffe_fpn_mstrain_1x_coco_20200430_014748.log.json) | + +### Training Speed + +The training speed is measure with s/iter. The lower, the better. + +| Type | Detectron2 | mmdetection | +| ------------ | ---------- | ----------- | +| Faster R-CNN | 0.210 | 0.216 | +| Mask R-CNN | 0.261 | 0.265 | +| Retinanet | 0.200 | 0.205 | + +### Inference Speed + +The inference speed is measured with fps (img/s) on a single GPU, the higher, the better. +To be consistent with Detectron2, we report the pure inference speed (without the time of data loading). +For Mask R-CNN, we exclude the time of RLE encoding in post-processing. +We also include the officially reported speed in the parentheses, which is slightly higher +than the results tested on our server due to differences of hardwares. + +| Type | Detectron2 | mmdetection | +| ------------ | ----------- | ----------- | +| Faster R-CNN | 25.6 (26.3) | 22.2 | +| Mask R-CNN | 22.5 (23.3) | 19.6 | +| Retinanet | 17.8 (18.2) | 20.6 | + +### Training memory + +| Type | Detectron2 | mmdetection | +| ------------ | ---------- | ----------- | +| Faster R-CNN | 3.0 | 3.8 | +| Mask R-CNN | 3.4 | 3.9 | +| Retinanet | 3.9 | 3.4 | diff --git a/mmdet_code/mmdetection/docs/en/notes/changelog.md b/mmdet_code/mmdetection/docs/en/notes/changelog.md new file mode 100644 index 0000000000000000000000000000000000000000..00ed8f1c1e4a05cb05694eb02b4a9746f9264b63 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/notes/changelog.md @@ -0,0 +1,631 @@ +# Changelog of v3.x + +## v3.3.0 (05/01/2024) + +### Highlights + +Grounding-DINO is a state-of-the-art open-set detection model that tackles multiple vision tasks including Open-Vocabulary Detection (OVD), Phrase Grounding (PG), and Referring Expression Comprehension (REC). Its effectiveness has led to its widespread adoption as a mainstream architecture for various downstream applications. However, despite its significance, the original Grounding-DINO model lacks comprehensive public technical details due to the unavailability of its training code. To bridge this gap, we present MM-Grounding-DINO, an open-source, comprehensive, and user-friendly baseline, which is built with the MMDetection toolbox. It adopts abundant vision datasets for pre-training and various detection and grounding datasets for fine-tuning. We give a comprehensive analysis of each reported result and detailed settings for reproduction. The extensive experiments on the benchmarks mentioned demonstrate that our MM-Grounding-DINO-Tiny outperforms the Grounding-DINO-Tiny baseline. We release all our models to the research community. + +### New Features + +- Add RTMDet Swin / ConvNeXt backbone and results (#11259) +- Add `odinw` configs and evaluation results of `GLIP` (#11175) +- Add optional score threshold option to `coco_error_analysis.py` (#11117) +- Add new configs for `panoptic_fpn` (#11109) +- Replace partially weighted download links with OpenXLab for the `Faster-RCNN` (#11173) + +### Bug Fixes + +- Fix `Grounding DINO` nan when class tokens exceeds 256 (#11066) +- Fix the `CO-DETR` config files error (#11325) +- Fix `CO-DETR` load_from url in config (#11220) +- Fixed mask shape after Albu postprocess (#11280) +- Fix bug in `convert_coco_format` and `youtubevis2coco` (#11251, #11086) + +### Contributors + +A total of 15 developers contributed to this release. + +Thank @adnan-mujagic, @Cycyes, @ilcopione, @returnL, @honeybadger78, @okotaku, @xushilin1, @keyhsw, @guyleaf, @Crescent-Saturn, @LRJKD, @aaronzs, @Divadi, @AwePhD, @hhaAndroid + +## v3.2.0 (12/10/2023) + +### Highlights + +**(1) Detection Transformer SOTA Model Collection** + +- Supported four updated and stronger SOTA Transformer models: DDQ, CO-DETR, AlignDETR, and H-DINO. +- Based on CO-DETR, MMDet released a model with a COCO performance of 64.1 mAP. +- Algorithms such as DINO support AMP/Checkpoint/FrozenBN, which can effectively reduce memory usage. + +**(2) Comprehensive Performance Comparison between CNN and Transformer** + +RF100 consists of a dataset collection of 100 real-world datasets, including 7 domains. It can be used to assess the performance differences of Transformer models like DINO and CNN-based algorithms under different scenarios and data volumes. Users can utilize this benchmark to quickly evaluate the robustness of their algorithms in various scenarios. + +**(3) Support for GLIP and Grounding DINO fine-tuning, the only algorithm library that supports Grounding DINO fine-tuning** + +The Grounding DINO algorithm in MMDet is the only library that supports fine-tuning. Its performance is one point higher than the official version, and of course, GLIP also outperforms the official version. +We also provide a detailed process for training and evaluating Grounding DINO on custom datasets. Everyone is welcome to give it a try. + +**(4) Support for the open-vocabulary detection algorithm Detic and multi-dataset joint training.** + +**(5) Training detection models using FSDP and DeepSpeed.** + +**(6) Support for the V3Det dataset, a large-scale detection dataset with over 13,000 categories.** + +### New Features + +- Support CO-DETR/DDQ/AlignDETR/H-DINO +- Support GLIP and Grounding DINO fine-tuning +- Support Detic and Multi-Datasets training (#10926) +- Support V3Det and benchmark (#10938) +- Support Roboflow 100 Benchmark (#10915) +- Add custom dataset of grounding dino (#11012) +- Release RTMDet-X p6 (#10993) +- Support AMP of DINO (#10827) +- Support FrozenBN (#10845) +- Add new configuration files for `QDTrack/DETR/RTMDet/MaskRCNN/DINO/DeformableDETR/MaskFormer` algorithm +- Add a new script to support the WBF (#10808) +- Add `large_image_demo` (#10719) +- Support download dataset from OpenXLab (#10799) +- Update to support torch2onnx for DETR series models (#10910) +- Translation into Chinese of an English document (#10744, #10756, #10805, #10848) + +### Bug Fixes + +- Fix name error in DETR metafile.yml (#10595) +- Fix device of the tensors in `set_nms` (#10574) +- Remove some unicode chars from `en/` docs (#10648) +- Fix download dataset with mim script. (#10727) +- Fix export to torchserve (#10694) +- Fix typo in `mask-rcnn_r50_fpn_1x-wandb_coco` (#10757) +- Fix `eval_recalls` error in `voc_metric` (#10770) +- Fix torch version comparison (#10934) +- Fix incorrect behavior to access train pipeline from ConcatDataset in `analyze_results.py` (#11004) + +### Improvements + +- Update `useful_tools.md` (#10587) +- Update Instance segmentation Tutorial (#10711) +- Update `train.py` to compat with new config (#11025) +- Support `torch2onnx` for maskformer series (#10782) + +### Contributors + +A total of 36 developers contributed to this release. + +Thank @YQisme, @nskostas, @max-unfinity, @evdcush, @Xiangxu-0103, @ZhaoCake, @RangeKing, @captainIT, @ODAncona, @aaronzs, @zeyuanyin, @gotjd709, @Musiyuan, @YanxingLiu, @RunningLeon, @ytzfhqs, @zhangzhidaSunny, @yeungkong, @crazysteeaam, @timerring, @okotaku, @apatsekin, @Morty-Xu, @Markson-Young, @ZhaoQiiii, @Kuro96, @PhoenixZ810, @yhcao6, @myownskyW7, @jiongjiongli, @Johnson-Wang, @ryylcc, @guyleaf, @agpeshal, @SimonGuoNjust, @hhaAndroid + +## v3.1.0 (30/6/2023) + +### Highlights + +- Supports tracking algorithms including multi-object tracking (MOT) algorithms SORT, DeepSORT, StrongSORT, OCSORT, ByteTrack, QDTrack, and video instance segmentation (VIS) algorithm MaskTrackRCNN, Mask2Former-VIS. +- Support [ViTDet](../../../projects/ViTDet) +- Supports inference and evaluation of multimodal algorithms [GLIP](../../../configs/glip) and [XDecoder](../../../projects/XDecoder), and also supports datasets such as COCO semantic segmentation, COCO Caption, ADE20k general segmentation, and RefCOCO. GLIP fine-tuning will be supported in the future. +- Provides a [gradio demo](https://github.com/open-mmlab/mmdetection/blob/dev-3.x/projects/gradio_demo/README.md) for image type tasks of MMDetection, making it easy for users to experience. + +### New Features + +- Support DSDL Dataset (#9801) +- Support iSAID dataset (#10028) +- Support VISION dataset (#10530) +- Release SoftTeacher checkpoints (#10119) +- Release `centernet-update_r50-caffe_fpn_ms-1x_coco` checkpoints (#10327) +- Support SIoULoss (#10290) +- Support Eqlv2 loss (#10120) +- Support CopyPaste when mask is not available (#10509) +- Support MIM to download ODL dataset (#10460) +- Support new config (#10566) + +### Bug Fixes + +- Fix benchmark scripts error in windows (#10128) +- Fix error of `YOLOXModeSwitchHook` does not switch the mode when resumed from the checkpoint after switched (#10116) +- Fix pred and weight dims unmatch in SmoothL1Loss (#10423) + +### Improvements + +- Update MMDet_Tutorial.ipynb (#10081) +- Support to hide inference progress (#10519) +- Replace mmcls with mmpretrain (#10545) + +### Contributors + +A total of 29 developers contributed to this release. + +Thanks @lovelykite, @minato-ellie, @freepoet, @wufan-tb, @yalibian, @keyakiluo, @gihanjayatilaka, @i-aki-y, @xin-li-67, @RangeKing, @JingweiZhang12, @MambaWong, @lucianovk, @tall-josh, @xiuqhou, @jamiechoi1995, @YQisme, @yechenzhi, @bjzhb666, @xiexinch, @jamiechoi1995, @yarkable, @Renzhihan, @nijkah, @amaizr, @Lum1104, @zwhus, @Czm369, @hhaAndroid + +## v3.0.0 (6/4/2023) + +### Highlights + +- Support Semi-automatic annotation Base [Label-Studio](../../../projects/LabelStudio) (#10039) +- Support [EfficientDet](../../../projects/EfficientDet) in projects (#9810) + +### New Features + +- File I/O migration and reconstruction (#9709) +- Release DINO Swin-L 36e model (#9927) + +### Bug Fixes + +- Fix benchmark script (#9865) +- Fix the crop method of PolygonMasks (#9858) +- Fix Albu augmentation with the mask shape (#9918) +- Fix `RTMDetIns` prior generator device error (#9964) +- Fix `img_shape` in data pipeline (#9966) +- Fix cityscapes import error (#9984) +- Fix `solov2_r50_fpn_ms-3x_coco.py` config error (#10030) +- Fix Conditional DETR AP and Log (#9889) +- Fix accepting an unexpected argument local-rank in PyTorch 2.0 (#10050) +- Fix `common/ms_3x_coco-instance.py` config error (#10056) +- Fix compute flops error (#10051) +- Delete `data_root` in `CocoOccludedSeparatedMetric` to fix bug (#9969) +- Unifying metafile.yml (#9849) + +### Improvements + +- Added BoxInst r101 config (#9967) +- Added config migration guide (#9960) +- Added more social networking links (#10021) +- Added RTMDet config introduce (#10042) +- Added visualization docs (#9938, #10058) +- Refined data_prepare docs (#9935) +- Added support for setting the cache_size_limit parameter of dynamo in PyTorch 2.0 (#10054) +- Updated coco_metric.py (#10033) +- Update type hint (#10040) + +### Contributors + +A total of 19 developers contributed to this release. + +Thanks @IRONICBo, @vansin, @RangeKing, @Ghlerrix, @okotaku, @JosonChan1998, @zgzhengSE, @bobo0810, @yechenzh, @Zheng-LinXiao, @LYMDLUT, @yarkable, @xiejiajiannb, @chhluo, @BIGWangYuDong, @RangiLy, @zwhus, @hhaAndroid, @ZwwWayne + +## v3.0.0rc6 (24/2/2023) + +### Highlights + +- Support [Boxinst](../../../configs/boxinst), [Objects365 Dataset](../../../configs/objects365), and [Separated and Occluded COCO metric](../user_guides/useful_tools.md#COCO-Separated-&-Occluded-Mask-Metric) +- Support [ConvNeXt-V2](../../../projects/ConvNeXt-V2), [DiffusionDet](../../../projects/DiffusionDet), and inference of [EfficientDet](../../../projects/EfficientDet) and [Detic](../../../projects/Detic) in `Projects` +- Refactor [DETR](../../../configs/detr) series and support [Conditional-DETR](../../../configs/conditional_detr), [DAB-DETR](../../../configs/dab_detr), and [DINO](../../../configs/detr) +- Support `DetInferencer` for inference, Test Time Augmentation, and automatically importing modules from registry +- Support RTMDet-Ins ONNXRuntime and TensorRT [deployment](../../../configs/rtmdet/README.md#deployment-tutorial) +- Support [calculating FLOPs of detectors](../user_guides/useful_tools.md#Model-Complexity) + +### New Features + +- Support [Boxinst](https://arxiv.org/abs/2012.02310) (#9525) +- Support [Objects365 Dataset](https://openaccess.thecvf.com/content_ICCV_2019/papers/Shao_Objects365_A_Large-Scale_High-Quality_Dataset_for_Object_Detection_ICCV_2019_paper.pdf) (#9600) +- Support [ConvNeXt-V2](http://arxiv.org/abs/2301.00808) in `Projects` (#9619) +- Support [DiffusionDet](https://arxiv.org/abs/2211.09788) in `Projects` (#9639, #9768) +- Support [Detic](http://arxiv.org/abs/2201.02605) inference in `Projects` (#9645) +- Support [EfficientDet](https://arxiv.org/abs/1911.09070) inference in `Projects` (#9645) +- Support [Separated and Occluded COCO metric](https://arxiv.org/abs/2210.10046) (#9710) +- Support auto import modules from registry (#9143) +- Refactor DETR series and support Conditional-DETR, DAB-DETR and DINO (#9646) +- Support `DetInferencer` for inference (#9561) +- Support Test Time Augmentation (#9452) +- Support calculating FLOPs of detectors (#9777) + +### Bug Fixes + +- Fix deprecating old type alias due to new version of numpy (#9625, #9537) +- Fix VOC metrics (#9784) +- Fix the wrong link of RTMDet-x log (#9549) +- Fix RTMDet link in README (#9575) +- Fix MMDet get flops error (#9589) +- Fix `use_depthwise` in RTMDet (#9624) +- Fix `albumentations` augmentation post process with masks (#9551) +- Fix DETR series Unit Test (#9647) +- Fix `LoadPanopticAnnotations` bug (#9703) +- Fix `isort` CI (#9680) +- Fix amp pooling overflow (#9670) +- Fix docstring about noise in DINO (#9747) +- Fix potential bug in `MultiImageMixDataset` (#9764) + +### Improvements + +- Replace NumPy transpose with PyTorch permute to speed-up (#9762) +- Deprecate `sklearn` (#9725) +- Add RTMDet-Ins deployment guide (#9823) +- Update RTMDet config and README (#9603) +- Replace the models used in the tutorial document with RTMDet (#9843) +- Adjust the minimum supported python version to 3.7 (#9602) +- Support modifying palette through configuration (#9445) +- Update README document in `Project` (#9599) +- Replace `github` with `gitee` in `.pre-commit-config-zh-cn.yaml` file (#9586) +- Use official `isort` in `.pre-commit-config.yaml` file (#9701) +- Change MMCV minimum version to `2.0.0rc4` for `dev-3.x` (#9695) +- Add Chinese version of single_stage_as_rpn.md and test_results_submission.md (#9434) +- Add OpenDataLab download link (#9605, #9738) +- Add type hints of several layers (#9346) +- Add typehint for `DarknetBottleneck` (#9591) +- Add dockerfile (#9659) +- Add twitter, discord, medium, and youtube link (#9775) +- Prepare for merging refactor-detr (#9656) +- Add metafile to ConditionalDETR, DABDETR and DINO (#9715) +- Support to modify `non_blocking` parameters (#9723) +- Comment repeater visualizer register (#9740) +- Update user guide: `finetune.md` and `inference.md` (#9578) + +### New Contributors + +- @NoFish-528 made their first contribution in +- @137208 made their first contribution in +- @lyviva made their first contribution in +- @zwhus made their first contribution in +- @zylo117 made their first contribution in +- @chg0901 made their first contribution in +- @DanShouzhu made their first contribution in https://github.com/open-mmlab/mmdetection/pull/9578 + +### Contributors + +A total of 27 developers contributed to this release. + +Thanks @JosonChan1998, @RangeKing, @NoFish-528, @likyoo, @Xiangxu-0103, @137208, @PeterH0323, @tianleiSHI, @wufan-tb, @lyviva, @zwhus, @jshilong, @Li-Qingyun, @sanbuphy, @zylo117, @triple-Mu, @KeiChiTse, @LYMDLUT, @nijkah, @chg0901, @DanShouzhu, @zytx121, @vansin, @BIGWangYuDong, @hhaAndroid, @RangiLyu, @ZwwWayne + +## v3.0.0rc5 (26/12/2022) + +### Highlights + +- Support [RTMDet](https://arxiv.org/abs/2212.07784) instance segmentation models. The technical report of RTMDet is on [arxiv](https://arxiv.org/abs/2212.07784) +- Support SSHContextModule in paper [SSH: Single Stage Headless Face Detector](https://arxiv.org/abs/1708.03979). + +### New Features + +- Support [RTMDet](https://arxiv.org/abs/2212.07784) instance segmentation models and improve RTMDet test config (#9494) +- Support SSHContextModule in paper [SSH: Single Stage Headless Face Detector](https://arxiv.org/abs/1708.03979) (#8953) +- Release [CondInst](https://arxiv.org/abs/2003.05664) pre-trained model (#9406) + +### Bug Fixes + +- Fix CondInst predict error when `batch_size` is greater than 1 in inference (#9400) +- Fix the bug of visualization when the dtype of the pipeline output image is not uint8 in browse dataset (#9401) +- Fix `analyze_logs.py` to plot mAP and calculate train time correctly (#9409) +- Fix backward inplace error with `PAFPN` (#9450) +- Fix config import links in model converters (#9441) +- Fix `DeformableDETRHead` object has no attribute `loss_single` (#9477) +- Fix the logic of pseudo bboxes predicted by teacher model in SemiBaseDetector (#9414) +- Fix demo API in instance segmentation tutorial (#9226) +- Fix `analyze_results` (#9380) +- Fix the error that Readthedocs API cannot be displayed (#9510) +- Fix the error when there are no prediction results and support visualize the groundtruth of TTA (#9840) + +### Improvements + +- Remove legacy `builder.py` (#9479) +- Make sure the pipeline argument shape is in `(width, height)` order (#9324) +- Add `.pre-commit-config-zh-cn.yaml` file (#9388) +- Refactor dataset metainfo to lowercase (#9469) +- Add PyTorch 1.13 checking in CI (#9478) +- Adjust `FocalLoss` and `QualityFocalLoss` to allow different kinds of targets (#9481) +- Refactor `setup.cfg` (#9370) +- Clip saturation value to valid range `[0, 1]` (#9391) +- Only keep meta and state_dict when publishing model (#9356) +- Add segm evaluator in ms-poly_3x_coco_instance config (#9524) +- Update deployment guide (#9527) +- Update zh_cn `faq.md` (#9396) +- Update `get_started` (#9480) +- Update the zh_cn user_guides of `useful_tools.md` and `useful_hooks.md` (#9453) +- Add type hints for `bfp` and `channel_mapper` (#9410) +- Add type hints of several losses (#9397) +- Add type hints and update docstring for task modules (#9468) + +### New Contributors + +- @lihua199710 made their first contribution in +- @twmht made their first contribution in +- @tianleiSHI made their first contribution in +- @kitecats made their first contribution in +- @QJC123654 made their first contribution in + +### Contributors + +A total of 20 developers contributed to this release. + +Thanks @liuyanyi, @RangeKing, @lihua199710, @MambaWong, @sanbuphy, @Xiangxu-0103, @twmht, @JunyaoHu, @Chan-Sun, @tianleiSHI, @zytx121, @kitecats, @QJC123654, @JosonChan1998, @lvhan028, @Czm369, @BIGWangYuDong, @RangiLyu, @hhaAndroid, @ZwwWayne + +## v3.0.0rc4 (23/11/2022) + +### Highlights + +- Support [CondInst](https://arxiv.org/abs/2003.05664) +- Add `projects/` folder, which will be a place for some experimental models/features. +- Support [SparseInst](https://arxiv.org/abs/2203.12827) in [`projects`](./projects/SparseInst/README.md) + +### New Features + +- Support [CondInst](https://arxiv.org/abs/2003.05664) (#9223) +- Add `projects/` folder, which will be a place for some experimental models/features (#9341) +- Support [SparseInst](https://arxiv.org/abs/2203.12827) in [`projects`](./projects/SparseInst/README.md) (#9377) + +### Bug Fixes + +- Fix `pixel_decoder_type` discrimination in MaskFormer Head. (#9176) +- Fix wrong padding value in cached MixUp (#9259) +- Rename `utils/typing.py` to `utils/typing_utils.py` to fix `collect_env` error (#9265) +- Fix resume arg conflict (#9287) +- Fix the configs of Faster R-CNN with caffe backbone (#9319) +- Fix torchserve and update related documentation (#9343) +- Fix bbox refine bug with sigmooid activation (#9538) + +### Improvements + +- Update the docs of GIoU Loss in README (#8810) +- Handle dataset wrapper in `inference_detector` (#9144) +- Update the type of `counts` in COCO's compressed RLE (#9274) +- Support saving config file in `print_config` (#9276) +- Update docs about video inference (#9305) +- Update guide about model deployment (#9344) +- Fix doc typos of useful tools (#9177) +- Allow to resume from specific checkpoint in CLI (#9284) +- Update FAQ about windows installation issues of pycocotools (#9292) + +### New Contributors + +- @Daa98 made their first contribution in +- @lvhan028 made their first contribution in + +### Contributors + +A total of 12 developers contributed to this release. + +Thanks @sanbuphy, @Czm369, @Daa98, @jbwang1997, @BIGWangYuDong, @JosonChan1998, @lvhan028, @RunningLeon, @RangiLyu, @Daa98, @ZwwWayne, @hhaAndroid + +## v3.0.0rc3 (4/11/2022) + +Upgrade the minimum version requirement of MMEngine to 0.3.0 to use `ignore_key` of `ConcatDataset` for training VOC datasets (#9058) + +### Highlights + +- Support [CrowdDet](https://arxiv.org/abs/2003.09163) and [EIoU Loss](https://ieeexplore.ieee.org/document/9429909) +- Support training detection models in Detectron2 +- Refactor Fast R-CNN + +### New Features + +- Support [CrowdDet](https://arxiv.org/abs/2003.09163) (#8744) +- Support training detection models in Detectron2 with examples of Mask R-CNN, Faster R-CNN, and RetinaNet (#8672) +- Support [EIoU Loss](https://ieeexplore.ieee.org/document/9429909) (#9086) + +### Bug Fixes + +- Fix `XMLDataset` image size error (#9216) +- Fix bugs of empty_instances when predicting without nms in roi_head (#9015) +- Fix the config file of DETR (#9158) +- Fix SOLOv2 cannot dealing with empty gt image (#9192) +- Fix inference demo (#9153) +- Add `ignore_key` in VOC `ConcatDataset` (#9058) +- Fix dumping results issue in test scripts. (#9241) +- Fix configs of training coco subsets on MMDet 3.x (#9225) +- Fix corner2hbox of HorizontalBoxes for supporting empty bboxes (#9140) + +### Improvements + +- Refactor Fast R-CNN (#9132) +- Clean requirements of mmcv-full due to SyncBN (#9207) +- Support training detection models in detectron2 (#8672) +- Add `box_type` support for `DynamicSoftLabelAssigner` (#9179) +- Make scipy as a default dependency in runtime (#9187) +- Update eval_metric (#9062) +- Add `seg_map_suffix` in `BaseDetDataset` (#9088) + +### New Contributors + +- @Wwupup made their first contribution in +- @sanbuphy made their first contribution in +- @cxiang26 made their first contribution in +- @JosonChan1998 made their first contribution in + +### Contributors + +A total of 13 developers contributed to this release. + +Thanks @wanghonglie, @Wwupup, @sanbuphy, @BIGWangYuDong, @liuyanyi, @cxiang26, @jbwang1997, @ZwwWayne, @yuyoujiang, @RangiLyu, @hhaAndroid, @JosonChan1998, @Czm369 + +## v3.0.0rc2 (21/10/2022) + +### Highlights + +- Support [imagenet pre-training](configs/rtmdet/cspnext_imagenet_pretrain) for RTMDet's backbone + +### New Features + +- Support [imagenet pre-training](configs/rtmdet/cspnext_imagenet_pretrain) for RTMDet's backbone (#8887) +- Add `CrowdHumanDataset` and Metric (#8430) +- Add `FixShapeResize` to support resize of fixed shape (#8665) + +### Bug Fixes + +- Fix `ConcatDataset` Import Error (#8909) +- Fix `CircleCI` and `readthedoc` build failed (#8980, #8963) +- Fix bitmap mask translate when `out_shape` is different (#8993) +- Fix inconsistency in `Conv2d` weight channels (#8948) +- Fix bugs when plotting loss curve by analyze_logs.py (#8944) +- Fix type change of labels in `albumentations` (#9074) +- Fix some docs and types error (#8818) +- Update memory occupation of `RTMDet` in metafile (#9098) +- Fix wrong arguments of `OpenImageMetrics` in the config (#9061) + +### Improvements + +- Refactor standard roi head with `box type` (#8658) +- Support mask concatenation in `BitmapMasks` and `PolygonMasks` (#9006) +- Update PyTorch and dependencies' version in dockerfile (#8845) +- Update `robustness_eval.py` and `print_config` (#8452) +- Make compatible with `ConfigDict` and `dict` in `dense_heads` (#8942) +- Support logging coco metric copypaste (#9012) +- Remove `Normalize` transform (#8913) +- Support jittering the color of different instances of the same class (#8988) +- Add assertion for missing key in `PackDetInputs` (#8982) + +### New Contributors + +- @Chan-Sun made their first contribution in +- @MambaWong made their first contribution in +- @yuyoujiang made their first contribution in +- @sltlls made their first contribution in +- @Nioolek made their first contribution in +- @wufan-tb made their first contribution in + +### Contributors + +A total of 13 developers contributed to this release. + +Thanks @RangiLyu, @jbwang1997, @wanghonglie, @Chan-Sun, @RangeKing, @chhluo, @MambaWong, @yuyoujiang, @hhaAndroid, @sltlls, @Nioolek, @ZwwWayne, @wufan-tb + +## v3.0.0rc1 (26/9/2022) + +### Highlights + +- Release a high-precision, low-latency single-stage object detector [RTMDet](configs/rtmdet). + +### Bug Fixes + +- Fix UT to be compatible with PyTorch 1.6 (#8707) +- Fix `NumClassCheckHook` bug when model is wrapped (#8794) +- Update the right URL of R-50-FPN with BoundedIoULoss (#8805) +- Fix potential bug of indices in RandAugment (#8826) +- Fix some types and links (#8839, #8820, #8793, #8868) +- Fix incorrect background fill values in `FSAF` and `RepPoints` Head (#8813) + +### Improvements + +- Refactored anchor head and base head with `box type` (#8625) +- Refactored `SemiBaseDetector` and `SoftTeacher` (#8786) +- Add list to dict keys to avoid modify loss dict (#8828) +- Update `analyze_results.py` , `analyze_logs.py` and `loading.py` (#8430, #8402, #8784) +- Support dump results in `test.py` (#8814) +- Check empty predictions in `DetLocalVisualizer._draw_instances` (#8830) +- Fix `floordiv` warning in `SOLO` (#8738) + +### Contributors + +A total of 16 developers contributed to this release. + +Thanks @ZwwWayne, @jbwang1997, @Czm369, @ice-tong, @Zheng-LinXiao, @chhluo, @RangiLyu, @liuyanyi, @wanghonglie, @levan92, @JiayuXu0, @nye0, @hhaAndroid, @xin-li-67, @shuxp, @zytx121 + +## v3.0.0rc0 (31/8/2022) + +We are excited to announce the release of MMDetection 3.0.0rc0. MMDet 3.0.0rc0 is the first version of MMDetection 3.x, a part of the OpenMMLab 2.0 projects. Built upon the new [training engine](https://github.com/open-mmlab/mmengine), MMDet 3.x unifies the interfaces of the dataset, models, evaluation, and visualization with faster training and testing speed. It also provides a general semi-supervised object detection framework and strong baselines. + +### Highlights + +1. **New engine**. MMDet 3.x is based on [MMEngine](https://github.com/open-mmlab/mmengine), which provides a universal and powerful runner that allows more flexible customizations and significantly simplifies the entry points of high-level interfaces. + +2. **Unified interfaces**. As a part of the OpenMMLab 2.0 projects, MMDet 3.x unifies and refactors the interfaces and internal logic of training, testing, datasets, models, evaluation, and visualization. All the OpenMMLab 2.0 projects share the same design in those interfaces and logic to allow the emergence of multi-task/modality algorithms. + +3. **Faster speed**. We optimize the training and inference speed for common models and configurations, achieving a faster or similar speed than [Detection2](https://github.com/facebookresearch/detectron2/). Model details of benchmark will be updated in [this note](./benchmark.md#comparison-with-detectron2). + +4. **General semi-supervised object detection**. Benefitting from the unified interfaces, we support a general semi-supervised learning framework that works with all the object detectors supported in MMDet 3.x. Please refer to [semi-supervised object detection](../user_guides/semi_det.md) for details. + +5. **Strong baselines**. We release strong baselines of many popular models to enable fair comparisons among state-of-the-art models. + +6. **New features and algorithms**: + + - Enable all the single-stage detectors to serve as region proposal networks + - [SoftTeacher](https://arxiv.org/abs/2106.09018) + - [the updated CenterNet](https://arxiv.org/abs/2103.07461) + +7. **More documentation and tutorials**. We add a bunch of documentation and tutorials to help users get started more smoothly. Read it [here](https://mmdetection.readthedocs.io/en/3.x/). + +### Breaking Changes + +MMDet 3.x has undergone significant changes for better design, higher efficiency, more flexibility, and more unified interfaces. +Besides the changes in API, we briefly list the major breaking changes in this section. +We will update the [migration guide](../migration.md) to provide complete details and migration instructions. +Users can also refer to the [API doc](https://mmdetection.readthedocs.io/en/3.x/) for more details. + +#### Dependencies + +- MMDet 3.x runs on PyTorch>=1.6. We have deprecated the support of PyTorch 1.5 to embrace mixed precision training and other new features since PyTorch 1.6. Some models can still run on PyTorch 1.5, but the full functionality of MMDet 3.x is not guaranteed. +- MMDet 3.x relies on MMEngine to run. MMEngine is a new foundational library for training deep learning models of OpenMMLab and is the core dependency of OpenMMLab 2.0 projects. The dependencies of file IO and training are migrated from MMCV 1.x to MMEngine. +- MMDet 3.x relies on MMCV>=2.0.0rc0. Although MMCV no longer maintains the training functionalities since 2.0.0rc0, MMDet 3.x relies on the data transforms, CUDA operators, and image processing interfaces in MMCV. Note that the package `mmcv` is the version that provides pre-built CUDA operators and `mmcv-lite` does not since MMCV 2.0.0rc0, while `mmcv-full` has been deprecated since 2.0.0rc0. + +#### Training and testing + +- MMDet 3.x uses Runner in [MMEngine](https://github.com/open-mmlab/mmengine) rather than that in MMCV. The new Runner implements and unifies the building logic of the dataset, model, evaluation, and visualizer. Therefore, MMDet 3.x no longer maintains the building logic of those modules in `mmdet.train.apis` and `tools/train.py`. Those codes have been migrated into [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/runner.py). Please refer to the [migration guide of Runner in MMEngine](https://mmengine.readthedocs.io/en/latest/migration/runner.html) for more details. +- The Runner in MMEngine also supports testing and validation. The testing scripts are also simplified, which has similar logic to that in training scripts to build the runner. +- The execution points of hooks in the new Runner have been enriched to allow more flexible customization. Please refer to the [migration guide of Hook in MMEngine](https://mmengine.readthedocs.io/en/latest/migration/hook.html) for more details. +- Learning rate and momentum schedules have been migrated from Hook to [Parameter Scheduler in MMEngine](https://mmengine.readthedocs.io/en/latest/tutorials/param_scheduler.html). Please refer to the [migration guide of Parameter Scheduler in MMEngine](https://mmengine.readthedocs.io/en/latest/migration/param_scheduler.html) for more details. + +#### Configs + +- The [Runner in MMEngine](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/runner.py) uses a different config structure to ease the understanding of the components in the runner. Users can read the [config example of MMDet 3.x](../user_guides/config.md) or refer to the [migration guide in MMEngine](https://mmengine.readthedocs.io/en/latest/migration/runner.html) for migration details. +- The file names of configs and models are also refactored to follow the new rules unified across OpenMMLab 2.0 projects. The names of checkpoints are not updated for now as there is no BC-breaking of model weights between MMDet 3.x and 2.x. We will progressively replace all the model weights with those trained in MMDet 3.x. Please refer to the [user guides of config](../user_guides/config.md) for more details. + +#### Dataset + +The Dataset classes implemented in MMDet 3.x all inherit from the `BaseDetDataset`, which inherits from the [BaseDataset in MMEngine](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/basedataset.html). In addition to the changes in interfaces, there are several changes in Dataset in MMDet 3.x. + +- All the datasets support serializing the internal data list to reduce the memory when multiple workers are built for data loading. +- The internal data structure in the dataset is changed to be self-contained (without losing information like class names in MMDet 2.x) while keeping simplicity. +- The evaluation functionality of each dataset has been removed from the dataset so that some specific evaluation metrics like COCO AP can be used to evaluate the prediction on other datasets. + +#### Data Transforms + +The data transforms in MMDet 3.x all inherits from `BaseTransform` in MMCV>=2.0.0rc0, which defines a new convention in OpenMMLab 2.0 projects. +Besides the interface changes, there are several changes listed below: + +- The functionality of some data transforms (e.g., `Resize`) are decomposed into several transforms to simplify and clarify the usages. +- The format of data dict processed by each data transform is changed according to the new data structure of dataset. +- Some inefficient data transforms (e.g., normalization and padding) are moved into data preprocessor of model to improve data loading and training speed. +- The same data transforms in different OpenMMLab 2.0 libraries have the same augmentation implementation and the logic given the same arguments, i.e., `Resize` in MMDet 3.x and MMSeg 1.x will resize the image in the exact same manner given the same arguments. + +#### Model + +The models in MMDet 3.x all inherit from `BaseModel` in MMEngine, which defines a new convention of models in OpenMMLab 2.0 projects. +Users can refer to [the tutorial of the model in MMengine](https://mmengine.readthedocs.io/en/latest/tutorials/model.html) for more details. +Accordingly, there are several changes as the following: + +- The model interfaces, including the input and output formats, are significantly simplified and unified following the new convention in MMDet 3.x. + Specifically, all the input data in training and testing are packed into `inputs` and `data_samples`, where `inputs` contains model inputs like a list of image tensors, and `data_samples` contains other information of the current data sample such as ground truths, region proposals, and model predictions. In this way, different tasks in MMDet 3.x can share the same input arguments, which makes the models more general and suitable for multi-task learning and some flexible training paradigms like semi-supervised learning. +- The model has a data preprocessor module, which is used to pre-process the input data of the model. In MMDet 3.x, the data preprocessor usually does the necessary steps to form the input images into a batch, such as padding. It can also serve as a place for some special data augmentations or more efficient data transformations like normalization. +- The internal logic of the model has been changed. In MMdet 2.x, model uses `forward_train`, `forward_test`, `simple_test`, and `aug_test` to deal with different model forward logics. In MMDet 3.x and OpenMMLab 2.0, the forward function has three modes: 'loss', 'predict', and 'tensor' for training, inference, and tracing or other purposes, respectively. + The forward function calls `self.loss`, `self.predict`, and `self._forward` given the modes 'loss', 'predict', and 'tensor', respectively. + +#### Evaluation + +The evaluation in MMDet 2.x strictly binds with the dataset. In contrast, MMDet 3.x decomposes the evaluation from dataset so that all the detection datasets can evaluate with COCO AP and other metrics implemented in MMDet 3.x. +MMDet 3.x mainly implements corresponding metrics for each dataset, which are manipulated by [Evaluator](https://mmengine.readthedocs.io/en/latest/design/evaluator.html) to complete the evaluation. +Users can build an evaluator in MMDet 3.x to conduct offline evaluation, i.e., evaluate predictions that may not produce in MMDet 3.x with the dataset as long as the dataset and the prediction follow the dataset conventions. More details can be found in the [tutorial in mmengine](https://mmengine.readthedocs.io/en/latest/tutorials/evaluation.html). + +#### Visualization + +The functions of visualization in MMDet 2.x are removed. Instead, in OpenMMLab 2.0 projects, we use [Visualizer](https://mmengine.readthedocs.io/en/latest/design/visualization.html) to visualize data. MMDet 3.x implements `DetLocalVisualizer` to allow visualization of ground truths, model predictions, feature maps, etc., at any place. It also supports sending the visualization data to any external visualization backends such as Tensorboard. + +### Improvements + +- Optimized training and testing speed of FCOS, RetinaNet, Faster R-CNN, Mask R-CNN, and Cascade R-CNN. The training speed of those models with some common training strategies is also optimized, including those with synchronized batch normalization and mixed precision training. +- Support mixed precision training of all the models. However, some models may get undesirable performance due to some numerical issues. We will update the documentation and list the results (accuracy of failure) of mixed precision training. +- Release strong baselines of some popular object detectors. Their accuracy and pre-trained checkpoints will be released. + +### Bug Fixes + +- DeepFashion dataset: the config and results have been updated. + +### New Features + +1. Support a general semi-supervised learning framework that works with all the object detectors supported in MMDet 3.x. Please refer to [semi-supervised object detection](../user_guides/semi_det.md) for details. +2. Enable all the single-stage detectors to serve as region proposal networks. We give [an example of using FCOS as RPN](../user_guides/single_stage_as_rpn.md). +3. Support a semi-supervised object detection algorithm: [SoftTeacher](https://arxiv.org/abs/2106.09018). +4. Support [the updated CenterNet](https://arxiv.org/abs/2103.07461). +5. Support data structures `HorizontalBoxes` and `BaseBoxes` to encapsulate different kinds of bounding boxes. We are migrating to use data structures of boxes to replace the use of pure tensor boxes. This will unify the usages of different kinds of bounding boxes in MMDet 3.x and MMRotate 1.x to simplify the implementation and reduce redundant codes. + +### Planned changes + +We list several planned changes of MMDet 3.0.0rc0 so that the community could more comprehensively know the progress of MMDet 3.x. Feel free to create a PR, issue, or discussion if you are interested, have any suggestions and feedback, or want to participate. + +1. Test-time augmentation: which is supported in MMDet 2.x, is not implemented in this version due to the limited time slot. We will support it in the following releases with a new and simplified design. +2. Inference interfaces: unified inference interfaces will be supported in the future to ease the use of released models. +3. Interfaces of useful tools that can be used in Jupyter Notebook or Colab: more useful tools that are implemented in the `tools` directory will have their python interfaces so that they can be used in Jupyter Notebook, Colab, and downstream libraries. +4. Documentation: we will add more design docs, tutorials, and migration guidance so that the community can deep dive into our new design, participate the future development, and smoothly migrate downstream libraries to MMDet 3.x. +5. Wandb visualization: MMDet 2.x supports data visualization since v2.25.0, which has not been migrated to MMDet 3.x for now. Since WandB provides strong visualization and experiment management capabilities, a `DetWandBVisualizer` and maybe a hook are planned to fully migrate those functionalities from MMDet 2.x. +6. Full support of WiderFace dataset (#8508) and Fast R-CNN: we are verifying their functionalities and will fix related issues soon. +7. Migrate DETR-series algorithms (#8655, #8533) and YOLOv3 on IPU (#8552) from MMDet 2.x. + +### Contributors + +A total of 11 developers contributed to this release. +Thanks @shuxp, @wanghonglie, @Czm369, @BIGWangYuDong, @zytx121, @jbwang1997, @chhluo, @jshilong, @RangiLyu, @hhaAndroid, @ZwwWayne diff --git a/mmdet_code/mmdetection/docs/en/notes/changelog_v2.x.md b/mmdet_code/mmdetection/docs/en/notes/changelog_v2.x.md new file mode 100644 index 0000000000000000000000000000000000000000..2b3a230c0d94687e644c8ef15899781c079d5e1c --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/notes/changelog_v2.x.md @@ -0,0 +1,1681 @@ +# Changelog v2.x + +### v2.25.0 (31/5/2022) + +#### Highlights + +- Support dedicated `WandbLogger` hook +- Support [ConvNeXt](configs/convnext), [DDOD](configs/ddod), [SOLOv2](configs/solov2) +- Support [Mask2Former](configs/mask2former) for instance segmentation +- Rename [config files of Mask2Former](configs/mask2former) + +#### Backwards incompatible changes + +- Rename [config files of Mask2Former](configs/mask2former) (#7571) + + + + + + + + + + + +
before v2.25.0after v2.25.0
+ + - `mask2former_xxx_coco.py` represents config files for **panoptic segmentation**. + + + + - `mask2former_xxx_coco.py` represents config files for **instance segmentation**. + - `mask2former_xxx_coco-panoptic.py` represents config files for **panoptic segmentation**. + +
+ +#### New Features + +- Support [ConvNeXt](https://arxiv.org/abs/2201.03545) (#7281) +- Support [DDOD](https://arxiv.org/abs/2107.02963) (#7279) +- Support [SOLOv2](https://arxiv.org/abs/2003.10152) (#7441) +- Support [Mask2Former](https://arxiv.org/abs/2112.01527) for instance segmentation (#7571, #8032) + +#### Bug Fixes + +- Enable YOLOX training on different devices (#7912) +- Fix the log plot error when evaluation with `interval != 1` (#7784) +- Fix RuntimeError of HTC (#8083) + +#### Improvements + +- Support dedicated `WandbLogger` hook (#7459) + + Users can set + + ```python + cfg.log_config.hooks = [ + dict(type='MMDetWandbHook', + init_kwargs={'project': 'MMDetection-tutorial'}, + interval=10, + log_checkpoint=True, + log_checkpoint_metadata=True, + num_eval_images=10)] + ``` + + in the config to use `MMDetWandbHook`. Example can be found in this [colab tutorial](https://colab.research.google.com/drive/1RCSXHZwDZvakFh3eo9RuNrJbCGqD0dru?usp=sharing#scrollTo=WTEdPDRaBz2C) + +- Add `AvoidOOM` to avoid OOM (#7434, #8091) + + Try to use `AvoidCUDAOOM` to avoid GPU out of memory. It will first retry after calling `torch.cuda.empty_cache()`. If it still fails, it will then retry by converting the type of inputs to FP16 format. If it still fails, it will try to copy inputs from GPUs to CPUs to continue computing. Try AvoidOOM in code to make the code continue to run when GPU memory runs out: + + ```python + from mmdet.utils import AvoidCUDAOOM + + output = AvoidCUDAOOM.retry_if_cuda_oom(some_function)(input1, input2) + ``` + + Users can also try `AvoidCUDAOOM` as a decorator to make the code continue to run when GPU memory runs out: + + ```python + from mmdet.utils import AvoidCUDAOOM + + @AvoidCUDAOOM.retry_if_cuda_oom + def function(*args, **kwargs): + ... + return xxx + ``` + +- Support reading `gpu_collect` from `cfg.evaluation.gpu_collect` (#7672) + +- Speedup the Video Inference by Accelerating data-loading Stage (#7832) + +- Support replacing the `${key}` with the value of `cfg.key` (#7492) + +- Accelerate result analysis in `analyze_result.py`. The evaluation time is speedup by 10 ~ 15 times and only tasks 10 ~ 15 minutes now. (#7891) + +- Support to set `block_dilations` in `DilatedEncoder` (#7812) + +- Support panoptic segmentation result analysis (#7922) + +- Release DyHead with Swin-Large backbone (#7733) + +- Documentations updating and adding + + - Fix wrong default type of `act_cfg` in `SwinTransformer` (#7794) + - Fix text errors in the tutorials (#7959) + - Rewrite the [installation guide](docs/en/get_started.md) (#7897) + - [Useful hooks](docs/en/tutorials/useful_hooks.md) (#7810) + - Fix heading anchor in documentation (#8006) + - Replace `markdownlint` with `mdformat` for avoiding installing ruby (#8009) + +#### Contributors + +A total of 20 developers contributed to this release. + +Thanks @ZwwWayne, @DarthThomas, @solyaH, @LutingWang, @chenxinfeng4, @Czm369, @Chenastron, @chhluo, @austinmw, @Shanyaliux @hellock, @Y-M-Y, @jbwang1997, @hhaAndroid, @Irvingao, @zhanggefan, @BIGWangYuDong, @Keiku, @PeterVennerstrom, @ayulockin + +### v2.24.0 (26/4/2022) + +#### Highlights + +- Support [Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation](https://arxiv.org/abs/2012.07177) +- Support automatically scaling LR according to GPU number and samples per GPU +- Support Class Aware Sampler that improves performance on OpenImages Dataset + +#### New Features + +- Support [Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation](https://arxiv.org/abs/2012.07177), see [example configs](configs/simple_copy_paste/mask_rcnn_r50_fpn_syncbn-all_rpn-2conv_ssj_scp_32x2_270k_coco.py) (#7501) + +- Support Class Aware Sampler, users can set + + ```python + data=dict(train_dataloader=dict(class_aware_sampler=dict(num_sample_class=1)))) + ``` + + in the config to use `ClassAwareSampler`. Examples can be found in [the configs of OpenImages Dataset](https://github.com/open-mmlab/mmdetection/tree/main/configs/openimages/faster_rcnn_r50_fpn_32x2_cas_1x_openimages.py). (#7436) + +- Support automatically scaling LR according to GPU number and samples per GPU. (#7482) + In each config, there is a corresponding config of auto-scaling LR as below, + + ```python + auto_scale_lr = dict(enable=True, base_batch_size=N) + ``` + + where `N` is the batch size used for the current learning rate in the config (also equals to `samples_per_gpu` * gpu number to train this config). + By default, we set `enable=False` so that the original usages will not be affected. Users can set `enable=True` in each config or add `--auto-scale-lr` after the command line to enable this feature and should check the correctness of `base_batch_size` in customized configs. + +- Support setting dataloader arguments in config and add functions to handle config compatibility. (#7668) + The comparison between the old and new usages is as below. + + + + + + + + + + + +
v2.23.0v2.24.0
+ + ```python + data = dict( + samples_per_gpu=64, workers_per_gpu=4, + train=dict(type='xxx', ...), + val=dict(type='xxx', samples_per_gpu=4, ...), + test=dict(type='xxx', ...), + ) + ``` + + + + ```python + # A recommended config that is clear + data = dict( + train=dict(type='xxx', ...), + val=dict(type='xxx', ...), + test=dict(type='xxx', ...), + # Use different batch size during inference. + train_dataloader=dict(samples_per_gpu=64, workers_per_gpu=4), + val_dataloader=dict(samples_per_gpu=8, workers_per_gpu=2), + test_dataloader=dict(samples_per_gpu=8, workers_per_gpu=2), + ) + + # Old style still works but allows to set more arguments about data loaders + data = dict( + samples_per_gpu=64, # only works for train_dataloader + workers_per_gpu=4, # only works for train_dataloader + train=dict(type='xxx', ...), + val=dict(type='xxx', ...), + test=dict(type='xxx', ...), + # Use different batch size during inference. + val_dataloader=dict(samples_per_gpu=8, workers_per_gpu=2), + test_dataloader=dict(samples_per_gpu=8, workers_per_gpu=2), + ) + ``` + +
+ +- Support memory profile hook. Users can use it to monitor the memory usages during training as below (#7560) + + ```python + custom_hooks = [ + dict(type='MemoryProfilerHook', interval=50) + ] + ``` + +- Support to run on PyTorch with MLU chip (#7578) + +- Support re-spliting data batch with tag (#7641) + +- Support the `DiceCost` used by [K-Net](https://arxiv.org/abs/2106.14855) in `MaskHungarianAssigner` (#7716) + +- Support splitting COCO data for Semi-supervised object detection (#7431) + +- Support Pathlib for Config.fromfile (#7685) + +- Support to use file client in OpenImages dataset (#7433) + +- Add a probability parameter to Mosaic transformation (#7371) + +- Support specifying interpolation mode in `Resize` pipeline (#7585) + +#### Bug Fixes + +- Avoid invalid bbox after deform_sampling (#7567) +- Fix the issue that argument color_theme does not take effect when exporting confusion matrix (#7701) +- Fix the `end_level` in Necks, which should be the index of the end input backbone level (#7502) +- Fix the bug that `mix_results` may be None in `MultiImageMixDataset` (#7530) +- Fix the bug in ResNet plugin when two plugins are used (#7797) + +#### Improvements + +- Enhance `load_json_logs` of analyze_logs.py for resumed training logs (#7732) +- Add argument `out_file` in image_demo.py (#7676) +- Allow mixed precision training with `SimOTAAssigner` (#7516) +- Updated INF to 100000.0 to be the same as that in the official YOLOX (#7778) +- Add documentations of: + - how to get channels of a new backbone (#7642) + - how to unfreeze the backbone network (#7570) + - how to train fast_rcnn model (#7549) + - proposals in Deformable DETR (#7690) + - from-scratch install script in get_started.md (#7575) +- Release pre-trained models of + - [Mask2Former](configs/mask2former) (#7595, #7709) + - RetinaNet with ResNet-18 and release models (#7387) + - RetinaNet with EfficientNet backbone (#7646) + +#### Contributors + +A total of 27 developers contributed to this release. +Thanks @jovialio, @zhangsanfeng2022, @HarryZJ, @jamiechoi1995, @nestiank, @PeterH0323, @RangeKing, @Y-M-Y, @mattcasey02, @weiji14, @Yulv-git, @xiefeifeihu, @FANG-MING, @meng976537406, @nijkah, @sudz123, @CCODING04, @SheffieldCao, @Czm369, @BIGWangYuDong, @zytx121, @jbwang1997, @chhluo, @jshilong, @RangiLyu, @hhaAndroid, @ZwwWayne + +### v2.23.0 (28/3/2022) + +#### Highlights + +- Support Mask2Former: [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) +- Support EfficientNet: [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) +- Support setting data root through environment variable `MMDET_DATASETS`, users don't have to modify the corresponding path in config files anymore. +- Find a good recipe for fine-tuning high precision ResNet backbone pre-trained by Torchvision. + +#### New Features + +- Support [Mask2Former](configs/mask2former)(#6938)(#7466)(#7471) +- Support [EfficientNet](configs/efficientnet) (#7514) +- Support setting data root through environment variable `MMDET_DATASETS`, users don't have to modify the corresponding path in config files anymore. (#7386) +- Support setting different seeds to different ranks (#7432) +- Update the `dist_train.sh` so that the script can be used to support launching multi-node training on machines without slurm (#7415) +- Find a good recipe for fine-tuning high precision ResNet backbone pre-trained by Torchvision (#7489) + +#### Bug Fixes + +- Fix bug in VOC unit test which removes the data directory (#7270) +- Adjust the order of `get_classes` and `FileClient` (#7276) +- Force the inputs of `get_bboxes` in yolox_head to float32 (#7324) +- Fix misplaced arguments in LoadPanopticAnnotations (#7388) +- Fix reduction=mean in CELoss. (#7449) +- Update unit test of CrossEntropyCost (#7537) +- Fix memory leaking in panpotic segmentation evaluation (#7538) +- Fix the bug of shape broadcast in YOLOv3 (#7551) + +#### Improvements + +- Add Chinese version of onnx2tensorrt.md (#7219) +- Update colab tutorials (#7310) +- Update information about Localization Distillation (#7350) +- Add Chinese version of `finetune.md` (#7178) +- Update YOLOX log for non square input (#7235) +- Add `nproc` in `coco_panoptic.py` for panoptic quality computing (#7315) +- Allow to set channel_order in LoadImageFromFile (#7258) +- Take point sample related functions out of mask_point_head (#7353) +- Add instance evaluation for coco_panoptic (#7313) +- Enhance the robustness of analyze_logs.py (#7407) +- Supplementary notes of sync_random_seed (#7440) +- Update docstring of cross entropy loss (#7472) +- Update pascal voc result (#7503) +- We create How-to documentation to record any questions about How to xxx. In this version, we added + - How to use Mosaic augmentation (#7507) + - How to use backbone in mmcls (#7438) + - How to produce and submit the prediction results of panoptic segmentation models on COCO test-dev set (#7430)) + +#### Contributors + +A total of 27 developers contributed to this release. +Thanks @ZwwWayne, @haofanwang, @shinya7y, @chhluo, @yangrisheng, @triple-Mu, @jbwang1997, @HikariTJU, @imflash217, @274869388, @zytx121, @matrixgame2018, @jamiechoi1995, @BIGWangYuDong, @JingweiZhang12, @Xiangxu-0103, @hhaAndroid, @jshilong, @osbm, @ceroytres, @bunge-bedstraw-herb, @Youth-Got, @daavoo, @jiangyitong, @RangiLyu, @CCODING04, @yarkable + +### v2.22.0 (24/2/2022) + +#### Highlights + +- Support MaskFormer: [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278) (#7212) +- Support DyHead: [Dynamic Head: Unifying Object Detection Heads with Attentions](https://arxiv.org/abs/2106.08322) (#6823) +- Release a good recipe of using ResNet in object detectors pre-trained by [ResNet Strikes Back](https://arxiv.org/abs/2110.00476), which consistently brings about 3~4 mAP improvements over RetinaNet, Faster/Mask/Cascade Mask R-CNN (#7001) +- Support [Open Images Dataset](https://storage.googleapis.com/openimages/web/index.html) (#6331) +- Support TIMM backbone: [PyTorch Image Models](https://github.com/rwightman/pytorch-image-models) (#7020) + +#### New Features + +- Support [MaskFormer](configs/maskformer) (#7212) +- Support [DyHead](configs/dyhead) (#6823) +- Support [ResNet Strikes Back](configs/resnet_strikes_back) (#7001) +- Support [OpenImages Dataset](configs/openimages) (#6331) +- Support [TIMM backbone](configs/timm_example) (#7020) +- Support visualization for Panoptic Segmentation (#7041) + +#### Breaking Changes + +In order to support the visualization for Panoptic Segmentation, the `num_classes` can not be `None` when using the `get_palette` function to determine whether to use the panoptic palette. + +#### Bug Fixes + +- Fix bug for the best checkpoints can not be saved when the `key_score` is None (#7101) +- Fix MixUp transform filter boxes failing case (#7080) +- Add missing properties in SABLHead (#7091) +- Fix bug when NaNs exist in confusion matrix (#7147) +- Fix PALETTE AttributeError in downstream task (#7230) + +#### Improvements + +- Speed up SimOTA matching (#7098) +- Add Chinese translation of `docs_zh-CN/tutorials/init_cfg.md` (#7188) + +#### Contributors + +A total of 20 developers contributed to this release. +Thanks @ZwwWayne, @hhaAndroid, @RangiLyu, @AronLin, @BIGWangYuDong, @jbwang1997, @zytx121, @chhluo, @shinya7y, @LuooChen, @dvansa, @siatwangmin, @del-zhenwu, @vikashranjan26, @haofanwang, @jamiechoi1995, @HJoonKwon, @yarkable, @zhijian-liu, @RangeKing + +### v2.21.0 (8/2/2022) + +### Breaking Changes + +To standardize the contents in config READMEs and meta files of OpenMMLab projects, the READMEs and meta files in each config directory have been significantly changed. The template will be released in the future, for now, you can refer to the examples of README for [algorithm](https://github.com/open-mmlab/mmdetection/blob/master/configs/faster_rcnn/README.md), [dataset](https://github.com/open-mmlab/mmdetection/blob/master/configs/deepfashion/README.md) and [backbone](https://github.com/open-mmlab/mmdetection/blob/master/configs/regnet/README.md). To align with the standard, the configs in dcn are put into to two directories named `dcn` and `dcnv2`. + +#### New Features + +- Allow to customize colors of different classes during visualization (#6716) +- Support CPU training (#7016) +- Add download script of COCO, LVIS, and VOC dataset (#7015) + +#### Bug Fixes + +- Fix weight conversion issue of RetinaNet with Swin-S (#6973) +- Update `__repr__` of `Compose` (#6951) +- Fix BadZipFile Error when build docker (#6966) +- Fix bug in non-distributed multi-gpu training/testing (#7019) +- Fix bbox clamp in PyTorch 1.10 (#7074) +- Relax the requirement of PALETTE in dataset wrappers (#7085) +- Keep the same weights before reassign in the PAA head (#7032) +- Update code demo in doc (#7092) + +#### Improvements + +- Speed-up training by allow to set variables of multi-processing (#6974, #7036) +- Add links of Chinese tutorials in readme (#6897) +- Disable cv2 multiprocessing by default for acceleration (#6867) +- Deprecate the support for "python setup.py test" (#6998) +- Re-organize metafiles and config readmes (#7051) +- Fix None grad problem during training TOOD by adding `SigmoidGeometricMean` (#7090) + +#### Contributors + +A total of 26 developers contributed to this release. +Thanks @del-zhenwu, @zimoqingfeng, @srishilesh, @imyhxy, @jenhaoyang, @jliu-ac, @kimnamu, @ShengliLiu, @garvan2021, @ciusji, @DIYer22, @kimnamu, @q3394101, @zhouzaida, @gaotongxiao, @topsy404, @AntoAndGar, @jbwang1997, @nijkah, @ZwwWayne, @Czm369, @jshilong, @RangiLyu, @BIGWangYuDong, @hhaAndroid, @AronLin + +### v2.20.0 (27/12/2021) + +#### New Features + +- Support [TOOD](configs/tood/README.md): Task-aligned One-stage Object Detection (ICCV 2021 Oral) (#6746) +- Support resuming from the latest checkpoint automatically (#6727) + +#### Bug Fixes + +- Fix wrong bbox `loss_weight` of the PAA head (#6744) +- Fix the padding value of `gt_semantic_seg` in batch collating (#6837) +- Fix test error of lvis when using `classwise` (#6845) +- Avoid BC-breaking of `get_local_path` (#6719) +- Fix bug in `sync_norm_hook` when the BN layer does not exist (#6852) +- Use pycocotools directly no matter what platform it is (#6838) + +#### Improvements + +- Add unit test for SimOTA with no valid bbox (#6770) +- Use precommit to check readme (#6802) +- Support selecting GPU-ids in non-distributed testing time (#6781) + +#### Contributors + +A total of 16 developers contributed to this release. +Thanks @ZwwWayne, @Czm369, @jshilong, @RangiLyu, @BIGWangYuDong, @hhaAndroid, @jamiechoi1995, @AronLin, @Keiku, @gkagkos, @fcakyon, @www516717402, @vansin, @zactodd, @kimnamu, @jenhaoyang + +### v2.19.1 (14/12/2021) + +#### New Features + +- Release [YOLOX](configs/yolox/README.md) COCO pretrained models (#6698) + +#### Bug Fixes + +- Fix DCN initialization in DenseHead (#6625) +- Fix initialization of ConvFCHead (#6624) +- Fix PseudoSampler in RCNN (#6622) +- Fix weight initialization in Swin and PVT (#6663) +- Fix dtype bug in BaseDenseHead (#6767) +- Fix SimOTA with no valid bbox (#6733) + +#### Improvements + +- Add an example of combining swin and one-stage models (#6621) +- Add `get_ann_info` to dataset_wrappers (#6526) +- Support keeping image ratio in the multi-scale training of YOLOX (#6732) +- Support `bbox_clip_border` for the augmentations of YOLOX (#6730) + +#### Documents + +- Update metafile (#6717) +- Add mmhuman3d in readme (#6699) +- Update FAQ docs (#6587) +- Add doc for `detect_anomalous_params` (#6697) + +#### Contributors + +A total of 11 developers contributed to this release. +Thanks @ZwwWayne, @LJoson, @Czm369, @jshilong, @ZCMax, @RangiLyu, @BIGWangYuDong, @hhaAndroid, @zhaoxin111, @GT9505, @shinya7y + +### v2.19.0 (29/11/2021) + +#### Highlights + +- Support [Label Assignment Distillation](https://arxiv.org/abs/2108.10520) +- Support `persistent_workers` for Pytorch >= 1.7 +- Align accuracy to the updated official YOLOX + +#### New Features + +- Support [Label Assignment Distillation](https://arxiv.org/abs/2108.10520) (#6342) +- Support `persistent_workers` for Pytorch >= 1.7 (#6435) + +#### Bug Fixes + +- Fix repeatedly output warning message (#6584) +- Avoid infinite GPU waiting in dist training (#6501) +- Fix SSD512 config error (#6574) +- Fix MMDetection model to ONNX command (#6558) + +#### Improvements + +- Refactor configs of FP16 models (#6592) +- Align accuracy to the updated official YOLOX (#6443) +- Speed up training and reduce memory cost when using PhotoMetricDistortion. (#6442) +- Make OHEM work with seesaw loss (#6514) + +#### Documents + +- Update README.md (#6567) + +#### Contributors + +A total of 11 developers contributed to this release. +Thanks @FloydHsiu, @RangiLyu, @ZwwWayne, @AndreaPi, @st9007a, @hachreak, @BIGWangYuDong, @hhaAndroid, @AronLin, @chhluo, @vealocia, @HarborYuan, @st9007a, @jshilong + +### v2.18.1 (15/11/2021) + +#### Highlights + +- Release [QueryInst](http://arxiv.org/abs/2105.01928) pre-trained weights (#6460) +- Support plot confusion matrix (#6344) + +#### New Features + +- Release [QueryInst](http://arxiv.org/abs/2105.01928) pre-trained weights (#6460) +- Support plot confusion matrix (#6344) + +#### Bug Fixes + +- Fix aug test error when the number of prediction bboxes is 0 (#6398) +- Fix SpatialReductionAttention in PVT (#6488) +- Fix wrong use of `trunc_normal_init` in PVT and Swin-Transformer (#6432) + +#### Improvements + +- Save the printed AP information of COCO API to logger (#6505) +- Always map location to cpu when load checkpoint (#6405) +- Set a random seed when the user does not set a seed (#6457) + +#### Documents + +- Chinese version of [Corruption Benchmarking](robustness_benchmarking.md) (#6375) +- Fix config path in docs (#6396) +- Update GRoIE readme (#6401) + +#### Contributors + +A total of 11 developers contributed to this release. +Thanks @st9007a, @hachreak, @HarborYuan, @vealocia, @chhluo, @AndreaPi, @AronLin, @BIGWangYuDong, @hhaAndroid, @RangiLyu, @ZwwWayne + +### v2.18.0 (27/10/2021) + +#### Highlights + +- Support [QueryInst](http://arxiv.org/abs/2105.01928) (#6050) +- Refactor dense heads to decouple onnx export logics from `get_bboxes` and speed up inference (#5317, #6003, #6369, #6268, #6315) + +#### New Features + +- Support [QueryInst](http://arxiv.org/abs/2105.01928) (#6050) +- Support infinite sampler (#5996) + +#### Bug Fixes + +- Fix init_weight in fcn_mask_head (#6378) +- Fix type error in imshow_bboxes of RPN (#6386) +- Fix broken colab link in MMDetection Tutorial (#6382) +- Make sure the device and dtype of scale_factor are the same as bboxes (#6374) +- Remove sampling hardcode (#6317) +- Fix RandomAffine bbox coordinate recorrection (#6293) +- Fix init bug of final cls/reg layer in convfc head (#6279) +- Fix img_shape broken in auto_augment (#6259) +- Fix kwargs parameter missing error in two_stage (#6256) + +#### Improvements + +- Unify the interface of stuff head and panoptic head (#6308) +- Polish readme (#6243) +- Add code-spell pre-commit hook and fix a typo (#6306) +- Fix typo (#6245, #6190) +- Fix sampler unit test (#6284) +- Fix `forward_dummy` of YOLACT to enable `get_flops` (#6079) +- Fix link error in the config documentation (#6252) +- Adjust the order to beautify the document (#6195) + +#### Refactors + +- Refactor one-stage get_bboxes logic (#5317) +- Refactor ONNX export of One-Stage models (#6003, #6369) +- Refactor dense_head and speedup (#6268) +- Migrate to use prior_generator in training of dense heads (#6315) + +#### Contributors + +A total of 18 developers contributed to this release. +Thanks @Boyden, @onnkeat, @st9007a, @vealocia, @yhcao6, @DapangpangX, @yellowdolphin, @cclauss, @kennymckormick, +@pingguokiller, @collinzrj, @AndreaPi, @AronLin, @BIGWangYuDong, @hhaAndroid, @jshilong, @RangiLyu, @ZwwWayne + +### v2.17.0 (28/9/2021) + +#### Highlights + +- Support [PVT](https://arxiv.org/abs/2102.12122) and [PVTv2](https://arxiv.org/abs/2106.13797) +- Support [SOLO](https://arxiv.org/abs/1912.04488) +- Support large scale jittering and New Mask R-CNN baselines +- Speed up `YOLOv3` inference + +#### New Features + +- Support [PVT](https://arxiv.org/abs/2102.12122) and [PVTv2](https://arxiv.org/abs/2106.13797) (#5780) +- Support [SOLO](https://arxiv.org/abs/1912.04488) (#5832) +- Support large scale jittering and New Mask R-CNN baselines (#6132) +- Add a general data structure for the results of models (#5508) +- Added a base class for one-stage instance segmentation (#5904) +- Speed up `YOLOv3` inference (#5991) +- Release Swin Transformer pre-trained models (#6100) +- Support mixed precision training in `YOLOX` (#5983) +- Support `val` workflow in `YOLACT` (#5986) +- Add script to test `torchserve` (#5936) +- Support `onnxsim` with dynamic input shape (#6117) + +#### Bug Fixes + +- Fix the function naming errors in `model_wrappers` (#5975) +- Fix regression loss bug when the input is an empty tensor (#5976) +- Fix scores not contiguous error in `centernet_head` (#6016) +- Fix missing parameters bug in `imshow_bboxes` (#6034) +- Fix bug in `aug_test` of `HTC` when the length of `det_bboxes` is 0 (#6088) +- Fix empty proposal errors in the training of some two-stage models (#5941) +- Fix `dynamic_axes` parameter error in `ONNX` dynamic shape export (#6104) +- Fix `dynamic_shape` bug of `SyncRandomSizeHook` (#6144) +- Fix the Swin Transformer config link error in the configuration (#6172) + +#### Improvements + +- Add filter rules in `Mosaic` transform (#5897) +- Add size divisor in get flops to avoid some potential bugs (#6076) +- Add Chinese translation of `docs_zh-CN/tutorials/customize_dataset.md` (#5915) +- Add Chinese translation of `conventions.md` (#5825) +- Add description of the output of data pipeline (#5886) +- Add dataset information in the README file for `PanopticFPN` (#5996) +- Add `extra_repr` for `DropBlock` layer to get details in the model printing (#6140) +- Fix CI out of memory and add PyTorch1.9 Python3.9 unit tests (#5862) +- Fix download links error of some model (#6069) +- Improve the generalization of XML dataset (#5943) +- Polish assertion error messages (#6017) +- Remove `opencv-python-headless` dependency by `albumentations` (#5868) +- Check dtype in transform unit tests (#5969) +- Replace the default theme of documentation with PyTorch Sphinx Theme (#6146) +- Update the paper and code fields in the metafile (#6043) +- Support to customize padding value of segmentation map (#6152) +- Support to resize multiple segmentation maps (#5747) + +#### Contributors + +A total of 24 developers contributed to this release. +Thanks @morkovka1337, @HarborYuan, @guillaumefrd, @guigarfr, @www516717402, @gaotongxiao, @ypwhs, @MartaYang, @shinya7y, @justiceeem, @zhaojinjian0000, @VVsssssk, @aravind-anantha, @wangbo-zhao, @czczup, @whai362, @czczup, @marijnl, @AronLin, @BIGWangYuDong, @hhaAndroid, @jshilong, @RangiLyu, @ZwwWayne + +### v2.16.0 (30/8/2021) + +#### Highlights + +- Support [Panoptic FPN](https://arxiv.org/abs/1901.02446) and [Swin Transformer](https://arxiv.org/abs/2103.14030) + +#### New Features + +- Support [Panoptic FPN](https://arxiv.org/abs/1901.02446) and release models (#5577, #5902) +- Support Swin Transformer backbone (#5748) +- Release RetinaNet models pre-trained with multi-scale 3x schedule (#5636) +- Add script to convert unlabeled image list to coco format (#5643) +- Add hook to check whether the loss value is valid (#5674) +- Add YOLO anchor optimizing tool (#5644) +- Support export onnx models without post process. (#5851) +- Support classwise evaluation in CocoPanopticDataset (#5896) +- Adapt browse_dataset for concatenated datasets. (#5935) +- Add `PatchEmbed` and `PatchMerging` with `AdaptivePadding` (#5952) + +#### Bug Fixes + +- Fix unit tests of YOLOX (#5859) +- Fix lose randomness in `imshow_det_bboxes` (#5845) +- Make output result of `ImageToTensor` contiguous (#5756) +- Fix inference bug when calling `regress_by_class` in RoIHead in some cases (#5884) +- Fix bug in CIoU loss where alpha should not have gradient. (#5835) +- Fix the bug that `multiscale_output` is defined but not used in HRNet (#5887) +- Set the priority of EvalHook to LOW. (#5882) +- Fix a YOLOX bug when applying bbox rescaling in test mode (#5899) +- Fix mosaic coordinate error (#5947) +- Fix dtype of bbox in RandomAffine. (#5930) + +#### Improvements + +- Add Chinese version of `data_pipeline` and (#5662) +- Support to remove state dicts of EMA when publishing models. (#5858) +- Refactor the loss function in HTC and SCNet (#5881) +- Use warnings instead of logger.warning (#5540) +- Use legacy coordinate in metric of VOC (#5627) +- Add Chinese version of customize_losses (#5826) +- Add Chinese version of model_zoo (#5827) + +#### Contributors + +A total of 19 developers contributed to this release. +Thanks @ypwhs, @zywvvd, @collinzrj, @OceanPang, @ddonatien, @@haotian-liu, @viibridges, @Muyun99, @guigarfr, @zhaojinjian0000, @jbwang1997,@wangbo-zhao, @xvjiarui, @RangiLyu, @jshilong, @AronLin, @BIGWangYuDong, @hhaAndroid, @ZwwWayne + +### v2.15.1 (11/8/2021) + +#### Highlights + +- Support [YOLOX](https://arxiv.org/abs/2107.08430) + +#### New Features + +- Support [YOLOX](https://arxiv.org/abs/2107.08430)(#5756, #5758, #5760, #5767, #5770, #5774, #5777, #5808, #5828, #5848) + +#### Bug Fixes + +- Update correct SSD models. (#5789) +- Fix casting error in mask structure (#5820) +- Fix MMCV deployment documentation links. (#5790) + +#### Improvements + +- Use dynamic MMCV download link in TorchServe dockerfile (#5779) +- Rename the function `upsample_like` to `interpolate_as` for more general usage (#5788) + +#### Contributors + +A total of 14 developers contributed to this release. +Thanks @HAOCHENYE, @xiaohu2015, @HsLOL, @zhiqwang, @Adamdad, @shinya7y, @Johnson-Wang, @RangiLyu, @jshilong, @mmeendez8, @AronLin, @BIGWangYuDong, @hhaAndroid, @ZwwWayne + +### v2.15.0 (02/8/2021) + +#### Highlights + +- Support adding [MIM](https://github.com/open-mmlab/mim) dependencies during pip installation +- Support MobileNetV2 for SSD-Lite and YOLOv3 +- Support Chinese Documentation + +#### New Features + +- Add function `upsample_like` (#5732) +- Support to output pdf and epub format documentation (#5738) +- Support and release Cascade Mask R-CNN 3x pre-trained models (#5645) +- Add `ignore_index` to CrossEntropyLoss (#5646) +- Support adding [MIM](https://github.com/open-mmlab/mim) dependencies during pip installation (#5676) +- Add MobileNetV2 config and models for YOLOv3 (#5510) +- Support COCO Panoptic Dataset (#5231) +- Support ONNX export of cascade models (#5486) +- Support DropBlock with RetinaNet (#5544) +- Support MobileNetV2 SSD-Lite (#5526) + +#### Bug Fixes + +- Fix the device of label in multiclass_nms (#5673) +- Fix error of backbone initialization from pre-trained checkpoint in config file (#5603, #5550) +- Fix download links of RegNet pretrained weights (#5655) +- Fix two-stage runtime error given empty proposal (#5559) +- Fix flops count error in DETR (#5654) +- Fix unittest for `NumClassCheckHook` when it is not used. (#5626) +- Fix description bug of using custom dataset (#5546) +- Fix bug of `multiclass_nms` that returns the global indices (#5592) +- Fix `valid_mask` logic error in RPNHead (#5562) +- Fix unit test error of pretrained configs (#5561) +- Fix typo error in anchor_head.py (#5555) +- Fix bug when using dataset wrappers (#5552) +- Fix a typo error in demo/MMDet_Tutorial.ipynb (#5511) +- Fixing crash in `get_root_logger` when `cfg.log_level` is not None (#5521) +- Fix docker version (#5502) +- Fix optimizer parameter error when using `IterBasedRunner` (#5490) + +#### Improvements + +- Add unit tests for MMTracking (#5620) +- Add Chinese translation of documentation (#5718, #5618, #5558, #5423, #5593, #5421, #5408. #5369, #5419, #5530, #5531) +- Update resource limit (#5697) +- Update docstring for InstaBoost (#5640) +- Support key `reduction_override` in all loss functions (#5515) +- Use repeatdataset to accelerate CenterNet training (#5509) +- Remove unnecessary code in autoassign (#5519) +- Add documentation about `init_cfg` (#5273) + +#### Contributors + +A total of 18 developers contributed to this release. +Thanks @OceanPang, @AronLin, @hellock, @Outsider565, @RangiLyu, @ElectronicElephant, @likyoo, @BIGWangYuDong, @hhaAndroid, @noobying, @yyz561, @likyoo, +@zeakey, @ZwwWayne, @ChenyangLiu, @johnson-magic, @qingswu, @BuxianChen + +### v2.14.0 (29/6/2021) + +#### Highlights + +- Add `simple_test` to dense heads to improve the consistency of single-stage and two-stage detectors +- Revert the `test_mixins` to single image test to improve efficiency and readability +- Add Faster R-CNN and Mask R-CNN config using multi-scale training with 3x schedule + +#### New Features + +- Support pretrained models from MoCo v2 and SwAV (#5286) +- Add Faster R-CNN and Mask R-CNN config using multi-scale training with 3x schedule (#5179, #5233) +- Add `reduction_override` in MSELoss (#5437) +- Stable support of exporting DETR to ONNX with dynamic shapes and batch inference (#5168) +- Stable support of exporting PointRend to ONNX with dynamic shapes and batch inference (#5440) + +#### Bug Fixes + +- Fix size mismatch bug in `multiclass_nms` (#4980) +- Fix the import path of `MultiScaleDeformableAttention` (#5338) +- Fix errors in config of GCNet ResNext101 models (#5360) +- Fix Grid-RCNN error when there is no bbox result (#5357) +- Fix errors in `onnx_export` of bbox_head when setting reg_class_agnostic (#5468) +- Fix type error of AutoAssign in the document (#5478) +- Fix web links ending with `.md` (#5315) + +#### Improvements + +- Add `simple_test` to dense heads to improve the consistency of single-stage and two-stage detectors (#5264) +- Add support for mask diagonal flip in TTA (#5403) +- Revert the `test_mixins` to single image test to improve efficiency and readability (#5249) +- Make YOLOv3 Neck more flexible (#5218) +- Refactor SSD to make it more general (#5291) +- Refactor `anchor_generator` and `point_generator` (#5349) +- Allow to configure out the `mask_head` of the HTC algorithm (#5389) +- Delete deprecated warning in FPN (#5311) +- Move `model.pretrained` to `model.backbone.init_cfg` (#5370) +- Make deployment tools more friendly to use (#5280) +- Clarify installation documentation (#5316) +- Add ImageNet Pretrained Models docs (#5268) +- Add FAQ about training loss=nan solution and COCO AP or AR =-1 (# 5312, #5313) +- Change all weight links of http to https (#5328) + +### v2.13.0 (01/6/2021) + +#### Highlights + +- Support new methods: [CenterNet](https://arxiv.org/abs/1904.07850), [Seesaw Loss](https://arxiv.org/abs/2008.10032), [MobileNetV2](https://arxiv.org/abs/1801.04381) + +#### New Features + +- Support paper [Objects as Points](https://arxiv.org/abs/1904.07850) (#4602) +- Support paper [Seesaw Loss for Long-Tailed Instance Segmentation (CVPR 2021)](https://arxiv.org/abs/2008.10032) (#5128) +- Support [MobileNetV2](https://arxiv.org/abs/1801.04381) backbone and inverted residual block (#5122) +- Support [MIM](https://github.com/open-mmlab/mim) (#5143) +- ONNX exportation with dynamic shapes of CornerNet (#5136) +- Add `mask_soft` config option to allow non-binary masks (#4615) +- Add PWC metafile (#5135) + +#### Bug Fixes + +- Fix YOLOv3 FP16 training error (#5172) +- Fix Cacscade R-CNN TTA test error when `det_bboxes` length is 0 (#5221) +- Fix `iou_thr` variable naming errors in VOC recall calculation function (#5195) +- Fix Faster R-CNN performance dropped in ONNX Runtime (#5197) +- Fix DETR dict changed error when using python 3.8 during iteration (#5226) + +#### Improvements + +- Refactor ONNX export of two stage detector (#5205) +- Replace MMDetection's EvalHook with MMCV's EvalHook for consistency (#4806) +- Update RoI extractor for ONNX (#5194) +- Use better parameter initialization in YOLOv3 head for higher performance (#5181) +- Release new DCN models of Mask R-CNN by mixed-precision training (#5201) +- Update YOLOv3 model weights (#5229) +- Add DetectoRS ResNet-101 model weights (#4960) +- Discard bboxes with sizes equals to `min_bbox_size` (#5011) +- Remove duplicated code in DETR head (#5129) +- Remove unnecessary object in class definition (#5180) +- Fix doc link (#5192) + +### v2.12.0 (01/5/2021) + +#### Highlights + +- Support new methods: [AutoAssign](https://arxiv.org/abs/2007.03496), [YOLOF](https://arxiv.org/abs/2103.09460), and [Deformable DETR](https://arxiv.org/abs/2010.04159) +- Stable support of exporting models to ONNX with batched images and dynamic shape (#5039) + +#### Backwards Incompatible Changes + +MMDetection is going through big refactoring for more general and convenient usages during the releases from v2.12.0 to v2.15.0 (maybe longer). +In v2.12.0 MMDetection inevitably brings some BC-breakings, including the MMCV dependency, model initialization, model registry, and mask AP evaluation. + +- MMCV version. MMDetection v2.12.0 relies on the newest features in MMCV 1.3.3, including `BaseModule` for unified parameter initialization, model registry, and the CUDA operator `MultiScaleDeformableAttn` for [Deformable DETR](https://arxiv.org/abs/2010.04159). Note that MMCV 1.3.2 already contains all the features used by MMDet but has known issues. Therefore, we recommend users skip MMCV v1.3.2 and use v1.3.3, though v1.3.2 might work for most cases. +- Unified model initialization (#4750). To unify the parameter initialization in OpenMMLab projects, MMCV supports `BaseModule` that accepts `init_cfg` to allow the modules' parameters initialized in a flexible and unified manner. Now the users need to explicitly call `model.init_weights()` in the training script to initialize the model (as in [here](https://github.com/open-mmlab/mmdetection/blob/master/tools/train.py#L162), previously this was handled by the detector. The models in MMDetection have been re-benchmarked to ensure accuracy based on PR #4750. __The downstream projects should update their code accordingly to use MMDetection v2.12.0__. +- Unified model registry (#5059). To easily use backbones implemented in other OpenMMLab projects, MMDetection migrates to inherit the model registry created in MMCV (#760). In this way, as long as the backbone is supported in an OpenMMLab project and that project also uses the registry in MMCV, users can use that backbone in MMDetection by simply modifying the config without copying the code of that backbone into MMDetection. +- Mask AP evaluation (#4898). Previous versions calculate the areas of masks through the bounding boxes when calculating the mask AP of small, medium, and large instances. To indeed use the areas of masks, we pop the key `bbox` during mask AP calculation. This change does not affect the overall mask AP evaluation and aligns the mask AP of similar models in other projects like Detectron2. + +#### New Features + +- Support paper [AutoAssign: Differentiable Label Assignment for Dense Object Detection](https://arxiv.org/abs/2007.03496) (#4295) +- Support paper [You Only Look One-level Feature](https://arxiv.org/abs/2103.09460) (#4295) +- Support paper [Deformable DETR: Deformable Transformers for End-to-End Object Detection](https://arxiv.org/abs/2010.04159) (#4778) +- Support calculating IoU with FP16 tensor in `bbox_overlaps` to save memory and keep speed (#4889) +- Add `__repr__` in custom dataset to count the number of instances (#4756) +- Add windows support by updating requirements.txt (#5052) +- Stable support of exporting models to ONNX with batched images and dynamic shape, including SSD, FSAF,FCOS, YOLOv3, RetinaNet, Faster R-CNN, and Mask R-CNN (#5039) + +#### Improvements + +- Use MMCV `MODEL_REGISTRY` (#5059) +- Unified parameter initialization for more flexible usage (#4750) +- Rename variable names and fix docstring in anchor head (#4883) +- Support training with empty GT in Cascade RPN (#4928) +- Add more details of usage of `test_robustness` in documentation (#4917) +- Changing to use `pycocotools` instead of `mmpycocotools` to fully support Detectron2 and MMDetection in one environment (#4939) +- Update torch serve dockerfile to support dockers of more versions (#4954) +- Add check for training with single class dataset (#4973) +- Refactor transformer and DETR Head (#4763) +- Update FPG model zoo (#5079) +- More accurate mask AP of small/medium/large instances (#4898) + +#### Bug Fixes + +- Fix bug in mean_ap.py when calculating mAP by 11 points (#4875) +- Fix error when key `meta` is not in old checkpoints (#4936) +- Fix hanging bug when training with empty GT in VFNet, GFL, and FCOS by changing the place of `reduce_mean` (#4923, #4978, #5058) +- Fix asyncronized inference error and provide related demo (#4941) +- Fix IoU losses dimensionality unmatch error (#4982) +- Fix torch.randperm whtn using PyTorch 1.8 (#5014) +- Fix empty bbox error in `mask_head` when using CARAFE (#5062) +- Fix `supplement_mask` bug when there are zero-size RoIs (#5065) +- Fix testing with empty rois in RoI Heads (#5081) + +### v2.11.0 (01/4/2021) + +__Highlights__ + +- Support new method: [Localization Distillation for Object Detection](https://arxiv.org/pdf/2102.12252.pdf) +- Support Pytorch2ONNX with batch inference and dynamic shape + +__New Features__ + +- Support [Localization Distillation for Object Detection](https://arxiv.org/pdf/2102.12252.pdf) (#4758) +- Support Pytorch2ONNX with batch inference and dynamic shape for Faster-RCNN and mainstream one-stage detectors (#4796) + +__Improvements__ + +- Support batch inference in head of RetinaNet (#4699) +- Add batch dimension in second stage of Faster-RCNN (#4785) +- Support batch inference in bbox coder (#4721) +- Add check for `ann_ids` in `COCODataset` to ensure it is unique (#4789) +- support for showing the FPN results (#4716) +- support dynamic shape for grid_anchor (#4684) +- Move pycocotools version check to when it is used (#4880) + +__Bug Fixes__ + +- Fix a bug of TridentNet when doing the batch inference (#4717) +- Fix a bug of Pytorch2ONNX in FASF (#4735) +- Fix a bug when show the image with float type (#4732) + +### v2.10.0 (01/03/2021) + +#### Highlights + +- Support new methods: [FPG](https://arxiv.org/abs/2004.03580) +- Support ONNX2TensorRT for SSD, FSAF, FCOS, YOLOv3, and Faster R-CNN. + +#### New Features + +- Support ONNX2TensorRT for SSD, FSAF, FCOS, YOLOv3, and Faster R-CNN (#4569) +- Support [Feature Pyramid Grids (FPG)](https://arxiv.org/abs/2004.03580) (#4645) +- Support video demo (#4420) +- Add seed option for sampler (#4665) +- Support to customize type of runner (#4570, #4669) +- Support synchronizing BN buffer in `EvalHook` (#4582) +- Add script for GIF demo (#4573) + +#### Bug Fixes + +- Fix ConfigDict AttributeError and add Colab link (#4643) +- Avoid crash in empty gt training of GFL head (#4631) +- Fix `iou_thrs` bug in RPN evaluation (#4581) +- Fix syntax error of config when upgrading model version (#4584) + +#### Improvements + +- Refactor unit test file structures (#4600) +- Refactor nms config (#4636) +- Get loading pipeline by checking the class directly rather than through config strings (#4619) +- Add doctests for mask target generation and mask structures (#4614) +- Use deep copy when copying pipeline arguments (#4621) +- Update documentations (#4642, #4650, #4620, #4630) +- Remove redundant code calling `import_modules_from_strings` (#4601) +- Clean deprecated FP16 API (#4571) +- Check whether `CLASSES` is correctly initialized in the initialization of `XMLDataset` (#4555) +- Support batch inference in the inference API (#4462, #4526) +- Clean deprecated warning and fix 'meta' error (#4695) + +### v2.9.0 (01/02/2021) + +#### Highlights + +- Support new methods: [SCNet](https://arxiv.org/abs/2012.10150), [Sparse R-CNN](https://arxiv.org/abs/2011.12450) +- Move `train_cfg` and `test_cfg` into model in configs +- Support to visualize results based on prediction quality + +#### New Features + +- Support [SCNet](https://arxiv.org/abs/2012.10150) (#4356) +- Support [Sparse R-CNN](https://arxiv.org/abs/2011.12450) (#4219) +- Support evaluate mAP by multiple IoUs (#4398) +- Support concatenate dataset for testing (#4452) +- Support to visualize results based on prediction quality (#4441) +- Add ONNX simplify option to Pytorch2ONNX script (#4468) +- Add hook for checking compatibility of class numbers in heads and datasets (#4508) + +#### Bug Fixes + +- Fix CPU inference bug of Cascade RPN (#4410) +- Fix NMS error of CornerNet when there is no prediction box (#4409) +- Fix TypeError in CornerNet inference (#4411) +- Fix bug of PAA when training with background images (#4391) +- Fix the error that the window data is not destroyed when `out_file is not None` and `show==False` (#4442) +- Fix order of NMS `score_factor` that will decrease the performance of YOLOv3 (#4473) +- Fix bug in HTC TTA when the number of detection boxes is 0 (#4516) +- Fix resize error in mask data structures (#4520) + +#### Improvements + +- Allow to customize classes in LVIS dataset (#4382) +- Add tutorials for building new models with existing datasets (#4396) +- Add CPU compatibility information in documentation (#4405) +- Add documentation of deprecated `ImageToTensor` for batch inference (#4408) +- Add more details in documentation for customizing dataset (#4430) +- Switch `imshow_det_bboxes` visualization backend from OpenCV to Matplotlib (#4389) +- Deprecate `ImageToTensor` in `image_demo.py` (#4400) +- Move train_cfg/test_cfg into model (#4347, #4489) +- Update docstring for `reg_decoded_bbox` option in bbox heads (#4467) +- Update dataset information in documentation (#4525) +- Release pre-trained R50 and R101 PAA detectors with multi-scale 3x training schedules (#4495) +- Add guidance for speed benchmark (#4537) + +### v2.8.0 (04/01/2021) + +#### Highlights + +- Support new methods: [Cascade RPN](https://arxiv.org/abs/1909.06720), [TridentNet](https://arxiv.org/abs/1901.01892) + +#### New Features + +- Support [Cascade RPN](https://arxiv.org/abs/1909.06720) (#1900) +- Support [TridentNet](https://arxiv.org/abs/1901.01892) (#3313) + +#### Bug Fixes + +- Fix bug of show result in async_benchmark (#4367) +- Fix scale factor in MaskTestMixin (#4366) +- Fix but when returning indices in `multiclass_nms` (#4362) +- Fix bug of empirical attention in resnext backbone error (#4300) +- Fix bug of `img_norm_cfg` in FCOS-HRNet models with updated performance and models (#4250) +- Fix invalid checkpoint and log in Mask R-CNN models on Cityscapes dataset (#4287) +- Fix bug in distributed sampler when dataset is too small (#4257) +- Fix bug of 'PAFPN has no attribute extra_convs_on_inputs' (#4235) + +#### Improvements + +- Update model url from aws to aliyun (#4349) +- Update ATSS for PyTorch 1.6+ (#4359) +- Update script to install ruby in pre-commit installation (#4360) +- Delete deprecated `mmdet.ops` (#4325) +- Refactor hungarian assigner for more general usage in Sparse R-CNN (#4259) +- Handle scipy import in DETR to reduce package dependencies (#4339) +- Update documentation of usages for config options after MMCV (1.2.3) supports overriding list in config (#4326) +- Update pre-train models of faster rcnn trained on COCO subsets (#4307) +- Avoid zero or too small value for beta in Dynamic R-CNN (#4303) +- Add doccumentation for Pytorch2ONNX (#4271) +- Add deprecated warning FPN arguments (#4264) +- Support returning indices of kept bboxes when using nms (#4251) +- Update type and device requirements when creating tensors `GFLHead` (#4210) +- Update device requirements when creating tensors in `CrossEntropyLoss` (#4224) + +### v2.7.0 (30/11/2020) + +- Support new method: [DETR](https://arxiv.org/abs/2005.12872), [ResNest](https://arxiv.org/abs/2004.08955), Faster R-CNN DC5. +- Support YOLO, Mask R-CNN, and Cascade R-CNN models exportable to ONNX. + +#### New Features + +- Support [DETR](https://arxiv.org/abs/2005.12872) (#4201, #4206) +- Support to link the best checkpoint in training (#3773) +- Support to override config through options in inference.py (#4175) +- Support YOLO, Mask R-CNN, and Cascade R-CNN models exportable to ONNX (#4087, #4083) +- Support [ResNeSt](https://arxiv.org/abs/2004.08955) backbone (#2959) +- Support unclip border bbox regression (#4076) +- Add tpfp func in evaluating AP (#4069) +- Support mixed precision training of SSD detector with other backbones (#4081) +- Add Faster R-CNN DC5 models (#4043) + +#### Bug Fixes + +- Fix bug of `gpu_id` in distributed training mode (#4163) +- Support Albumentations with version higher than 0.5 (#4032) +- Fix num_classes bug in faster rcnn config (#4088) +- Update code in docs/2_new_data_model.md (#4041) + +#### Improvements + +- Ensure DCN offset to have similar type as features in VFNet (#4198) +- Add config links in README files of models (#4190) +- Add tutorials for loss conventions (#3818) +- Add solution to installation issues in 30-series GPUs (#4176) +- Update docker version in get_started.md (#4145) +- Add model statistics and polish some titles in configs README (#4140) +- Clamp neg probability in FreeAnchor (#4082) +- Speed up expanding large images (#4089) +- Fix Pytorch 1.7 incompatibility issues (#4103) +- Update trouble shooting page to resolve segmentation fault (#4055) +- Update aLRP-Loss in project page (#4078) +- Clean duplicated `reduce_mean` function (#4056) +- Refactor Q&A (#4045) + +### v2.6.0 (1/11/2020) + +- Support new method: [VarifocalNet](https://arxiv.org/abs/2008.13367). +- Refactored documentation with more tutorials. + +#### New Features + +- Support GIoU calculation in `BboxOverlaps2D`, and re-implement `giou_loss` using `bbox_overlaps` (#3936) +- Support random sampling in CPU mode (#3948) +- Support VarifocalNet (#3666, #4024) + +#### Bug Fixes + +- Fix SABL validating bug in Cascade R-CNN (#3913) +- Avoid division by zero in PAA head when num_pos=0 (#3938) +- Fix temporary directory bug of multi-node testing error (#4034, #4017) +- Fix `--show-dir` option in test script (#4025) +- Fix GA-RetinaNet r50 model url (#3983) +- Update code in docs and fix broken urls (#3947) + +#### Improvements + +- Refactor pytorch2onnx API into `mmdet.core.export` and use `generate_inputs_and_wrap_model` for pytorch2onnx (#3857, #3912) +- Update RPN upgrade scripts for v2.5.0 compatibility (#3986) +- Use mmcv `tensor2imgs` (#4010) +- Update test robustness (#4000) +- Update trouble shooting page (#3994) +- Accelerate PAA training speed (#3985) +- Support batch_size > 1 in validation (#3966) +- Use RoIAlign implemented in MMCV for inference in CPU mode (#3930) +- Documentation refactoring (#4031) + +### v2.5.0 (5/10/2020) + +#### Highlights + +- Support new methods: [YOLACT](https://arxiv.org/abs/1904.02689), [CentripetalNet](https://arxiv.org/abs/2003.09119). +- Add more documentations for easier and more clear usage. + +#### Backwards Incompatible Changes + +__FP16 related methods are imported from mmcv instead of mmdet. (#3766, #3822)__ +Mixed precision training utils in `mmdet.core.fp16` are moved to `mmcv.runner`, including `force_fp32`, `auto_fp16`, `wrap_fp16_model`, and `Fp16OptimizerHook`. A deprecation warning will be raised if users attempt to import those methods from `mmdet.core.fp16`, and will be finally removed in V2.10.0. + +__\[0, N-1\] represents foreground classes and N indicates background classes for all models. (#3221)__ +Before v2.5.0, the background label for RPN is 0, and N for other heads. Now the behavior is consistent for all models. Thus `self.background_labels` in `dense_heads` is removed and all heads use `self.num_classes` to indicate the class index of background labels. +This change has no effect on the pre-trained models in the v2.x model zoo, but will affect the training of all models with RPN heads. Two-stage detectors whose RPN head uses softmax will be affected because the order of categories is changed. + +**Only call `get_subset_by_classes` when `test_mode=True` and `self.filter_empty_gt=True` (#3695)** +Function `get_subset_by_classes` in dataset is refactored and only filters out images when `test_mode=True` and `self.filter_empty_gt=True`. +In the original implementation, `get_subset_by_classes` is not related to the flag `self.filter_empty_gt` and will only be called when the classes is set during initialization no matter `test_mode` is `True` or `False`. This brings ambiguous behavior and potential bugs in many cases. After v2.5.0, if `filter_empty_gt=False`, no matter whether the classes are specified in a dataset, the dataset will use all the images in the annotations. If `filter_empty_gt=True` and `test_mode=True`, no matter whether the classes are specified, the dataset will call \`\`get_subset_by_classes\` to check the images and filter out images containing no GT boxes. Therefore, the users should be responsible for the data filtering/cleaning process for the test dataset. + +#### New Features + +- Test time augmentation for single stage detectors (#3844, #3638) +- Support to show the name of experiments during training (#3764) +- Add `Shear`, `Rotate`, `Translate` Augmentation (#3656, #3619, #3687) +- Add image-only transformations including `Constrast`, `Equalize`, `Color`, and `Brightness`. (#3643) +- Support [YOLACT](https://arxiv.org/abs/1904.02689) (#3456) +- Support [CentripetalNet](https://arxiv.org/abs/2003.09119) (#3390) +- Support PyTorch 1.6 in docker (#3905) + +#### Bug Fixes + +- Fix the bug of training ATSS when there is no ground truth boxes (#3702) +- Fix the bug of using Focal Loss when there is `num_pos` is 0 (#3702) +- Fix the label index mapping in dataset browser (#3708) +- Fix Mask R-CNN training stuck problem when their is no positive rois (#3713) +- Fix the bug of `self.rpn_head.test_cfg` in `RPNTestMixin` by using `self.rpn_head` in rpn head (#3808) +- Fix deprecated `Conv2d` from mmcv.ops (#3791) +- Fix device bug in RepPoints (#3836) +- Fix SABL validating bug (#3849) +- Use `https://download.openmmlab.com/mmcv/dist/index.html` for installing MMCV (#3840) +- Fix nonzero in NMS for PyTorch 1.6.0 (#3867) +- Fix the API change bug of PAA (#3883) +- Fix typo in bbox_flip (#3886) +- Fix cv2 import error of ligGL.so.1 in Dockerfile (#3891) + +#### Improvements + +- Change to use `mmcv.utils.collect_env` for collecting environment information to avoid duplicate codes (#3779) +- Update checkpoint file names to v2.0 models in documentation (#3795) +- Update tutorials for changing runtime settings (#3778), modifying loss (#3777) +- Improve the function of `simple_test_bboxes` in SABL (#3853) +- Convert mask to bool before using it as img's index for robustness and speedup (#3870) +- Improve documentation of modules and dataset customization (#3821) + +### v2.4.0 (5/9/2020) + +__Highlights__ + +- Fix lots of issues/bugs and reorganize the trouble shooting page +- Support new methods [SABL](https://arxiv.org/abs/1912.04260), [YOLOv3](https://arxiv.org/abs/1804.02767), and [PAA Assign](https://arxiv.org/abs/2007.08103) +- Support Batch Inference +- Start to publish `mmdet` package to PyPI since v2.3.0 +- Switch model zoo to download.openmmlab.com + +__Backwards Incompatible Changes__ + +- Support Batch Inference (#3564, #3686, #3705): Since v2.4.0, MMDetection could inference model with multiple images in a single GPU. + This change influences all the test APIs in MMDetection and downstream codebases. To help the users migrate their code, we use `replace_ImageToTensor` (#3686) to convert legacy test data pipelines during dataset initialization. +- Support RandomFlip with horizontal/vertical/diagonal direction (#3608): Since v2.4.0, MMDetection supports horizontal/vertical/diagonal flip in the data augmentation. This influences bounding box, mask, and image transformations in data augmentation process and the process that will map those data back to the original format. +- Migrate to use `mmlvis` and `mmpycocotools` for COCO and LVIS dataset (#3727). The APIs are fully compatible with the original `lvis` and `pycocotools`. Users need to uninstall the existing pycocotools and lvis packages in their environment first and install `mmlvis` & `mmpycocotools`. + +__Bug Fixes__ + +- Fix default mean/std for onnx (#3491) +- Fix coco evaluation and add metric items (#3497) +- Fix typo for install.md (#3516) +- Fix atss when sampler per gpu is 1 (#3528) +- Fix import of fuse_conv_bn (#3529) +- Fix bug of gaussian_target, update unittest of heatmap (#3543) +- Fixed VOC2012 evaluate (#3553) +- Fix scale factor bug of rescale (#3566) +- Fix with_xxx_attributes in base detector (#3567) +- Fix boxes scaling when number is 0 (#3575) +- Fix rfp check when neck config is a list (#3591) +- Fix import of fuse conv bn in benchmark.py (#3606) +- Fix webcam demo (#3634) +- Fix typo and itemize issues in tutorial (#3658) +- Fix error in distributed training when some levels of FPN are not assigned with bounding boxes (#3670) +- Fix the width and height orders of stride in valid flag generation (#3685) +- Fix weight initialization bug in Res2Net DCN (#3714) +- Fix bug in OHEMSampler (#3677) + +__New Features__ + +- Support Cutout augmentation (#3521) +- Support evaluation on multiple datasets through ConcatDataset (#3522) +- Support [PAA assign](https://arxiv.org/abs/2007.08103) #(3547) +- Support eval metric with pickle results (#3607) +- Support [YOLOv3](https://arxiv.org/abs/1804.02767) (#3083) +- Support [SABL](https://arxiv.org/abs/1912.04260) (#3603) +- Support to publish to Pypi in github-action (#3510) +- Support custom imports (#3641) + +__Improvements__ + +- Refactor common issues in documentation (#3530) +- Add pytorch 1.6 to CI config (#3532) +- Add config to runner meta (#3534) +- Add eval-option flag for testing (#3537) +- Add init_eval to evaluation hook (#3550) +- Add include_bkg in ClassBalancedDataset (#3577) +- Using config's loading in inference_detector (#3611) +- Add ATSS ResNet-101 models in model zoo (#3639) +- Update urls to download.openmmlab.com (#3665) +- Support non-mask training for CocoDataset (#3711) + +### v2.3.0 (5/8/2020) + +__Highlights__ + +- The CUDA/C++ operators have been moved to `mmcv.ops`. For backward compatibility `mmdet.ops` is kept as warppers of `mmcv.ops`. +- Support new methods [CornerNet](https://arxiv.org/abs/1808.01244), [DIOU](https://arxiv.org/abs/1911.08287)/[CIOU](https://arxiv.org/abs/2005.03572) loss, and new dataset: [LVIS V1](https://arxiv.org/abs/1908.03195) +- Provide more detailed colab training tutorials and more complete documentation. +- Support to convert RetinaNet from Pytorch to ONNX. + +__Bug Fixes__ + +- Fix the model initialization bug of DetectoRS (#3187) +- Fix the bug of module names in NASFCOSHead (#3205) +- Fix the filename bug in publish_model.py (#3237) +- Fix the dimensionality bug when `inside_flags.any()` is `False` in dense heads (#3242) +- Fix the bug of forgetting to pass flip directions in `MultiScaleFlipAug` (#3262) +- Fixed the bug caused by default value of `stem_channels` (#3333) +- Fix the bug of model checkpoint loading for CPU inference (#3318, #3316) +- Fix topk bug when box number is smaller than the expected topk number in ATSSAssigner (#3361) +- Fix the gt priority bug in center_region_assigner.py (#3208) +- Fix NaN issue of iou calculation in iou_loss.py (#3394) +- Fix the bug that `iou_thrs` is not actually used during evaluation in coco.py (#3407) +- Fix test-time augmentation of RepPoints (#3435) +- Fix runtimeError caused by incontiguous tensor in Res2Net+DCN (#3412) + +__New Features__ + +- Support [CornerNet](https://arxiv.org/abs/1808.01244) (#3036) +- Support [DIOU](https://arxiv.org/abs/1911.08287)/[CIOU](https://arxiv.org/abs/2005.03572) loss (#3151) +- Support [LVIS V1](https://arxiv.org/abs/1908.03195) dataset (#) +- Support customized hooks in training (#3395) +- Support fp16 training of generalized focal loss (#3410) +- Support to convert RetinaNet from Pytorch to ONNX (#3075) + +__Improvements__ + +- Support to process ignore boxes in ATSS assigner (#3082) +- Allow to crop images without ground truth in `RandomCrop` (#3153) +- Enable the the `Accuracy` module to set threshold (#3155) +- Refactoring unit tests (#3206) +- Unify the training settings of `to_float32` and `norm_cfg` in RegNets configs (#3210) +- Add colab training tutorials for beginners (#3213, #3273) +- Move CUDA/C++ operators into `mmcv.ops` and keep `mmdet.ops` as warppers for backward compatibility (#3232)(#3457) +- Update installation scripts in documentation (#3290) and dockerfile (#3320) +- Support to set image resize backend (#3392) +- Remove git hash in version file (#3466) +- Check mmcv version to force version compatibility (#3460) + +### v2.2.0 (1/7/2020) + +__Highlights__ + +- Support new methods: [DetectoRS](https://arxiv.org/abs/2006.02334), [PointRend](https://arxiv.org/abs/1912.08193), [Generalized Focal Loss](https://arxiv.org/abs/2006.04388), [Dynamic R-CNN](https://arxiv.org/abs/2004.06002) + +__Bug Fixes__ + +- Fix FreeAnchor when no gt in image (#3176) +- Clean up deprecated usage of `register_module()` (#3092, #3161) +- Fix pretrain bug in NAS FCOS (#3145) +- Fix `num_classes` in SSD (#3142) +- Fix FCOS warmup (#3119) +- Fix `rstrip` in `tools/publish_model.py` +- Fix `flip_ratio` default value in RandomFLip pipeline (#3106) +- Fix cityscapes eval with ms_rcnn (#3112) +- Fix RPN softmax (#3056) +- Fix filename of LVIS@v0.5 (#2998) +- Fix nan loss by filtering out-of-frame gt_bboxes in COCO (#2999) +- Fix bug in FSAF (#3018) +- Add FocalLoss `num_classes` check (#2964) +- Fix PISA Loss when there are no gts (#2992) +- Avoid nan in `iou_calculator` (#2975) +- Prevent possible bugs in loading and transforms caused by shallow copy (#2967) + +__New Features__ + +- Add DetectoRS (#3064) +- Support Generalize Focal Loss (#3097) +- Support PointRend (#2752) +- Support Dynamic R-CNN (#3040) +- Add DeepFashion dataset (#2968) +- Implement FCOS training tricks (#2935) +- Use BaseDenseHead as base class for anchor-base heads (#2963) +- Add `with_cp` for BasicBlock (#2891) +- Add `stem_channels` argument for ResNet (#2954) + +__Improvements__ + +- Add anchor free base head (#2867) +- Migrate to github action (#3137) +- Add docstring for datasets, pipelines, core modules and methods (#3130, #3125, #3120) +- Add VOC benchmark (#3060) +- Add `concat` mode in GRoI (#3098) +- Remove cmd arg `autorescale-lr` (#3080) +- Use `len(data['img_metas'])` to indicate `num_samples` (#3073, #3053) +- Switch to EpochBasedRunner (#2976) + +### v2.1.0 (8/6/2020) + +__Highlights__ + +- Support new backbones: [RegNetX](https://arxiv.org/abs/2003.13678), [Res2Net](https://arxiv.org/abs/1904.01169) +- Support new methods: [NASFCOS](https://arxiv.org/abs/1906.04423), [PISA](https://arxiv.org/abs/1904.04821), [GRoIE](https://arxiv.org/abs/2004.13665) +- Support new dataset: [LVIS](https://arxiv.org/abs/1908.03195) + +__Bug Fixes__ + +- Change the CLI argument `--validate` to `--no-validate` to enable validation after training epochs by default. (#2651) +- Add missing cython to docker file (#2713) +- Fix bug in nms cpu implementation (#2754) +- Fix bug when showing mask results (#2763) +- Fix gcc requirement (#2806) +- Fix bug in async test (#2820) +- Fix mask encoding-decoding bugs in test API (#2824) +- Fix bug in test time augmentation (#2858, #2921, #2944) +- Fix a typo in comment of apis/train (#2877) +- Fix the bug of returning None when no gt bboxes are in the original image in `RandomCrop`. Fix the bug that misses to handle `gt_bboxes_ignore`, `gt_label_ignore`, and `gt_masks_ignore` in `RandomCrop`, `MinIoURandomCrop` and `Expand` modules. (#2810) +- Fix bug of `base_channels` of regnet (#2917) +- Fix the bug of logger when loading pre-trained weights in base detector (#2936) + +__New Features__ + +- Add IoU models (#2666) +- Add colab demo for inference +- Support class agnostic nms (#2553) +- Add benchmark gathering scripts for development only (#2676) +- Add mmdet-based project links (#2736, #2767, #2895) +- Add config dump in training (#2779) +- Add ClassBalancedDataset (#2721) +- Add res2net backbone (#2237) +- Support RegNetX models (#2710) +- Use `mmcv.FileClient` to support different storage backends (#2712) +- Add ClassBalancedDataset (#2721) +- Code Release: Prime Sample Attention in Object Detection (CVPR 2020) (#2626) +- Implement NASFCOS (#2682) +- Add class weight in CrossEntropyLoss (#2797) +- Support LVIS dataset (#2088) +- Support GRoIE (#2584) + +__Improvements__ + +- Allow different x and y strides in anchor heads. (#2629) +- Make FSAF loss more robust to no gt (#2680) +- Compute pure inference time instead (#2657) and update inference speed (#2730) +- Avoided the possibility that a patch with 0 area is cropped. (#2704) +- Add warnings when deprecated `imgs_per_gpu` is used. (#2700) +- Add a mask rcnn example for config (#2645) +- Update model zoo (#2762, #2866, #2876, #2879, #2831) +- Add `ori_filename` to img_metas and use it in test show-dir (#2612) +- Use `img_fields` to handle multiple images during image transform (#2800) +- Add upsample_cfg support in FPN (#2787) +- Add `['img']` as default `img_fields` for back compatibility (#2809) +- Rename the pretrained model from `open-mmlab://resnet50_caffe` and `open-mmlab://resnet50_caffe_bgr` to `open-mmlab://detectron/resnet50_caffe` and `open-mmlab://detectron2/resnet50_caffe`. (#2832) +- Added sleep(2) in test.py to reduce hanging problem (#2847) +- Support `c10::half` in CARAFE (#2890) +- Improve documentations (#2918, #2714) +- Use optimizer constructor in mmcv and clean the original implementation in `mmdet.core.optimizer` (#2947) + +### v2.0.0 (6/5/2020) + +In this release, we made lots of major refactoring and modifications. + +1. __Faster speed__. We optimize the training and inference speed for common models, achieving up to 30% speedup for training and 25% for inference. Please refer to [model zoo](model_zoo.md#comparison-with-detectron2) for details. + +2. __Higher performance__. We change some default hyperparameters with no additional cost, which leads to a gain of performance for most models. Please refer to [compatibility](compatibility.md#training-hyperparameters) for details. + +3. __More documentation and tutorials__. We add a bunch of documentation and tutorials to help users get started more smoothly. Read it [here](https://mmdetection.readthedocs.io/en/latest/). + +4. __Support PyTorch 1.5__. The support for 1.1 and 1.2 is dropped, and we switch to some new APIs. + +5. __Better configuration system__. Inheritance is supported to reduce the redundancy of configs. + +6. __Better modular design__. Towards the goal of simplicity and flexibility, we simplify some encapsulation while add more other configurable modules like BBoxCoder, IoUCalculator, OptimizerConstructor, RoIHead. Target computation is also included in heads and the call hierarchy is simpler. + +7. Support new methods: [FSAF](https://arxiv.org/abs/1903.00621) and PAFPN (part of [PAFPN](https://arxiv.org/abs/1803.01534)). + +__Breaking Changes__ +Models training with MMDetection 1.x are not fully compatible with 2.0, please refer to the [compatibility doc](compatibility.md) for the details and how to migrate to the new version. + +__Improvements__ + +- Unify cuda and cpp API for custom ops. (#2277) +- New config files with inheritance. (#2216) +- Encapsulate the second stage into RoI heads. (#1999) +- Refactor GCNet/EmpericalAttention into plugins. (#2345) +- Set low quality match as an option in IoU-based bbox assigners. (#2375) +- Change the codebase's coordinate system. (#2380) +- Refactor the category order in heads. 0 means the first positive class instead of background now. (#2374) +- Add bbox sampler and assigner registry. (#2419) +- Speed up the inference of RPN. (#2420) +- Add `train_cfg` and `test_cfg` as class members in all anchor heads. (#2422) +- Merge target computation methods into heads. (#2429) +- Add bbox coder to support different bbox encoding and losses. (#2480) +- Unify the API for regression loss. (#2156) +- Refactor Anchor Generator. (#2474) +- Make `lr` an optional argument for optimizers. (#2509) +- Migrate to modules and methods in MMCV. (#2502, #2511, #2569, #2572) +- Support PyTorch 1.5. (#2524) +- Drop the support for Python 3.5 and use F-string in the codebase. (#2531) + +__Bug Fixes__ + +- Fix the scale factors for resized images without keep the aspect ratio. (#2039) +- Check if max_num > 0 before slicing in NMS. (#2486) +- Fix Deformable RoIPool when there is no instance. (#2490) +- Fix the default value of assigned labels. (#2536) +- Fix the evaluation of Cityscapes. (#2578) + +__New Features__ + +- Add deep_stem and avg_down option to ResNet, i.e., support ResNetV1d. (#2252) +- Add L1 loss. (#2376) +- Support both polygon and bitmap for instance masks. (#2353, #2540) +- Support CPU mode for inference. (#2385) +- Add optimizer constructor for complicated configuration of optimizers. (#2397, #2488) +- Implement PAFPN. (#2392) +- Support empty tensor input for some modules. (#2280) +- Support for custom dataset classes without overriding it. (#2408, #2443) +- Support to train subsets of coco dataset. (#2340) +- Add iou_calculator to potentially support more IoU calculation methods. (2405) +- Support class wise mean AP (was removed in the last version). (#2459) +- Add option to save the testing result images. (#2414) +- Support MomentumUpdaterHook. (#2571) +- Add a demo to inference a single image. (#2605) + +### v1.1.0 (24/2/2020) + +__Highlights__ + +- Dataset evaluation is rewritten with a unified api, which is used by both evaluation hooks and test scripts. +- Support new methods: [CARAFE](https://arxiv.org/abs/1905.02188). + +__Breaking Changes__ + +- The new MMDDP inherits from the official DDP, thus the `__init__` api is changed to be the same as official DDP. +- The `mask_head` field in HTC config files is modified. +- The evaluation and testing script is updated. +- In all transforms, instance masks are stored as a numpy array shaped (n, h, w) instead of a list of (h, w) arrays, where n is the number of instances. + +__Bug Fixes__ + +- Fix IOU assigners when ignore_iof_thr > 0 and there is no pred boxes. (#2135) +- Fix mAP evaluation when there are no ignored boxes. (#2116) +- Fix the empty RoI input for Deformable RoI Pooling. (#2099) +- Fix the dataset settings for multiple workflows. (#2103) +- Fix the warning related to `torch.uint8` in PyTorch 1.4. (#2105) +- Fix the inference demo on devices other than gpu:0. (#2098) +- Fix Dockerfile. (#2097) +- Fix the bug that `pad_val` is unused in Pad transform. (#2093) +- Fix the albumentation transform when there is no ground truth bbox. (#2032) + +__Improvements__ + +- Use torch instead of numpy for random sampling. (#2094) +- Migrate to the new MMDDP implementation in MMCV v0.3. (#2090) +- Add meta information in logs. (#2086) +- Rewrite Soft NMS with pytorch extension and remove cython as a dependency. (#2056) +- Rewrite dataset evaluation. (#2042, #2087, #2114, #2128) +- Use numpy array for masks in transforms. (#2030) + +__New Features__ + +- Implement "CARAFE: Content-Aware ReAssembly of FEatures". (#1583) +- Add `worker_init_fn()` in data_loader when seed is set. (#2066, #2111) +- Add logging utils. (#2035) + +### v1.0.0 (30/1/2020) + +This release mainly improves the code quality and add more docstrings. + +__Highlights__ + +- Documentation is online now: . +- Support new models: [ATSS](https://arxiv.org/abs/1912.02424). +- DCN is now available with the api `build_conv_layer` and `ConvModule` like the normal conv layer. +- A tool to collect environment information is available for trouble shooting. + +__Bug Fixes__ + +- Fix the incompatibility of the latest numpy and pycocotools. (#2024) +- Fix the case when distributed package is unavailable, e.g., on Windows. (#1985) +- Fix the dimension issue for `refine_bboxes()`. (#1962) +- Fix the typo when `seg_prefix` is a list. (#1906) +- Add segmentation map cropping to RandomCrop. (#1880) +- Fix the return value of `ga_shape_target_single()`. (#1853) +- Fix the loaded shape of empty proposals. (#1819) +- Fix the mask data type when using albumentation. (#1818) + +__Improvements__ + +- Enhance AssignResult and SamplingResult. (#1995) +- Add ability to overwrite existing module in Registry. (#1982) +- Reorganize requirements and make albumentations and imagecorruptions optional. (#1969) +- Check NaN in `SSDHead`. (#1935) +- Encapsulate the DCN in ResNe(X)t into a ConvModule & Conv_layers. (#1894) +- Refactoring for mAP evaluation and support multiprocessing and logging. (#1889) +- Init the root logger before constructing Runner to log more information. (#1865) +- Split `SegResizeFlipPadRescale` into different existing transforms. (#1852) +- Move `init_dist()` to MMCV. (#1851) +- Documentation and docstring improvements. (#1971, #1938, #1869, #1838) +- Fix the color of the same class for mask visualization. (#1834) +- Remove the option `keep_all_stages` in HTC and Cascade R-CNN. (#1806) + +__New Features__ + +- Add two test-time options `crop_mask` and `rle_mask_encode` for mask heads. (#2013) +- Support loading grayscale images as single channel. (#1975) +- Implement "Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection". (#1872) +- Add sphinx generated docs. (#1859, #1864) +- Add GN support for flops computation. (#1850) +- Collect env info for trouble shooting. (#1812) + +### v1.0rc1 (13/12/2019) + +The RC1 release mainly focuses on improving the user experience, and fixing bugs. + +__Highlights__ + +- Support new models: [FoveaBox](https://arxiv.org/abs/1904.03797), [RepPoints](https://arxiv.org/abs/1904.11490) and [FreeAnchor](https://arxiv.org/abs/1909.02466). +- Add a Dockerfile. +- Add a jupyter notebook demo and a webcam demo. +- Setup the code style and CI. +- Add lots of docstrings and unit tests. +- Fix lots of bugs. + +__Breaking Changes__ + +- There was a bug for computing COCO-style mAP w.r.t different scales (AP_s, AP_m, AP_l), introduced by #621. (#1679) + +__Bug Fixes__ + +- Fix a sampling interval bug in Libra R-CNN. (#1800) +- Fix the learning rate in SSD300 WIDER FACE. (#1781) +- Fix the scaling issue when `keep_ratio=False`. (#1730) +- Fix typos. (#1721, #1492, #1242, #1108, #1107) +- Fix the shuffle argument in `build_dataloader`. (#1693) +- Clip the proposal when computing mask targets. (#1688) +- Fix the "index out of range" bug for samplers in some corner cases. (#1610, #1404) +- Fix the NMS issue on devices other than GPU:0. (#1603) +- Fix SSD Head and GHM Loss on CPU. (#1578) +- Fix the OOM error when there are too many gt bboxes. (#1575) +- Fix the wrong keyword argument `nms_cfg` in HTC. (#1573) +- Process masks and semantic segmentation in Expand and MinIoUCrop transforms. (#1550, #1361) +- Fix a scale bug in the Non Local op. (#1528) +- Fix a bug in transforms when `gt_bboxes_ignore` is None. (#1498) +- Fix a bug when `img_prefix` is None. (#1497) +- Pass the device argument to `grid_anchors` and `valid_flags`. (#1478) +- Fix the data pipeline for test_robustness. (#1476) +- Fix the argument type of deformable pooling. (#1390) +- Fix the coco_eval when there are only two classes. (#1376) +- Fix a bug in Modulated DeformableConv when deformable_group>1. (#1359) +- Fix the mask cropping in RandomCrop. (#1333) +- Fix zero outputs in DeformConv when not running on cuda:0. (#1326) +- Fix the type issue in Expand. (#1288) +- Fix the inference API. (#1255) +- Fix the inplace operation in Expand. (#1249) +- Fix the from-scratch training config. (#1196) +- Fix inplace add in RoIExtractor which cause an error in PyTorch 1.2. (#1160) +- Fix FCOS when input images has no positive sample. (#1136) +- Fix recursive imports. (#1099) + +__Improvements__ + +- Print the config file and mmdet version in the log. (#1721) +- Lint the code before compiling in travis CI. (#1715) +- Add a probability argument for the `Expand` transform. (#1651) +- Update the PyTorch and CUDA version in the docker file. (#1615) +- Raise a warning when specifying `--validate` in non-distributed training. (#1624, #1651) +- Beautify the mAP printing. (#1614) +- Add pre-commit hook. (#1536) +- Add the argument `in_channels` to backbones. (#1475) +- Add lots of docstrings and unit tests, thanks to [@Erotemic](https://github.com/Erotemic). (#1603, #1517, #1506, #1505, #1491, #1479, #1477, #1475, #1474) +- Add support for multi-node distributed test when there is no shared storage. (#1399) +- Optimize Dockerfile to reduce the image size. (#1306) +- Update new results of HRNet. (#1284, #1182) +- Add an argument `no_norm_on_lateral` in FPN. (#1240) +- Test the compiling in CI. (#1235) +- Move docs to a separate folder. (#1233) +- Add a jupyter notebook demo. (#1158) +- Support different type of dataset for training. (#1133) +- Use int64_t instead of long in cuda kernels. (#1131) +- Support unsquare RoIs for bbox and mask heads. (#1128) +- Manually add type promotion to make compatible to PyTorch 1.2. (#1114) +- Allowing validation dataset for computing validation loss. (#1093) +- Use `.scalar_type()` instead of `.type()` to suppress some warnings. (#1070) + +__New Features__ + +- Add an option `--with_ap` to compute the AP for each class. (#1549) +- Implement "FreeAnchor: Learning to Match Anchors for Visual Object Detection". (#1391) +- Support [Albumentations](https://github.com/albumentations-team/albumentations) for augmentations in the data pipeline. (#1354) +- Implement "FoveaBox: Beyond Anchor-based Object Detector". (#1339) +- Support horizontal and vertical flipping. (#1273, #1115) +- Implement "RepPoints: Point Set Representation for Object Detection". (#1265) +- Add test-time augmentation to HTC and Cascade R-CNN. (#1251) +- Add a COCO result analysis tool. (#1228) +- Add Dockerfile. (#1168) +- Add a webcam demo. (#1155, #1150) +- Add FLOPs counter. (#1127) +- Allow arbitrary layer order for ConvModule. (#1078) + +### v1.0rc0 (27/07/2019) + +- Implement lots of new methods and components (Mixed Precision Training, HTC, Libra R-CNN, Guided Anchoring, Empirical Attention, Mask Scoring R-CNN, Grid R-CNN (Plus), GHM, GCNet, FCOS, HRNet, Weight Standardization, etc.). Thank all collaborators! +- Support two additional datasets: WIDER FACE and Cityscapes. +- Refactoring for loss APIs and make it more flexible to adopt different losses and related hyper-parameters. +- Speed up multi-gpu testing. +- Integrate all compiling and installing in a single script. + +### v0.6.0 (14/04/2019) + +- Up to 30% speedup compared to the model zoo. +- Support both PyTorch stable and nightly version. +- Replace NMS and SigmoidFocalLoss with Pytorch CUDA extensions. + +### v0.6rc0(06/02/2019) + +- Migrate to PyTorch 1.0. + +### v0.5.7 (06/02/2019) + +- Add support for Deformable ConvNet v2. (Many thanks to the authors and [@chengdazhi](https://github.com/chengdazhi)) +- This is the last release based on PyTorch 0.4.1. + +### v0.5.6 (17/01/2019) + +- Add support for Group Normalization. +- Unify RPNHead and single stage heads (RetinaHead, SSDHead) with AnchorHead. + +### v0.5.5 (22/12/2018) + +- Add SSD for COCO and PASCAL VOC. +- Add ResNeXt backbones and detection models. +- Refactoring for Samplers/Assigners and add OHEM. +- Add VOC dataset and evaluation scripts. + +### v0.5.4 (27/11/2018) + +- Add SingleStageDetector and RetinaNet. + +### v0.5.3 (26/11/2018) + +- Add Cascade R-CNN and Cascade Mask R-CNN. +- Add support for Soft-NMS in config files. + +### v0.5.2 (21/10/2018) + +- Add support for custom datasets. +- Add a script to convert PASCAL VOC annotations to the expected format. + +### v0.5.1 (20/10/2018) + +- Add BBoxAssigner and BBoxSampler, the `train_cfg` field in config files are restructured. +- `ConvFCRoIHead` / `SharedFCRoIHead` are renamed to `ConvFCBBoxHead` / `SharedFCBBoxHead` for consistency. diff --git a/mmdet_code/mmdetection/docs/en/notes/compatibility.md b/mmdet_code/mmdetection/docs/en/notes/compatibility.md new file mode 100644 index 0000000000000000000000000000000000000000..26325e249dc6f867925c10390b0c52cc6c52e6e0 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/notes/compatibility.md @@ -0,0 +1,178 @@ +# Compatibility of MMDetection 2.x + +## MMDetection 2.25.0 + +In order to support Mask2Former for instance segmentation, the original config files of Mask2Former for panpotic segmentation need to be renamed [PR #7571](https://github.com/open-mmlab/mmdetection/pull/7571). + + + + + + + + + + + +
before v2.25.0after v2.25.0
+ +``` +'mask2former_xxx_coco.py' represents config files for **panoptic segmentation**. +``` + + + +``` +'mask2former_xxx_coco.py' represents config files for **instance segmentation**. +'mask2former_xxx_coco-panoptic.py' represents config files for **panoptic segmentation**. +``` + +
+ +## MMDetection 2.21.0 + +In order to support CPU training, the logic of scatter in batch collating has been changed. We recommend to use +MMCV v1.4.4 or higher. For more details, please refer to [MMCV PR #1621](https://github.com/open-mmlab/mmcv/pull/1621). + +## MMDetection 2.18.1 + +### MMCV compatibility + +In order to fix the wrong weight reference bug in BaseTransformerLayer, the logic in batch first mode of MultiheadAttention has been changed. +We recommend to use MMCV v1.3.17 or higher. For more details, please refer to [MMCV PR #1418](https://github.com/open-mmlab/mmcv/pull/1418). + +## MMDetection 2.18.0 + +### DIIHead compatibility + +In order to support QueryInst, attn_feats is added into the returned tuple of DIIHead. + +## MMDetection 2.14.0 + +### MMCV Version + +In order to fix the problem that the priority of EvalHook is too low, all hook priorities have been re-adjusted in 1.3.8, so MMDetection 2.14.0 needs to rely on the latest MMCV 1.3.8 version. For related information, please refer to [#1120](https://github.com/open-mmlab/mmcv/pull/1120), for related issues, please refer to [#5343](https://github.com/open-mmlab/mmdetection/issues/5343). + +### SSD compatibility + +In v2.14.0, to make SSD more flexible to use, [PR5291](https://github.com/open-mmlab/mmdetection/pull/5291) refactored its backbone, neck and head. The users can use the script `tools/model_converters/upgrade_ssd_version.py` to convert their models. + +```bash +python tools/model_converters/upgrade_ssd_version.py ${OLD_MODEL_PATH} ${NEW_MODEL_PATH} +``` + +- OLD_MODEL_PATH: the path to load the old version SSD model. +- NEW_MODEL_PATH: the path to save the converted model weights. + +## MMDetection 2.12.0 + +MMDetection is going through big refactoring for more general and convenient usages during the releases from v2.12.0 to v2.18.0 (maybe longer). +In v2.12.0 MMDetection inevitably brings some BC-breakings, including the MMCV dependency, model initialization, model registry, and mask AP evaluation. + +### MMCV Version + +MMDetection v2.12.0 relies on the newest features in MMCV 1.3.3, including `BaseModule` for unified parameter initialization, model registry, and the CUDA operator `MultiScaleDeformableAttn` for [Deformable DETR](https://arxiv.org/abs/2010.04159). Note that MMCV 1.3.2 already contains all the features used by MMDet but has known issues. Therefore, we recommend users to skip MMCV v1.3.2 and use v1.3.2, though v1.3.2 might work for most of the cases. + +### Unified model initialization + +To unify the parameter initialization in OpenMMLab projects, MMCV supports `BaseModule` that accepts `init_cfg` to allow the modules' parameters initialized in a flexible and unified manner. Now the users need to explicitly call `model.init_weights()` in the training script to initialize the model (as in [here](https://github.com/open-mmlab/mmdetection/blob/main/tools/train.py#L162), previously this was handled by the detector. **The downstream projects must update their model initialization accordingly to use MMDetection v2.12.0**. Please refer to PR #4750 for details. + +### Unified model registry + +To easily use backbones implemented in other OpenMMLab projects, MMDetection v2.12.0 inherits the model registry created in MMCV (#760). In this way, as long as the backbone is supported in an OpenMMLab project and that project also uses the registry in MMCV, users can use that backbone in MMDetection by simply modifying the config without copying the code of that backbone into MMDetection. Please refer to PR #5059 for more details. + +### Mask AP evaluation + +Before [PR 4898](https://github.com/open-mmlab/mmdetection/pull/4898) and V2.12.0, the mask AP of small, medium, and large instances is calculated based on the bounding box area rather than the real mask area. This leads to higher `APs` and `APm` but lower `APl` but will not affect the overall mask AP. [PR 4898](https://github.com/open-mmlab/mmdetection/pull/4898) change it to use mask areas by deleting `bbox` in mask AP calculation. +The new calculation does not affect the overall mask AP evaluation and is consistent with [Detectron2](https://github.com/facebookresearch/detectron2/). + +## Compatibility with MMDetection 1.x + +MMDetection 2.0 goes through a big refactoring and addresses many legacy issues. It is not compatible with the 1.x version, i.e., running inference with the same model weights in these two versions will produce different results. Thus, MMDetection 2.0 re-benchmarks all the models and provides their links and logs in the model zoo. + +The major differences are in four folds: coordinate system, codebase conventions, training hyperparameters, and modular design. + +### Coordinate System + +The new coordinate system is consistent with [Detectron2](https://github.com/facebookresearch/detectron2/) and treats the center of the most left-top pixel as (0, 0) rather than the left-top corner of that pixel. +Accordingly, the system interprets the coordinates in COCO bounding box and segmentation annotations as coordinates in range `[0, width]` or `[0, height]`. +This modification affects all the computation related to the bbox and pixel selection, +which is more natural and accurate. + +- The height and width of a box with corners (x1, y1) and (x2, y2) in the new coordinate system is computed as `width = x2 - x1` and `height = y2 - y1`. + In MMDetection 1.x and previous version, a "+ 1" was added both height and width. + This modification are in three folds: + + 1. Box transformation and encoding/decoding in regression. + 2. IoU calculation. This affects the matching process between ground truth and bounding box and the NMS process. The effect to compatibility is very negligible, though. + 3. The corners of bounding box is in float type and no longer quantized. This should provide more accurate bounding box results. This also makes the bounding box and RoIs not required to have minimum size of 1, whose effect is small, though. + +- The anchors are center-aligned to feature grid points and in float type. + In MMDetection 1.x and previous version, the anchors are in `int` type and not center-aligned. + This affects the anchor generation in RPN and all the anchor-based methods. + +- ROIAlign is better aligned with the image coordinate system. The new implementation is adopted from [Detectron2](https://github.com/facebookresearch/detectron2/tree/master/detectron2/layers/csrc/ROIAlign). + The RoIs are shifted by half a pixel by default when they are used to cropping RoI features, compared to MMDetection 1.x. + The old behavior is still available by setting `aligned=False` instead of `aligned=True`. + +- Mask cropping and pasting are more accurate. + + 1. We use the new RoIAlign to crop mask targets. In MMDetection 1.x, the bounding box is quantized before it is used to crop mask target, and the crop process is implemented by numpy. In new implementation, the bounding box for crop is not quantized and sent to RoIAlign. This implementation accelerates the training speed by a large margin (~0.1s per iter, ~2 hour when training Mask R50 for 1x schedule) and should be more accurate. + + 2. In MMDetection 2.0, the "`paste_mask()`" function is different and should be more accurate than those in previous versions. This change follows the modification in [Detectron2](https://github.com/facebookresearch/detectron2/blob/master/detectron2/structures/masks.py) and can improve mask AP on COCO by ~0.5% absolute. + +### Codebase Conventions + +- MMDetection 2.0 changes the order of class labels to reduce unused parameters in regression and mask branch more naturally (without +1 and -1). + This effect all the classification layers of the model to have a different ordering of class labels. The final layers of regression branch and mask head no longer keep K+1 channels for K categories, and their class orders are consistent with the classification branch. + + - In MMDetection 2.0, label "K" means background, and labels \[0, K-1\] correspond to the K = num_categories object categories. + + - In MMDetection 1.x and previous version, label "0" means background, and labels \[1, K\] correspond to the K categories. + + - **Note**: The class order of softmax RPN is still the same as that in 1.x in versions\<=2.4.0 while sigmoid RPN is not affected. The class orders in all heads are unified since MMDetection v2.5.0. + +- Low quality matching in R-CNN is not used. In MMDetection 1.x and previous versions, the `max_iou_assigner` will match low quality boxes for each ground truth box in both RPN and R-CNN training. We observe this sometimes does not assign the most perfect GT box to some bounding boxes, + thus MMDetection 2.0 do not allow low quality matching by default in R-CNN training in the new system. This sometimes may slightly improve the box AP (~0.1% absolute). + +- Separate scale factors for width and height. In MMDetection 1.x and previous versions, the scale factor is a single float in mode `keep_ratio=True`. This is slightly inaccurate because the scale factors for width and height have slight difference. MMDetection 2.0 adopts separate scale factors for width and height, the improvement on AP ~0.1% absolute. + +- Configs name conventions are changed. MMDetection V2.0 adopts the new name convention to maintain the gradually growing model zoo as the following: + + ```shell + [model]_(model setting)_[backbone]_[neck]_(norm setting)_(misc)_(gpu x batch)_[schedule]_[dataset].py, + ``` + + where the (`misc`) includes DCN and GCBlock, etc. More details are illustrated in the [documentation for config](tutorials/config) + +- MMDetection V2.0 uses new ResNet Caffe backbones to reduce warnings when loading pre-trained models. Most of the new backbones' weights are the same as the former ones but do not have `conv.bias`, except that they use a different `img_norm_cfg`. Thus, the new backbone will not cause warning of unexpected keys. + +### Training Hyperparameters + +The change in training hyperparameters does not affect +model-level compatibility but slightly improves the performance. The major ones are: + +- The number of proposals after nms is changed from 2000 to 1000 by setting `nms_post=1000` and `max_num=1000`. + This slightly improves both mask AP and bbox AP by ~0.2% absolute. + +- The default box regression losses for Mask R-CNN, Faster R-CNN and RetinaNet are changed from smooth L1 Loss to L1 loss. This leads to an overall improvement in box AP (~0.6% absolute). However, using L1-loss for other methods such as Cascade R-CNN and HTC does not improve the performance, so we keep the original settings for these methods. + +- The sample num of RoIAlign layer is set to be 0 for simplicity. This leads to slightly improvement on mask AP (~0.2% absolute). + +- The default setting does not use gradient clipping anymore during training for faster training speed. This does not degrade performance of the most of models. For some models such as RepPoints we keep using gradient clipping to stabilize the training process and to obtain better performance. + +- The default warmup ratio is changed from 1/3 to 0.001 for a more smooth warming up process since the gradient clipping is usually not used. The effect is found negligible during our re-benchmarking, though. + +### Upgrade Models from 1.x to 2.0 + +To convert the models trained by MMDetection V1.x to MMDetection V2.0, the users can use the script `tools/model_converters/upgrade_model_version.py` to convert +their models. The converted models can be run in MMDetection V2.0 with slightly dropped performance (less than 1% AP absolute). +Details can be found in `configs/legacy`. + +## pycocotools compatibility + +`mmpycocotools` is the OpenMMlab's fork of official `pycocotools`, which works for both MMDetection and Detectron2. +Before [PR 4939](https://github.com/open-mmlab/mmdetection/pull/4939), since `pycocotools` and `mmpycocotool` have the same package name, if users already installed `pycocotools` (installed Detectron2 first under the same environment), then the setup of MMDetection will skip installing `mmpycocotool`. Thus MMDetection fails due to the missing `mmpycocotools`. +If MMDetection is installed before Detectron2, they could work under the same environment. +[PR 4939](https://github.com/open-mmlab/mmdetection/pull/4939) deprecates mmpycocotools in favor of official pycocotools. +Users may install MMDetection and Detectron2 under the same environment after [PR 4939](https://github.com/open-mmlab/mmdetection/pull/4939), no matter what the installation order is. diff --git a/mmdet_code/mmdetection/docs/en/notes/contribution_guide.md b/mmdet_code/mmdetection/docs/en/notes/contribution_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d622c0abed31f206faef9be121f57050f2a9447c --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/notes/contribution_guide.md @@ -0,0 +1 @@ +# Contribution diff --git a/mmdet_code/mmdetection/docs/en/notes/faq.md b/mmdet_code/mmdetection/docs/en/notes/faq.md new file mode 100644 index 0000000000000000000000000000000000000000..f1a176e4d0437648805a4c48802efa48cbad455b --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/notes/faq.md @@ -0,0 +1,241 @@ +# Frequently Asked Questions + +We list some common troubles faced by many users and their corresponding solutions here. Feel free to enrich the list if you find any frequent issues and have ways to help others to solve them. If the contents here do not cover your issue, please create an issue using the [provided templates](https://github.com/open-mmlab/mmdetection/blob/main/.github/ISSUE_TEMPLATE/error-report.md/) and make sure you fill in all required information in the template. + +## PyTorch 2.0 Support + +The vast majority of algorithms in MMDetection now support PyTorch 2.0 and its `torch.compile` function. Users only need to install MMDetection 3.0.0rc7 or later versions to enjoy this feature. If any unsupported algorithms are found during use, please feel free to give us feedback. We also welcome contributions from the community to benchmark the speed improvement brought by using the `torch.compile` function. + +To enable the `torch.compile` function, simply add `--cfg-options compile=True` after `train.py` or `test.py`. For example, to enable `torch.compile` for RTMDet, you can use the following command: + +```shell +# Single GPU +python tools/train.py configs/rtmdet/rtmdet_s_8xb32-300e_coco.py --cfg-options compile=True + +# Single node multiple GPUs +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True + +# Single node multiple GPUs + AMP +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True --amp +``` + +It is important to note that PyTorch 2.0's support for dynamic shapes is not yet fully developed. In most object detection algorithms, not only are the input shapes dynamic, but the loss calculation and post-processing parts are also dynamic. This can lead to slower training speeds when using the `torch.compile` function. Therefore, if you wish to enable the `torch.compile` function, you should follow these principles: + +1. Input images to the network are fixed shape, not multi-scale +2. set `torch._dynamo.config.cache_size_limit` parameter. TorchDynamo will convert and cache the Python bytecode, and the compiled functions will be stored in the cache. When the next check finds that the function needs to be recompiled, the function will be recompiled and cached. However, if the number of recompilations exceeds the maximum value set (64), the function will no longer be cached or recompiled. As mentioned above, the loss calculation and post-processing parts of the object detection algorithm are also dynamically calculated, and these functions need to be recompiled every time. Therefore, setting the `torch._dynamo.config.cache_size_limit` parameter to a smaller value can effectively reduce the compilation time + +In MMDetection, you can set the `torch._dynamo.config.cache_size_limit` parameter through the environment variable `DYNAMO_CACHE_SIZE_LIMIT`. For example, the command is as follows: + +```shell +# Single GPU +export DYNAMO_CACHE_SIZE_LIMIT = 4 +python tools/train.py configs/rtmdet/rtmdet_s_8xb32-300e_coco.py --cfg-options compile=True + +# Single node multiple GPUs +export DYNAMO_CACHE_SIZE_LIMIT = 4 +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True +``` + +About the common questions about PyTorch 2.0's dynamo, you can refer to [here](https://pytorch.org/docs/stable/dynamo/faq.html) + +## Installation + +Compatibility issue between MMCV and MMDetection; "ConvWS is already registered in conv layer"; "AssertionError: MMCV==xxx is used but incompatible. Please install mmcv>=xxx, \<=xxx." + +Compatible MMDetection, MMEngine, and MMCV versions are shown as below. Please choose the correct version of MMCV to avoid installation issues. + +| MMDetection version | MMCV version | MMEngine version | +| :-----------------: | :---------------------: | :----------------------: | +| main | mmcv>=2.0.0, \<2.2.0 | mmengine>=0.7.1, \<1.0.0 | +| 3.3.0 | mmcv>=2.0.0, \<2.2.0 | mmengine>=0.7.1, \<1.0.0 | +| 3.2.0 | mmcv>=2.0.0, \<2.2.0 | mmengine>=0.7.1, \<1.0.0 | +| 3.1.0 | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | +| 3.0.0 | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | +| 3.0.0rc6 | mmcv>=2.0.0rc4, \<2.1.0 | mmengine>=0.6.0, \<1.0.0 | +| 3.0.0rc5 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | +| 3.0.0rc4 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | +| 3.0.0rc3 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | +| 3.0.0rc2 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | +| 3.0.0rc1 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | +| 3.0.0rc0 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | + +**Note:** + +1. If you want to install mmdet-v2.x, the compatible MMDetection and MMCV versions table can be found at [here](https://mmdetection.readthedocs.io/en/stable/faq.html#installation). Please choose the correct version of MMCV to avoid installation issues. +2. In MMCV-v2.x, `mmcv-full` is rename to `mmcv`, if you want to install `mmcv` without CUDA ops, you can install `mmcv-lite`. + +- "No module named 'mmcv.ops'"; "No module named 'mmcv.\_ext'". + + 1. Uninstall existing `mmcv-lite` in the environment using `pip uninstall mmcv-lite`. + 2. Install `mmcv` following the [installation instruction](https://mmcv.readthedocs.io/en/2.x/get_started/installation.html). + +- "Microsoft Visual C++ 14.0 or graeter is required" during installation on Windows. + + This error happens when building the 'pycocotools.\_mask' extension of pycocotools and the environment lacks corresponding C++ compilation dependencies. You need to download it at Microsoft officials [visual-cpp-build-tools](https://visualstudio.microsoft.com/zh-hans/visual-cpp-build-tools/), select the "Use C ++ Desktop Development" option to install the minimum dependencies, and then reinstall pycocotools. + +- Using Albumentations + + If you would like to use `albumentations`, we suggest using `pip install -r requirements/albu.txt` or + `pip install -U albumentations --no-binary qudida,albumentations`. + If you simply use `pip install albumentations>=0.3.2`, it will install `opencv-python-headless` simultaneously (even though you have already installed `opencv-python`). + Please refer to the [official documentation](https://albumentations.ai/docs/getting_started/installation/#note-on-opencv-dependencies) for details. + +- ModuleNotFoundError is raised when using some algorithms + + Some extra dependencies are required for Instaboost, Panoptic Segmentation, LVIS dataset, etc. Please note the error message and install corresponding packages, e.g., + + ```shell + # for instaboost + pip install instaboostfast + # for panoptic segmentation + pip install git+https://github.com/cocodataset/panopticapi.git + # for LVIS dataset + pip install git+https://github.com/lvis-dataset/lvis-api.git + ``` + +## Coding + +- Do I need to reinstall mmdet after some code modifications + + If you follow the best practice and install mmdet with `pip install -e .`, any local modifications made to the code will take effect without reinstallation. + +- How to develop with multiple MMDetection versions + + You can have multiple folders like mmdet-3.0, mmdet-3.1. + When you run the train or test script, it will adopt the mmdet package in the current folder. + + To use the default MMDetection installed in the environment rather than the one you are working with, you can remove the following line in those scripts: + + ```shell + PYTHONPATH="$(dirname $0)/..":$PYTHONPATH + ``` + +## PyTorch/CUDA Environment + +- "RTX 30 series card fails when building MMCV or MMDet" + + 1. Temporary work-around: do `MMCV_WITH_OPS=1 MMCV_CUDA_ARGS='-gencode=arch=compute_80,code=sm_80' pip install -e .`. + The common issue is `nvcc fatal : Unsupported gpu architecture 'compute_86'`. This means that the compiler should optimize for sm_86, i.e., nvidia 30 series card, but such optimizations have not been supported by CUDA toolkit 11.0. + This work-around modifies the compile flag by adding `MMCV_CUDA_ARGS='-gencode=arch=compute_80,code=sm_80'`, which tells `nvcc` to optimize for **sm_80**, i.e., Nvidia A100. Although A100 is different from the 30 series card, they use similar ampere architecture. This may hurt the performance but it works. + 2. PyTorch developers have updated that the default compiler flags should be fixed by [pytorch/pytorch#47585](https://github.com/pytorch/pytorch/pull/47585). So using PyTorch-nightly may also be able to solve the problem, though we have not tested it yet. + +- "invalid device function" or "no kernel image is available for execution". + + 1. Check if your cuda runtime version (under `/usr/local/`), `nvcc --version` and `conda list cudatoolkit` version match. + 2. Run `python mmdet/utils/collect_env.py` to check whether PyTorch, torchvision, and MMCV are built for the correct GPU architecture. + You may need to set `TORCH_CUDA_ARCH_LIST` to reinstall MMCV. + The GPU arch table could be found [here](https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#gpu-feature-list), + i.e. run `TORCH_CUDA_ARCH_LIST=7.0 pip install mmcv` to build MMCV for Volta GPUs. + The compatibility issue could happen when using old GPUS, e.g., Tesla K80 (3.7) on colab. + 3. Check whether the running environment is the same as that when mmcv/mmdet has compiled. + For example, you may compile mmcv using CUDA 10.0 but run it on CUDA 9.0 environments. + +- "undefined symbol" or "cannot open xxx.so". + + 1. If those symbols are CUDA/C++ symbols (e.g., libcudart.so or GLIBCXX), check whether the CUDA/GCC runtimes are the same as those used for compiling mmcv, + i.e. run `python mmdet/utils/collect_env.py` to see if `"MMCV Compiler"`/`"MMCV CUDA Compiler"` is the same as `"GCC"`/`"CUDA_HOME"`. + 2. If those symbols are PyTorch symbols (e.g., symbols containing caffe, aten, and TH), check whether the PyTorch version is the same as that used for compiling mmcv. + 3. Run `python mmdet/utils/collect_env.py` to check whether PyTorch, torchvision, and MMCV are built by and running on the same environment. + +- setuptools.sandbox.UnpickleableException: DistutilsSetupError("each element of 'ext_modules' option must be an Extension instance or 2-tuple") + + 1. If you are using miniconda rather than anaconda, check whether Cython is installed as indicated in [#3379](https://github.com/open-mmlab/mmdetection/issues/3379). + You need to manually install Cython first and then run command `pip install -r requirements.txt`. + 2. You may also need to check the compatibility between the `setuptools`, `Cython`, and `PyTorch` in your environment. + +- "Segmentation fault". + + 1. Check you GCC version and use GCC 5.4. This usually caused by the incompatibility between PyTorch and the environment (e.g., GCC \< 4.9 for PyTorch). We also recommend the users to avoid using GCC 5.5 because many feedbacks report that GCC 5.5 will cause "segmentation fault" and simply changing it to GCC 5.4 could solve the problem. + + 2. Check whether PyTorch is correctly installed and could use CUDA op, e.g. type the following command in your terminal. + + ```shell + python -c 'import torch; print(torch.cuda.is_available())' + ``` + + And see whether they could correctly output results. + + 3. If Pytorch is correctly installed, check whether MMCV is correctly installed. + + ```shell + python -c 'import mmcv; import mmcv.ops' + ``` + + If MMCV is correctly installed, then there will be no issue of the above two commands. + + 4. If MMCV and Pytorch is correctly installed, you man use `ipdb`, `pdb` to set breakpoints or directly add 'print' in mmdetection code and see which part leads the segmentation fault. + +## Training + +- "Loss goes Nan" + + 1. Check if the dataset annotations are valid: zero-size bounding boxes will cause the regression loss to be Nan due to the commonly used transformation for box regression. Some small size (width or height are smaller than 1) boxes will also cause this problem after data augmentation (e.g., instaboost). So check the data and try to filter out those zero-size boxes and skip some risky augmentations on the small-size boxes when you face the problem. + 2. Reduce the learning rate: the learning rate might be too large due to some reasons, e.g., change of batch size. You can rescale them to the value that could stably train the model. + 3. Extend the warmup iterations: some models are sensitive to the learning rate at the start of the training. You can extend the warmup iterations, e.g., change the `warmup_iters` from 500 to 1000 or 2000. + 4. Add gradient clipping: some models requires gradient clipping to stabilize the training process. The default of `grad_clip` is `None`, you can add gradient clippint to avoid gradients that are too large, i.e., set `optim_wrapper=dict(clip_grad=dict(max_norm=35, norm_type=2))` in your config file. + +- "GPU out of memory" + + 1. There are some scenarios when there are large amount of ground truth boxes, which may cause OOM during target assignment. You can set `gpu_assign_thr=N` in the config of assigner thus the assigner will calculate box overlaps through CPU when there are more than N GT boxes. + + 2. Set `with_cp=True` in the backbone. This uses the sublinear strategy in PyTorch to reduce GPU memory cost in the backbone. + + 3. Try mixed precision training using following the examples in `config/fp16`. The `loss_scale` might need further tuning for different models. + + 4. Try to use `AvoidCUDAOOM` to avoid GPU out of memory. It will first retry after calling `torch.cuda.empty_cache()`. If it still fails, it will then retry by converting the type of inputs to FP16 format. If it still fails, it will try to copy inputs from GPUs to CPUs to continue computing. Try AvoidOOM in you code to make the code continue to run when GPU memory runs out: + + ```python + from mmdet.utils import AvoidCUDAOOM + + output = AvoidCUDAOOM.retry_if_cuda_oom(some_function)(input1, input2) + ``` + + You can also try `AvoidCUDAOOM` as a decorator to make the code continue to run when GPU memory runs out: + + ```python + from mmdet.utils import AvoidCUDAOOM + + @AvoidCUDAOOM.retry_if_cuda_oom + def function(*args, **kwargs): + ... + return xxx + ``` + +- "RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one" + + 1. This error indicates that your module has parameters that were not used in producing loss. This phenomenon may be caused by running different branches in your code in DDP mode. + 2. You can set `find_unused_parameters = True` in the config to solve the above problems, but this will slow down the training speed. + 3. You can set `detect_anomalous_params = True` in the config or `model_wrapper_cfg = dict(type='MMDistributedDataParallel', detect_anomalous_params=True)` (More details please refer to [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/mmengine/model/wrappers/distributed.py#L91)) to get the name of those unused parameters. Note `detect_anomalous_params = True` will slow down the training speed, so it is recommended for debugging only. + +- Save the best model + + It can be turned on by configuring `default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=1, save_best='auto'),`. In the case of the `auto` parameter, the first key in the returned evaluation result will be used as the basis for selecting the best model. You can also directly set the key in the evaluation result to manually set it, for example, `save_best='coco/bbox_mAP'`. + +## Evaluation + +- COCO Dataset, AP or AR = -1 + 1. According to the definition of COCO dataset, the small and medium areas in an image are less than 1024 (32\*32), 9216 (96\*96), respectively. + 2. If the corresponding area has no object, the result of AP and AR will set to -1. + +## Model + +- `style` in ResNet + + The `style` parameter in ResNet allows either `pytorch` or `caffe` style. It indicates the difference in the Bottleneck module. Bottleneck is a stacking structure of `1x1-3x3-1x1` convolutional layers. In the case of `caffe` mode, the convolution layer with `stride=2` is the first `1x1` convolution, while in `pyorch` mode, it is the second `3x3` convolution has `stride=2`. A sample code is as below: + + ```python + if self.style == 'pytorch': + self.conv1_stride = 1 + self.conv2_stride = stride + else: + self.conv1_stride = stride + self.conv2_stride = 1 + ``` + +- ResNeXt parameter description + + ResNeXt comes from the paper [`Aggregated Residual Transformations for Deep Neural Networks`](https://arxiv.org/abs/1611.05431). It introduces group and uses “cardinality” to control the number of groups to achieve a balance between accuracy and complexity. It controls the basic width and grouping parameters of the internal Bottleneck module through two hyperparameters `baseWidth` and `cardinality`. An example configuration name in MMDetection is `mask_rcnn_x101_64x4d_fpn_mstrain-poly_3x_coco.py`, where `mask_rcnn` represents the algorithm using Mask R-CNN, `x101` represents the backbone network using ResNeXt-101, and `64x4d` represents that the bottleneck block has 64 group and each group has basic width of 4. + +- `norm_eval` in backbone + + Since the detection model is usually large and the input image resolution is high, this will result in a small batch of the detection model, which will make the variance of the statistics calculated by BatchNorm during the training process very large and not as stable as the statistics obtained during the pre-training of the backbone network . Therefore, the `norm_eval=True` mode is generally used in training, and the BatchNorm statistics in the pre-trained backbone network are directly used. The few algorithms that use large batches are the `norm_eval=False` mode, such as NASFPN. For the backbone network without ImageNet pre-training and the batch is relatively small, you can consider using `SyncBN`. diff --git a/mmdet_code/mmdetection/docs/en/notes/projects.md b/mmdet_code/mmdetection/docs/en/notes/projects.md new file mode 100644 index 0000000000000000000000000000000000000000..3123e2b020e912683190ef44389b2a14d0ee6c4a --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/notes/projects.md @@ -0,0 +1,57 @@ +# Projects based on MMDetection + +There are many projects built upon MMDetection. +We list some of them as examples of how to extend MMDetection for your own projects. +As the page might not be completed, please feel free to create a PR to update this page. + +## Projects as an extension + +Some projects extend the boundary of MMDetection for deployment or other research fields. +They reveal the potential of what MMDetection can do. We list several of them as below. + +- [OTEDetection](https://github.com/opencv/mmdetection): OpenVINO training extensions for object detection. +- [MMDetection3d](https://github.com/open-mmlab/mmdetection3d): OpenMMLab's next-generation platform for general 3D object detection. + +## Projects of papers + +There are also projects released with papers. +Some of the papers are published in top-tier conferences (CVPR, ICCV, and ECCV), the others are also highly influential. +To make this list also a reference for the community to develop and compare new object detection algorithms, we list them following the time order of top-tier conferences. +Methods already supported and maintained by MMDetection are not listed. + +- Involution: Inverting the Inherence of Convolution for Visual Recognition, CVPR21. [\[paper\]](https://arxiv.org/abs/2103.06255)[\[github\]](https://github.com/d-li14/involution) +- Multiple Instance Active Learning for Object Detection, CVPR 2021. [\[paper\]](https://openaccess.thecvf.com/content/CVPR2021/papers/Yuan_Multiple_Instance_Active_Learning_for_Object_Detection_CVPR_2021_paper.pdf)[\[github\]](https://github.com/yuantn/MI-AOD) +- Adaptive Class Suppression Loss for Long-Tail Object Detection, CVPR 2021. [\[paper\]](https://arxiv.org/abs/2104.00885)[\[github\]](https://github.com/CASIA-IVA-Lab/ACSL) +- Generalizable Pedestrian Detection: The Elephant In The Room, CVPR2021. [\[paper\]](https://arxiv.org/abs/2003.08799)[\[github\]](https://github.com/hasanirtiza/Pedestron) +- Group Fisher Pruning for Practical Network Compression, ICML2021. [\[paper\]](https://github.com/jshilong/FisherPruning/blob/main/resources/paper.pdf)[\[github\]](https://github.com/jshilong/FisherPruning) +- Overcoming Classifier Imbalance for Long-tail Object Detection with Balanced Group Softmax, CVPR2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/papers/Li_Overcoming_Classifier_Imbalance_for_Long-Tail_Object_Detection_With_Balanced_Group_CVPR_2020_paper.pdf)[\[github\]](https://github.com/FishYuLi/BalancedGroupSoftmax) +- Coherent Reconstruction of Multiple Humans from a Single Image, CVPR2020. [\[paper\]](https://jiangwenpl.github.io/multiperson/)[\[github\]](https://github.com/JiangWenPL/multiperson) +- Look-into-Object: Self-supervised Structure Modeling for Object Recognition, CVPR 2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/papers/Zhou_Look-Into-Object_Self-Supervised_Structure_Modeling_for_Object_Recognition_CVPR_2020_paper.pdf)[\[github\]](https://github.com/JDAI-CV/LIO) +- Video Panoptic Segmentation, CVPR2020. [\[paper\]](https://arxiv.org/abs/2006.11339)[\[github\]](https://github.com/mcahny/vps) +- D2Det: Towards High Quality Object Detection and Instance Segmentation, CVPR2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/html/Cao_D2Det_Towards_High_Quality_Object_Detection_and_Instance_Segmentation_CVPR_2020_paper.html)[\[github\]](https://github.com/JialeCao001/D2Det) +- CentripetalNet: Pursuing High-quality Keypoint Pairs for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.09119)[\[github\]](https://github.com/KiveeDong/CentripetalNet) +- Learning a Unified Sample Weighting Network for Object Detection, CVPR 2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/html/Cai_Learning_a_Unified_Sample_Weighting_Network_for_Object_Detection_CVPR_2020_paper.html)[\[github\]](https://github.com/caiqi/sample-weighting-network) +- Scale-equalizing Pyramid Convolution for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2005.03101) [\[github\]](https://github.com/jshilong/SEPC) +- Revisiting the Sibling Head in Object Detector, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.07540)[\[github\]](https://github.com/Sense-X/TSD) +- PolarMask: Single Shot Instance Segmentation with Polar Representation, CVPR2020. [\[paper\]](https://arxiv.org/abs/1909.13226)[\[github\]](https://github.com/xieenze/PolarMask) +- Hit-Detector: Hierarchical Trinity Architecture Search for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.11818)[\[github\]](https://github.com/ggjy/HitDet.pytorch) +- ZeroQ: A Novel Zero Shot Quantization Framework, CVPR2020. [\[paper\]](https://arxiv.org/abs/2001.00281)[\[github\]](https://github.com/amirgholami/ZeroQ) +- CBNet: A Novel Composite Backbone Network Architecture for Object Detection, AAAI2020. [\[paper\]](https://aaai.org/Papers/AAAI/2020GB/AAAI-LiuY.1833.pdf)[\[github\]](https://github.com/VDIGPKU/CBNet) +- RDSNet: A New Deep Architecture for Reciprocal Object Detection and Instance Segmentation, AAAI2020. [\[paper\]](https://arxiv.org/abs/1912.05070)[\[github\]](https://github.com/wangsr126/RDSNet) +- Training-Time-Friendly Network for Real-Time Object Detection, AAAI2020. [\[paper\]](https://arxiv.org/abs/1909.00700)[\[github\]](https://github.com/ZJULearning/ttfnet) +- Cascade RPN: Delving into High-Quality Region Proposal Network with Adaptive Convolution, NeurIPS 2019. [\[paper\]](https://arxiv.org/abs/1909.06720)[\[github\]](https://github.com/thangvubk/Cascade-RPN) +- Reasoning R-CNN: Unifying Adaptive Global Reasoning into Large-scale Object Detection, CVPR2019. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2019/papers/Xu_Reasoning-RCNN_Unifying_Adaptive_Global_Reasoning_Into_Large-Scale_Object_Detection_CVPR_2019_paper.pdf)[\[github\]](https://github.com/chanyn/Reasoning-RCNN) +- Learning RoI Transformer for Oriented Object Detection in Aerial Images, CVPR2019. [\[paper\]](https://arxiv.org/abs/1812.00155)[\[github\]](https://github.com/dingjiansw101/AerialDetection) +- SOLO: Segmenting Objects by Locations. [\[paper\]](https://arxiv.org/abs/1912.04488)[\[github\]](https://github.com/WXinlong/SOLO) +- SOLOv2: Dynamic, Faster and Stronger. [\[paper\]](https://arxiv.org/abs/2003.10152)[\[github\]](https://github.com/WXinlong/SOLO) +- Dense Peppoints: Representing Visual Objects with Dense Point Sets. [\[paper\]](https://arxiv.org/abs/1912.11473)[\[github\]](https://github.com/justimyhxu/Dense-RepPoints) +- IterDet: Iterative Scheme for Object Detection in Crowded Environments. [\[paper\]](https://arxiv.org/abs/2005.05708)[\[github\]](https://github.com/saic-vul/iterdet) +- Cross-Iteration Batch Normalization. [\[paper\]](https://arxiv.org/abs/2002.05712)[\[github\]](https://github.com/Howal/Cross-iterationBatchNorm) +- A Ranking-based, Balanced Loss Function Unifying Classification and Localisation in Object Detection, NeurIPS2020 [\[paper\]](https://arxiv.org/abs/2009.13592)[\[github\]](https://github.com/kemaloksuz/aLRPLoss) +- RelationNet++: Bridging Visual Representations for Object Detection via Transformer Decoder, NeurIPS2020 [\[paper\]](https://arxiv.org/abs/2010.15831)[\[github\]](https://github.com/microsoft/RelationNet2) +- Generalized Focal Loss V2: Learning Reliable Localization Quality Estimation for Dense Object Detection, CVPR2021[\[paper\]](https://arxiv.org/abs/2011.12885)[\[github\]](https://github.com/implus/GFocalV2) +- Swin Transformer: Hierarchical Vision Transformer using Shifted Windows, ICCV2021[\[paper\]](https://arxiv.org/abs/2103.14030)[\[github\]](https://github.com/SwinTransformer/) +- Focal Transformer: Focal Self-attention for Local-Global Interactions in Vision Transformers, NeurIPS2021[\[paper\]](https://arxiv.org/abs/2107.00641)[\[github\]](https://github.com/microsoft/Focal-Transformer) +- End-to-End Semi-Supervised Object Detection with Soft Teacher, ICCV2021[\[paper\]](https://arxiv.org/abs/2106.09018)[\[github\]](https://github.com/microsoft/SoftTeacher) +- CBNetV2: A Novel Composite Backbone Network Architecture for Object Detection [\[paper\]](http://arxiv.org/abs/2107.00420)[\[github\]](https://github.com/VDIGPKU/CBNetV2) +- Instances as Queries, ICCV2021 [\[paper\]](https://openaccess.thecvf.com/content/ICCV2021/papers/Fang_Instances_As_Queries_ICCV_2021_paper.pdf)[\[github\]](https://github.com/hustvl/QueryInst) diff --git a/mmdet_code/mmdetection/docs/en/overview.md b/mmdet_code/mmdetection/docs/en/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..7c7d96b70872bc5590f6b5c2dbc6ce4fb7afa938 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/overview.md @@ -0,0 +1,54 @@ +# OVERVIEW + +This chapter introduces you to the framework of MMDetection, and provides links to detailed tutorials about MMDetection. + +## What is MMDetection + +![image](https://user-images.githubusercontent.com/12907710/137271636-56ba1cd2-b110-4812-8221-b4c120320aa9.png) + +MMDetection is an object detection toolbox that contains a rich set of object detection, instance segmentation, and panoptic segmentation methods as well as related components and modules, and below is its whole framework: + +MMDetection consists of 7 main parts, apis, structures, datasets, models, engine, evaluation and visualization. + +- **apis** provides high-level APIs for model inference. +- **structures** provides data structures like bbox, mask, and DetDataSample. +- **datasets** supports various dataset for object detection, instance segmentation, and panoptic segmentation. + - **transforms** contains a lot of useful data augmentation transforms. + - **samplers** defines different data loader sampling strategy. +- **models** is the most vital part for detectors and contains different components of a detector. + - **detectors** defines all of the detection model classes. + - **data_preprocessors** is for preprocessing the input data of the model. + - **backbones** contains various backbone networks. + - **necks** contains various neck components. + - **dense_heads** contains various detection heads that perform dense predictions. + - **roi_heads** contains various detection heads that predict from RoIs. + - **seg_heads** contains various segmentation heads. + - **losses** contains various loss functions. + - **task_modules** provides modules for detection tasks. E.g. assigners, samplers, box coders, and prior generators. + - **layers** provides some basic neural network layers. +- **engine** is a part for runtime components. + - **runner** provides extensions for [MMEngine's runner](https://mmengine.readthedocs.io/en/latest/tutorials/runner.html). + - **schedulers** provides schedulers for adjusting optimization hyperparameters. + - **optimizers** provides optimizers and optimizer wrappers. + - **hooks** provides various hooks of the runner. +- **evaluation** provides different metrics for evaluating model performance. +- **visualization** is for visualizing detection results. + +## How to Use this Guide + +Here is a detailed step-by-step guide to learn more about MMDetection: + +1. For installation instructions, please see [get_started](get_started.md). + +2. Refer to the below tutorials for the basic usage of MMDetection. + + - [Train and Test](https://mmdetection.readthedocs.io/en/latest/user_guides/index.html#train-test) + + - [Useful Tools](https://mmdetection.readthedocs.io/en/latest/user_guides/index.html#useful-tools) + +3. Refer to the below tutorials to dive deeper: + + - [Basic Concepts](https://mmdetection.readthedocs.io/en/latest/advanced_guides/index.html#basic-concepts) + - [Component Customization](https://mmdetection.readthedocs.io/en/latest/advanced_guides/index.html#component-customization) + +4. For users of MMDetection 2.x version, we provide a guide to help you adapt to the new version. You can find it in the [migration guide](./migration/migration.md). diff --git a/mmdet_code/mmdetection/docs/en/stat.py b/mmdet_code/mmdetection/docs/en/stat.py new file mode 100644 index 0000000000000000000000000000000000000000..f0589e337e0da6e3dbac0e2827433c77709064ea --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/stat.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +import functools as func +import glob +import os.path as osp +import re + +import numpy as np + +url_prefix = 'https://github.com/open-mmlab/mmdetection/blob/main/configs' + +files = sorted(glob.glob('../../configs/*/README.md')) + +stats = [] +titles = [] +num_ckpts = 0 + +for f in files: + url = osp.dirname(f.replace('../../configs', url_prefix)) + + with open(f, 'r') as content_file: + content = content_file.read() + + title = content.split('\n')[0].replace('# ', '').strip() + ckpts = set(x.lower().strip() + for x in re.findall(r'\[model\]\((https?.*)\)', content)) + + if len(ckpts) == 0: + continue + + _papertype = [x for x in re.findall(r'\[([A-Z]+)\]', content)] + assert len(_papertype) > 0 + papertype = _papertype[0] + + paper = set([(papertype, title)]) + + titles.append(title) + num_ckpts += len(ckpts) + + statsmsg = f""" +\t* [{papertype}] [{title}]({url}) ({len(ckpts)} ckpts) +""" + stats.append((paper, ckpts, statsmsg)) + +allpapers = func.reduce(lambda a, b: a.union(b), [p for p, _, _ in stats]) +msglist = '\n'.join(x for _, _, x in stats) + +papertypes, papercounts = np.unique([t for t, _ in allpapers], + return_counts=True) +countstr = '\n'.join( + [f' - {t}: {c}' for t, c in zip(papertypes, papercounts)]) + +modelzoo = f""" +# Model Zoo Statistics + +* Number of papers: {len(set(titles))} +{countstr} + +* Number of checkpoints: {num_ckpts} + +{msglist} +""" + +with open('modelzoo_statistics.md', 'w') as f: + f.write(modelzoo) diff --git a/mmdet_code/mmdetection/docs/en/switch_language.md b/mmdet_code/mmdetection/docs/en/switch_language.md new file mode 100644 index 0000000000000000000000000000000000000000..b2c4ad9db394a147483388b245ffb3c72f81642e --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/switch_language.md @@ -0,0 +1,3 @@ +## English + +## 简体中文 diff --git a/mmdet_code/mmdetection/docs/en/user_guides/config.md b/mmdet_code/mmdetection/docs/en/user_guides/config.md new file mode 100644 index 0000000000000000000000000000000000000000..69bd91194e0da67a40733a72a715374192767d50 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/config.md @@ -0,0 +1,612 @@ +# Learn about Configs + +MMDetection and other OpenMMLab repositories use [MMEngine's config system](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html). It has a modular and inheritance design, which is convenient to conduct various experiments. + +## Config file content + +MMDetection uses a modular design, all modules with different functions can be configured through the config. Taking Mask R-CNN as an example, we will introduce each field in the config according to different function modules: + +### Model config + +In MMDetection's config, we use `model` to set up detection algorithm components. In addition to neural network components such as `backbone`, `neck`, etc, it also requires `data_preprocessor`, `train_cfg`, and `test_cfg`. `data_preprocessor` is responsible for processing a batch of data output by dataloader. `train_cfg`, and `test_cfg` in the model config are for training and testing hyperparameters of the components. + +```python +model = dict( + type='MaskRCNN', # The name of detector + data_preprocessor=dict( # The config of data preprocessor, usually includes image normalization and padding + type='DetDataPreprocessor', # The type of the data preprocessor, refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.data_preprocessors.DetDataPreprocessor + mean=[123.675, 116.28, 103.53], # Mean values used to pre-training the pre-trained backbone models, ordered in R, G, B + std=[58.395, 57.12, 57.375], # Standard variance used to pre-training the pre-trained backbone models, ordered in R, G, B + bgr_to_rgb=True, # whether to convert image from BGR to RGB + pad_mask=True, # whether to pad instance masks + pad_size_divisor=32), # The size of padded image should be divisible by ``pad_size_divisor`` + backbone=dict( # The config of backbone + type='ResNet', # The type of backbone network. Refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.backbones.ResNet + depth=50, # The depth of backbone, usually it is 50 or 101 for ResNet and ResNext backbones. + num_stages=4, # Number of stages of the backbone. + out_indices=(0, 1, 2, 3), # The index of output feature maps produced in each stage + frozen_stages=1, # The weights in the first stage are frozen + norm_cfg=dict( # The config of normalization layers. + type='BN', # Type of norm layer, usually it is BN or GN + requires_grad=True), # Whether to train the gamma and beta in BN + norm_eval=True, # Whether to freeze the statistics in BN + style='pytorch', # The style of backbone, 'pytorch' means that stride 2 layers are in 3x3 Conv, 'caffe' means stride 2 layers are in 1x1 Convs. + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), # The ImageNet pretrained backbone to be loaded + neck=dict( + type='FPN', # The neck of detector is FPN. We also support 'NASFPN', 'PAFPN', etc. Refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.necks.FPN for more details. + in_channels=[256, 512, 1024, 2048], # The input channels, this is consistent with the output channels of backbone + out_channels=256, # The output channels of each level of the pyramid feature map + num_outs=5), # The number of output scales + rpn_head=dict( + type='RPNHead', # The type of RPN head is 'RPNHead', we also support 'GARPNHead', etc. Refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.dense_heads.RPNHead for more details. + in_channels=256, # The input channels of each input feature map, this is consistent with the output channels of neck + feat_channels=256, # Feature channels of convolutional layers in the head. + anchor_generator=dict( # The config of anchor generator + type='AnchorGenerator', # Most of methods use AnchorGenerator, SSD Detectors uses `SSDAnchorGenerator`. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/prior_generators/anchor_generator.py#L18 for more details + scales=[8], # Basic scale of the anchor, the area of the anchor in one position of a feature map will be scale * base_sizes + ratios=[0.5, 1.0, 2.0], # The ratio between height and width. + strides=[4, 8, 16, 32, 64]), # The strides of the anchor generator. This is consistent with the FPN feature strides. The strides will be taken as base_sizes if base_sizes is not set. + bbox_coder=dict( # Config of box coder to encode and decode the boxes during training and testing + type='DeltaXYWHBBoxCoder', # Type of box coder. 'DeltaXYWHBBoxCoder' is applied for most of the methods. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/coders/delta_xywh_bbox_coder.py#L13 for more details. + target_means=[0.0, 0.0, 0.0, 0.0], # The target means used to encode and decode boxes + target_stds=[1.0, 1.0, 1.0, 1.0]), # The standard variance used to encode and decode boxes + loss_cls=dict( # Config of loss function for the classification branch + type='CrossEntropyLoss', # Type of loss for classification branch, we also support FocalLoss etc. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/cross_entropy_loss.py#L201 for more details + use_sigmoid=True, # RPN usually performs two-class classification, so it usually uses the sigmoid function. + loss_weight=1.0), # Loss weight of the classification branch. + loss_bbox=dict( # Config of loss function for the regression branch. + type='L1Loss', # Type of loss, we also support many IoU Losses and smooth L1-loss, etc. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/smooth_l1_loss.py#L56 for implementation. + loss_weight=1.0)), # Loss weight of the regression branch. + roi_head=dict( # RoIHead encapsulates the second stage of two-stage/cascade detectors. + type='StandardRoIHead', + bbox_roi_extractor=dict( # RoI feature extractor for bbox regression. + type='SingleRoIExtractor', # Type of the RoI feature extractor, most of methods uses SingleRoIExtractor. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/roi_extractors/single_level_roi_extractor.py#L13 for details. + roi_layer=dict( # Config of RoI Layer + type='RoIAlign', # Type of RoI Layer, DeformRoIPoolingPack and ModulatedDeformRoIPoolingPack are also supported. Refer to https://mmcv.readthedocs.io/en/latest/api.html#mmcv.ops.RoIAlign for details. + output_size=7, # The output size of feature maps. + sampling_ratio=0), # Sampling ratio when extracting the RoI features. 0 means adaptive ratio. + out_channels=256, # output channels of the extracted feature. + featmap_strides=[4, 8, 16, 32]), # Strides of multi-scale feature maps. It should be consistent with the architecture of the backbone. + bbox_head=dict( # Config of box head in the RoIHead. + type='Shared2FCBBoxHead', # Type of the bbox head, Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py#L220 for implementation details. + in_channels=256, # Input channels for bbox head. This is consistent with the out_channels in roi_extractor + fc_out_channels=1024, # Output feature channels of FC layers. + roi_feat_size=7, # Size of RoI features + num_classes=80, # Number of classes for classification + bbox_coder=dict( # Box coder used in the second stage. + type='DeltaXYWHBBoxCoder', # Type of box coder. 'DeltaXYWHBBoxCoder' is applied for most of the methods. + target_means=[0.0, 0.0, 0.0, 0.0], # Means used to encode and decode box + target_stds=[0.1, 0.1, 0.2, 0.2]), # Standard variance for encoding and decoding. It is smaller since the boxes are more accurate. [0.1, 0.1, 0.2, 0.2] is a conventional setting. + reg_class_agnostic=False, # Whether the regression is class agnostic. + loss_cls=dict( # Config of loss function for the classification branch + type='CrossEntropyLoss', # Type of loss for classification branch, we also support FocalLoss etc. + use_sigmoid=False, # Whether to use sigmoid. + loss_weight=1.0), # Loss weight of the classification branch. + loss_bbox=dict( # Config of loss function for the regression branch. + type='L1Loss', # Type of loss, we also support many IoU Losses and smooth L1-loss, etc. + loss_weight=1.0)), # Loss weight of the regression branch. + mask_roi_extractor=dict( # RoI feature extractor for mask generation. + type='SingleRoIExtractor', # Type of the RoI feature extractor, most of methods uses SingleRoIExtractor. + roi_layer=dict( # Config of RoI Layer that extracts features for instance segmentation + type='RoIAlign', # Type of RoI Layer, DeformRoIPoolingPack and ModulatedDeformRoIPoolingPack are also supported + output_size=14, # The output size of feature maps. + sampling_ratio=0), # Sampling ratio when extracting the RoI features. + out_channels=256, # Output channels of the extracted feature. + featmap_strides=[4, 8, 16, 32]), # Strides of multi-scale feature maps. + mask_head=dict( # Mask prediction head + type='FCNMaskHead', # Type of mask head, refer to https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.roi_heads.FCNMaskHead for implementation details. + num_convs=4, # Number of convolutional layers in mask head. + in_channels=256, # Input channels, should be consistent with the output channels of mask roi extractor. + conv_out_channels=256, # Output channels of the convolutional layer. + num_classes=80, # Number of class to be segmented. + loss_mask=dict( # Config of loss function for the mask branch. + type='CrossEntropyLoss', # Type of loss used for segmentation + use_mask=True, # Whether to only train the mask in the correct class. + loss_weight=1.0))), # Loss weight of mask branch. + train_cfg = dict( # Config of training hyperparameters for rpn and rcnn + rpn=dict( # Training config of rpn + assigner=dict( # Config of assigner + type='MaxIoUAssigner', # Type of assigner, MaxIoUAssigner is used for many common detectors. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/assigners/max_iou_assigner.py#L14 for more details. + pos_iou_thr=0.7, # IoU >= threshold 0.7 will be taken as positive samples + neg_iou_thr=0.3, # IoU < threshold 0.3 will be taken as negative samples + min_pos_iou=0.3, # The minimal IoU threshold to take boxes as positive samples + match_low_quality=True, # Whether to match the boxes under low quality (see API doc for more details). + ignore_iof_thr=-1), # IoF threshold for ignoring bboxes + sampler=dict( # Config of positive/negative sampler + type='RandomSampler', # Type of sampler, PseudoSampler and other samplers are also supported. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/samplers/random_sampler.py#L14 for implementation details. + num=256, # Number of samples + pos_fraction=0.5, # The ratio of positive samples in the total samples. + neg_pos_ub=-1, # The upper bound of negative samples based on the number of positive samples. + add_gt_as_proposals=False), # Whether add GT as proposals after sampling. + allowed_border=-1, # The border allowed after padding for valid anchors. + pos_weight=-1, # The weight of positive samples during training. + debug=False), # Whether to set the debug mode + rpn_proposal=dict( # The config to generate proposals during training + nms_across_levels=False, # Whether to do NMS for boxes across levels. Only work in `GARPNHead`, naive rpn does not support do nms cross levels. + nms_pre=2000, # The number of boxes before NMS + nms_post=1000, # The number of boxes to be kept by NMS. Only work in `GARPNHead`. + max_per_img=1000, # The number of boxes to be kept after NMS. + nms=dict( # Config of NMS + type='nms', # Type of NMS + iou_threshold=0.7 # NMS threshold + ), + min_bbox_size=0), # The allowed minimal box size + rcnn=dict( # The config for the roi heads. + assigner=dict( # Config of assigner for second stage, this is different for that in rpn + type='MaxIoUAssigner', # Type of assigner, MaxIoUAssigner is used for all roi_heads for now. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/assigners/max_iou_assigner.py#L14 for more details. + pos_iou_thr=0.5, # IoU >= threshold 0.5 will be taken as positive samples + neg_iou_thr=0.5, # IoU < threshold 0.5 will be taken as negative samples + min_pos_iou=0.5, # The minimal IoU threshold to take boxes as positive samples + match_low_quality=False, # Whether to match the boxes under low quality (see API doc for more details). + ignore_iof_thr=-1), # IoF threshold for ignoring bboxes + sampler=dict( + type='RandomSampler', # Type of sampler, PseudoSampler and other samplers are also supported. Refer to https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/samplers/random_sampler.py#L14 for implementation details. + num=512, # Number of samples + pos_fraction=0.25, # The ratio of positive samples in the total samples. + neg_pos_ub=-1, # The upper bound of negative samples based on the number of positive samples. + add_gt_as_proposals=True + ), # Whether add GT as proposals after sampling. + mask_size=28, # Size of mask + pos_weight=-1, # The weight of positive samples during training. + debug=False)), # Whether to set the debug mode + test_cfg = dict( # Config for testing hyperparameters for rpn and rcnn + rpn=dict( # The config to generate proposals during testing + nms_across_levels=False, # Whether to do NMS for boxes across levels. Only work in `GARPNHead`, naive rpn does not support do nms cross levels. + nms_pre=1000, # The number of boxes before NMS + nms_post=1000, # The number of boxes to be kept by NMS. Only work in `GARPNHead`. + max_per_img=1000, # The number of boxes to be kept after NMS. + nms=dict( # Config of NMS + type='nms', #Type of NMS + iou_threshold=0.7 # NMS threshold + ), + min_bbox_size=0), # The allowed minimal box size + rcnn=dict( # The config for the roi heads. + score_thr=0.05, # Threshold to filter out boxes + nms=dict( # Config of NMS in the second stage + type='nms', # Type of NMS + iou_thr=0.5), # NMS threshold + max_per_img=100, # Max number of detections of each image + mask_thr_binary=0.5))) # Threshold of mask prediction +``` + +### Dataset and evaluator config + +[Dataloaders](https://mmengine.readthedocs.io/en/latest/tutorials/dataset.html) are required for the training, validation, and testing of the [runner](https://mmengine.readthedocs.io/en/latest/tutorials/runner.html). Dataset and data pipeline need to be set to build the dataloader. Due to the complexity of this part, we use intermediate variables to simplify the writing of dataloader configs. + +```python +dataset_type = 'CocoDataset' # Dataset type, this will be used to define the dataset +data_root = 'data/coco/' # Root path of data +backend_args = None # Arguments to instantiate the corresponding file backend + +train_pipeline = [ # Training data processing pipeline + dict(type='LoadImageFromFile', backend_args=backend_args), # First pipeline to load images from file path + dict( + type='LoadAnnotations', # Second pipeline to load annotations for current image + with_bbox=True, # Whether to use bounding box, True for detection + with_mask=True, # Whether to use instance mask, True for instance segmentation + poly2mask=True), # Whether to convert the polygon mask to instance mask, set False for acceleration and to save memory + dict( + type='Resize', # Pipeline that resizes the images and their annotations + scale=(1333, 800), # The largest scale of the images + keep_ratio=True # Whether to keep the ratio between height and width + ), + dict( + type='RandomFlip', # Augmentation pipeline that flips the images and their annotations + prob=0.5), # The probability to flip + dict(type='PackDetInputs') # Pipeline that formats the annotation data and decides which keys in the data should be packed into data_samples +] +test_pipeline = [ # Testing data processing pipeline + dict(type='LoadImageFromFile', backend_args=backend_args), # First pipeline to load images from file path + dict(type='Resize', scale=(1333, 800), keep_ratio=True), # Pipeline that resizes the images + dict( + type='PackDetInputs', # Pipeline that formats the annotation data and decides which keys in the data should be packed into data_samples + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( # Train dataloader config + batch_size=2, # Batch size of a single GPU + num_workers=2, # Worker to pre-fetch data for each single GPU + persistent_workers=True, # If ``True``, the dataloader will not shut down the worker processes after an epoch end, which can accelerate training speed. + sampler=dict( # training data sampler + type='DefaultSampler', # DefaultSampler which supports both distributed and non-distributed training. Refer to https://mmengine.readthedocs.io/en/latest/api/generated/mmengine.dataset.DefaultSampler.html#mmengine.dataset.DefaultSampler + shuffle=True), # randomly shuffle the training data in each epoch + batch_sampler=dict(type='AspectRatioBatchSampler'), # Batch sampler for grouping images with similar aspect ratio into a same batch. It can reduce GPU memory cost. + dataset=dict( # Train dataset config + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', # Path of annotation file + data_prefix=dict(img='train2017/'), # Prefix of image path + filter_cfg=dict(filter_empty_gt=True, min_size=32), # Config of filtering images and annotations + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( # Validation dataloader config + batch_size=1, # Batch size of a single GPU. If batch-size > 1, the extra padding area may influence the performance. + num_workers=2, # Worker to pre-fetch data for each single GPU + persistent_workers=True, # If ``True``, the dataloader will not shut down the worker processes after an epoch end, which can accelerate training speed. + drop_last=False, # Whether to drop the last incomplete batch, if the dataset size is not divisible by the batch size + sampler=dict( + type='DefaultSampler', + shuffle=False), # not shuffle during validation and testing + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, # Turn on the test mode of the dataset to avoid filtering annotations or images + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader # Testing dataloader config +``` + +[Evaluators](https://mmengine.readthedocs.io/en/latest/tutorials/evaluation.html) are used to compute the metrics of the trained model on the validation and testing datasets. The config of evaluators consists of one or a list of metric configs: + +```python +val_evaluator = dict( # Validation evaluator config + type='CocoMetric', # The coco metric used to evaluate AR, AP, and mAP for detection and instance segmentation + ann_file=data_root + 'annotations/instances_val2017.json', # Annotation file path + metric=['bbox', 'segm'], # Metrics to be evaluated, `bbox` for detection and `segm` for instance segmentation + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator # Testing evaluator config +``` + +Since the test dataset has no annotation files, the test_dataloader and test_evaluator config in MMDetection are generally equal to the val's. If you want to save the detection results on the test dataset, you can write the config like this: + +```python +# inference on test dataset and +# format the output results for submission. +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'annotations/image_info_test-dev2017.json', + data_prefix=dict(img='test2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/image_info_test-dev2017.json', + metric=['bbox', 'segm'], # Metrics to be evaluated + format_only=True, # Only format and save the results to coco json file + outfile_prefix='./work_dirs/coco_detection/test') # The prefix of output json files +``` + +### Training and testing config + +MMEngine's runner uses Loop to control the training, validation, and testing processes. +Users can set the maximum training epochs and validation intervals with these fields. + +```python +train_cfg = dict( + type='EpochBasedTrainLoop', # The training loop type. Refer to https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py + max_epochs=12, # Maximum training epochs + val_interval=1) # Validation intervals. Run validation every epoch. +val_cfg = dict(type='ValLoop') # The validation loop type +test_cfg = dict(type='TestLoop') # The testing loop type +``` + +### Optimization config + +`optim_wrapper` is the field to configure optimization-related settings. The optimizer wrapper not only provides the functions of the optimizer, but also supports functions such as gradient clipping, mixed precision training, etc. Find more in [optimizer wrapper tutorial](https://mmengine.readthedocs.io/en/latest/tutorials/optim_wrapper.html). + +```python +optim_wrapper = dict( # Optimizer wrapper config + type='OptimWrapper', # Optimizer wrapper type, switch to AmpOptimWrapper to enable mixed precision training. + optimizer=dict( # Optimizer config. Support all kinds of optimizers in PyTorch. Refer to https://pytorch.org/docs/stable/optim.html#algorithms + type='SGD', # Stochastic gradient descent optimizer + lr=0.02, # The base learning rate + momentum=0.9, # Stochastic gradient descent with momentum + weight_decay=0.0001), # Weight decay of SGD + clip_grad=None, # Gradient clip option. Set None to disable gradient clip. Find usage in https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html + ) +``` + +`param_scheduler` is a field that configures methods of adjusting optimization hyperparameters such as learning rate and momentum. Users can combine multiple schedulers to create a desired parameter adjustment strategy. Find more in [parameter scheduler tutorial](https://mmengine.readthedocs.io/en/latest/tutorials/param_scheduler.html) and [parameter scheduler API documents](https://mmengine.readthedocs.io/en/latest/api/generated/mmengine.optim._ParamScheduler.html#mmengine.optim._ParamScheduler) + +```python +param_scheduler = [ + # Linear learning rate warm-up scheduler + dict( + type='LinearLR', # Use linear policy to warmup learning rate + start_factor=0.001, # The ratio of the starting learning rate used for warmup + by_epoch=False, # The warmup learning rate is updated by iteration + begin=0, # Start from the first iteration + end=500), # End the warmup at the 500th iteration + # The main LRScheduler + dict( + type='MultiStepLR', # Use multi-step learning rate policy during training + by_epoch=True, # The learning rate is updated by epoch + begin=0, # Start from the first epoch + end=12, # End at the 12th epoch + milestones=[8, 11], # Epochs to decay the learning rate + gamma=0.1) # The learning rate decay ratio +] +``` + +### Hook config + +Users can attach Hooks to training, validation, and testing loops to insert some operations during running. There are two different hook fields, one is `default_hooks` and the other is `custom_hooks`. + +`default_hooks` is a dict of hook configs, and they are the hooks must be required at the runtime. They have default priority which should not be modified. If not set, runner will use the default values. To disable a default hook, users can set its config to `None`. Find more in [HOOK](https://mmengine.readthedocs.io/en/latest/tutorials/hook.html). + +```python +default_hooks = dict( + timer=dict(type='IterTimerHook'), # Update the time spent during iteration into message hub + logger=dict(type='LoggerHook', interval=50), # Collect logs from different components of Runner and write them to terminal, JSON file, tensorboard and wandb .etc + param_scheduler=dict(type='ParamSchedulerHook'), # update some hyper-parameters of optimizer + checkpoint=dict(type='CheckpointHook', interval=1), # Save checkpoints periodically + sampler_seed=dict(type='DistSamplerSeedHook'), # Ensure distributed Sampler shuffle is active + visualization=dict(type='DetVisualizationHook')) # Detection Visualization Hook. Used to visualize validation and testing process prediction results +``` + +`custom_hooks` is a list of all other hook configs. Users can develop their own hooks and insert them in this field. + +```python +custom_hooks = [] +``` + +### Runtime config + +```python +default_scope = 'mmdet' # The default registry scope to find modules. Refer to https://mmengine.readthedocs.io/en/latest/advanced_tutorials/registry.html + +env_cfg = dict( + cudnn_benchmark=False, # Whether to enable cudnn benchmark + mp_cfg=dict( # Multi-processing config + mp_start_method='fork', # Use fork to start multi-processing threads. 'fork' usually faster than 'spawn' but maybe unsafe. See discussion in https://github.com/pytorch/pytorch/issues/1355 + opencv_num_threads=0), # Disable opencv multi-threads to avoid system being overloaded + dist_cfg=dict(backend='nccl'), # Distribution configs +) + +vis_backends = [dict(type='LocalVisBackend')] # Visualization backends. Refer to https://mmengine.readthedocs.io/en/latest/advanced_tutorials/visualization.html +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +log_processor = dict( + type='LogProcessor', # Log processor to process runtime logs + window_size=50, # Smooth interval of log values + by_epoch=True) # Whether to format logs with epoch type. Should be consistent with the train loop's type. + +log_level = 'INFO' # The level of logging. +load_from = None # Load model checkpoint as a pre-trained model from a given path. This will not resume training. +resume = False # Whether to resume from the checkpoint defined in `load_from`. If `load_from` is None, it will resume the latest checkpoint in the `work_dir`. +``` + +## Iter-based config + +MMEngine's Runner also provides an iter-based training loop except for epoch-based. +To use iter-based training, users should modify the `train_cfg`, `param_scheduler`, `train_dataloader`, `default_hooks`, and `log_processor`. +Here is an example of changing an epoch-based RetinaNet config to iter-based: `configs/retinanet/retinanet_r50_fpn_90k_coco.py` + +```python +# Iter-based training config +train_cfg = dict( + _delete_=True, # Ignore the base config setting (optional) + type='IterBasedTrainLoop', # Use iter-based training loop + max_iters=90000, # Maximum iterations + val_interval=10000) # Validation interval + + +# Change the scheduler to iter-based +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=90000, + by_epoch=False, + milestones=[60000, 80000], + gamma=0.1) +] + +# Switch to InfiniteSampler to avoid dataloader restart +train_dataloader = dict(sampler=dict(type='InfiniteSampler')) + +# Change the checkpoint saving interval to iter-based +default_hooks = dict(checkpoint=dict(by_epoch=False, interval=10000)) + +# Change the log format to iter-based +log_processor = dict(by_epoch=False) +``` + +## Config file inheritance + +There are 4 basic component types under `config/_base_`, dataset, model, schedule, default_runtime. +Many methods could be easily constructed with one of these models like Faster R-CNN, Mask R-CNN, Cascade R-CNN, RPN, SSD. +The configs that are composed by components from `_base_` are called the _primitive_. + +For all configs under the same folder, it is recommended to have only **one** _primitive_ config. All other configs should inherit from the _primitive_ config. In this way, the maximum of inheritance level is 3. + +For easy understanding, we recommend contributors to inherit from existing methods. +For example, if some modification is made based on Faster R-CNN, users may first inherit the basic Faster R-CNN structure by specifying `_base_ = ../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py`, then modify the necessary fields in the config files. + +If you are building an entirely new method that does not share the structure with any of the existing methods, you may create a folder `xxx_rcnn` under `configs`, + +Please refer to [mmengine config tutorial](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html) for detailed documentation. + +By setting the `_base_` field, we can set which files the current configuration file inherits from. + +When `_base_` is a string of a file path, it means inheriting the contents from one config file. + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' +``` + +When `_base_` is a list of multiple file paths, it means inheriting from multiple files. + +```python +_base_ = [ + '../_base_/models/mask-rcnn_r50_fpn.py', + '../_base_/datasets/coco_instance.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +``` + +If you wish to inspect the config file, you may run `python tools/misc/print_config.py /PATH/TO/CONFIG` to see the complete config. + +### Ignore some fields in the base configs + +Sometimes, you may set `_delete_=True` to ignore some of the fields in base configs. +You may refer to [mmengine config tutorial](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html) for a simple illustration. + +In MMDetection, for example, to change the backbone of Mask R-CNN with the following config. + +```python +model = dict( + type='MaskRCNN', + 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', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict(...), + rpn_head=dict(...), + roi_head=dict(...)) +``` + +`ResNet` and `HRNet` use different keywords to construct. + +```python +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + _delete_=True, + type='HRNet', + extra=dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128)), + stage4=dict( + num_modules=3, + num_branches=4, + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256))), + init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://msra/hrnetv2_w32')), + neck=dict(...)) +``` + +The `_delete_=True` would replace all old keys in `backbone` field with new keys. + +### Use intermediate variables in configs + +Some intermediate variables are used in the configs files, like `train_pipeline`/`test_pipeline` in datasets. +It's worth noting that when modifying intermediate variables in the children configs, users need to pass the intermediate variables into corresponding fields again. +For example, we would like to use a multi-scale strategy to train a Mask R-CNN. `train_pipeline`/`test_pipeline` are intermediate variables we would like to modify. + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', scale=[(1333, 640), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) +val_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +test_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +``` + +We first define the new `train_pipeline`/`test_pipeline` and pass them into dataloader fields. + +Similarly, if we would like to switch from `SyncBN` to `BN` or `MMSyncBN`, we need to substitute every `norm_cfg` in the config. + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' +norm_cfg = dict(type='BN', requires_grad=True) +model = dict( + backbone=dict(norm_cfg=norm_cfg), + neck=dict(norm_cfg=norm_cfg), + ...) +``` + +### Reuse variables in \_base\_ file + +If the users want to reuse the variables in the base file, they can get a copy of the corresponding variable by using `{{_base_.xxx}}`. E.g: + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' + +a = {{_base_.model}} # Variable `a` is equal to the `model` defined in `_base_` +``` + +## Modify config through script arguments + +When submitting jobs using `tools/train.py` or `tools/test.py`, you may specify `--cfg-options` to in-place modify the config. + +- Update config keys of dict chains. + + The config options can be specified following the order of the dict keys in the original config. + For example, `--cfg-options model.backbone.norm_eval=False` changes the all BN modules in model backbones to `train` mode. + +- Update keys inside a list of configs. + + Some config dicts are composed as a list in your config. For example, the training pipeline `train_dataloader.dataset.pipeline` is normally a list + e.g. `[dict(type='LoadImageFromFile'), ...]`. If you want to change `'LoadImageFromFile'` to `'LoadImageFromNDArray'` in the pipeline, + you may specify `--cfg-options data.train.pipeline.0.type=LoadImageFromNDArray`. + +- Update values of list/tuples. + + If the value to be updated is a list or a tuple. For example, the config file normally sets `model.data_preprocessor.mean=[123.675, 116.28, 103.53]`. If you want to + change the mean values, you may specify `--cfg-options model.data_preprocessor.mean="[127,127,127]"`. Note that the quotation mark `"` is necessary to + support list/tuple data types, and **NO** white space is allowed inside the quotation marks in the specified value. + +## Config name style + +We follow the below style to name config files. Contributors are advised to follow the same style. + +``` +{algorithm name}_{model component names [component1]_[component2]_[...]}_{training settings}_{training dataset information}_{testing dataset information}.py +``` + +The file name is divided into five parts. All parts and components are connected with `_` and words of each part or component should be connected with `-`. + +- `{algorithm name}`: The name of the algorithm. It can be a detector name such as `faster-rcnn`, `mask-rcnn`, etc. Or can be a semi-supervised or knowledge-distillation algorithm such as `soft-teacher`, `lad`. etc. +- `{model component names}`: Names of the components used in the algorithm such as backbone, neck, etc. For example, `r50-caffe_fpn_gn-head` means using caffe-style ResNet50, FPN and detection head with Group Norm in the algorithm. +- `{training settings}`: Information of training settings such as batch size, augmentations, loss trick, scheduler, and epochs/iterations. For example: `4xb4-mixup-giou-coslr-100e` means using 8-gpus x 4-images-per-gpu, mixup augmentation, GIoU loss, cosine annealing learning rate, and train 100 epochs. + Some abbreviations: + - `{gpu x batch_per_gpu}`: GPUs and samples per GPU. `bN` indicates N batch size per GPU. E.g. `4xb4` is the short term of 4-GPUs x 4-images-per-GPU. And `8xb2` is used by default if not mentioned. + - `{schedule}`: training schedule, options are `1x`, `2x`, `20e`, etc. + `1x` and `2x` means 12 epochs and 24 epochs respectively. + `20e` is adopted in cascade models, which denotes 20 epochs. + For `1x`/`2x`, the initial learning rate decays by a factor of 10 at the 8/16th and 11/22th epochs. + For `20e`, the initial learning rate decays by a factor of 10 at the 16th and 19th epochs. +- `{training dataset information}`: Training dataset names like `coco`, `coco-panoptic`, `cityscapes`, `voc-0712`, `wider-face`. +- `{testing dataset information}` (optional): Testing dataset name for models trained on one dataset but tested on another. If not mentioned, it means the model was trained and tested on the same dataset type. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/dataset_prepare.md b/mmdet_code/mmdetection/docs/en/user_guides/dataset_prepare.md new file mode 100644 index 0000000000000000000000000000000000000000..1e0259a118de1c149d83fc3aee0778690dc28654 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/dataset_prepare.md @@ -0,0 +1,310 @@ +# Dataset Prepare + +### Basic Detection Dataset Preparation + +MMDetection supports multiple public datasets including COCO, Pascal VOC, CityScapes, and [more](../../../configs/_base_/datasets). + +Public datasets like [Pascal VOC](http://host.robots.ox.ac.uk/pascal/VOC/index.html) or mirror and [COCO](https://cocodataset.org/#download) are available from official websites or mirrors. Note: In the detection task, Pascal VOC 2012 is an extension of Pascal VOC 2007 without overlap, and we usually use them together. +It is recommended to download and extract the dataset somewhere outside the project directory and symlink the dataset root to `$MMDETECTION/data` as below. +If your folder structure is different, you may need to change the corresponding paths in config files. + +We provide a script to download datasets such as COCO, you can run `python tools/misc/download_dataset.py --dataset-name coco2017` to download COCO dataset. +For users in China, more datasets can be downloaded from the opensource dataset platform: [OpenDataLab](https://opendatalab.com/?source=OpenMMLab%20GitHub). + +For more usage please refer to [dataset-download](./useful_tools.md#dataset-download) + +```text +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ ├── cityscapes +│ │ ├── annotations +│ │ ├── leftImg8bit +│ │ │ ├── train +│ │ │ ├── val +│ │ ├── gtFine +│ │ │ ├── train +│ │ │ ├── val +│ ├── VOCdevkit +│ │ ├── VOC2007 +│ │ ├── VOC2012 +``` + +Some models require additional [COCO-stuff](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip) datasets, such as HTC, DetectoRS and SCNet, you can download, unzip, and then move them to the coco folder. The directory should be like this. + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +``` + +Panoptic segmentation models like PanopticFPN require additional [COCO Panoptic](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip) datasets, you can download, unzip, and then move them to the coco annotation folder. The directory should be like this. + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── panoptic_train2017.json +│ │ │ ├── panoptic_train2017 +│ │ │ ├── panoptic_val2017.json +│ │ │ ├── panoptic_val2017 +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +``` + +The [cityscapes](https://www.cityscapes-dataset.com/) annotations need to be converted into the coco format using `tools/dataset_converters/cityscapes.py`: + +```shell +pip install cityscapesscripts + +python tools/dataset_converters/cityscapes.py \ + ./data/cityscapes \ + --nproc 8 \ + --out-dir ./data/cityscapes/annotations +``` + +### COCO Caption Dataset Preparation + +COCO Caption uses the COCO2014 dataset image and uses the annotation of karpathy. + +At first, you need to download the COCO2014 dataset. + +```shell +python tools/misc/download_dataset.py --dataset-name coco2014 --unzip +``` + +The dataset will be downloaded to `data/coco` under the current path. Then download the annotation of karpathy. + +```shell +cd data/coco/annotations +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_train.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val_gt.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test_gt.json +``` + +The final directory structure of the dataset folder that can be directly used for training and testing is as follows: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── coco_karpathy_train.json +│ │ │ ├── coco_karpathy_test.json +│ │ │ ├── coco_karpathy_val.json +│ │ │ ├── coco_karpathy_val_gt.json +│ │ │ ├── coco_karpathy_test_gt.json +│ │ ├── train2014 +│ │ ├── val2014 +│ │ ├── test2014 +``` + +### COCO Semantic Dataset Preparation + +There are two types of annotations for COCO semantic segmentation, which differ mainly in the definition of category names, so there are two ways to handle them. The first is to directly use the stuffthingmaps dataset, and the second is to use the panoptic dataset. + +**(1) Use stuffthingmaps dataset** + +The download link for this dataset is [stuffthingmaps_trainval2017](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip). Please download and extract it to the `data/coco` folder. + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +``` + +This dataset is different from the standard COCO category annotation in that it includes 172 classes: 80 "thing" classes, 91 "stuff" classes, and 1 "unlabeled" class. The description of each class can be found at https://github.com/nightrome/cocostuff/blob/master/labels.md. + +Although only 172 categories are annotated, the maximum label ID in `stuffthingmaps` is 182, and some categories in the middle are not annotated. In addition, the "unlabeled" category of class 0 is removed. Therefore, the relationship between the value at each position in the final `stuffthingmaps` image can be found at https://github.com/kazuto1011/deeplab-pytorch/blob/master/data/datasets/cocostuff/labels.txt. + +To train efficiently and conveniently for users, we need to remove 12 unannotated classes before starting training or evaluation. The names of these 12 classes are: `street sign, hat, shoe, eye glasses, plate, mirror, window, desk, door, blender, hair brush`. The category information that can be used for training and evaluation can be found in `mmdet/datasets/coco_semantic.py`. + +You can use `tools/dataset_converters/coco_stuff164k.py` to convert the downloaded `stuffthingmaps` to a dataset that can be directly used for training and evaluation. The directory structure of the converted dataset is as follows: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +│ │ ├── stuffthingmaps_semseg +``` + +`stuffthingmaps_semseg` is the newly generated COCO semantic segmentation dataset that can be directly used for training and testing. + +**(2) use panoptic dataset** + +The number of categories in the semantic segmentation dataset generated through panoptic annotation will be less than that generated using the `stuffthingmaps` dataset. First, you need to prepare the panoptic segmentation annotations, and then use the following script to complete the conversion. + +```shell +python tools/dataset_converters/prepare_coco_semantic_annos_from_panoptic_annos.py data/coco +``` + +The directory structure of the converted dataset is as follows: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── panoptic_train2017.json +│ │ │ ├── panoptic_train2017 +│ │ │ ├── panoptic_val2017.json +│ │ │ ├── panoptic_val2017 +│ │ │ ├── panoptic_semseg_train2017 +│ │ │ ├── panoptic_semseg_val2017 +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +``` + +`panoptic_semseg_train2017` and `panoptic_semseg_val2017` are the newly generated COCO semantic segmentation datasets that can be directly used for training and testing. Note that their category information is the same as that of COCO panoptic segmentation, including both "thing" and "stuff" categories. + +### RefCOCO Dataset Preparation + +The images and annotations of [RefCOCO](https://github.com/lichengunc/refer) series datasets can be download by running `tools/misc/download_dataset.py`: + +```shell +python tools/misc/download_dataset.py --dataset-name refcoco --save-dir data/coco --unzip +``` + +Then the directory should be like this: + +```text +data +├── coco +│ ├── refcoco +│ │ ├── instances.json +│ │ ├── refs(google).p +│ │ └── refs(unc).p +│ ├── refcoco+ +│ │ ├── instances.json +│ │ └── refs(unc).p +│ ├── refcocog +│ │ ├── instances.json +│ │ ├── refs(google).p +│ │ └── refs(umd).p +│ │── train2014 +``` + +### ADE20K 2016 Dataset Preparation + +The images and annotations of [ADE20K](https://groups.csail.mit.edu/vision/datasets/ADE20K/) dataset can be download by running `tools/misc/download_dataset.py`: + +```shell +python tools/misc/download_dataset.py --dataset-name ade20k_2016 --save-dir data --unzip +``` + +Then move the annotations to the `data/ADEChallengeData2016` directory and run the preprocess script to produce the coco format annotations: + +```shell +mv data/annotations_instance data/ADEChallengeData2016/ +mv data/categoryMapping.txt data/ADEChallengeData2016/ +mv data/imgCatIds.json data/ADEChallengeData2016/ +python tools/dataset_converters/ade20k2coco.py data/ADEChallengeData2016 --task panoptic +python tools/dataset_converters/ade20k2coco.py data/ADEChallengeData2016 --task instance +``` + +The directory should be like this. + +```text +data +├── ADEChallengeData2016 +│ ├── ade20k_instance_train.json +│ ├── ade20k_instance_val.json +│ ├── ade20k_panoptic_train +│ │ ├── ADE_train_00000001.png +│ │ ├── ADE_train_00000002.png +│ │ ├── ... +│ ├── ade20k_panoptic_train.json +│ ├── ade20k_panoptic_val +│ │ ├── ADE_val_00000001.png +│ │ ├── ADE_val_00000002.png +│ │ ├── ... +│ ├── ade20k_panoptic_val.json +│ ├── annotations +│ │ ├── training +│ │ │ ├── ADE_train_00000001.png +│ │ │ ├── ADE_train_00000002.png +│ │ │ ├── ... +│ │ ├── validation +│ │ │ ├── ADE_val_00000001.png +│ │ │ ├── ADE_val_00000002.png +│ │ │ ├── ... +│ ├── annotations_instance +│ │ ├── training +│ │ │ ├── ADE_train_00000001.png +│ │ │ ├── ADE_train_00000002.png +│ │ │ ├── ... +│ │ ├── validation +│ │ │ ├── ADE_val_00000001.png +│ │ │ ├── ADE_val_00000002.png +│ │ │ ├── ... +│ ├── categoryMapping.txt +│ ├── images +│ │ ├── training +│ │ │ ├── ADE_train_00000001.jpg +│ │ │ ├── ADE_train_00000002.jpg +│ │ │ ├── ... +│ │ ├── validation +│ │ │ ├── ADE_val_00000001.jpg +│ │ │ ├── ADE_val_00000002.jpg +│ │ │ ├── ... +│ ├── imgCatIds.json +│ ├── objectInfo150.txt +│ │── sceneCategories.txt +``` + +The above folders include all data of ADE20K's semantic segmentation, instance segmentation, and panoptic segmentation. + +### Download from OpenDataLab + +By using [OpenDataLab](https://opendatalab.com/), researchers can obtain free formatted datasets in various fields. Through the search function of the platform, researchers may address the dataset they look for quickly and easily. Using the formatted datasets from the platform, researchers can efficiently conduct tasks across datasets. + +Currently, MIM supports downloading VOC and COCO datasets from OpenDataLab with one command line. More datasets will be supported in the future. You can also directly download the datasets you need from the OpenDataLab platform and then convert them to the format required by MMDetection. + +If you use MIM to download, make sure that the version is greater than v0.3.8. You can use the following command to update: + +```Bash +pip install -U openmim +``` + +```Bash +# install OpenXLab CLI tools +pip install -U openxlab +# log in OpenXLab, registry +openxlab login + +# download voc2007 and preprocess by MIM +mim download mmdet --dataset voc2007 + +# download voc2012 and preprocess by MIM +mim download mmdet --dataset voc2012 + +# download coco2017 and preprocess by MIM +mim download mmdet --dataset coco2017 +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/deploy.md b/mmdet_code/mmdetection/docs/en/user_guides/deploy.md new file mode 100644 index 0000000000000000000000000000000000000000..db320d1409eb984f2eb79af2ee1bec455476f60f --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/deploy.md @@ -0,0 +1,173 @@ +# Model Deployment + +The deployment of OpenMMLab codebases, including MMDetection, MMPretrain and so on are supported by [MMDeploy](https://github.com/open-mmlab/mmdeploy). +The latest deployment guide for MMDetection can be found from [here](https://mmdeploy.readthedocs.io/en/dev-1.x/04-supported-codebases/mmdet.html). + +This tutorial is organized as follows: + +- [Installation](#installation) +- [Convert model](#convert-model) +- [Model specification](#model-specification) +- [Model inference](#model-inference) + - [Backend model inference](#backend-model-inference) + - [SDK model inference](#sdk-model-inference) +- [Supported models](#supported-models) + +## Installation + +Please follow the [guide](https://mmdetection.readthedocs.io/en/latest/get_started.html) to install mmdet. And then install mmdeploy from source by following [this](https://mmdeploy.readthedocs.io/en/1.x/get_started.html#installation) guide. + +```{note} +If you install mmdeploy prebuilt package, please also clone its repository by 'git clone https://github.com/open-mmlab/mmdeploy.git --depth=1' to get the deployment config files. +``` + +## Convert model + +Suppose mmdetection and mmdeploy repositories are in the same directory, and the working directory is the root path of mmdetection. + +Take [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py) model as an example. You can download its checkpoint from [here](https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth), and then convert it to onnx model as follows: + +```python +from mmdeploy.apis import torch2onnx +from mmdeploy.backend.sdk.export_info import export2SDK + +img = 'demo/demo.jpg' +work_dir = 'mmdeploy_models/mmdet/onnx' +save_file = 'end2end.onnx' +deploy_cfg = '../mmdeploy/configs/mmdet/detection/detection_onnxruntime_dynamic.py' +model_cfg = 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model_checkpoint = 'faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' +device = 'cpu' + +# 1. convert model to onnx +torch2onnx(img, work_dir, save_file, deploy_cfg, model_cfg, + model_checkpoint, device) + +# 2. extract pipeline info for inference by MMDeploy SDK +export2SDK(deploy_cfg, model_cfg, work_dir, pth=model_checkpoint, + device=device) +``` + +It is crucial to specify the correct deployment config during model conversion. MMDeploy has already provided builtin deployment config [files](https://github.com/open-mmlab/mmdeploy/tree/1.x/configs/mmdet) of all supported backends for mmdetection, under which the config file path follows the pattern: + +``` +{task}/{task}_{backend}-{precision}_{static | dynamic}_{shape}.py +``` + +- **{task}:** task in mmdetection. + + There are two of them. One is `detection` and the other is `instance-seg`, indicating instance segmentation. + + mmdet models like `RetinaNet`, `Faster R-CNN` and `DETR` and so on belongs to `detection` task. While `Mask R-CNN` is one of `instance-seg` models. + + **DO REMEMBER TO USE** `detection/detection_*.py` deployment config file when trying to convert detection models and use `instance-seg/instance-seg_*.py` to deploy instance segmentation models. + +- **{backend}:** inference backend, such as onnxruntime, tensorrt, pplnn, ncnn, openvino, coreml etc. + +- **{precision}:** fp16, int8. When it's empty, it means fp32 + +- **{static | dynamic}:** static shape or dynamic shape + +- **{shape}:** input shape or shape range of a model + +Therefore, in the above example, you can also convert `Faster R-CNN` to tensorrt-fp16 model by `detection_tensorrt-fp16_dynamic-320x320-1344x1344.py`. + +```{tip} +When converting mmdet models to tensorrt models, --device should be set to "cuda" +``` + +## Model specification + +Before moving on to model inference chapter, let's know more about the converted model structure which is very important for model inference. + +The converted model locates in the working directory like `mmdeploy_models/mmdet/onnx` in the previous example. It includes: + +``` +mmdeploy_models/mmdet/onnx +├── deploy.json +├── detail.json +├── end2end.onnx +└── pipeline.json +``` + +in which, + +- **end2end.onnx**: backend model which can be inferred by ONNX Runtime +- ***xxx*.json**: the necessary information for mmdeploy SDK + +The whole package **mmdeploy_models/mmdet/onnx** is defined as **mmdeploy SDK model**, i.e., **mmdeploy SDK model** includes both backend model and inference meta information. + +## Model inference + +### Backend model inference + +Take the previous converted `end2end.onnx` model as an example, you can use the following code to inference the model and visualize the results. + +```python +from mmdeploy.apis.utils import build_task_processor +from mmdeploy.utils import get_input_shape, load_config +import torch + +deploy_cfg = '../mmdeploy/configs/mmdet/detection/detection_onnxruntime_dynamic.py' +model_cfg = 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +device = 'cpu' +backend_model = ['mmdeploy_models/mmdet/onnx/end2end.onnx'] +image = 'demo/demo.jpg' + +# read deploy_cfg and model_cfg +deploy_cfg, model_cfg = load_config(deploy_cfg, model_cfg) + +# build task and backend model +task_processor = build_task_processor(model_cfg, deploy_cfg, device) +model = task_processor.build_backend_model(backend_model) + +# process input image +input_shape = get_input_shape(deploy_cfg) +model_inputs, _ = task_processor.create_input(image, input_shape) + +# do model inference +with torch.no_grad(): + result = model.test_step(model_inputs) + +# visualize results +task_processor.visualize( + image=image, + model=model, + result=result[0], + window_name='visualize', + output_file='output_detection.png') +``` + +### SDK model inference + +You can also perform SDK model inference like following, + +```python +from mmdeploy_python import Detector +import cv2 + +img = cv2.imread('demo/demo.jpg') + +# create a detector +detector = Detector(model_path='mmdeploy_models/mmdet/onnx', + device_name='cpu', device_id=0) +# perform inference +bboxes, labels, masks = detector(img) + +# visualize inference result +indices = [i for i in range(len(bboxes))] +for index, bbox, label_id in zip(indices, bboxes, labels): + [left, top, right, bottom], score = bbox[0:4].astype(int), bbox[4] + if score < 0.3: + continue + + cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0)) + +cv2.imwrite('output_detection.png', img) +``` + +Besides python API, mmdeploy SDK also provides other FFI (Foreign Function Interface), such as C, C++, C#, Java and so on. You can learn their usage from [demos](https://github.com/open-mmlab/mmdeploy/tree/1.x/demo). + +## Supported models + +Please refer to [here](https://mmdeploy.readthedocs.io/en/1.x/04-supported-codebases/mmdet.html#supported-models) for the supported model list. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/finetune.md b/mmdet_code/mmdetection/docs/en/user_guides/finetune.md new file mode 100644 index 0000000000000000000000000000000000000000..e181ebaece237a7b62cce4aaa8065b0839dc52ae --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/finetune.md @@ -0,0 +1,96 @@ +# Finetuning Models + +Detectors pre-trained on the COCO dataset can serve as a good pre-trained model for other datasets, e.g., CityScapes and KITTI Dataset. +This tutorial provides instructions for users to use the models provided in the [Model Zoo](../model_zoo.md) for other datasets to obtain better performance. + +There are two steps to finetune a model on a new dataset. + +- Add support for the new dataset following [Customize Datasets](../advanced_guides/customize_dataset.md). +- Modify the configs as will be discussed in this tutorial. + +Take the finetuning process on Cityscapes Dataset as an example, the users need to modify five parts in the config. + +## Inherit base configs + +To release the burden and reduce bugs in writing the whole configs, MMDetection V3.0 support inheriting configs from multiple existing configs. To finetune a Mask RCNN model, the new config needs to inherit +`_base_/models/mask-rcnn_r50_fpn.py` to build the basic structure of the model. To use the Cityscapes Dataset, the new config can also simply inherit `_base_/datasets/cityscapes_instance.py`. For runtime settings such as logger settings, the new config needs to inherit `_base_/default_runtime.py`. For training schedules, the new config can to inherit `_base_/schedules/schedule_1x.py`. These configs are in the `configs` directory and the users can also choose to write the whole contents rather than use inheritance. + +```python +_base_ = [ + '../_base_/models/mask-rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py', + '../_base_/schedules/schedule_1x.py' +] +``` + +## Modify head + +Then the new config needs to modify the head according to the class numbers of the new datasets. By only changing `num_classes` in the roi_head, the weights of the pre-trained models are mostly reused except for the final prediction head. + +```python +model = dict( + roi_head=dict( + bbox_head=dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[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='SmoothL1Loss', beta=1.0, loss_weight=1.0)), + mask_head=dict( + type='FCNMaskHead', + num_convs=4, + in_channels=256, + conv_out_channels=256, + num_classes=8, + loss_mask=dict( + type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) +``` + +## Modify dataset + +The users may also need to prepare the dataset and write the configs about dataset, refer to [Customize Datasets](../advanced_guides/customize_dataset.md) for more detail. MMDetection V3.0 already supports VOC, WIDERFACE, COCO, LIVS, OpenImages, DeepFashion, Objects365, and Cityscapes Dataset. + +## Modify training schedule + +The finetuning hyperparameters vary from the default schedule. It usually requires a smaller learning rate and fewer training epochs + +```python +# optimizer +# lr is set for a batch size of 8 +optim_wrapper = dict(optimizer=dict(lr=0.01)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=8, + by_epoch=True, + milestones=[7], + gamma=0.1) +] + +# max_epochs +train_cfg = dict(max_epochs=8) + +# log config +default_hooks = dict(logger=dict(interval=100)), +``` + +## Use pre-trained model + +To use the pre-trained model, the new config adds the link of pre-trained models in the `load_from`. The users might need to download the model weights before training to avoid the download time during training. + +```python +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth' # noqa +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/index.rst b/mmdet_code/mmdetection/docs/en/user_guides/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..e74fc5fb555312abad6077f2a51c9901d792bd11 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/index.rst @@ -0,0 +1,41 @@ +Train & Test +************** + +MMDetection provides hundreds of pretrained detection models in `Model Zoo `_, +and supports multiple standard datasets, including Pascal VOC, COCO, CityScapes, LVIS, etc. This note will show how to perform common tasks on these existing models and standard datasets: + + +.. toctree:: + :maxdepth: 1 + + config.md + inference.md + dataset_prepare.md + test.md + train.md + new_model.md + finetune.md + test_results_submission.md + init_cfg.md + single_stage_as_rpn.md + semi_det.md + + +Useful Tools +************ + +.. toctree:: + :maxdepth: 1 + + useful_tools.md + useful_hooks.md + visualization.md + robustness_benchmarking.md + deploy.md + label_studio.md + tracking_analysis_tools.md + tracking_config.md + tracking_dataset_prepare.md + tracking_inference.md + tracking_train_test.md + tracking_visualization.md diff --git a/mmdet_code/mmdetection/docs/en/user_guides/inference.md b/mmdet_code/mmdetection/docs/en/user_guides/inference.md new file mode 100644 index 0000000000000000000000000000000000000000..49186d236957f70d4c8abbae0554dde0fa80ec3b --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/inference.md @@ -0,0 +1,440 @@ +# Inference with existing models + +MMDetection provides hundreds of pre-trained detection models in [Model Zoo](https://mmdetection.readthedocs.io/en/latest/model_zoo.html). +This note will show how to inference, which means using trained models to detect objects on images. + +In MMDetection, a model is defined by a [configuration file](https://mmdetection.readthedocs.io/en/latest/user_guides/config.html) and existing model parameters are saved in a checkpoint file. + +To start with, we recommend [RTMDet](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet) with this [configuration file](https://github.com/open-mmlab/mmdetection/blob/main/configs/rtmdet/rtmdet_l_8xb32-300e_coco.py) and this [checkpoint file](https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_l_8xb32-300e_coco/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth). It is recommended to download the checkpoint file to `checkpoints` directory. + +## High-level APIs for inference - `Inferencer` + +In OpenMMLab, all the inference operations are unified into a new interface - Inferencer. Inferencer is designed to expose a neat and simple API to users, and shares very similar interface across different OpenMMLab libraries. +A notebook demo can be found in [demo/inference_demo.ipynb](https://github.com/open-mmlab/mmdetection/blob/main/demo/inference_demo.ipynb). + +### Basic Usage + +You can get inference results for an image with only 3 lines of code. + +```python +from mmdet.apis import DetInferencer + +# Initialize the DetInferencer +inferencer = DetInferencer('rtmdet_tiny_8xb32-300e_coco') + +# Perform inference +inferencer('demo/demo.jpg', show=True) +``` + +The resulting output will be displayed in a new window:. + +
+ +
+ +```{note} +If you are running MMDetection on a server without GUI or via SSH tunnel with X11 forwarding disabled, the `show` option will not work. However, you can still save visualizations to files by setting `out_dir` arguments. Read [Dumping Results](#dumping-results) for details. +``` + +### Initialization + +Each Inferencer must be initialized with a model. You can also choose the inference device during initialization. + +#### Model Initialization + +- To infer with MMDetection's pre-trained model, passing its name to the argument `model` can work. The weights will be automatically downloaded and loaded from OpenMMLab's model zoo. + + ```python + inferencer = DetInferencer(model='rtmdet_tiny_8xb32-300e_coco') + ``` + + There is a very easy to list all model names in MMDetection. + + ```python + # models is a list of model names, and them will print automatically + models = DetInferencer.list_models('mmdet') + ``` + + You can load another weight by passing its path/url to `weights`. + + ```python + inferencer = DetInferencer(model='rtmdet_tiny_8xb32-300e_coco', weights='path/to/rtmdet.pth') + ``` + +- To load custom config and weight, you can pass the path to the config file to `model` and the path to the weight to `weights`. + + ```python + inferencer = DetInferencer(model='path/to/rtmdet_config.py', weights='path/to/rtmdet.pth') + ``` + +- By default, [MMEngine](https://github.com/open-mmlab/mmengine/) dumps config to the weight. If you have a weight trained on MMEngine, you can also pass the path to the weight file to `weights` without specifying `model`: + + ```python + # It will raise an error if the config file cannot be found in the weight. Currently, within the MMDetection model repository, only the weights of ddq-detr-4scale_r50 can be loaded in this manner. + inferencer = DetInferencer(weights='https://download.openmmlab.com/mmdetection/v3.0/ddq/ddq-detr-4scale_r50_8xb2-12e_coco/ddq-detr-4scale_r50_8xb2-12e_coco_20230809_170711-42528127.pth') + ``` + +- Passing config file to `model` without specifying `weight` will result in a randomly initialized model. + +### Device + +Each Inferencer instance is bound to a device. +By default, the best device is automatically decided by [MMEngine](https://github.com/open-mmlab/mmengine/). You can also alter the device by specifying the `device` argument. For example, you can use the following code to create an Inferencer on GPU 1. + +```python +inferencer = DetInferencer(model='rtmdet_tiny_8xb32-300e_coco', device='cuda:1') +``` + +To create an Inferencer on CPU: + +```python +inferencer = DetInferencer(model='rtmdet_tiny_8xb32-300e_coco', device='cpu') +``` + +Refer to [torch.device](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) for all the supported forms. + +### Inference + +Once the Inferencer is initialized, you can directly pass in the raw data to be inferred and get the inference results from return values. + +#### Input + +Input can be either of these types: + +- str: Path/URL to the image. + + ```python + inferencer('demo/demo.jpg') + ``` + +- array: Image in numpy array. It should be in BGR order. + + ```python + import mmcv + array = mmcv.imread('demo/demo.jpg') + inferencer(array) + ``` + +- list: A list of basic types above. Each element in the list will be processed separately. + + ```python + inferencer(['img_1.jpg', 'img_2.jpg]) + # You can even mix the types + inferencer(['img_1.jpg', array]) + ``` + +- str: Path to the directory. All images in the directory will be processed. + + ```python + inferencer('path/to/your_imgs/') + ``` + +### Output + +By default, each `Inferencer` returns the prediction results in a dictionary format. + +- `visualization` contains the visualized predictions. + +- `predictions` contains the predictions results in a json-serializable format. But it's an empty list by default unless `return_vis=True`. + +```python +{ + 'predictions' : [ + # Each instance corresponds to an input image + { + 'labels': [...], # int list of length (N, ) + 'scores': [...], # float list of length (N, ) + 'bboxes': [...], # 2d list of shape (N, 4), format: [min_x, min_y, max_x, max_y] + }, + ... + ], + 'visualization' : [ + array(..., dtype=uint8), + ] + } +``` + +If you wish to get the raw outputs from the model, you can set `return_datasamples` to `True` to get the original [DataSample](advanced_guides/structures.md), which will be stored in `predictions`. + +#### Dumping Results + +Apart from obtaining predictions from the return value, you can also export the predictions/visualizations to files by setting `out_dir` and `no_save_pred`/`no_save_vis` arguments. + +```python +inferencer('demo/demo.jpg', out_dir='outputs/', no_save_pred=False) +``` + +Results in the directory structure like: + +```text +outputs +├── preds +│ └── demo.json +└── vis + └── demo.jpg +``` + +The filename of each file is the same as the corresponding input image filename. If the input image is an array, the filename will be a number starting from 0. + +#### Batch Inference + +You can customize the batch size by setting `batch_size`. The default batch size is 1. + +### API + +Here are extensive lists of parameters that you can use. + +- **DetInferencer.\_\_init\_\_():** + +| Arguments | Type | Type | Description | +| --------------- | ------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `model` | str, optional | None | Path to the config file or the model name defined in metafile. For example, it could be 'rtmdet-s' or 'rtmdet_s_8xb32-300e_coco' or 'configs/rtmdet/rtmdet_s_8xb32-300e_coco.py'. If the model is not specified, the user must provide the `weights` saved by MMEngine which contains the config string. | +| `weights` | str, optional | None | Path to the checkpoint. If it is not specified and `model` is a model name of metafile, the weights will be loaded from metafile. | +| `device` | str, optional | None | Device used for inference, accepting all allowed strings by `torch.device`. E.g., 'cuda:0' or 'cpu'. If None, the available device will be automatically used. | +| `scope` | str, optional | 'mmdet' | The scope of the model. | +| `palette` | str | 'none' | Color palette used for visualization. The order of priority is palette -> config -> checkpoint. | +| `show_progress` | bool | True | Control whether to display the progress bar during the inference process. | + +- **DetInferencer.\_\_call\_\_()** + +| Arguments | Type | Default | Description | +| -------------------- | ------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `inputs` | str/list/tuple/np.array | **required** | It can be a path to an image/a folder, an np array or a list/tuple (with img paths or np arrays) | +| `batch_size` | int | 1 | Inference batch size. | +| `print_result` | bool | False | Whether to print the inference result to the console. | +| `show` | bool | False | Whether to display the visualization results in a popup window. | +| `wait_time` | float | 0 | The interval of show(s). | +| `no_save_vis` | bool | False | Whether to force not to save prediction vis results. | +| `draw_pred` | bool | True | Whether to draw predicted bounding boxes. | +| `pred_score_thr` | float | 0.3 | Minimum score of bboxes to draw. | +| `return_datasamples` | bool | False | Whether to return results as DataSamples. If False, the results will be packed into a dict. | +| `print_result` | bool | False | Whether to print the inference result to the console. | +| `no_save_pred` | bool | True | Whether to force not to save prediction results. | +| `out_dir` | str | '' | Output directory of results. | +| `texts` | str/list\[str\], optional | None | Text prompts. | +| `stuff_texts` | str/list\[str\], optional | None | Stuff text prompts of open panoptic task. | +| `custom_entities` | bool | False | Whether to use custom entities. Only used in GLIP. | +| \*\*kwargs | | | Other keyword arguments passed to :meth:`preprocess`, :meth:`forward`, :meth:`visualize` and :meth:`postprocess`. Each key in kwargs should be in the corresponding set of `preprocess_kwargs`, `forward_kwargs`, `visualize_kwargs` and `postprocess_kwargs`. | + +## Demos + +We also provide four demo scripts, implemented with high-level APIs and supporting functionality codes. +Source codes are available [here](https://github.com/open-mmlab/mmdetection/blob/main/demo). + +### Image demo + +This script performs inference on a single image. + +```shell +python demo/image_demo.py \ + ${IMAGE_FILE} \ + ${CONFIG_FILE} \ + [--weights ${WEIGHTS}] \ + [--device ${GPU_ID}] \ + [--pred-score-thr ${SCORE_THR}] +``` + +Examples: + +```shell +python demo/image_demo.py demo/demo.jpg \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + --weights checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --device cpu +``` + +### Webcam demo + +This is a live demo from a webcam. + +```shell +python demo/webcam_demo.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--camera-id ${CAMERA-ID}] \ + [--score-thr ${SCORE_THR}] +``` + +Examples: + +```shell +python demo/webcam_demo.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth +``` + +### Video demo + +This script performs inference on a video. + +```shell +python demo/video_demo.py \ + ${VIDEO_FILE} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--score-thr ${SCORE_THR}] \ + [--out ${OUT_FILE}] \ + [--show] \ + [--wait-time ${WAIT_TIME}] +``` + +Examples: + +```shell +python demo/video_demo.py demo/demo.mp4 \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --out result.mp4 +``` + +#### Video demo with GPU acceleration + +This script performs inference on a video with GPU acceleration. + +```shell +python demo/video_gpuaccel_demo.py \ + ${VIDEO_FILE} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--score-thr ${SCORE_THR}] \ + [--nvdecode] \ + [--out ${OUT_FILE}] \ + [--show] \ + [--wait-time ${WAIT_TIME}] +``` + +Examples: + +```shell +python demo/video_gpuaccel_demo.py demo/demo.mp4 \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --nvdecode --out result.mp4 +``` + +### Large-image inference demo + +This is a script for slicing inference on large images. + +``` +python demo/large_image_demo.py \ + ${IMG_PATH} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --device ${GPU_ID} \ + --show \ + --tta \ + --score-thr ${SCORE_THR} \ + --patch-size ${PATCH_SIZE} \ + --patch-overlap-ratio ${PATCH_OVERLAP_RATIO} \ + --merge-iou-thr ${MERGE_IOU_THR} \ + --merge-nms-type ${MERGE_NMS_TYPE} \ + --batch-size ${BATCH_SIZE} \ + --debug \ + --save-patch +``` + +Examples: + +```shell +# inferecnce without tta +wget -P checkpoint https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r101_fpn_2x_coco/faster_rcnn_r101_fpn_2x_coco_bbox_mAP-0.398_20200504_210455-1d2dac9c.pth + +python demo/large_image_demo.py \ + demo/large_image.jpg \ + configs/faster_rcnn/faster-rcnn_r101_fpn_2x_coco.py \ + checkpoint/faster_rcnn_r101_fpn_2x_coco_bbox_mAP-0.398_20200504_210455-1d2dac9c.pth + +# inference with tta +wget -P checkpoint https://download.openmmlab.com/mmdetection/v2.0/retinanet/retinanet_r50_fpn_1x_coco/retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth + +python demo/large_image_demo.py \ + demo/large_image.jpg \ + configs/retinanet/retinanet_r50_fpn_1x_coco.py \ + checkpoint/retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth --tta + +``` + +## Multi-modal algorithm inference demo and evaluation + +As multimodal vision algorithms continue to evolve, MMDetection has also supported such algorithms. This section demonstrates how to use the demo and eval scripts corresponding to multimodal algorithms using the GLIP algorithm and model as the example. Moreover, MMDetection integrated a [gradio_demo project](../../../projects/gradio_demo/), which allows developers to quickly play with all image input tasks in MMDetection on their local devices. Check the [document](../../../projects/gradio_demo/README.md) for more details. + +### Preparation + +Please first make sure that you have the correct dependencies installed: + +```shell +# if source +pip install -r requirements/multimodal.txt + +# if wheel +mim install mmdet[multimodal] +``` + +MMDetection has already implemented GLIP algorithms and provided the weights, you can download directly from urls: + +```shell +cd mmdetection +wget https://download.openmmlab.com/mmdetection/v3.0/glip/glip_tiny_a_mmdet-b3654169.pth +``` + +### Inference + +Once the model is successfully downloaded, you can use the `demo/image_demo.py` script to run the inference. + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts bench +``` + +Demo result will be similar to this: + +
+ +
+ +If users would like to detect multiple targets, please declare them in the format of `xx. xx` after the `--texts`. + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts 'bench. car' +``` + +And the result will be like this one: + +
+ +
+ +You can also use a sentence as the input prompt for the `--texts` field, for example: + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts 'There are a lot of cars here.' +``` + +The result will be similar to this: + +
+ +
+ +### Evaluation + +The GLIP implementation in MMDetection does not have any performance degradation, our benchmark is as follows: + +| Model | official mAP | mmdet mAP | +| ----------------------- | :----------: | :-------: | +| glip_A_Swin_T_O365.yaml | 42.9 | 43.0 | +| glip_Swin_T_O365.yaml | 44.9 | 44.9 | +| glip_Swin_L.yaml | 51.4 | 51.3 | + +Users can use the test script we provided to run evaluation as well. Here is a basic example: + +```shell +# 1 gpu +python tools/test.py configs/glip/glip_atss_swin-t_fpn_dyhead_pretrain_obj365.py glip_tiny_a_mmdet-b3654169.pth + +# 8 GPU +./tools/dist_test.sh configs/glip/glip_atss_swin-t_fpn_dyhead_pretrain_obj365.py glip_tiny_a_mmdet-b3654169.pth 8 +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/init_cfg.md b/mmdet_code/mmdetection/docs/en/user_guides/init_cfg.md new file mode 100644 index 0000000000000000000000000000000000000000..312b67a875b3803a0bee5d0253b4ee2a6b97522a --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/init_cfg.md @@ -0,0 +1,161 @@ +# Weight initialization + +During training, a proper initialization strategy is beneficial to speeding up the training or obtaining a higher performance. [MMCV](https://github.com/open-mmlab/mmcv/blob/master/mmcv/cnn/utils/weight_init.py) provide some commonly used methods for initializing modules like `nn.Conv2d`. Model initialization in MMdetection mainly uses `init_cfg`. Users can initialize models with following two steps: + +1. Define `init_cfg` for a model or its components in `model_cfg`, but `init_cfg` of children components have higher priority and will override `init_cfg` of parents modules. +2. Build model as usual, but call `model.init_weights()` method explicitly, and model parameters will be initialized as configuration. + +The high-level workflow of initialization in MMdetection is : + +model_cfg(init_cfg) -> build_from_cfg -> model -> init_weight() -> initialize(self, self.init_cfg) -> children's init_weight() + +### Description + +It is dict or list\[dict\], and contains the following keys and values: + +- `type` (str), containing the initializer name in `INTIALIZERS`, and followed by arguments of the initializer. +- `layer` (str or list\[str\]), containing the names of basic layers in Pytorch or MMCV with learnable parameters that will be initialized, e.g. `'Conv2d'`,`'DeformConv2d'`. +- `override` (dict or list\[dict\]), containing the sub-modules that not inherit from BaseModule and whose initialization configuration is different from other layers' which are in `'layer'` key. Initializer defined in `type` will work for all layers defined in `layer`, so if sub-modules are not derived Classes of `BaseModule` but can be initialized as same ways of layers in `layer`, it does not need to use `override`. `override` contains: + - `type` followed by arguments of initializer; + - `name` to indicate sub-module which will be initialized. + +### Initialize parameters + +Inherit a new model from `mmcv.runner.BaseModule` or `mmdet.models` Here we show an example of FooModel. + +```python +import torch.nn as nn +from mmcv.runner import BaseModule + +class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=None): + super(FooModel, self).__init__(init_cfg) + ... +``` + +- Initialize model by using `init_cfg` directly in code + + ```python + import torch.nn as nn + from mmcv.runner import BaseModule + # or directly inherit mmdet models + + class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=XXX): + super(FooModel, self).__init__(init_cfg) + ... + ``` + +- Initialize model by using `init_cfg` directly in `mmcv.Sequential` or `mmcv.ModuleList` code + + ```python + from mmcv.runner import BaseModule, ModuleList + + class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=None): + super(FooModel, self).__init__(init_cfg) + ... + self.conv1 = ModuleList(init_cfg=XXX) + ``` + +- Initialize model by using `init_cfg` in config file + + ```python + model = dict( + ... + model = dict( + type='FooModel', + arg1=XXX, + arg2=XXX, + init_cfg=XXX), + ... + ``` + +### Usage of init_cfg + +1. Initialize model by `layer` key + + If we only define `layer`, it just initialize the layer in `layer` key. + + NOTE: Value of `layer` key is the class name with attributes weights and bias of Pytorch, (so such as `MultiheadAttention layer` is not supported). + +- Define `layer` key for initializing module with same configuration. + + ```python + init_cfg = dict(type='Constant', layer=['Conv1d', 'Conv2d', 'Linear'], val=1) + # initialize whole module with same configuration + ``` + +- Define `layer` key for initializing layer with different configurations. + +```python +init_cfg = [dict(type='Constant', layer='Conv1d', val=1), + dict(type='Constant', layer='Conv2d', val=2), + dict(type='Constant', layer='Linear', val=3)] +# nn.Conv1d will be initialized with dict(type='Constant', val=1) +# nn.Conv2d will be initialized with dict(type='Constant', val=2) +# nn.Linear will be initialized with dict(type='Constant', val=3) +``` + +2. Initialize model by `override` key + +- When initializing some specific part with its attribute name, we can use `override` key, and the value in `override` will ignore the value in init_cfg. + + ```python + # layers: + # self.feat = nn.Conv1d(3, 1, 3) + # self.reg = nn.Conv2d(3, 3, 3) + # self.cls = nn.Linear(1,2) + + init_cfg = dict(type='Constant', + layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(type='Constant', name='reg', val=3, bias=4)) + # self.feat and self.cls will be initialized with dict(type='Constant', val=1, bias=2) + # The module called 'reg' will be initialized with dict(type='Constant', val=3, bias=4) + ``` + +- If `layer` is None in init_cfg, only sub-module with the name in override will be initialized, and type and other args in override can be omitted. + + ```python + # layers: + # self.feat = nn.Conv1d(3, 1, 3) + # self.reg = nn.Conv2d(3, 3, 3) + # self.cls = nn.Linear(1,2) + + init_cfg = dict(type='Constant', val=1, bias=2, override=dict(name='reg')) + + # self.feat and self.cls will be initialized by Pytorch + # The module called 'reg' will be initialized with dict(type='Constant', val=1, bias=2) + ``` + +- If we don't define `layer` key or `override` key, it will not initialize anything. + +- Invalid usage + + ```python + # It is invalid that override don't have name key + init_cfg = dict(type='Constant', layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(type='Constant', val=3, bias=4)) + + # It is also invalid that override has name and other args except type + init_cfg = dict(type='Constant', layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(name='reg', val=3, bias=4)) + ``` + +3. Initialize model with the pretrained model + + ```python + init_cfg = dict(type='Pretrained', + checkpoint='torchvision://resnet50') + ``` + +More details can refer to the documentation in [MMEngine](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/initialize.html) diff --git a/mmdet_code/mmdetection/docs/en/user_guides/label_studio.md b/mmdet_code/mmdetection/docs/en/user_guides/label_studio.md new file mode 100644 index 0000000000000000000000000000000000000000..d4b3744734984aaf91d95183248785394ba53959 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/label_studio.md @@ -0,0 +1,256 @@ +# Semi-automatic Object Detection Annotation with MMDetection and Label-Studio + +Annotation data is a time-consuming and laborious task. This article introduces how to perform semi-automatic annotation using the RTMDet algorithm in MMDetection in conjunction with Label-Studio software. Specifically, using RTMDet to predict image annotations and then refining the annotations with Label-Studio. Community users can refer to this process and methodology and apply it to other fields. + +- RTMDet: RTMDet is a high-precision single-stage object detection algorithm developed by OpenMMLab, open-sourced in the MMDetection object detection toolbox. Its open-source license is Apache 2.0, and it can be used freely without restrictions by industrial users. + +- [Label Studio](https://github.com/heartexlabs/label-studio) is an excellent annotation software covering the functionality of dataset annotation in areas such as image classification, object detection, and segmentation. + +In this article, we will use [cat](https://download.openmmlab.com/mmyolo/data/cat_dataset.zip) images for semi-automatic annotation. + +## Environment Configuration + +To begin with, you need to create a virtual environment and then install PyTorch and MMCV. In this article, we will specify the versions of PyTorch and MMCV. Next, you can install MMDetection, Label-Studio, and label-studio-ml-backend using the following steps: + +Create a virtual environment: + +```shell +conda create -n rtmdet python=3.9 -y +conda activate rtmdet +``` + +Install PyTorch: + +```shell +# Linux and Windows CPU only +pip install torch==1.10.1+cpu torchvision==0.11.2+cpu torchaudio==0.10.1 -f https://download.pytorch.org/whl/cpu/torch_stable.html +# Linux and Windows CUDA 11.3 +pip install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio==0.10.1 -f https://download.pytorch.org/whl/cu113/torch_stable.html +# OSX +pip install torch==1.10.1 torchvision==0.11.2 torchaudio==0.10.1 +``` + +Install MMCV: + +```shell +pip install -U openmim +mim install "mmcv>=2.0.0" +# Installing mmcv will automatically install mmengine +``` + +Install MMDetection: + +```shell +git clone https://github.com/open-mmlab/mmdetection +cd mmdetection +pip install -v -e . +``` + +Install Label-Studio and label-studio-ml-backend: + +```shell +# Installing Label-Studio may take some time, if the version is not found, please use the official source +pip install label-studio==1.7.2 +pip install label-studio-ml==1.0.9 +``` + +Download the rtmdet weights: + +```shell +cd path/to/mmetection +mkdir work_dirs +cd work_dirs +wget https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_m_8xb32-300e_coco/rtmdet_m_8xb32-300e_coco_20220719_112220-229f527c.pth +``` + +## Start the Service + +Start the RTMDet backend inference service: + +```shell +cd path/to/mmetection + +label-studio-ml start projects/LabelStudio/backend_template --with \ +config_file=configs/rtmdet/rtmdet_m_8xb32-300e_coco.py \ +checkpoint_file=./work_dirs/rtmdet_m_8xb32-300e_coco_20220719_112220-229f527c.pth \ +device=cpu \ +--port 8003 +# Set device=cpu to use CPU inference, and replace cpu with cuda:0 to use GPU inference. +``` + +![](https://cdn.vansin.top/picgo20230330131601.png) + +The RTMDet backend inference service has now been started. To configure it in the Label-Studio web system, use http://localhost:8003 as the backend inference service. + +Now, start the Label-Studio web service: + +```shell +label-studio start +``` + +![](https://cdn.vansin.top/picgo20230330132913.png) + +Open your web browser and go to http://localhost:8080/ to see the Label-Studio interface. + +![](https://cdn.vansin.top/picgo20230330133118.png) + +Register a user and then create an RTMDet-Semiautomatic-Label project. + +![](https://cdn.vansin.top/picgo20230330133333.png) + +Download the example cat images by running the following command and import them using the Data Import button: + +```shell +cd path/to/mmetection +mkdir data && cd data + +wget https://download.openmmlab.com/mmyolo/data/cat_dataset.zip && unzip cat_dataset.zip +``` + +![](https://cdn.vansin.top/picgo20230330133628.png) + +![](https://cdn.vansin.top/picgo20230330133715.png) + +Then, select the Object Detection With Bounding Boxes template. + +![](https://cdn.vansin.top/picgo20230330133807.png) + +```shell +airplane +apple +backpack +banana +baseball_bat +baseball_glove +bear +bed +bench +bicycle +bird +boat +book +bottle +bowl +broccoli +bus +cake +car +carrot +cat +cell_phone +chair +clock +couch +cow +cup +dining_table +dog +donut +elephant +fire_hydrant +fork +frisbee +giraffe +hair_drier +handbag +horse +hot_dog +keyboard +kite +knife +laptop +microwave +motorcycle +mouse +orange +oven +parking_meter +person +pizza +potted_plant +refrigerator +remote +sandwich +scissors +sheep +sink +skateboard +skis +snowboard +spoon +sports_ball +stop_sign +suitcase +surfboard +teddy_bear +tennis_racket +tie +toaster +toilet +toothbrush +traffic_light +train +truck +tv +umbrella +vase +wine_glass +zebra +``` + +Then, copy and add the above categories to Label-Studio and click Save. + +![](https://cdn.vansin.top/picgo20230330134027.png) + +In the Settings, click Add Model to add the RTMDet backend inference service. + +![](https://cdn.vansin.top/picgo20230330134320.png) + +Click Validate and Save, and then click Start Labeling. + +![](https://cdn.vansin.top/picgo20230330134424.png) + +If you see Connected as shown below, the backend inference service has been successfully added. + +![](https://cdn.vansin.top/picgo20230330134554.png) + +## Start Semi-Automatic Labeling + +Click on Label to start labeling. + +![](https://cdn.vansin.top/picgo20230330134804.png) + +We can see that the RTMDet backend inference service has successfully returned the predicted results and displayed them on the image. However, we noticed that the predicted bounding boxes for the cats are a bit too large and not very accurate. + +![](https://cdn.vansin.top/picgo20230403104419.png) + +We manually adjust the position of the cat bounding box, and then click Submit to complete the annotation of this image. + +![](https://cdn.vansin.top/picgo/20230403105923.png) + +After submitting all images, click export to export the labeled dataset in COCO format. + +![](https://cdn.vansin.top/picgo20230330135921.png) + +Use VS Code to open the unzipped folder to see the labeled dataset, which includes the images and the annotation files in JSON format. + +![](https://cdn.vansin.top/picgo20230330140321.png) + +At this point, the semi-automatic labeling is complete. We can use this dataset to train a more accurate model in MMDetection and then continue semi-automatic labeling on newly collected images with this model. This way, we can iteratively expand the high-quality dataset and improve the accuracy of the model. + +## Use MMYOLO as the Backend Inference Service + +If you want to use Label-Studio in MMYOLO, you can refer to replacing the config_file and checkpoint_file with the configuration file and weight file of MMYOLO when starting the backend inference service. + +```shell +cd path/to/mmetection + +label-studio-ml start projects/LabelStudio/backend_template --with \ +config_file= path/to/mmyolo_config.py \ +checkpoint_file= path/to/mmyolo_weights.pth \ +device=cpu \ +--port 8003 +# device=cpu is for using CPU inference. If using GPU inference, replace cpu with cuda:0. +``` + +Rotation object detection and instance segmentation are still under development, please stay tuned. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/new_model.md b/mmdet_code/mmdetection/docs/en/user_guides/new_model.md new file mode 100644 index 0000000000000000000000000000000000000000..c7af855ae3165fcc96d30f65887b620323d85c68 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/new_model.md @@ -0,0 +1,290 @@ +# Train with customized models and standard datasets + +In this note, you will know how to train, test and inference your own customized models under standard datasets. We use the cityscapes dataset to train a customized Cascade Mask R-CNN R50 model as an example to demonstrate the whole process, which using [`AugFPN`](https://github.com/Gus-Guo/AugFPN) to replace the default `FPN` as neck, and add `Rotate` or `TranslateX` as training-time auto augmentation. + +The basic steps are as below: + +1. Prepare the standard dataset +2. Prepare your own customized model +3. Prepare a config +4. Train, test, and inference models on the standard dataset. + +## Prepare the standard dataset + +In this note, as we use the standard cityscapes dataset as an example. + +It is recommended to symlink the dataset root to `$MMDETECTION/data`. +If your folder structure is different, you may need to change the corresponding paths in config files. + +```none +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ ├── cityscapes +│ │ ├── annotations +│ │ ├── leftImg8bit +│ │ │ ├── train +│ │ │ ├── val +│ │ ├── gtFine +│ │ │ ├── train +│ │ │ ├── val +│ ├── VOCdevkit +│ │ ├── VOC2007 +│ │ ├── VOC2012 + +``` + +Or you can set your dataset root through + +```bash +export MMDET_DATASETS=$data_root +``` + +We will replace dataset root with `$MMDET_DATASETS`, so you don't have to modify the corresponding path in config files. + +The cityscapes annotations have to be converted into the coco format using `tools/dataset_converters/cityscapes.py`: + +```shell +pip install cityscapesscripts +python tools/dataset_converters/cityscapes.py ./data/cityscapes --nproc 8 --out-dir ./data/cityscapes/annotations +``` + +Currently, the config files in `cityscapes` use COCO pre-trained weights to initialize. +You could download the pre-trained models in advance if the network is unavailable or slow, otherwise, it would cause errors at the beginning of training. + +## Prepare your own customized model + +The second step is to use your own module or training setting. Assume that we want to implement a new neck called `AugFPN` to replace with the default `FPN` under the existing detector Cascade Mask R-CNN R50. The following implements `AugFPN` under MMDetection. + +### 1. Define a new neck (e.g. AugFPN) + +Firstly create a new file `mmdet/models/necks/augfpn.py`. + +```python +import torch.nn as nn +from mmdet.registry import MODELS + + +@MODELS.register_module() +class AugFPN(nn.Module): + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False): + pass + + def forward(self, inputs): + # implementation is ignored + pass +``` + +### 2. Import the module + +You can either add the following line to `mmdet/models/necks/__init__.py`, + +```python +from .augfpn import AugFPN +``` + +or alternatively add + +```python +custom_imports = dict( + imports=['mmdet.models.necks.augfpn'], + allow_failed_imports=False) +``` + +to the config file and avoid modifying the original code. + +### 3. Modify the config file + +```python +neck=dict( + type='AugFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5) +``` + +For more detailed usages about customizing your own models (e.g. implement a new backbone, head, loss, etc) and runtime training settings (e.g. define a new optimizer, use gradient clip, customize training schedules and hooks, etc), please refer to the guideline [Customize Models](../advanced_guides/customize_models.md) and [Customize Runtime Settings](../advanced_guides/customize_runtime.md) respectively. + +## Prepare a config + +The third step is to prepare a config for your own training setting. Assume that we want to add `AugFPN` and `Rotate` or `Translate` augmentation to existing Cascade Mask R-CNN R50 to train the cityscapes dataset, and assume the config is under directory `configs/cityscapes/` and named as `cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py`, the config is as below. + +```python +# The new config inherits the base configs to highlight the necessary modification +_base_ = [ + '../_base_/models/cascade-mask-rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py' +] + +model = dict( + # set None to avoid loading ImageNet pre-trained backbone, + # instead here we set `load_from` to load from COCO pre-trained detectors. + backbone=dict(init_cfg=None), + # replace neck from defaultly `FPN` to our new implemented module `AugFPN` + neck=dict( + type='AugFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5), + # We also need to change the num_classes in head from 80 to 8, to match the + # cityscapes dataset's annotation. This modification involves `bbox_head` and `mask_head`. + roi_head=dict( + bbox_head=[ + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # change the number of classes from defaultly COCO to cityscapes + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.1, 0.1, 0.2, 0.2]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, + loss_weight=1.0)), + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # change the number of classes from defaultly COCO to cityscapes + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.05, 0.05, 0.1, 0.1]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, + loss_weight=1.0)), + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # change the number of classes from defaultly COCO to cityscapes + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.033, 0.033, 0.067, 0.067]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) + ], + mask_head=dict( + type='FCNMaskHead', + num_convs=4, + in_channels=256, + conv_out_channels=256, + # change the number of classes from default COCO to cityscapes + num_classes=8, + loss_mask=dict( + type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) + +# over-write `train_pipeline` for new added `AutoAugment` training setting +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='AutoAugment', + policies=[ + [dict( + type='Rotate', + level=5, + img_border_value=(124, 116, 104), + prob=0.5) + ], + [dict(type='Rotate', level=7, img_border_value=(124, 116, 104)), + dict( + type='TranslateX', + level=5, + prob=0.5, + img_border_value=(124, 116, 104)) + ], + ]), + dict( + type='RandomResize', + scale=[(2048, 800), (2048, 1024)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs'), +] + +# set batch_size per gpu, and set new training pipeline +train_dataloader = dict( + batch_size=1, + num_workers=3, + # over-write `pipeline` with new training pipeline setting + dataset=dict(pipeline=train_pipeline)) + +# Set optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)) + +# Set customized learning policy +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=10, + by_epoch=True, + milestones=[8], + gamma=0.1) +] + +# train, val, test loop config +train_cfg = dict(max_epochs=10, val_interval=1) + +# We can use the COCO pre-trained Cascade Mask R-CNN R50 model for a more stable performance initialization +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco/cascade_mask_rcnn_r50_fpn_1x_coco_20200203-9d4dcb24.pth' +``` + +## Train a new model + +To train a model with the new config, you can simply run + +```shell +python tools/train.py configs/cityscapes/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py +``` + +For more detailed usages, please refer to the [training guide](train.md). + +## Test and inference + +To test the trained model, you can simply run + +```shell +python tools/test.py configs/cityscapes/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py work_dirs/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes/epoch_10.pth +``` + +For more detailed usages, please refer to the [testing guide](test.md). diff --git a/mmdet_code/mmdetection/docs/en/user_guides/robustness_benchmarking.md b/mmdet_code/mmdetection/docs/en/user_guides/robustness_benchmarking.md new file mode 100644 index 0000000000000000000000000000000000000000..f6579564293379b6cf05705311368a7aa750b3fe --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/robustness_benchmarking.md @@ -0,0 +1,110 @@ +# Corruption Benchmarking + +## Introduction + +We provide tools to test object detection and instance segmentation models on the image corruption benchmark defined in [Benchmarking Robustness in Object Detection: Autonomous Driving when Winter is Coming](https://arxiv.org/abs/1907.07484). +This page provides basic tutorials how to use the benchmark. + +```latex +@article{michaelis2019winter, + title={Benchmarking Robustness in Object Detection: + Autonomous Driving when Winter is Coming}, + author={Michaelis, Claudio and Mitzkus, Benjamin and + Geirhos, Robert and Rusak, Evgenia and + Bringmann, Oliver and Ecker, Alexander S. and + Bethge, Matthias and Brendel, Wieland}, + journal={arXiv:1907.07484}, + year={2019} +} +``` + +![image corruption example](../../../resources/corruptions_sev_3.png) + +## About the benchmark + +To submit results to the benchmark please visit the [benchmark homepage](https://github.com/bethgelab/robust-detection-benchmark) + +The benchmark is modelled after the [imagenet-c benchmark](https://github.com/hendrycks/robustness) which was originally +published in [Benchmarking Neural Network Robustness to Common Corruptions and Perturbations](https://arxiv.org/abs/1903.12261) (ICLR 2019) by Dan Hendrycks and Thomas Dietterich. + +The image corruption functions are included in this library but can be installed separately using: + +```shell +pip install imagecorruptions +``` + +Compared to imagenet-c a few changes had to be made to handle images of arbitrary size and greyscale images. +We also modified the 'motion blur' and 'snow' corruptions to remove dependency from a linux specific library, +which would have to be installed separately otherwise. For details please refer to the [imagecorruptions repository](https://github.com/bethgelab/imagecorruptions). + +## Inference with pretrained models + +We provide a testing script to evaluate a models performance on any combination of the corruptions provided in the benchmark. + +### Test a dataset + +- [x] single GPU testing +- [ ] multiple GPU testing +- [ ] visualize detection results + +You can use the following commands to test a models performance under the 15 corruptions used in the benchmark. + +```shell +# single-gpu testing +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] +``` + +Alternatively different group of corruptions can be selected. + +```shell +# noise +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] --corruptions noise + +# blur +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] --corruptions blur + +# wetaher +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] --corruptions weather + +# digital +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] --corruptions digital +``` + +Or a costom set of corruptions e.g.: + +```shell +# gaussian noise, zoom blur and snow +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions gaussian_noise zoom_blur snow +``` + +Finally the corruption severities to evaluate can be chosen. +Severity 0 corresponds to clean data and the effect increases from 1 to 5. + +```shell +# severity 1 +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --severities 1 + +# severities 0,2,4 +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --severities 0 2 4 +``` + +## Results for modelzoo models + +The results on COCO 2017val are shown in the below table. + +| Model | Backbone | Style | Lr schd | box AP clean | box AP corr. | box % | mask AP clean | mask AP corr. | mask % | +| :-----------------: | :-----------------: | :-----: | :-----: | :----------: | :----------: | :---: | :-----------: | :-----------: | :----: | +| Faster R-CNN | R-50-FPN | pytorch | 1x | 36.3 | 18.2 | 50.2 | - | - | - | +| Faster R-CNN | R-101-FPN | pytorch | 1x | 38.5 | 20.9 | 54.2 | - | - | - | +| Faster R-CNN | X-101-32x4d-FPN | pytorch | 1x | 40.1 | 22.3 | 55.5 | - | - | - | +| Faster R-CNN | X-101-64x4d-FPN | pytorch | 1x | 41.3 | 23.4 | 56.6 | - | - | - | +| Faster R-CNN | R-50-FPN-DCN | pytorch | 1x | 40.0 | 22.4 | 56.1 | - | - | - | +| Faster R-CNN | X-101-32x4d-FPN-DCN | pytorch | 1x | 43.4 | 26.7 | 61.6 | - | - | - | +| Mask R-CNN | R-50-FPN | pytorch | 1x | 37.3 | 18.7 | 50.1 | 34.2 | 16.8 | 49.1 | +| Mask R-CNN | R-50-FPN-DCN | pytorch | 1x | 41.1 | 23.3 | 56.7 | 37.2 | 20.7 | 55.7 | +| Cascade R-CNN | R-50-FPN | pytorch | 1x | 40.4 | 20.1 | 49.7 | - | - | - | +| Cascade Mask R-CNN | R-50-FPN | pytorch | 1x | 41.2 | 20.7 | 50.2 | 35.7 | 17.6 | 49.3 | +| RetinaNet | R-50-FPN | pytorch | 1x | 35.6 | 17.8 | 50.1 | - | - | - | +| Hybrid Task Cascade | X-101-64x4d-FPN-DCN | pytorch | 1x | 50.6 | 32.7 | 64.7 | 43.8 | 28.1 | 64.0 | + +Results may vary slightly due to the stochastic application of the corruptions. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/semi_det.md b/mmdet_code/mmdetection/docs/en/user_guides/semi_det.md new file mode 100644 index 0000000000000000000000000000000000000000..ee86c302f336d17a1a911b39dbcc24e3d9311457 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/semi_det.md @@ -0,0 +1,325 @@ +# Semi-supervised Object Detection + +Semi-supervised object detection uses both labeled data and unlabeled data for training. It not only reduces the annotation burden for training high-performance object detectors but also further improves the object detector by using a large number of unlabeled data. + +A typical procedure to train a semi-supervised object detector is as below: + +- [Semi-supervised Object Detection](#semi-supervised-object-detection) + - [Prepare and split dataset](#prepare-and-split-dataset) + - [Configure multi-branch pipeline](#configure-multi-branch-pipeline) + - [Configure semi-supervised dataloader](#configure-semi-supervised-dataloader) + - [Configure semi-supervised model](#configure-semi-supervised-model) + - [Configure MeanTeacherHook](#configure-meanteacherhook) + - [Configure TeacherStudentValLoop](#configure-teacherstudentvalloop) + +## Prepare and split dataset + +We provide a dataset download script, which downloads the coco2017 dataset by default and decompresses it automatically. + +```shell +python tools/misc/download_dataset.py +``` + +The decompressed dataset directory structure is as below: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +There are two common experimental settings for semi-supervised object detection on the coco2017 dataset: + +(1) Split `train2017` according to a fixed percentage (1%, 2%, 5% and 10%) as a labeled dataset, and the rest of `train2017` as an unlabeled dataset. Because the different splits of `train2017` as labeled datasets will cause significant fluctuation on the accuracy of the semi-supervised detectors, five-fold cross-validation is used in practice to evaluate the algorithm. We provide the dataset split script: + +```shell +python tools/misc/split_coco.py +``` + +By default, the script will split `train2017` according to the labeled data ratio 1%, 2%, 5% and 10%, and each split will be randomly repeated 5 times for cross-validation. The generated semi-supervised annotation file name format is as below: + +- the name format of labeled dataset: `instances_train2017.{fold}@{percent}.json` +- the name format of unlabeled dataset: `instances_train2017.{fold}@{percent}-unlabeled.json` + +Here, `fold` is used for cross-validation, and `percent` represents the ratio of labeled data. The directory structure of the divided dataset is as below: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── semi_anns +│ │ │ ├── instances_train2017.1@1.json +│ │ │ ├── instances_train2017.1@1-unlabeled.json +│ │ │ ├── instances_train2017.1@2.json +│ │ │ ├── instances_train2017.1@2-unlabeled.json +│ │ │ ├── instances_train2017.1@5.json +│ │ │ ├── instances_train2017.1@5-unlabeled.json +│ │ │ ├── instances_train2017.1@10.json +│ │ │ ├── instances_train2017.1@10-unlabeled.json +│ │ │ ├── instances_train2017.2@1.json +│ │ │ ├── instances_train2017.2@1-unlabeled.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +(2) Use `train2017` as the labeled dataset and `unlabeled2017` as the unlabeled dataset. Since `image_info_unlabeled2017.json` does not contain `categories` information, the `CocoDataset` cannot be initialized, so you need to write the `categories` of `instances_train2017.json` into `image_info_unlabeled2017.json` and save it as `instances_unlabeled2017.json`, the relevant script is as below: + +```python +from mmengine.fileio import load, dump + +anns_train = load('instances_train2017.json') +anns_unlabeled = load('image_info_unlabeled2017.json') +anns_unlabeled['categories'] = anns_train['categories'] +dump(anns_unlabeled, 'instances_unlabeled2017.json') +``` + +The processed dataset directory is as below: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_unlabeled2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +## Configure multi-branch pipeline + +There are two main approaches to semi-supervised learning, +[consistency regularization](https://research.nvidia.com/sites/default/files/publications/laine2017iclr_paper.pdf) +and [pseudo label](https://www.researchgate.net/profile/Dong-Hyun-Lee/publication/280581078_Pseudo-Label_The_Simple_and_Efficient_Semi-Supervised_Learning_Method_for_Deep_Neural_Networks/links/55bc4ada08ae092e9660b776/Pseudo-Label-The-Simple-and-Efficient-Semi-Supervised-Learning-Method-for-Deep-Neural-Networks.pdf). +Consistency regularization often requires some careful design, while pseudo label have a simpler form and are easier to extend to downstream tasks. +We adopt a teacher-student joint training semi-supervised object detection framework based on pseudo label, so labeled data and unlabeled data need to configure different data pipeline: + +(1) Pipeline for labeled data: + +```python +# pipeline used to augment labeled data, +# which will be sent to student model for supervised training. +sup_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict(type='MultiBranch', sup=dict(type='PackDetInputs')) +] +``` + +(2) Pipeline for unlabeled data: + +```python +# pipeline used to augment unlabeled data weakly, +# which will be sent to teacher model for predicting pseudo instances. +weak_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data strongly, +# which will be sent to student model for unsupervised training. +strong_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomOrder', + transforms=[ + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='RandAugment', aug_space=geometric, aug_num=1), + ]), + dict(type='RandomErasing', n_patches=(1, 5), ratio=(0, 0.2)), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data into different views +unsup_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadEmptyAnnotations'), + dict( + type='MultiBranch', + unsup_teacher=weak_pipeline, + unsup_student=strong_pipeline, + ) +] +``` + +## Configure semi-supervised dataloader + +(1) Build a semi-supervised dataset. Use `ConcatDataset` to concatenate labeled and unlabeled datasets. + +```python +labeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=sup_pipeline) + +unlabeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_unlabeled2017.json', + data_prefix=dict(img='unlabeled2017/'), + filter_cfg=dict(filter_empty_gt=False), + pipeline=unsup_pipeline) + +train_dataloader = dict( + batch_size=batch_size, + num_workers=num_workers, + persistent_workers=True, + sampler=dict( + type='GroupMultiSourceSampler', + batch_size=batch_size, + source_ratio=[1, 4]), + dataset=dict( + type='ConcatDataset', datasets=[labeled_dataset, unlabeled_dataset])) +``` + +(2) Use multi-source dataset sampler. Use `GroupMultiSourceSampler` to sample data form batches from `labeled_dataset` and `labeled_dataset`, `source_ratio` controls the proportion of labeled data and unlabeled data in the batch. `GroupMultiSourceSampler` also ensures that the images in the same batch have similar aspect ratios. If you don't need to guarantee the aspect ratio of the images in the batch, you can use `MultiSourceSampler`. The sampling diagram of `GroupMultiSourceSampler` is as below: + +
+ +
+ +`sup=1000` indicates that the scale of the labeled dataset is 1000, `sup_h=200` indicates that the scale of the images with an aspect ratio greater than or equal to 1 in the labeled dataset is 200, and `sup_w=800` indicates that the scale of the images with an aspect ratio less than 1 in the labeled dataset is 800, +`unsup=9000` indicates that the scale of the unlabeled dataset is 9000, `unsup_h=1800` indicates that the scale of the images with an aspect ratio greater than or equal to 1 in the unlabeled dataset is 1800, and `unsup_w=7200` indicates the scale of the images with an aspect ratio less than 1 in the unlabeled dataset is 7200. +`GroupMultiSourceSampler` randomly selects a group according to the overall aspect ratio distribution of the images in the labeled dataset and the unlabeled dataset, and then sample data to form batches from the two datasets according to `source_ratio`, so labeled datasets and unlabeled datasets have different repetitions. + +## Configure semi-supervised model + +We choose `Faster R-CNN` as `detector` for semi-supervised training. Take the semi-supervised object detection algorithm `SoftTeacher` as an example, +the model configuration can be inherited from `_base_/models/faster-rcnn_r50_fpn.py`, replacing the backbone network of the detector with `caffe` style. +Note that unlike the supervised training configs, `Faster R-CNN` as `detector` is an attribute of `model`, not `model` . +In addition, `data_preprocessor` needs to be set to `MultiBranchDataPreprocessor`, which is used to pad and normalize images from different pipelines. +Finally, parameters required for semi-supervised training and testing can be configured via `semi_train_cfg` and `semi_test_cfg`. + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', '../_base_/default_runtime.py', + '../_base_/datasets/semi_coco_detection.py' +] + +detector = _base_.model +detector.data_preprocessor = dict( + type='DetDataPreprocessor', + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False, + pad_size_divisor=32) +detector.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=False), + norm_eval=True, + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe')) + +model = dict( + _delete_=True, + type='SoftTeacher', + detector=detector, + data_preprocessor=dict( + type='MultiBranchDataPreprocessor', + data_preprocessor=detector.data_preprocessor), + semi_train_cfg=dict( + freeze_teacher=True, + sup_weight=1.0, + unsup_weight=4.0, + pseudo_label_initial_score_thr=0.5, + rpn_pseudo_thr=0.9, + cls_pseudo_thr=0.9, + reg_pseudo_thr=0.02, + jitter_times=10, + jitter_scale=0.06, + min_pseudo_bbox_wh=(1e-2, 1e-2)), + semi_test_cfg=dict(predict_on='teacher')) +``` + +In addition, we also support semi-supervised training for other detection models, such as `RetinaNet` and `Cascade R-CNN`. Since `SoftTeacher` only supports `Faster R-CNN`, it needs to be replaced with `SemiBaseDetector`, example is as below: + +```python +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', '../_base_/default_runtime.py', + '../_base_/datasets/semi_coco_detection.py' +] + +detector = _base_.model + +model = dict( + _delete_=True, + type='SemiBaseDetector', + detector=detector, + data_preprocessor=dict( + type='MultiBranchDataPreprocessor', + data_preprocessor=detector.data_preprocessor), + semi_train_cfg=dict( + freeze_teacher=True, + sup_weight=1.0, + unsup_weight=1.0, + cls_pseudo_thr=0.9, + min_pseudo_bbox_wh=(1e-2, 1e-2)), + semi_test_cfg=dict(predict_on='teacher')) +``` + +Following the semi-supervised training configuration of `SoftTeacher`, change `batch_size` to 2 and `source_ratio` to `[1, 1]`, the experimental results of supervised and semi-supervised training of `RetinaNet`, `Faster R-CNN`, `Cascade R-CNN` and `SoftTeacher` on the 10% coco `train2017` are as below: + +| Model | Detector | BackBone | Style | sup-0.1-coco mAP | semi-0.1-coco mAP | +| :--------------: | :-----------: | :------: | :---: | :--------------: | :---------------: | +| SemiBaseDetector | RetinaNet | R-50-FPN | caffe | 23.5 | 27.7 | +| SemiBaseDetector | Faster R-CNN | R-50-FPN | caffe | 26.7 | 28.4 | +| SemiBaseDetector | Cascade R-CNN | R-50-FPN | caffe | 28.0 | 29.7 | +| SoftTeacher | Faster R-CNN | R-50-FPN | caffe | 26.7 | 31.1 | + +## Configure MeanTeacherHook + +Usually, the teacher model is updated by Exponential Moving Average (EMA) the student model, and then the teacher model is optimized with the optimization of the student model, which can be achieved by configuring `custom_hooks`: + +```python +custom_hooks = [dict(type='MeanTeacherHook')] +``` + +## Configure TeacherStudentValLoop + +Since there are two models in the teacher-student joint training framework, we can replace `ValLoop` with `TeacherStudentValLoop` to test the accuracy of both models during the training process. + +```python +val_cfg = dict(type='TeacherStudentValLoop') +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/single_stage_as_rpn.md b/mmdet_code/mmdetection/docs/en/user_guides/single_stage_as_rpn.md new file mode 100644 index 0000000000000000000000000000000000000000..93a48dd7c5c26ebebac417370737e80032bc63ee --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/single_stage_as_rpn.md @@ -0,0 +1,176 @@ +# Use a single stage detector as RPN + +Region proposal network (RPN) is a submodule in [Faster R-CNN](https://arxiv.org/abs/1506.01497), which generates proposals for the second stage of Faster R-CNN. Most two-stage detectors in MMDetection use [`RPNHead`](../../../mmdet/models/dense_heads/rpn_head.py) to generate proposals as RPN. However, any single-stage detector can serve as an RPN since their bounding box predictions can also be regarded as region proposals and thus be refined in the R-CNN. Therefore, MMDetection v3.0 supports that. + +To illustrate the whole process, here we give an example of how to use an anchor-free single-stage model [FCOS](../../../configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py) as an RPN in [Faster R-CNN](../../../configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py). + +The outline of this tutorial is as below: + +1. Use `FCOSHead` as an `RPNHead` in Faster R-CNN +2. Evaluate proposals +3. Train the customized Faster R-CNN with pre-trained FCOS + +## Use `FCOSHead` as an `RPNHead` in Faster R-CNN + +To set `FCOSHead` as an `RPNHead` in Faster R-CNN, we should create a new config file named `configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py`, and replace with the setting of `rpn_head` with the setting of `bbox_head` in `configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py`. Besides, we still use the neck setting of FCOS with strides of `[8, 16, 32, 64, 128]`, and update `featmap_strides` of `bbox_roi_extractor` to `[8, 16, 32, 64, 128]`. To avoid loss goes NAN, we apply warmup during the first 1000 iterations instead of the first 500 iterations, which means that the lr increases more slowly. The config is as follows: + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +model = dict( + # copied from configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py + neck=dict( + start_level=1, + add_extra_convs='on_output', # use P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # ignore the unused old settings + type='FCOSHead', + num_classes=1, # num_classes = 1 for rpn, if num_classes > 1, it will be set to 1 in TwoStageDetector automatically + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + roi_head=dict( # update featmap_strides due to the strides in neck + bbox_roi_extractor=dict(featmap_strides=[8, 16, 32, 64, 128]))) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), # Slowly increase lr, otherwise loss becomes NAN + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[8, 11], + gamma=0.1) +] +``` + +Then, we could use the following command to train our customized model. For more training commands, please refer to [here](train.md). + +```python +# training with 8 GPUS +bash tools/dist_train.sh configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py \ + 8 \ + --work-dir ./work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco +``` + +## Evaluate proposals + +The quality of proposals is of great importance to the performance of detector, therefore, we also provide a way to evaluate proposals. Same as above, create a new config file named `configs/rpn/fcos-rpn_r50_fpn_1x_coco.py`, and replace with setting of `rpn_head` with the setting of `bbox_head` in `configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py`. + +```python +_base_ = [ + '../_base_/models/rpn_r50_fpn.py', '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +val_evaluator = dict(metric='proposal_fast') +test_evaluator = val_evaluator + +model = dict( + # copied from configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py + neck=dict( + start_level=1, + add_extra_convs='on_output', # use P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # ignore the unused old settings + type='FCOSHead', + num_classes=1, # num_classes = 1 for rpn, if num_classes > 1, it will be set to 1 in RPN automatically + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) +``` + +Suppose we have the checkpoint `./work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco/epoch_12.pth` after training, then we can evaluate the quality of proposals with the following command. + +```python +# testing with 8 GPUs +bash tools/dist_test.sh \ + configs/rpn/fcos-rpn_r50_fpn_1x_coco.py \ + ./work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco/epoch_12.pth \ + 8 +``` + +## Train the customized Faster R-CNN with pre-trained FCOS + +Pre-training not only speeds up convergence of training, but also improves the performance of the detector. Therefore, here we give an example to illustrate how to do use a pre-trained FCOS as an RPN to accelerate training and improve the accuracy. Suppose we want to use `FCOSHead` as an rpn head in Faster R-CNN and train with the pre-trained [`fcos_r50-caffe_fpn_gn-head_1x_coco`](https://download.openmmlab.com/mmdetection/v2.0/fcos/fcos_r50_caffe_fpn_gn-head_1x_coco/fcos_r50_caffe_fpn_gn-head_1x_coco-821213aa.pth). The content of config file named `configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco.py` is as the following. Note that `fcos_r50-caffe_fpn_gn-head_1x_coco` uses a caffe version of ResNet50, the pixel mean and std in `data_preprocessor` thus need to be updated. + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +model = dict( + data_preprocessor=dict( + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False), + backbone=dict( + norm_cfg=dict(type='BN', requires_grad=False), + style='caffe', + init_cfg=None), # the checkpoint in ``load_from`` contains the weights of backbone + neck=dict( + start_level=1, + add_extra_convs='on_output', # use P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # ignore the unused old settings + type='FCOSHead', + num_classes=1, # num_classes = 1 for rpn, if num_classes > 1, it will be set to 1 in TwoStageDetector automatically + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + roi_head=dict( # update featmap_strides due to the strides in neck + bbox_roi_extractor=dict(featmap_strides=[8, 16, 32, 64, 128]))) + +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/fcos/fcos_r50_caffe_fpn_gn-head_1x_coco/fcos_r50_caffe_fpn_gn-head_1x_coco-821213aa.pth' +``` + +The command for training is as below. + +```python +bash tools/dist_train.sh \ + configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco.py \ + 8 \ + --work-dir ./work_dirs/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/test.md b/mmdet_code/mmdetection/docs/en/user_guides/test.md new file mode 100644 index 0000000000000000000000000000000000000000..129a2409021ba7e5f2752ddb21cdc0c2d0f6c543 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/test.md @@ -0,0 +1,303 @@ +# Test existing models on standard datasets + +To evaluate a model's accuracy, one usually tests the model on some standard datasets, please refer to [dataset prepare guide](dataset_prepare.md) to prepare the dataset. + +This section will show how to test existing models on supported datasets. + +## Test existing models + +We provide testing scripts for evaluating an existing model on the whole dataset (COCO, PASCAL VOC, Cityscapes, etc.). +The following testing environments are supported: + +- single GPU +- CPU +- single node multiple GPUs +- multiple nodes + +Choose the proper script to perform testing depending on the testing environment. + +```shell +# Single-gpu testing +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# CPU: disable GPUs and run single-gpu testing script +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# Multi-gpu testing +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--out ${RESULT_FILE}] +``` + +`tools/dist_test.sh` also supports multi-node testing, but relies on PyTorch's [launch utility](https://pytorch.org/docs/stable/distributed.html#launch-utility). + +Optional arguments: + +- `RESULT_FILE`: Filename of the output results in pickle format. If not specified, the results will not be saved to a file. +- `--show`: If specified, detection results will be plotted on the images and shown in a new window. It is only applicable to single GPU testing and used for debugging and visualization. Please make sure that GUI is available in your environment. Otherwise, you may encounter an error like `cannot connect to X server`. +- `--show-dir`: If specified, detection results will be plotted on the images and saved to the specified directory. It is only applicable to single GPU testing and used for debugging and visualization. You do NOT need a GUI available in your environment for using this option. +- `--work-dir`: If specified, detection results containing evaluation metrics will be saved to the specified directory. +- `--cfg-options`: If specified, the key-value pair optional cfg will be merged into config file + +## Examples + +Assuming that you have already downloaded the checkpoints to the directory `checkpoints/`. + +1. Test RTMDet and visualize the results. Press any key for the next image. + Config and checkpoint files are available [here](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet). + + ```shell + python tools/test.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --show + ``` + +2. Test RTMDet and save the painted images for future visualization. + Config and checkpoint files are available [here](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet). + + ```shell + python tools/test.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --show-dir faster_rcnn_r50_fpn_1x_results + ``` + +3. Test Faster R-CNN on PASCAL VOC (without saving the test results). + Config and checkpoint files are available [here](../../../configs/pascal_voc). + + ```shell + python tools/test.py \ + configs/pascal_voc/faster-rcnn_r50_fpn_1x_voc0712.py \ + checkpoints/faster_rcnn_r50_fpn_1x_voc0712_20200624-c9895d40.pth + ``` + +4. Test Mask R-CNN with 8 GPUs, and evaluate. + Config and checkpoint files are available [here](../../../configs/mask_rcnn). + + ```shell + ./tools/dist_test.sh \ + configs/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 \ + --out results.pkl + ``` + +5. Test Mask R-CNN with 8 GPUs, and evaluate the metric **class-wise**. + Config and checkpoint files are available [here](../../../configs/mask_rcnn). + + ```shell + ./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 \ + --out results.pkl \ + --cfg-options test_evaluator.classwise=True + ``` + +6. Test Mask R-CNN on COCO test-dev with 8 GPUs, and generate JSON files for submitting to the official evaluation server. + Config and checkpoint files are available [here](../../../configs/mask_rcnn). + + Replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in [config](../../../configs/_base_/datasets/coco_instance.py) and run: + + ```shell + ./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 + ``` + + This command generates two JSON files `./work_dirs/coco_instance/test.bbox.json` and `./work_dirs/coco_instance/test.segm.json`. + +7. Test Mask R-CNN on Cityscapes test with 8 GPUs, and generate txt and png files for submitting to the official evaluation server. + Config and checkpoint files are available [here](../../../configs/cityscapes). + + Replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in [config](../../../configs/_base_/datasets/cityscapes_instance.py) and run: + + ```shell + ./tools/dist_test.sh \ + configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py \ + checkpoints/mask_rcnn_r50_fpn_1x_cityscapes_20200227-afe51d5a.pth \ + 8 + ``` + + The generated png and txt would be under `./work_dirs/cityscapes_metric/` directory. + +## Test without Ground Truth Annotations + +MMDetection supports to test models without ground-truth annotations using `CocoDataset`. If your dataset format is not in COCO format, please convert them to COCO format. For example, if your dataset format is VOC, you can directly convert it to COCO format by the [script in tools.](../../../tools/dataset_converters/pascal_voc.py) If your dataset format is Cityscapes, you can directly convert it to COCO format by the [script in tools.](../../../tools/dataset_converters/cityscapes.py) The rest of the formats can be converted using [this script](../../../tools/dataset_converters/images2coco.py). + +```shell +python tools/dataset_converters/images2coco.py \ + ${IMG_PATH} \ + ${CLASSES} \ + ${OUT} \ + [--exclude-extensions] +``` + +arguments: + +- `IMG_PATH`: The root path of images. +- `CLASSES`: The text file with a list of categories. +- `OUT`: The output annotation json file name. The save dir is in the same directory as `IMG_PATH`. +- `exclude-extensions`: The suffix of images to be excluded, such as 'png' and 'bmp'. + +After the conversion is complete, you need to replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in [config](../../../configs/_base_/datasets/coco_detection.py)(find which dataset in 'configs/_base_/datasets' the current config corresponds to) and run: + +```shell +# Single-gpu testing +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--show] + +# CPU: disable GPUs and run single-gpu testing script +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# Multi-gpu testing +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--show] +``` + +Assuming that the checkpoints in the [model zoo](https://mmdetection.readthedocs.io/en/latest/modelzoo_statistics.html) have been downloaded to the directory `checkpoints/`, we can test Mask R-CNN on COCO test-dev with 8 GPUs, and generate JSON files using the following command. + +```sh +./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 +``` + +This command generates two JSON files `./work_dirs/coco_instance/test.bbox.json` and `./work_dirs/coco_instance/test.segm.json`. + +## Batch Inference + +MMDetection supports inference with a single image or batched images in test mode. By default, we use single-image inference and you can use batch inference by modifying `samples_per_gpu` in the config of test data. You can do that either by modifying the config as below. + +```shell +data = dict(train_dataloader=dict(...), val_dataloader=dict(...), test_dataloader=dict(batch_size=2, ...)) +``` + +Or you can set it through `--cfg-options` as `--cfg-options test_dataloader.batch_size=2` + +## Test Time Augmentation (TTA) + +Test time augmentation (TTA) is a data augmentation strategy used during the test phase. It applies different augmentations, such as flipping and scaling, to the same image for model inference, and then merges the predictions of each augmented image to obtain more accurate predictions. To make it easier for users to use TTA, MMEngine provides [BaseTTAModel](https://mmengine.readthedocs.io/en/latest/api/generated/mmengine.model.BaseTTAModel.html#mmengine.model.BaseTTAModel) class, which allows users to implement different TTA strategies by simply extending the BaseTTAModel class according to their needs. + +In MMDetection, we provides [DetTTAModel](../../../mmdet/models/test_time_augs/det_tta.py) class, which inherits from BaseTTAModel. + +### Use case + +Using TTA requires two steps. First, you need to add `tta_model` and `tta_pipeline` in the configuration file: + +```shell +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict( + type='nms', + iou_threshold=0.5), + max_per_img=100)) + +tta_pipeline = [ + dict(type='LoadImageFromFile', + backend_args=None), + dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=(1333, 800), keep_ratio=True) + ], [ # It uses 2 flipping transformations (flipping and not flipping). + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ]])] +``` + +Second, set `--tta` when running the test scripts as examples below: + +```shell +# Single-gpu testing +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--tta] + +# CPU: disable GPUs and run single-gpu testing script +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--tta] + +# Multi-gpu testing +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--tta] +``` + +You can also modify the TTA config by yourself, such as adding scaling enhancement: + +```shell +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict( + type='nms', + iou_threshold=0.5), + max_per_img=100)) + +img_scales = [(1333, 800), (666, 400), (2000, 1200)] +tta_pipeline = [ + dict(type='LoadImageFromFile', + backend_args=None), + dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=s, keep_ratio=True) for s in img_scales + ], [ + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ]])] +``` + +The above data augmentation pipeline will first perform 3 multi-scaling transformations on the image, followed by 2 flipping transformations (flipping and not flipping). Finally, the image is packaged into the final result using PackDetInputs. + +Here are more TTA use cases for your reference: + +- [RetinaNet](../../../configs/retinanet/retinanet_tta.py) +- [CenterNet](../../../configs/centernet/centernet_tta.py) +- [YOLOX](../../../configs/rtmdet/rtmdet_tta.py) +- [RTMDet](../../../configs/yolox/yolox_tta.py) + +For more advanced usage and data flow of TTA, please refer to [MMEngine](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/test_time_augmentation.html#data-flow). We will support instance segmentation TTA latter. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/test_results_submission.md b/mmdet_code/mmdetection/docs/en/user_guides/test_results_submission.md new file mode 100644 index 0000000000000000000000000000000000000000..721347ea1e9b7d3d50dc3b64d9adec7eda19d2ae --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/test_results_submission.md @@ -0,0 +1,182 @@ +# Test Results Submission + +## Panoptic segmentation test results submission + +The following sections introduce how to produce the prediction results of panoptic segmentation models on the COCO test-dev set and submit the predictions to [COCO evaluation server](https://competitions.codalab.org/competitions/19507). + +### Prerequisites + +- Download [COCO test dataset images](http://images.cocodataset.org/zips/test2017.zip), [testing image info](http://images.cocodataset.org/annotations/image_info_test2017.zip), and [panoptic train/val annotations](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip), then unzip them, put 'test2017' to `data/coco/`, put json files and annotation files to `data/coco/annotations/`. + +```shell +# suppose data/coco/ does not exist +mkdir -pv data/coco/ + +# download test2017 +wget -P data/coco/ http://images.cocodataset.org/zips/test2017.zip +wget -P data/coco/ http://images.cocodataset.org/annotations/image_info_test2017.zip +wget -P data/coco/ http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip + +# unzip them +unzip data/coco/test2017.zip -d data/coco/ +unzip data/coco/image_info_test2017.zip -d data/coco/ +unzip data/coco/panoptic_annotations_trainval2017.zip -d data/coco/ + +# remove zip files (optional) +rm -rf data/coco/test2017.zip data/coco/image_info_test2017.zip data/coco/panoptic_annotations_trainval2017.zip +``` + +- Run the following code to update category information in testing image info. Since the attribute `isthing` is missing in category information of 'image_info_test-dev2017.json', we need to update it with the category information in 'panoptic_val2017.json'. + +```shell +python tools/misc/gen_coco_panoptic_test_info.py data/coco/annotations +``` + +After completing the above preparations, your directory structure of `data` should be like this: + +```text +data +`-- coco + |-- annotations + | |-- image_info_test-dev2017.json + | |-- image_info_test2017.json + | |-- panoptic_image_info_test-dev2017.json + | |-- panoptic_train2017.json + | |-- panoptic_train2017.zip + | |-- panoptic_val2017.json + | `-- panoptic_val2017.zip + `-- test2017 +``` + +### Inference on coco test-dev + +To do inference on coco test-dev, we should update the setting of `test_dataloder` and `test_evaluator` first. There two ways to do this: 1. update them in config file; 2. update them in command line. + +#### Update them in config file + +The relevant settings are provided at the end of `configs/_base_/datasets/coco_panoptic.py`, as below. + +```python +test_dataloader = dict( + batch_size=1, + num_workers=1, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/panoptic_image_info_test-dev2017.json', + data_prefix=dict(img='test2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_evaluator = dict( + type='CocoPanopticMetric', + format_only=True, + ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', + outfile_prefix='./work_dirs/coco_panoptic/test') +``` + +Any of the following way can be used to update the setting for inference on coco test-dev set. + +Case 1: Directly uncomment the setting in `configs/_base_/datasets/coco_panoptic.py`. + +Case 2: Copy the following setting to the config file you used now. + +```python +test_dataloader = dict( + dataset=dict( + ann_file='annotations/panoptic_image_info_test-dev2017.json', + data_prefix=dict(img='test2017/', _delete_=True))) +test_evaluator = dict( + format_only=True, + ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', + outfile_prefix='./work_dirs/coco_panoptic/test') +``` + +Then infer on coco test-dev et by the following command. + +```shell +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} +``` + +#### Update them in command line + +The command for update of the related settings and inference on coco test-dev are as below. + +```shell +# test with single gpu +CUDA_VISIBLE_DEVICES=0 python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results + +# test with four gpus +CUDA_VISIBLE_DEVICES=0,1,3,4 bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + 8 \ # eights gpus + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results + +# test with slurm +GPUS=8 tools/slurm_test.sh \ + ${Partition} \ + ${JOB_NAME} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results +``` + +Example + +Suppose we perform inference on `test2017` using pretrained MaskFormer with ResNet-50 backbone. + +```shell +# test with single gpu +CUDA_VISIBLE_DEVICES=0 python tools/test.py \ + configs/maskformer/maskformer_r50_mstrain_16x1_75e_coco.py \ + checkpoints/maskformer_r50_mstrain_16x1_75e_coco_20220221_141956-bc2699cb.pth \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=work_dirs/maskformer/results +``` + +### Rename files and zip results + +After inference, the panoptic segmentation results (a json file and a directory where the masks are stored) will be in `WORK_DIR`. We should rename them according to the naming convention described on [COCO's Website](https://cocodataset.org/#upload). Finally, we need to compress the json and the directory where the masks are stored into a zip file, and rename the zip file according to the naming convention. Note that the zip file should **directly** contains the above two files. + +The commands to rename files and zip results: + +```shell +# In WORK_DIR, we have panoptic segmentation results: 'panoptic' and 'results.panoptic.json'. +cd ${WORK_DIR} + +# replace '[algorithm_name]' with the name of algorithm you used. +mv ./panoptic ./panoptic_test-dev2017_[algorithm_name]_results +mv ./results.panoptic.json ./panoptic_test-dev2017_[algorithm_name]_results.json +zip panoptic_test-dev2017_[algorithm_name]_results.zip -ur panoptic_test-dev2017_[algorithm_name]_results panoptic_test-dev2017_[algorithm_name]_results.json +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/tracking_analysis_tools.md b/mmdet_code/mmdetection/docs/en/user_guides/tracking_analysis_tools.md new file mode 100644 index 0000000000000000000000000000000000000000..acced58d47baa6d73227ab7b5b267c2ae84623eb --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/tracking_analysis_tools.md @@ -0,0 +1,86 @@ +**We provide lots of useful tools under the `tools/` directory.** + +## MOT Test-time Parameter Search + +`tools/analysis_tools/mot/mot_param_search.py` can search the parameters of the `tracker` in MOT models. +It is used as the same manner with `tools/test.py` but **different** in the configs. + +Here is an example that shows how to modify the configs: + +1. Define the desirable evaluation metrics to record. + + For example, you can define the `evaluator` as + + ```python + test_evaluator=dict(type='MOTChallengeMetrics', metric=['HOTA', 'CLEAR', 'Identity']) + ``` + + Of course, you can also customize the content of `metric` in `test_evaluator`. You are free to choose one or more of `['HOTA', 'CLEAR', 'Identity']`. + +2. Define the parameters and the values to search. + + Assume you have a tracker like + + ```python + model=dict( + tracker=dict( + type='BaseTracker', + obj_score_thr=0.5, + match_iou_thr=0.5 + ) + ) + ``` + + If you want to search the parameters of the tracker, just change the value to a list as follow + + ```python + model=dict( + tracker=dict( + type='BaseTracker', + obj_score_thr=[0.4, 0.5, 0.6], + match_iou_thr=[0.4, 0.5, 0.6, 0.7] + ) + ) + ``` + + Then the script will test the totally 12 cases and log the results. + +## MOT Error Visualize + +`tools/analysis_tools/mot/mot_error_visualize.py` can visualize errors for multiple object tracking. +This script needs the result of inference. By Default, the **red** bounding box denotes false positive, the **yellow** bounding box denotes the false negative and the **blue** bounding box denotes ID switch. + +``` +python tools/analysis_tools/mot/mot_error_visualize.py \ + ${CONFIG_FILE}\ + --input ${INPUT} \ + --result-dir ${RESULT_DIR} \ + [--output-dir ${OUTPUT}] \ + [--fps ${FPS}] \ + [--show] \ + [--backend ${BACKEND}] +``` + +The `RESULT_DIR` contains the inference results of all videos and the inference result is a `txt` file. + +Optional arguments: + +- `OUTPUT`: Output of the visualized demo. If not specified, the `--show` is obligate to show the video on the fly. +- `FPS`: FPS of the output video. +- `--show`: Whether show the video on the fly. +- `BACKEND`: The backend to visualize the boxes. Options are `cv2` and `plt`. + +## Browse dataset + +`tools/analysis_tools/mot/browse_dataset.py` can visualize the training dataset to check whether the dataset configuration is correct. + +**Examples:** + +```shell +python tools/analysis_tools/browse_dataset.py ${CONFIG_FILE} [--show-interval ${SHOW_INTERVAL}] +``` + +Optional arguments: + +- `SHOW_INTERVAL`: The interval of show (s). +- `--show`: Whether show the images on the fly. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/tracking_config.md b/mmdet_code/mmdetection/docs/en/user_guides/tracking_config.md new file mode 100644 index 0000000000000000000000000000000000000000..fa8aeea04f8ad1337b67ae50bbdd92b6dfbb1cdc --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/tracking_config.md @@ -0,0 +1,112 @@ +# Learn about Configs + +We use python files as our config system. You can find all the provided configs under $MMDetection/configs. + +We incorporate modular and inheritance design into our config system, +which is convenient to conduct various experiments. +If you wish to inspect the config file, +you may run `python tools/misc/print_config.py /PATH/TO/CONFIG` to see the complete config. + +## A brief description of a complete config + +A complete config usually contains the following primary fields: + +- `model`: the basic config of model, which may contain `data_preprocessor`, modules (e.g., `detector`, `motion`),`train_cfg`, `test_cfg`, etc. +- `train_dataloader`: the config of training dataloader, which usually contains `batch_size`, `num_workers`, `sampler`, `dataset`, etc. +- `val_dataloader`: the config of validation dataloader, which is similar with `train_dataloader`. +- `test_dataloader`: the config of testing dataloader, which is similar with `train_dataloader`. +- `val_evaluator`: the config of validation evaluator. For example,`type='MOTChallengeMetrics'` for MOT task on the MOTChallenge benchmarks. +- `test_evaluator`: the config of testing evaluator, which is similar with `val_evaluator`. +- `train_cfg`: the config of training loop. For example, `type='EpochBasedTrainLoop'`. +- `val_cfg`: the config of validation loop. For example, `type='VideoValLoop'`. +- `test_cfg`: the config of testing loop. For example, `type='VideoTestLoop'`. +- `default_hooks`: the config of default hooks, which may include hooks for timer, logger, param_scheduler, checkpoint, sampler_seed, visualization, etc. +- `vis_backends`: the config of visualization backends, which uses `type='LocalVisBackend'` as default. +- `visualizer`: the config of visualizer. `type='TrackLocalVisualizer'` for MOT tasks. +- `param_scheduler`: the config of parameter scheduler, which usually sets the learning rate scheduler. +- `optim_wrapper`: the config of optimizer wrapper, which contains optimization-related information, for example optimizer, gradient clipping, etc. +- `load_from`: load models as a pre-trained model from a given path. +- `resume`: If `True`, resume checkpoints from `load_from`, and the training will be resumed from the epoch when the checkpoint is saved. + +## Modify config through script arguments + +When submitting jobs using `tools/train.py` or `tools/test_tracking.py`, +you may specify `--cfg-options` to in-place modify the config. +We present several examples as follows. +For more details, please refer to [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/config.md). + +- **Update config keys of dict chains.** + + The config options can be specified following the order of the dict keys in the original config. + For example, `--cfg-options model.detector.backbone.norm_eval=False` changes the all BN modules in model backbones to train mode. + +- **Update keys inside a list of configs.** + + Some config dicts are composed as a list in your config. + For example, the testing pipeline `test_dataloader.dataset.pipeline` is normally a list e.g. `[dict(type='LoadImageFromFile'), ...]`. + If you want to change `LoadImageFromFile` to `LoadImageFromWebcam` in the pipeline, + you may specify `--cfg-options test_dataloader.dataset.pipeline.0.type=LoadImageFromWebcam`. + +- **Update values of list/tuples.** + + Maybe the value to be updated is a list or a tuple. + For example, you can change the key `mean` of `data_preprocessor` by specifying `--cfg-options model.data_preprocessor.mean=[0,0,0]`. + Note that **NO** white space is allowed inside the specified value. + +## Config File Structure + +There are 3 basic component types under `config/_base_`, i.e., dataset, model and default_runtime. +Many methods could be easily constructed with one of each like SORT, DeepSORT. +The configs that are composed by components from `_base_` are called *primitive*. + +For all configs under the same folder, it is recommended to have only **one** *primitive* config. +All other configs should inherit from the *primitive* config. +In this way, the maximum of inheritance level is 3. + +For easy understanding, we recommend contributors to inherit from exiting methods. +For example, if some modification is made base on Faster R-CNN, +user may first inherit the basic Faster R-CNN structure +by specifying `_base_ = ../_base_/models/faster-rcnn_r50-dc5.py`, +then modify the necessary fields in the config files. + +If you are building an entirely new method that does not share the structure with any of the existing methods, +you may create a folder `method_name` under `configs`. + +Please refer to [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/config.md) for detailed documentation. + +## Config Name Style + +We follow the below style to name config files. Contributors are advised to follow the same style. + +```shell +{method}_{module}_{train_cfg}_{train_data}_{test_data} +``` + +- `{method}`: method name, like `sort`. +- `{module}`: basic modules of the method, like `faster-rcnn_r50_fpn`. +- `{train_cfg}`: training config which usually contains batch size, epochs, etc, like `8xb4-80e`. +- `{train_data}`: training data, like `mot17halftrain`. +- `{test_data}`: testing data, like `test-mot17halfval`. + +## FAQ + +**Ignore some fields in the base configs** + +Sometimes, you may set `_delete_=True` to ignore some of fields in base configs. +You may refer to [MMEngine](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/config.md) for simple illustration. + +## Tracking Data Structure Introduction + +### Advantages and new features + +In mmdetection tracking task, we employ videos to organize the dataset and use +TrackDataSample to descirbe dataset info. + +- Based on video organization, we provide transform `UniformRefFrameSample` to sample key frames and ref frames and use `TransformBroadcaster` for for clip training. +- TrackDataSample can be viewd as a wrapper of multiple DetDataSample to some extent. It contains a property `video_data_samples` which is a list of DetDataSample, each of which corresponds to a single frame. In addition, it's metainfo includes key_frames_inds and ref_frames_inds to apply clip training way. +- Thanks to video-based data organization, the entire video can be directly tested. This way is more concise and intuitive. We also provide image_based test method, if your GPU mmemory cannot fit the entire video. + +### TODO + +- Some algorithms like StrongSORT, Mask2Former can not support video_based testing. These algorithms pose a challenge to GPU memory. we will optimize this problem in the future. +- Now we do not support joint training of video_based dataset like MOT Challenge Dataset and image_based dataset like Crowdhuman for the algorithm QDTrack. we will optimize this problem in the future. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/tracking_dataset_prepare.md b/mmdet_code/mmdetection/docs/en/user_guides/tracking_dataset_prepare.md new file mode 100644 index 0000000000000000000000000000000000000000..56a4b77fc6e6fc1802ef54544413c2d082bfa49b --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/tracking_dataset_prepare.md @@ -0,0 +1,247 @@ +## Dataset Preparation + +This page provides the instructions for dataset preparation on existing benchmarks, include + +- Multiple Object Tracking + + - [MOT Challenge](https://motchallenge.net/) + - [CrowdHuman](https://www.crowdhuman.org/) + +- Video Instance Segmentation + + - [YouTube-VIS](https://youtube-vos.org/dataset/vis/) + +### 1. Download Datasets + +Please download the datasets from the official websites. It is recommended to symlink the root of the datasets to `$MMDETECTION/data`. + +#### 1.1 Multiple Object Tracking + +- For the training and testing of multi object tracking task, one of the MOT Challenge datasets (e.g. MOT17, MOT20) are needed, CrowdHuman can be served as comlementary dataset. + +- For users in China, the following datasets can be downloaded from [OpenDataLab](https://opendatalab.com/) with high speed: + + - [MOT17](https://opendatalab.com/MOT17/download) + - [MOT20](https://opendatalab.com/MOT20/download) + - [CrowdHuman](https://opendatalab.com/CrowdHuman/download) + +#### 1.2 Video Instance Segmentation + +- For the training and testing of video instance segmetatioon task, only one of YouTube-VIS datasets (e.g. YouTube-VIS 2019, YouTube-VIS 2021) is needed. + +- YouTube-VIS 2019 dataset can be download from [YouTubeVOS](https://codalab.lisn.upsaclay.fr/competitions/6064) + +- YouTube-VIS 2021 dataset can be download from [YouTubeVOS](https://codalab.lisn.upsaclay.fr/competitions/7680) + +#### 1.3 Data Structure + +If your folder structure is different from the following, you may need to change the corresponding paths in config files. + +``` +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── annotations +│ │ +| ├── MOT15/MOT16/MOT17/MOT20 +| | ├── train +| | | ├── MOT17-02-DPM +| | | | ├── det +| │ │ │ ├── gt +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── test +| | | ├── MOT17-01-DPM +| | | | ├── det +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +│ │ +│ ├── crowdhuman +│ │ ├── annotation_train.odgt +│ │ ├── annotation_val.odgt +│ │ ├── train +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_train01.zip +│ │ │ ├── CrowdHuman_train02.zip +│ │ │ ├── CrowdHuman_train03.zip +│ │ ├── val +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_val.zip +│ │ +``` + +### 2. Convert Annotations + +In this case, you need to convert the official annotations to coco style. We provide scripts and the usages are as following: + +```shell +# MOT17 +# The processing of other MOT Challenge dataset is the same as MOT17 +python ./tools/dataset_converters/mot2coco.py -i ./data/MOT17/ -o ./data/MOT17/annotations --split-train --convert-det +python ./tools/dataset_converters/mot2reid.py -i ./data/MOT17/ -o ./data/MOT17/reid --val-split 0.2 --vis-threshold 0.3 + +# CrowdHuman +python ./tools/dataset_converters/crowdhuman2coco.py -i ./data/crowdhuman -o ./data/crowdhuman/annotations + +# YouTube-VIS 2019 +python ./tools/dataset_converters/youtubevis2coco.py -i ./data/youtube_vis_2019 -o ./data/youtube_vis_2019/annotations --version 2019 + +# YouTube-VIS 2021 +python ./tools/dataset_converters/youtubevis2coco.py -i ./data/youtube_vis_2021 -o ./data/youtube_vis_2021/annotations --version 2021 + +``` + +The folder structure will be as following after your run these scripts: + +``` +mmdetection +├── mmtrack +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── annotations +│ │ +| ├── MOT15/MOT16/MOT17/MOT20 +| | ├── train +| | | ├── MOT17-02-DPM +| | | | ├── det +| │ │ │ ├── gt +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── test +| | | ├── MOT17-01-DPM +| | | | ├── det +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── annotations +| | ├── reid +│ │ │ ├── imgs +│ │ │ ├── meta +│ │ +│ ├── crowdhuman +│ │ ├── annotation_train.odgt +│ │ ├── annotation_val.odgt +│ │ ├── train +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_train01.zip +│ │ │ ├── CrowdHuman_train02.zip +│ │ │ ├── CrowdHuman_train03.zip +│ │ ├── val +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_val.zip +│ │ ├── annotations +│ │ │ ├── crowdhuman_train.json +│ │ │ ├── crowdhuman_val.json +│ │ +│ ├── youtube_vis_2019 +│ │ │── train +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── valid +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── test +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── train.json (the official annotation files) +│ │ │── valid.json (the official annotation files) +│ │ │── test.json (the official annotation files) +│ │ │── annotations (the converted annotation file) +│ │ +│ ├── youtube_vis_2021 +│ │ │── train +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── valid +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── test +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── annotations (the converted annotation file) +``` + +#### The folder of annotations and reid in MOT15/MOT16/MOT17/MOT20 + +We take MOT17 dataset as examples, the other datasets share similar structure. + +There are 8 JSON files in `data/MOT17/annotations`: + +`train_cocoformat.json`: JSON file containing the annotations information of the training set in MOT17 dataset. + +`train_detections.pkl`: Pickle file containing the public detections of the training set in MOT17 dataset. + +`test_cocoformat.json`: JSON file containing the annotations information of the testing set in MOT17 dataset. + +`test_detections.pkl`: Pickle file containing the public detections of the testing set in MOT17 dataset. + +`half-train_cocoformat.json`, `half-train_detections.pkl`, `half-val_cocoformat.json`and `half-val_detections.pkl` share similar meaning with `train_cocoformat.json` and `train_detections.pkl`. The `half` means we split each video in the training set into half. The first half videos are denoted as `half-train` set, and the second half videos are denoted as`half-val` set. + +The structure of `data/MOT17/reid` is as follows: + +``` +reid +├── imgs +│ ├── MOT17-02-FRCNN_000002 +│ │ ├── 000000.jpg +│ │ ├── 000001.jpg +│ │ ├── ... +│ ├── MOT17-02-FRCNN_000003 +│ │ ├── 000000.jpg +│ │ ├── 000001.jpg +│ │ ├── ... +├── meta +│ ├── train_80.txt +│ ├── val_20.txt +``` + +The `80` in `train_80.txt` means the proportion of the training dataset to the whole ReID dataset is 80%. While the proportion of the validation dataset is 20%. + +For training, we provide a annotation list `train_80.txt`. Each line of the list contains a filename and its corresponding ground-truth labels. The format is as follows: + +``` +MOT17-05-FRCNN_000110/000018.jpg 0 +MOT17-13-FRCNN_000146/000014.jpg 1 +MOT17-05-FRCNN_000088/000004.jpg 2 +MOT17-02-FRCNN_000009/000081.jpg 3 +``` + +`MOT17-05-FRCNN_000110` denotes the 110-th person in `MOT17-05-FRCNN` video. + +For validation, The annotation list `val_20.txt` remains the same as format above. + +Images in `reid/imgs` are cropped from raw images in `MOT17/train` by the corresponding `gt.txt`. The value of ground-truth labels should fall in range `[0, num_classes - 1]`. + +#### The folder of annotations in crowdhuman + +There are 2 JSON files in `data/crowdhuman/annotations`: + +`crowdhuman_train.json`: JSON file containing the annotations information of the training set in CrowdHuman dataset. +`crowdhuman_val.json`: JSON file containing the annotations information of the validation set in CrowdHuman dataset. + +#### The folder of annotations in youtube_vis_2019/youtube_vis2021 + +There are 3 JSON files in `data/youtube_vis_2019/annotations` or `data/youtube_vis_2021/annotations`: + +`youtube_vis_2019_train.json`/`youtube_vis_2021_train.json`: JSON file containing the annotations information of the training set in youtube_vis_2019/youtube_vis2021 dataset. + +`youtube_vis_2019_valid.json`/`youtube_vis_2021_valid.json`: JSON file containing the annotations information of the validation set in youtube_vis_2019/youtube_vis2021 dataset. + +`youtube_vis_2019_test.json`/`youtube_vis_2021_test.json`: JSON file containing the annotations information of the testing set in youtube_vis_2019/youtube_vis2021 dataset. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/tracking_inference.md b/mmdet_code/mmdetection/docs/en/user_guides/tracking_inference.md new file mode 100644 index 0000000000000000000000000000000000000000..06a6912acf649ea9c02db25901260233cf99b697 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/tracking_inference.md @@ -0,0 +1,55 @@ +# Inference + +We provide demo scripts to inference a given video or a folder that contains continuous images. The source codes are available [here](https://github.com/open-mmlab/mmdetection/tree/tracking/demo). + +Note that if you use a folder as the input, the image names there must be **sortable** , which means we can re-order the images according to the numbers contained in the filenames. We now only support reading the images whose filenames end with `.jpg`, `.jpeg` and `.png`. + +## Inference MOT models + +This script can inference an input video / images with a multiple object tracking or video instance segmentation model. + +```shell +python demo/mot_demo.py \ + ${INPUTS} + ${CONFIG_FILE} \ + [--checkpoint ${CHECKPOINT_FILE}] \ + [--detector ${DETECTOR_FILE}] \ + [--reid ${REID_FILE}] \ + [--score-thr ${SCORE_THR}] \ + [--device ${DEVICE}] \ + [--out ${OUTPUT}] \ + [--show] +``` + +The `INPUT` and `OUTPUT` support both _mp4 video_ format and the _folder_ format. + +**Important:** For `DeepSORT`, `SORT`, `StrongSORT`, they need load the weight of the `reid` and the weight of the `detector` separately. Therefore, we use `--detector` and `--reid` to load weights. Other algorithms such as `ByteTrack`, `OCSORT` `QDTrack` `MaskTrackRCNN` and `Mask2Former` use `--checkpoint` to load weights. + +Optional arguments: + +- `CHECKPOINT_FILE`: The checkpoint is optional. +- `DETECTOR_FILE`: The detector is optional. +- `REID_FILE`: The reid is optional. +- `SCORE_THR`: The threshold of score to filter bboxes. +- `DEVICE`: The device for inference. Options are `cpu` or `cuda:0`, etc. +- `OUTPUT`: Output of the visualized demo. If not specified, the `--show` is obligate to show the video on the fly. +- `--show`: Whether show the video on the fly. + +**Examples of running mot model:** + +```shell +# Example 1: do not specify --checkpoint to use --detector +python demo/mot_demo.py \ + demo/demo_mot.mp4 \ + configs/sort/sort_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py \ + --detector \ + https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-half-64ee2ed4.pth \ + --out mot.mp4 + +# Example 2: use --checkpoint +python demo/mot_demo.py \ + demo/demo_mot.mp4 \ + configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py \ + --checkpoint https://download.openmmlab.com/mmtracking/mot/qdtrack/mot_dataset/qdtrack_faster-rcnn_r50_fpn_4e_mot17_20220315_145635-76f295ef.pth \ + --out mot.mp4 +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/tracking_train_test.md b/mmdet_code/mmdetection/docs/en/user_guides/tracking_train_test.md new file mode 100644 index 0000000000000000000000000000000000000000..1a6871d717d4740355788dd95047a80703184da9 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/tracking_train_test.md @@ -0,0 +1,229 @@ +# Learn to train and test + +## Train + +This section will show how to train existing models on supported datasets. +The following training environments are supported: + +- CPU +- single GPU +- single node multiple GPUs +- multiple nodes + +You can also manage jobs with Slurm. + +Important: + +- You can change the evaluation interval during training by modifying the `train_cfg` as + `train_cfg = dict(val_interval=10)`. That means evaluating the model every 10 epochs. +- The default learning rate in all config files is for 8 GPUs. + According to the [Linear Scaling Rule](https://arxiv.org/abs/1706.02677), + you need to set the learning rate proportional to the batch size if you use different GPUs or images per GPU, + e.g., `lr=0.01` for 8 GPUs * 1 img/gpu and lr=0.04 for 16 GPUs * 2 imgs/gpu. +- During training, log files and checkpoints will be saved to the working directory, + which is specified by CLI argument `--work-dir`. It uses `./work_dirs/CONFIG_NAME` as default. +- If you want the mixed precision training, simply specify CLI argument `--amp`. + +#### 1. Train on CPU + +The model is default put on cuda device. +Only if there are no cuda devices, the model will be put on cpu. +So if you want to train the model on CPU, you need to `export CUDA_VISIBLE_DEVICES=-1` to disable GPU visibility first. +More details in [MMEngine](https://github.com/open-mmlab/mmengine/blob/ca282aee9e402104b644494ca491f73d93a9544f/mmengine/runner/runner.py#L849-L850). + +```shell script +CUDA_VISIBLE_DEVICES=-1 python tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +An example of training the MOT model QDTrack on CPU: + +```shell script +CUDA_VISIBLE_DEVICES=-1 python tools/train.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +``` + +#### 2. Train on single GPU + +If you want to train the model on single GPU, you can directly use the `tools/train.py` as follows. + +```shell script +python tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +You can use `export CUDA_VISIBLE_DEVICES=$GPU_ID` to select the GPU. + +An example of training the MOT model QDTrack on single GPU: + +```shell script +CUDA_VISIBLE_DEVICES=2 python tools/train.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +``` + +#### 3. Train on single node multiple GPUs + +We provide `tools/dist_train.sh` to launch training on multiple GPUs. +The basic usage is as follows. + +```shell script +bash ./tools/dist_train.sh ${CONFIG_FILE} ${GPU_NUM} [optional arguments] +``` + +If you would like to launch multiple jobs on a single machine, +e.g., 2 jobs of 4-GPU training on a machine with 8 GPUs, +you need to specify different ports (29500 by default) for each job to avoid communication conflict. + +For example, you can set the port in commands as follows. + +```shell script +CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4 +CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4 +``` + +An example of training the MOT model QDTrack on single node multiple GPUs: + +```shell script +bash ./tools/dist_train.sh configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py 8 +``` + +#### 4. Train on multiple nodes + +If you launch with multiple machines simply connected with ethernet, you can simply run following commands: + +On the first machine: + +```shell script +NNODES=2 NODE_RANK=0 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR bash tools/dist_train.sh $CONFIG $GPUS +``` + +On the second machine: + +```shell script +NNODES=2 NODE_RANK=1 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR bash tools/dist_train.sh $CONFIG $GPUS +``` + +Usually it is slow if you do not have high speed networking like InfiniBand. + +#### 5. Train with Slurm + +[Slurm](https://slurm.schedmd.com/) is a good job scheduling system for computing clusters. +On a cluster managed by Slurm, you can use `slurm_train.sh` to spawn training jobs. +It supports both single-node and multi-node training. + +The basic usage is as follows. + +```shell script +bash ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR} ${GPUS} +``` + +An example of training the MOT model QDTrack with Slurm: + +```shell script +PORT=29501 \ +GPUS_PER_NODE=8 \ +SRUN_ARGS="--quotatype=reserved" \ +bash ./tools/slurm_train.sh \ +mypartition \ +mottrack +configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +./work_dirs/QDTrack \ +8 +``` + +## Test + +This section will show how to test existing models on supported datasets. +The following testing environments are supported: + +- CPU +- single GPU +- single node multiple GPUs +- multiple nodes + +You can also manage jobs with Slurm. + +Important: + +- In MOT, some algorithms like `DeepSORT`, `SORT`, `StrongSORT` need load the weight of the `reid` and the weight of the `detector` separately. + Other algorithms such as `ByteTrack`, `OCSORT` and `QDTrack` don't need. So we provide `--checkpoint`, `--detector` and `--reid` to load weights. +- We provide two ways to evaluate and test models, video_basede test and image_based test. some algorithms like `StrongSORT`, `Mask2former` only support + video_based test. if your GPU memory can't fit the entire video, you can switch test way by set sampler type. + For example: + video_based test: `sampler=dict(type='DefaultSampler', shuffle=False, round_up=False)` + image_based test: `sampler=dict(type='TrackImgSampler')` +- You can set the results saving path by modifying the key `outfile_prefix` in evaluator. + For example, `val_evaluator = dict(outfile_prefix='results/sort_mot17')`. + Otherwise, a temporal file will be created and will be removed after evaluation. +- If you just want the formatted results without evaluation, you can set `format_only=True`. + For example, `test_evaluator = dict(type='MOTChallengeMetric', metric=['HOTA', 'CLEAR', 'Identity'], outfile_prefix='sort_mot17_results', format_only=True)` + +#### 1. Test on CPU + +The model is default put on cuda device. +Only if there are no cuda devices, the model will be put on cpu. +So if you want to test the model on CPU, you need to `export CUDA_VISIBLE_DEVICES=-1` to disable GPU visibility first. +More details in [MMEngine](https://github.com/open-mmlab/mmengine/blob/ca282aee9e402104b644494ca491f73d93a9544f/mmengine/runner/runner.py#L849-L850). + +```shell script +CUDA_VISIBLE_DEVICES=-1 python tools/test_tracking.py ${CONFIG_FILE} [optional arguments] +``` + +An example of testing the MOT model SORT on CPU: + +```shell script +CUDA_VISIBLE_DEVICES=-1 python tools/test_tracking.py configs/sort/sort_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py --detector ${CHECKPOINT_FILE} +``` + +#### 2. Test on single GPU + +If you want to test the model on single GPU, you can directly use the `tools/test_tracking.py` as follows. + +```shell script +python tools/test_tracking.py ${CONFIG_FILE} [optional arguments] +``` + +You can use `export CUDA_VISIBLE_DEVICES=$GPU_ID` to select the GPU. + +An example of testing the MOT model QDTrack on single GPU: + +```shell script +CUDA_VISIBLE_DEVICES=2 python tools/test_tracking.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py --detector ${CHECKPOINT_FILE} +``` + +#### 3. Test on single node multiple GPUs + +We provide `tools/dist_test_tracking.sh` to launch testing on multiple GPUs. +The basic usage is as follows. + +```shell script +bash ./tools/dist_test_tracking.sh ${CONFIG_FILE} ${GPU_NUM} [optional arguments] +``` + +An example of testing the MOT model DeepSort on single node multiple GPUs: + +```shell script +bash ./tools/dist_test_tracking.sh configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py 8 --detector ${CHECKPOINT_FILE} --reid ${CHECKPOINT_FILE} +``` + +#### 4. Test on multiple nodes + +You can test on multiple nodes, which is similar with "Train on multiple nodes". + +#### 5. Test with Slurm + +On a cluster managed by Slurm, you can use `slurm_test_tracking.sh` to spawn testing jobs. +It supports both single-node and multi-node testing. + +The basic usage is as follows. + +```shell script +[GPUS=${GPUS}] bash tools/slurm_test_tracking.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} [optional arguments] +``` + +An example of testing the VIS model Mask2former with Slurm: + +```shell script +GPUS=8 +bash tools/slurm_test_tracking.sh \ +mypartition \ +vis \ +configs/mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py \ +--checkpoint ${CHECKPOINT_FILE} +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/tracking_visualization.md b/mmdet_code/mmdetection/docs/en/user_guides/tracking_visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..28953256200a3a6c76254de46f74875f070be172 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/tracking_visualization.md @@ -0,0 +1,47 @@ +# Learn about Visualization + +## Local Visualization + +This section will present how to visualize the detection/tracking results with local visualizer. + +If you want to draw prediction results, you can turn this feature on by setting `draw=True` in `TrackVisualizationHook` as follows. + +```shell script +default_hooks = dict(visualization=dict(type='TrackVisualizationHook', draw=True)) +``` + +Specifically, the `TrackVisualizationHook` has the following arguments: + +- `draw`: whether to draw prediction results. If it is False, it means that no drawing will be done. Defaults to False. +- `interval`: The interval of visualization. Defaults to 30. +- `score_thr`: The threshold to visualize the bboxes and masks. Defaults to 0.3. +- `show`: Whether to display the drawn image. Default to False. +- `wait_time`: The interval of show (s). Defaults to 0. +- `test_out_dir`: directory where painted images will be saved in testing process. +- `backend_args`: Arguments to instantiate a file client. Defaults to `None`. + +In the `TrackVisualizationHook`, `TrackLocalVisualizer` will be called to implement visualization for MOT and VIS tasks. +We will present the details below. +You can refer to MMEngine for more details about [Visualization](https://github.com/open-mmlab/mmengine/blob/main/docs/en/advanced_tutorials/visualization.md) and [Hook](https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/hook.md). + +#### Tracking Visualization + +We realize the tracking visualization with class `TrackLocalVisualizer`. +You can call it as follows. + +```python +visualizer = dict(type='TrackLocalVisualizer') +``` + +It has the following arguments: + +- `name`: Name of the instance. Defaults to 'visualizer'. +- `image`: The origin image to draw. The format should be RGB. Defaults to None. +- `vis_backends`: Visual backend config list. Defaults to None. +- `save_dir`: Save file dir for all storage backends. If it is None, the backend storage will not save any data. +- `line_width`: The linewidth of lines. Defaults to 3. +- `alpha`: The transparency of bboxes or mask. Defaults to 0.8. + +Here is a visualization example of DeepSORT: + +![test_img_89](https://user-images.githubusercontent.com/99722489/186062929-6d0e4663-0d8e-4045-9ec8-67e0e41da876.png) diff --git a/mmdet_code/mmdetection/docs/en/user_guides/train.md b/mmdet_code/mmdetection/docs/en/user_guides/train.md new file mode 100644 index 0000000000000000000000000000000000000000..a68d5e4fa11179c62b1c0d72f1316f5fbe7d55f6 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/train.md @@ -0,0 +1,456 @@ +# Train predefined models on standard datasets + +MMDetection also provides out-of-the-box tools for training detection models. +This section will show how to train _predefined_ models (under [configs](../../../configs)) on standard datasets i.e. COCO. + +## Prepare datasets + +Preparing datasets is also necessary for training. See section [Prepare datasets](#prepare-datasets) above for details. + +**Note**: +Currently, the config files under `configs/cityscapes` use COCO pre-trained weights to initialize. +If your network connection is slow or unavailable, it's advisable to download existing models before beginning training to avoid errors. + +## Learning rate auto scaling + +**Important**: The default learning rate in config files is for 8 GPUs and 2 sample per GPU (batch size = 8 * 2 = 16). And it had been set to `auto_scale_lr.base_batch_size` in `config/_base_/schedules/schedule_1x.py`. The learning rate will be automatically scaled based on the value at a batch size of 16. Meanwhile, to avoid affecting other codebases that use mmdet, the default setting for the `auto_scale_lr.enable` flag is `False`. + +If you want to enable this feature, you need to add argument `--auto-scale-lr`. And you need to check the config name which you want to use before you process the command, because the config name indicates the default batch size. +By default, it is `8 x 2 = 16 batch size`, like `faster_rcnn_r50_caffe_fpn_90k_coco.py` or `pisa_faster_rcnn_x101_32x4d_fpn_1x_coco.py`. In other cases, you will see the config file name have `_NxM_` in dictating, like `cornernet_hourglass104_mstest_32x3_210e_coco.py` which batch size is `32 x 3 = 96`, or `scnet_x101_64x4d_fpn_8x1_20e_coco.py` which batch size is `8 x 1 = 8`. + +**Please remember to check the bottom of the specific config file you want to use, it will have `auto_scale_lr.base_batch_size` if the batch size is not `16`. If you can't find those values, check the config file which in `_base_=[xxx]` and you will find it. Please do not modify its values if you want to automatically scale the LR.** + +The basic usage of learning rate auto scaling is as follows. + +```shell +python tools/train.py \ + ${CONFIG_FILE} \ + --auto-scale-lr \ + [optional arguments] +``` + +If you enabled this feature, the learning rate will be automatically scaled according to the number of GPUs on the machine and the batch size of training. See [linear scaling rule](https://arxiv.org/abs/1706.02677) for details. For example, If there are 4 GPUs and 2 pictures on each GPU, `lr = 0.01`, then if there are 16 GPUs and 4 pictures on each GPU, it will automatically scale to `lr = 0.08`. + +If you don't want to use it, you need to calculate the learning rate according to the [linear scaling rule](https://arxiv.org/abs/1706.02677) manually then change `optimizer.lr` in specific config file. + +## Training on a single GPU + +We provide `tools/train.py` to launch training jobs on a single GPU. +The basic usage is as follows. + +```shell +python tools/train.py \ + ${CONFIG_FILE} \ + [optional arguments] +``` + +During training, log files and checkpoints will be saved to the working directory, which is specified by `work_dir` in the config file or via CLI argument `--work-dir`. + +By default, the model is evaluated on the validation set every epoch, the evaluation interval can be specified in the config file as shown below. + +```python +# evaluate the model every 12 epochs. +train_cfg = dict(val_interval=12) +``` + +This tool accepts several optional arguments, including: + +- `--work-dir ${WORK_DIR}`: Override the working directory. +- `--resume`: resume from the latest checkpoint in the work_dir automatically. +- `--resume ${CHECKPOINT_FILE}`: resume from the specific checkpoint. +- `--cfg-options 'Key=value'`: Overrides other settings in the used config. + +**Note:** + +There is a difference between `resume` and `load-from`: + +`resume` loads both the weights of the model and the state of the optimizer, and it inherits the iteration number from the specified checkpoint, so training does not start again from scratch. `load-from`, on the other hand, only loads the weights of the model, and its training starts from scratch. It is often used for fine-tuning a model. `load-from` needs to be written in the config file, while `resume` is passed as a command line argument. + +## Training on CPU + +The process of training on the CPU is consistent with single GPU training. We just need to disable GPUs before the training process. + +```shell +export CUDA_VISIBLE_DEVICES=-1 +``` + +And then run the script [above](#training-on-a-single-GPU). + +**Note**: + +We do not recommend users to use the CPU for training because it is too slow. We support this feature to allow users to debug on machines without GPU for convenience. + +## Training on multiple GPUs + +We provide `tools/dist_train.sh` to launch training on multiple GPUs. +The basic usage is as follows. + +```shell +bash ./tools/dist_train.sh \ + ${CONFIG_FILE} \ + ${GPU_NUM} \ + [optional arguments] +``` + +Optional arguments remain the same as stated [above](#training-on-a-single-GPU). + +### Launch multiple jobs simultaneously + +If you would like to launch multiple jobs on a single machine, e.g., 2 jobs of 4-GPU training on a machine with 8 GPUs, +you need to specify different ports (29500 by default) for each job to avoid communication conflict. + +If you use `dist_train.sh` to launch training jobs, you can set the port in the commands. + +```shell +CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4 +CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4 +``` + +## Train with multiple machines + +If you launch with multiple machines simply connected with ethernet, you can simply run the following commands: + +On the first machine: + +```shell +NNODES=2 NODE_RANK=0 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS +``` + +On the second machine: + +```shell +NNODES=2 NODE_RANK=1 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS +``` + +Usually, it is slow if you do not have high-speed networking like InfiniBand. + +## Manage jobs with Slurm + +[Slurm](https://slurm.schedmd.com/) is a good job scheduling system for computing clusters. +On a cluster managed by Slurm, you can use `slurm_train.sh` to spawn training jobs. It supports both single-node and multi-node training. + +The basic usage is as follows. + +```shell +[GPUS=${GPUS}] ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR} +``` + +Below is an example of using 16 GPUs to train Mask R-CNN on a Slurm partition named _dev_, and set the work-dir to some shared file systems. + +```shell +GPUS=16 ./tools/slurm_train.sh dev mask_r50_1x configs/mask-rcnn_r50_fpn_1x_coco.py /nfs/xxxx/mask_rcnn_r50_fpn_1x +``` + +You can check [the source code](../../../tools/slurm_train.sh) to review full arguments and environment variables. + +When using Slurm, the port option needs to be set in one of the following ways: + +1. Set the port through `--options`. This is more recommended since it does not change the original configs. + + ```shell + CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} --cfg-options 'dist_params.port=29500' + CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} --cfg-options 'dist_params.port=29501' + ``` + +2. Modify the config files to set different communication ports. + + In `config1.py`, set + + ```python + dist_params = dict(backend='nccl', port=29500) + ``` + + In `config2.py`, set + + ```python + dist_params = dict(backend='nccl', port=29501) + ``` + + Then you can launch two jobs with `config1.py` and `config2.py`. + + ```shell + CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} + CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} + ``` + +# Train with customized datasets + +In this part, you will know how to train predefined models with customized datasets and then test it. We use the [balloon dataset](https://github.com/matterport/Mask_RCNN/tree/master/samples/balloon) as an example to describe the whole process. + +The basic steps are as below: + +1. Prepare the customized dataset +2. Prepare a config +3. Train, test, and infer models on the customized dataset. + +## Prepare the customized dataset + +There are three ways to support a new dataset in MMDetection: + +1. Reorganize the dataset into COCO format. +2. Reorganize the dataset into a middle format. +3. Implement a new dataset. + +Usually, we recommend using the first two methods which are usually easier than the third. + +In this note, we give an example of converting the data into COCO format. + +**Note**: Datasets and metrics have been decoupled except CityScapes since MMDetection 3.0. Therefore, users can use any kind of evaluation metrics for any format of datasets during validation. For example: evaluate on COCO dataset with VOC metric, or evaluate on OpenImages dataset with both VOC and COCO metrics. + +### COCO annotation format + +The necessary keys of COCO format for instance segmentation are as below, for the complete details, please refer [here](https://cocodataset.org/#format-data). + +```json +{ + "images": [image], + "annotations": [annotation], + "categories": [category] +} + +image = { + "id": int, + "width": int, + "height": int, + "file_name": str, +} + +annotation = { + "id": int, + "image_id": int, + "category_id": int, + "segmentation": RLE or [polygon], + "area": float, + "bbox": [x,y,width,height], # (x, y) are the coordinates of the upper left corner of the bbox + "iscrowd": 0 or 1, +} + +categories = [{ + "id": int, + "name": str, + "supercategory": str, +}] +``` + +Assume we use the balloon dataset. +After downloading the data, we need to implement a function to convert the annotation format into the COCO format. Then we can use implemented `CocoDataset` to load the data and perform training and evaluation. + +If you take a look at the dataset, you will find the dataset format is as below: + +```json +{'base64_img_data': '', + 'file_attributes': {}, + 'filename': '34020010494_e5cb88e1c4_k.jpg', + 'fileref': '', + 'regions': {'0': {'region_attributes': {}, + 'shape_attributes': {'all_points_x': [1020, + 1000, + 994, + 1003, + 1023, + 1050, + 1089, + 1134, + 1190, + 1265, + 1321, + 1361, + 1403, + 1428, + 1442, + 1445, + 1441, + 1427, + 1400, + 1361, + 1316, + 1269, + 1228, + 1198, + 1207, + 1210, + 1190, + 1177, + 1172, + 1174, + 1170, + 1153, + 1127, + 1104, + 1061, + 1032, + 1020], + 'all_points_y': [963, + 899, + 841, + 787, + 738, + 700, + 663, + 638, + 621, + 619, + 643, + 672, + 720, + 765, + 800, + 860, + 896, + 942, + 990, + 1035, + 1079, + 1112, + 1129, + 1134, + 1144, + 1153, + 1166, + 1166, + 1150, + 1136, + 1129, + 1122, + 1112, + 1084, + 1037, + 989, + 963], + 'name': 'polygon'}}}, + 'size': 1115004} +``` + +The annotation is a JSON file where each key indicates an image's all annotations. +The code to convert the balloon dataset into coco format is as below. + +```python +import os.path as osp + +import mmcv + +from mmengine.fileio import dump, load +from mmengine.utils import track_iter_progress + + +def convert_balloon_to_coco(ann_file, out_file, image_prefix): + data_infos = load(ann_file) + + annotations = [] + images = [] + obj_count = 0 + for idx, v in enumerate(track_iter_progress(data_infos.values())): + filename = v['filename'] + img_path = osp.join(image_prefix, filename) + height, width = mmcv.imread(img_path).shape[:2] + + images.append( + dict(id=idx, file_name=filename, height=height, width=width)) + + for _, obj in v['regions'].items(): + assert not obj['region_attributes'] + obj = obj['shape_attributes'] + px = obj['all_points_x'] + py = obj['all_points_y'] + poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)] + poly = [p for x in poly for p in x] + + x_min, y_min, x_max, y_max = (min(px), min(py), max(px), max(py)) + + data_anno = dict( + image_id=idx, + id=obj_count, + category_id=0, + bbox=[x_min, y_min, x_max - x_min, y_max - y_min], + area=(x_max - x_min) * (y_max - y_min), + segmentation=[poly], + iscrowd=0) + annotations.append(data_anno) + obj_count += 1 + + coco_format_json = dict( + images=images, + annotations=annotations, + categories=[{ + 'id': 0, + 'name': 'balloon' + }]) + dump(coco_format_json, out_file) + + +if __name__ == '__main__': + convert_balloon_to_coco(ann_file='data/balloon/train/via_region_data.json', + out_file='data/balloon/train/annotation_coco.json', + image_prefix='data/balloon/train') + convert_balloon_to_coco(ann_file='data/balloon/val/via_region_data.json', + out_file='data/balloon/val/annotation_coco.json', + image_prefix='data/balloon/val') + +``` + +Using the function above, users can successfully convert the annotation file into json format, then we can use `CocoDataset` to train and evaluate the model with `CocoMetric`. + +## Prepare a config + +The second step is to prepare a config thus the dataset could be successfully loaded. Assume that we want to use Mask R-CNN with FPN, the config to train the detector on balloon dataset is as below. Assume the config is under directory `configs/balloon/` and named as `mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py`, the config is as below. Please refer [Learn about Configs - MMDetection 3.0.0 documentation](https://mmdetection.readthedocs.io/en/latest/user_guides/config.html) to get detailed information about config files. + +```python +# The new config inherits a base config to highlight the necessary modification +_base_ = '../mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_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 +data_root = 'data/balloon/' +metainfo = { + 'classes': ('balloon', ), + 'palette': [ + (220, 20, 60), + ] +} +train_dataloader = dict( + batch_size=1, + dataset=dict( + data_root=data_root, + metainfo=metainfo, + ann_file='train/annotation_coco.json', + data_prefix=dict(img='train/'))) +val_dataloader = dict( + dataset=dict( + data_root=data_root, + metainfo=metainfo, + ann_file='val/annotation_coco.json', + data_prefix=dict(img='val/'))) +test_dataloader = val_dataloader + +# Modify metric related settings +val_evaluator = dict(ann_file=data_root + 'val/annotation_coco.json') +test_evaluator = val_evaluator + +# We can use the pre-trained Mask RCNN model to obtain higher performance +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth' + +``` + +## Train a new model + +To train a model with the new config, you can simply run + +```shell +python tools/train.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py +``` + +For more detailed usages, please refer to the [training guide](https://mmdetection.readthedocs.io/en/latest/user_guides/train.html#train-predefined-models-on-standard-datasets). + +## Test and inference + +To test the trained model, you can simply run + +```shell +python tools/test.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py work_dirs/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon/epoch_12.pth +``` + +For more detailed usages, please refer to the [testing guide](https://mmdetection.readthedocs.io/en/latest/user_guides/test.html). diff --git a/mmdet_code/mmdetection/docs/en/user_guides/useful_hooks.md b/mmdet_code/mmdetection/docs/en/user_guides/useful_hooks.md new file mode 100644 index 0000000000000000000000000000000000000000..4c30686d68ac555707fa3af0432b914ee0672f76 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/useful_hooks.md @@ -0,0 +1,105 @@ +# Useful Hooks + +MMDetection and MMEngine provide users with various useful hooks including log hooks, `NumClassCheckHook`, etc. This tutorial introduces the functionalities and usages of hooks implemented in MMDetection. For using hooks in MMEngine, please read the [API documentation in MMEngine](https://github.com/open-mmlab/mmengine/tree/main/docs/en/tutorials/hook.md). + +## CheckInvalidLossHook + +## NumClassCheckHook + +## MemoryProfilerHook + +[Memory profiler hook](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/engine/hooks/memory_profiler_hook.py) records memory information including virtual memory, swap memory, and the memory of the current process. This hook helps grasp the memory usage of the system and discover potential memory leak bugs. To use this hook, users should install `memory_profiler` and `psutil` by `pip install memory_profiler psutil` first. + +### Usage + +To use this hook, users should add the following code to the config file. + +```python +custom_hooks = [ + dict(type='MemoryProfilerHook', interval=50) +] +``` + +### Result + +During training, you can see the messages in the log recorded by `MemoryProfilerHook` as below. + +```text +The system has 250 GB (246360 MB + 9407 MB) of memory and 8 GB (5740 MB + 2452 MB) of swap memory in total. Currently 9407 MB (4.4%) of memory and 5740 MB (29.9%) of swap memory were consumed. And the current training process consumed 5434 MB of memory. +``` + +```text +2022-04-21 08:49:56,881 - mmengine - INFO - Memory information available_memory: 246360 MB, used_memory: 9407 MB, memory_utilization: 4.4 %, available_swap_memory: 5740 MB, used_swap_memory: 2452 MB, swap_memory_utilization: 29.9 %, current_process_memory: 5434 MB +``` + +## SetEpochInfoHook + +## SyncNormHook + +## SyncRandomSizeHook + +## YOLOXLrUpdaterHook + +## YOLOXModeSwitchHook + +## How to implement a custom hook + +In general, there are 20 points where hooks can be inserted from the beginning to the end of model training. The users can implement custom hooks and insert them at different points in the process of training to do what they want. + +- global points: `before_run`, `after_run` +- points in training: `before_train`, `before_train_epoch`, `before_train_iter`, `after_train_iter`, `after_train_epoch`, `after_train` +- points in validation: `before_val`, `before_val_epoch`, `before_val_iter`, `after_val_iter`, `after_val_epoch`, `after_val` +- points at testing: `before_test`, `before_test_epoch`, `before_test_iter`, `after_test_iter`, `after_test_epoch`, `after_test` +- other points: `before_save_checkpoint`, `after_save_checkpoint` + +For example, users can implement a hook to check loss and terminate training when loss goes NaN. To achieve that, there are three steps to go: + +1. Implement a new hook that inherits the `Hook` class in MMEngine, and implement `after_train_iter` method which checks whether loss goes NaN after every `n` training iterations. +2. The implemented hook should be registered in `HOOKS` by `@HOOKS.register_module()` as shown in the code below. +3. Add `custom_hooks = [dict(type='MemoryProfilerHook', interval=50)]` in the config file. + +```python +from typing import Optional + +import torch +from mmengine.hooks import Hook +from mmengine.runner import Runner + +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class CheckInvalidLossHook(Hook): + """Check invalid loss hook. + + This hook will regularly check whether the loss is valid + during training. + + Args: + interval (int): Checking interval (every k iterations). + Default: 50. + """ + + def __init__(self, interval: int = 50) -> None: + self.interval = interval + + def after_train_iter(self, + runner: Runner, + batch_idx: int, + data_batch: Optional[dict] = None, + outputs: Optional[dict] = None) -> None: + """Regularly check whether the loss is valid every n iterations. + + Args: + runner (:obj:`Runner`): The runner of the training process. + batch_idx (int): The index of the current batch in the train loop. + data_batch (dict, Optional): Data from dataloader. + Defaults to None. + outputs (dict, Optional): Outputs from model. Defaults to None. + """ + if self.every_n_train_iters(runner, self.interval): + assert torch.isfinite(outputs['loss']), \ + runner.logger.info('loss become infinite or NaN!') +``` + +Please read [customize_runtime](../advanced_guides/customize_runtime.md) for more about implementing a custom hook. diff --git a/mmdet_code/mmdetection/docs/en/user_guides/useful_tools.md b/mmdet_code/mmdetection/docs/en/user_guides/useful_tools.md new file mode 100644 index 0000000000000000000000000000000000000000..8a79f0c2f1b1bcd82c5aa82544ae68bd824696bc --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/useful_tools.md @@ -0,0 +1,660 @@ +Apart from training/testing scripts, We provide lots of useful tools under the +`tools/` directory. + +## Log Analysis + +`tools/analysis_tools/analyze_logs.py` plots loss/mAP curves given a training +log file. Run `pip install seaborn` first to install the dependency. + +```shell +python tools/analysis_tools/analyze_logs.py plot_curve [--keys ${KEYS}] [--eval-interval ${EVALUATION_INTERVAL}] [--title ${TITLE}] [--legend ${LEGEND}] [--backend ${BACKEND}] [--style ${STYLE}] [--out ${OUT_FILE}] +``` + +![loss curve image](../../../resources/loss_curve.png) + +Examples: + +- Plot the classification loss of some run. + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log.json --keys loss_cls --legend loss_cls + ``` + +- Plot the classification and regression loss of some run, and save the figure to a pdf. + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log.json --keys loss_cls loss_bbox --out losses.pdf + ``` + +- Compare the bbox mAP of two runs in the same figure. + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log1.json log2.json --keys bbox_mAP --legend run1 run2 + ``` + +- Compute the average training speed. + + ```shell + python tools/analysis_tools/analyze_logs.py cal_train_time log.json [--include-outliers] + ``` + + The output is expected to be like the following. + + ```text + -----Analyze train time of work_dirs/some_exp/20190611_192040.log.json----- + slowest epoch 11, average time is 1.2024 + fastest epoch 1, average time is 1.1909 + time std over epochs is 0.0028 + average iter time: 1.1959 s/iter + ``` + +## Result Analysis + +`tools/analysis_tools/analyze_results.py` calculates single image mAP and saves or shows the topk images with the highest and lowest scores based on prediction results. + +**Usage** + +```shell +python tools/analysis_tools/analyze_results.py \ + ${CONFIG} \ + ${PREDICTION_PATH} \ + ${SHOW_DIR} \ + [--show] \ + [--wait-time ${WAIT_TIME}] \ + [--topk ${TOPK}] \ + [--show-score-thr ${SHOW_SCORE_THR}] \ + [--cfg-options ${CFG_OPTIONS}] +``` + +Description of all arguments: + +- `config` : The path of a model config file. +- `prediction_path`: Output result file in pickle format from `tools/test.py` +- `show_dir`: Directory where painted GT and detection images will be saved +- `--show`: Determines whether to show painted images, If not specified, it will be set to `False` +- `--wait-time`: The interval of show (s), 0 is block +- `--topk`: The number of saved images that have the highest and lowest `topk` scores after sorting. If not specified, it will be set to `20`. +- `--show-score-thr`: Show score threshold. If not specified, it will be set to `0`. +- `--cfg-options`: If specified, the key-value pair optional cfg will be merged into config file + +**Examples**: + +Assume that you have got result file in pickle format from `tools/test.py` in the path './result.pkl'. + +1. Test Faster R-CNN and visualize the results, save images to the directory `results/` + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --show +``` + +2. Test Faster R-CNN and specified topk to 50, save images to the directory `results/` + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --topk 50 +``` + +3. If you want to filter the low score prediction results, you can specify the `show-score-thr` parameter + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --show-score-thr 0.3 +``` + +## Fusing results from multiple models + +`tools/analysis_tools/fusion_results.py` can fusing predictions using Weighted Boxes Fusion(WBF) from different object detection models. (Currently support coco format only) + +**Usage** + +```shell +python tools/analysis_tools/fuse_results.py \ + ${PRED_RESULTS} \ + [--annotation ${ANNOTATION}] \ + [--weights ${WEIGHTS}] \ + [--fusion-iou-thr ${FUSION_IOU_THR}] \ + [--skip-box-thr ${SKIP_BOX_THR}] \ + [--conf-type ${CONF_TYPE}] \ + [--eval-single ${EVAL_SINGLE}] \ + [--save-fusion-results ${SAVE_FUSION_RESULTS}] \ + [--out-dir ${OUT_DIR}] +``` + +Description of all arguments: + +- `pred-results`: Paths of detection results from different models.(Currently support coco format only) +- `--annotation`: Path of ground-truth. +- `--weights`: List of weights for each model. Default: `None`, which means weight == 1 for each model. +- `--fusion-iou-thr`: IoU value for boxes to be a match。Default: `0.55`。 +- `--skip-box-thr`: The confidence threshold that needs to be excluded in the WBF algorithm. bboxes whose confidence is less than this value will be excluded.。Default: `0`。 +- `--conf-type`: How to calculate confidence in weighted boxes. + - `avg`: average value,default. + - `max`: maximum value. + - `box_and_model_avg`: box and model wise hybrid weighted average. + - `absent_model_aware_avg`: weighted average that takes into account the absent model. +- `--eval-single`: Whether evaluate every single model. Default: `False`. +- `--save-fusion-results`: Whether save fusion results. Default: `False`. +- `--out-dir`: Path of fusion results. + +**Examples**: +Assume that you have got 3 result files from corresponding models through `tools/test.py`, which paths are './faster-rcnn_r50-caffe_fpn_1x_coco.json', './retinanet_r50-caffe_fpn_1x_coco.json', './cascade-rcnn_r50-caffe_fpn_1x_coco.json' respectively. The ground-truth file path is './annotation.json'. + +1. Fusion of predictions from three models and evaluation of their effectiveness + +```shell +python tools/analysis_tools/fuse_results.py \ + ./faster-rcnn_r50-caffe_fpn_1x_coco.json \ + ./retinanet_r50-caffe_fpn_1x_coco.json \ + ./cascade-rcnn_r50-caffe_fpn_1x_coco.json \ + --annotation ./annotation.json \ + --weights 1 2 3 \ +``` + +2. Simultaneously evaluate each single model and fusion results + +```shell +python tools/analysis_tools/fuse_results.py \ + ./faster-rcnn_r50-caffe_fpn_1x_coco.json \ + ./retinanet_r50-caffe_fpn_1x_coco.json \ + ./cascade-rcnn_r50-caffe_fpn_1x_coco.json \ + --annotation ./annotation.json \ + --weights 1 2 3 \ + --eval-single +``` + +3. Fusion of prediction results from three models and save + +```shell +python tools/analysis_tools/fuse_results.py \ + ./faster-rcnn_r50-caffe_fpn_1x_coco.json \ + ./retinanet_r50-caffe_fpn_1x_coco.json \ + ./cascade-rcnn_r50-caffe_fpn_1x_coco.json \ + --annotation ./annotation.json \ + --weights 1 2 3 \ + --save-fusion-results \ + --out-dir outputs/fusion +``` + +## Visualization + +### Visualize Datasets + +`tools/analysis_tools/browse_dataset.py` helps the user to browse a detection dataset (both +images and bounding box annotations) visually, or save the image to a +designated directory. + +```shell +python tools/analysis_tools/browse_dataset.py ${CONFIG} [-h] [--skip-type ${SKIP_TYPE[SKIP_TYPE...]}] [--output-dir ${OUTPUT_DIR}] [--not-show] [--show-interval ${SHOW_INTERVAL}] +``` + +### Visualize Models + +First, convert the model to ONNX as described +[here](#convert-mmdetection-model-to-onnx-experimental). +Note that currently only RetinaNet is supported, support for other models +will be coming in later versions. +The converted model could be visualized by tools like [Netron](https://github.com/lutzroeder/netron). + +### Visualize Predictions + +If you need a lightweight GUI for visualizing the detection results, you can refer [DetVisGUI project](https://github.com/Chien-Hung/DetVisGUI/tree/mmdetection). + +## Error Analysis + +`tools/analysis_tools/coco_error_analysis.py` analyzes COCO results per category and by +different criterion. It can also make a plot to provide useful information. + +```shell +python tools/analysis_tools/coco_error_analysis.py ${RESULT} ${OUT_DIR} [-h] [--ann ${ANN}] [--types ${TYPES[TYPES...]}] +``` + +Example: + +Assume that you have got [Mask R-CNN checkpoint file](https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_fpn_1x_coco/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth) in the path 'checkpoint'. For other checkpoints, please refer to our [model zoo](./model_zoo.md). + +You can modify the test_evaluator to save the results bbox by: + +1. Find which dataset in 'configs/base/datasets' the current config corresponds to. +2. Replace the original test_evaluator and test_dataloader with test_evaluator and test_dataloader in the comment in dataset config. +3. Use the following command to get the results bbox and segmentation json file. + +```shell +python tools/test.py \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoint/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ +``` + +1. Get COCO bbox error results per category , save analyze result images to the directory(In [config](../../../configs/_base_/datasets/coco_instance.py) the default directory is './work_dirs/coco_instance/test') + +```shell +python tools/analysis_tools/coco_error_analysis.py \ + results.bbox.json \ + results \ + --ann=data/coco/annotations/instances_val2017.json \ +``` + +2. Get COCO segmentation error results per category , save analyze result images to the directory + +```shell +python tools/analysis_tools/coco_error_analysis.py \ + results.segm.json \ + results \ + --ann=data/coco/annotations/instances_val2017.json \ + --types='segm' +``` + +## Model Serving + +In order to serve an `MMDetection` model with [`TorchServe`](https://pytorch.org/serve/), you can follow the steps: + +### 1. Install TorchServe + +Suppose you have a `Python` environment with `PyTorch` and `MMDetection` successfully installed, +then you could run the following command to install `TorchServe` and its dependencies. +For more other installation options, please refer to the [quick start](https://github.com/pytorch/serve/blob/master/README.md#serve-a-model). + +```shell +python -m pip install torchserve torch-model-archiver torch-workflow-archiver nvgpu +``` + +**Note**: Please refer to [torchserve docker](https://github.com/pytorch/serve/blob/master/docker/README.md) if you want to use `TorchServe` in docker. + +### 2. Convert model from MMDetection to TorchServe + +```shell +python tools/deployment/mmdet2torchserve.py ${CONFIG_FILE} ${CHECKPOINT_FILE} \ +--output-folder ${MODEL_STORE} \ +--model-name ${MODEL_NAME} +``` + +### 3. Start `TorchServe` + +```shell +torchserve --start --ncs \ + --model-store ${MODEL_STORE} \ + --models ${MODEL_NAME}.mar +``` + +### 4. Test deployment + +```shell +curl -O curl -O https://raw.githubusercontent.com/pytorch/serve/master/docs/images/3dogs.jpg +curl http://127.0.0.1:8080/predictions/${MODEL_NAME} -T 3dogs.jpg +``` + +You should obtain a response similar to: + +```json +[ + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 294.63409423828125, + 203.99111938476562, + 417.048583984375, + 281.62744140625 + ], + "score": 0.9987992644309998 + }, + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 404.26019287109375, + 126.0080795288086, + 574.5091552734375, + 293.6662292480469 + ], + "score": 0.9979367256164551 + }, + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 197.2144775390625, + 93.3067855834961, + 307.8505554199219, + 276.7560119628906 + ], + "score": 0.993338406085968 + } +] +``` + +#### Compare results + +And you can use `test_torchserver.py` to compare result of `TorchServe` and `PyTorch`, and visualize them. + +```shell +python tools/deployment/test_torchserver.py ${IMAGE_FILE} ${CONFIG_FILE} ${CHECKPOINT_FILE} ${MODEL_NAME} +[--inference-addr ${INFERENCE_ADDR}] [--device ${DEVICE}] [--score-thr ${SCORE_THR}] [--work-dir ${WORK_DIR}] +``` + +Example: + +```shell +python tools/deployment/test_torchserver.py \ +demo/demo.jpg \ +configs/yolo/yolov3_d53_8xb8-320-273e_coco.py \ +checkpoint/yolov3_d53_320_273e_coco-421362b6.pth \ +yolov3 \ +--work-dir ./work-dir +``` + +### 5. Stop `TorchServe` + +```shell +torchserve --stop +``` + +## Model Complexity + +`tools/analysis_tools/get_flops.py` is a script adapted from [flops-counter.pytorch](https://github.com/sovrasov/flops-counter.pytorch) to compute the FLOPs and params of a given model. + +```shell +python tools/analysis_tools/get_flops.py ${CONFIG_FILE} [--shape ${INPUT_SHAPE}] +``` + +You will get the results like this. + +```text +============================== +Input shape: (3, 1280, 800) +Flops: 239.32 GFLOPs +Params: 37.74 M +============================== +``` + +**Note**: This tool is still experimental and we do not guarantee that the +number is absolutely correct. You may well use the result for simple +comparisons, but double check it before you adopt it in technical reports or papers. + +1. FLOPs are related to the input shape while parameters are not. The default + input shape is (1, 3, 1280, 800). +2. Some operators are not counted into FLOPs like GN and custom operators. Refer to [`mmcv.cnn.get_model_complexity_info()`](https://github.com/open-mmlab/mmcv/blob/2.x/mmcv/cnn/utils/flops_counter.py) for details. +3. The FLOPs of two-stage detectors is dependent on the number of proposals. + +## Model conversion + +### MMDetection model to ONNX + +We provide a script to convert model to [ONNX](https://github.com/onnx/onnx) format. We also support comparing the output results between Pytorch and ONNX model for verification. More details can refer to [mmdeploy](https://github.com/open-mmlab/mmdeploy) + +### MMDetection 1.x model to MMDetection 2.x + +`tools/model_converters/upgrade_model_version.py` upgrades a previous MMDetection checkpoint +to the new version. Note that this script is not guaranteed to work as some +breaking changes are introduced in the new version. It is recommended to +directly use the new checkpoints. + +```shell +python tools/model_converters/upgrade_model_version.py ${IN_FILE} ${OUT_FILE} [-h] [--num-classes NUM_CLASSES] +``` + +### RegNet model to MMDetection + +`tools/model_converters/regnet2mmdet.py` convert keys in pycls pretrained RegNet models to +MMDetection style. + +```shell +python tools/model_converters/regnet2mmdet.py ${SRC} ${DST} [-h] +``` + +### Detectron ResNet to Pytorch + +`tools/model_converters/detectron2pytorch.py` converts keys in the original detectron pretrained +ResNet models to PyTorch style. + +```shell +python tools/model_converters/detectron2pytorch.py ${SRC} ${DST} ${DEPTH} [-h] +``` + +### Prepare a model for publishing + +`tools/model_converters/publish_model.py` helps users to prepare their model for publishing. + +Before you upload a model to AWS, you may want to + +1. convert model weights to CPU tensors +2. delete the optimizer states and +3. compute the hash of the checkpoint file and append the hash id to the + filename. + +```shell +python tools/model_converters/publish_model.py ${INPUT_FILENAME} ${OUTPUT_FILENAME} +``` + +E.g., + +```shell +python tools/model_converters/publish_model.py work_dirs/faster_rcnn/latest.pth faster_rcnn_r50_fpn_1x_20190801.pth +``` + +The final output filename will be `faster_rcnn_r50_fpn_1x_20190801-{hash id}.pth`. + +## Dataset Conversion + +`tools/data_converters/` contains tools to convert the Cityscapes dataset +and Pascal VOC dataset to the COCO format. + +```shell +python tools/dataset_converters/cityscapes.py ${CITYSCAPES_PATH} [-h] [--img-dir ${IMG_DIR}] [--gt-dir ${GT_DIR}] [-o ${OUT_DIR}] [--nproc ${NPROC}] +python tools/dataset_converters/pascal_voc.py ${DEVKIT_PATH} [-h] [-o ${OUT_DIR}] +``` + +## Dataset Download + +`tools/misc/download_dataset.py` supports downloading datasets such as COCO, VOC, and LVIS. + +```shell +python tools/misc/download_dataset.py --dataset-name coco2017 +python tools/misc/download_dataset.py --dataset-name voc2007 +python tools/misc/download_dataset.py --dataset-name lvis +``` + +For users in China, these datasets can also be downloaded from [OpenDataLab](https://opendatalab.com/?source=OpenMMLab%20GitHub) with high speed: + +- [COCO2017](https://opendatalab.com/COCO_2017/download?source=OpenMMLab%20GitHub) +- [VOC2007](https://opendatalab.com/PASCAL_VOC2007/download?source=OpenMMLab%20GitHub) +- [VOC2012](https://opendatalab.com/PASCAL_VOC2012/download?source=OpenMMLab%20GitHub) +- [LVIS](https://opendatalab.com/LVIS/download?source=OpenMMLab%20GitHub) + +## Benchmark + +### Robust Detection Benchmark + +`tools/analysis_tools/test_robustness.py` and`tools/analysis_tools/robustness_eval.py` helps users to evaluate model robustness. The core idea comes from [Benchmarking Robustness in Object Detection: Autonomous Driving when Winter is Coming](https://arxiv.org/abs/1907.07484). For more information how to evaluate models on corrupted images and results for a set of standard models please refer to [robustness_benchmarking.md](robustness_benchmarking.md). + +### FPS Benchmark + +`tools/analysis_tools/benchmark.py` helps users to calculate FPS. The FPS value includes model forward and post-processing. In order to get a more accurate value, currently only supports single GPU distributed startup mode. + +```shell +python -m torch.distributed.launch --nproc_per_node=1 --master_port=${PORT} tools/analysis_tools/benchmark.py \ + ${CONFIG} \ + [--checkpoint ${CHECKPOINT}] \ + [--repeat-num ${REPEAT_NUM}] \ + [--max-iter ${MAX_ITER}] \ + [--log-interval ${LOG_INTERVAL}] \ + --launcher pytorch +``` + +Examples: Assuming that you have already downloaded the `Faster R-CNN` model checkpoint to the directory `checkpoints/`. + +```shell +python -m torch.distributed.launch --nproc_per_node=1 --master_port=29500 tools/analysis_tools/benchmark.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \ + --launcher pytorch +``` + +## Miscellaneous + +### Evaluating a metric + +`tools/analysis_tools/eval_metric.py` evaluates certain metrics of a pkl result file +according to a config file. + +```shell +python tools/analysis_tools/eval_metric.py ${CONFIG} ${PKL_RESULTS} [-h] [--format-only] [--eval ${EVAL[EVAL ...]}] + [--cfg-options ${CFG_OPTIONS [CFG_OPTIONS ...]}] + [--eval-options ${EVAL_OPTIONS [EVAL_OPTIONS ...]}] +``` + +### Print the entire config + +`tools/misc/print_config.py` prints the whole config verbatim, expanding all its +imports. + +```shell +python tools/misc/print_config.py ${CONFIG} [-h] [--options ${OPTIONS [OPTIONS...]}] +``` + +## Hyper-parameter Optimization + +### YOLO Anchor Optimization + +`tools/analysis_tools/optimize_anchors.py` provides two method to optimize YOLO anchors. + +One is k-means anchor cluster which refers from [darknet](https://github.com/AlexeyAB/darknet/blob/master/src/detector.c#L1421). + +```shell +python tools/analysis_tools/optimize_anchors.py ${CONFIG} --algorithm k-means --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} --output-dir ${OUTPUT_DIR} +``` + +Another is using differential evolution to optimize anchors. + +```shell +python tools/analysis_tools/optimize_anchors.py ${CONFIG} --algorithm differential_evolution --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} --output-dir ${OUTPUT_DIR} +``` + +E.g., + +```shell +python tools/analysis_tools/optimize_anchors.py configs/yolo/yolov3_d53_8xb8-320-273e_coco.py --algorithm differential_evolution --input-shape 608 608 --device cuda --output-dir work_dirs +``` + +You will get: + +``` +loading annotations into memory... +Done (t=9.70s) +creating index... +index created! +2021-07-19 19:37:20,951 - mmdet - INFO - Collecting bboxes from annotation... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 117266/117266, 15874.5 task/s, elapsed: 7s, ETA: 0s + +2021-07-19 19:37:28,753 - mmdet - INFO - Collected 849902 bboxes. +differential_evolution step 1: f(x)= 0.506055 +differential_evolution step 2: f(x)= 0.506055 +...... + +differential_evolution step 489: f(x)= 0.386625 +2021-07-19 19:46:40,775 - mmdet - INFO Anchor evolution finish. Average IOU: 0.6133754253387451 +2021-07-19 19:46:40,776 - mmdet - INFO Anchor differential evolution result:[[10, 12], [15, 30], [32, 22], [29, 59], [61, 46], [57, 116], [112, 89], [154, 198], [349, 336]] +2021-07-19 19:46:40,798 - mmdet - INFO Result saved in work_dirs/anchor_optimize_result.json +``` + +## Confusion Matrix + +A confusion matrix is a summary of prediction results. + +`tools/analysis_tools/confusion_matrix.py` can analyze the prediction results and plot a confusion matrix table. + +First, run `tools/test.py` to save the `.pkl` detection results. + +Then, run + +``` +python tools/analysis_tools/confusion_matrix.py ${CONFIG} ${DETECTION_RESULTS} ${SAVE_DIR} --show +``` + +And you will get a confusion matrix like this: + +![confusion_matrix_example](https://user-images.githubusercontent.com/12907710/140513068-994cdbf4-3a4a-48f0-8fd8-2830d93fd963.png) + +## COCO Separated & Occluded Mask Metric + +Detecting occluded objects still remains a challenge for state-of-the-art object detectors. +We implemented the metric presented in paper [A Tri-Layer Plugin to Improve Occluded Detection](https://arxiv.org/abs/2210.10046) to calculate the recall of separated and occluded masks. + +There are two ways to use this metric: + +### Offline evaluation + +We provide a script to calculate the metric with a dumped prediction file. + +First, use the `tools/test.py` script to dump the detection results: + +```shell +python tools/test.py ${CONFIG} ${MODEL_PATH} --out results.pkl +``` + +Then, run the `tools/analysis_tools/coco_occluded_separated_recall.py` script to get the recall of separated and occluded masks: + +```shell +python tools/analysis_tools/coco_occluded_separated_recall.py results.pkl --out occluded_separated_recall.json +``` + +The output should be like this: + +``` +loading annotations into memory... +Done (t=0.51s) +creating index... +index created! +processing detection results... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5000/5000, 109.3 task/s, elapsed: 46s, ETA: 0s +computing occluded mask recall... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5550/5550, 780.5 task/s, elapsed: 7s, ETA: 0s +COCO occluded mask recall: 58.79% +COCO occluded mask success num: 3263 +computing separated mask recall... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 3522/3522, 778.3 task/s, elapsed: 5s, ETA: 0s +COCO separated mask recall: 31.94% +COCO separated mask success num: 1125 + ++-----------+--------+-------------+ +| mask type | recall | num correct | ++-----------+--------+-------------+ +| occluded | 58.79% | 3263 | +| separated | 31.94% | 1125 | ++-----------+--------+-------------+ +Evaluation results have been saved to occluded_separated_recall.json. +``` + +### Online evaluation + +We implement `CocoOccludedSeparatedMetric` which inherits from the `CocoMetic`. +To evaluate the recall of separated and occluded masks during training, just replace the evaluator metric type with `'CocoOccludedSeparatedMetric'` in your config: + +```python +val_evaluator = dict( + type='CocoOccludedSeparatedMetric', # modify this + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False) +test_evaluator = val_evaluator +``` + +Please cite the paper if you use this metric: + +```latex +@article{zhan2022triocc, + title={A Tri-Layer Plugin to Improve Occluded Detection}, + author={Zhan, Guanqi and Xie, Weidi and Zisserman, Andrew}, + journal={British Machine Vision Conference}, + year={2022} +} +``` diff --git a/mmdet_code/mmdetection/docs/en/user_guides/visualization.md b/mmdet_code/mmdetection/docs/en/user_guides/visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..dade26ed6883fde2e299039008946d29a879f2b2 --- /dev/null +++ b/mmdet_code/mmdetection/docs/en/user_guides/visualization.md @@ -0,0 +1,91 @@ +# Visualization + +Before reading this tutorial, it is recommended to read MMEngine's [Visualization](https://github.com/open-mmlab/mmengine/blob/main/docs/en/advanced_tutorials/visualization.md) documentation to get a first glimpse of the `Visualizer` definition and usage. + +In brief, the [`Visualizer`](mmengine.visualization.Visualizer) is implemented in MMEngine to meet the daily visualization needs, and contains three main functions: + +- Implement common drawing APIs, such as [`draw_bboxes`](mmengine.visualization.Visualizer.draw_bboxes) which implements bounding box drawing functions, [`draw_lines`](mmengine.visualization.Visualizer.draw_lines) implements the line drawing function. +- Support writing visualization results, learning rate curves, loss function curves, and verification accuracy curves to various backends, including local disks and common deep learning training logging tools such as [TensorBoard](https://www.tensorflow.org/tensorboard) and [Wandb](https://wandb.ai/site). +- Support calling anywhere in the code to visualize or record intermediate states of the model during training or testing, such as feature maps and validation results. + +Based on MMEngine's Visualizer, MMDet comes with a variety of pre-built visualization tools that can be used by the user by simply modifying the following configuration files. + +- The `tools/analysis_tools/browse_dataset.py` script provides a dataset visualization function that draws images and corresponding annotations after Data Transforms, as described in [`browse_dataset.py`](useful_tools.md#Visualization). +- MMEngine implements `LoggerHook`, which uses `Visualizer` to write the learning rate, loss and evaluation results to the backend set by `Visualizer`. Therefore, by modifying the `Visualizer` backend in the configuration file, for example to ` TensorBoardVISBackend` or `WandbVISBackend`, you can implement logging to common training logging tools such as `TensorBoard` or `WandB`, thus making it easy for users to use these visualization tools to analyze and monitor the training process. +- The `VisualizerHook` is implemented in MMDet, which uses the `Visualizer` to visualize or store the prediction results of the validation or prediction phase into the backend set by the `Visualizer`, so by modifying the `Visualizer` backend in the configuration file, for example, to ` TensorBoardVISBackend` or `WandbVISBackend`, you can implement storing the predicted images to `TensorBoard` or `Wandb`. + +## Configuration + +Thanks to the use of the registration mechanism, in MMDet we can set the behavior of the `Visualizer` by modifying the configuration file. Usually, we define the default configuration for the visualizer in `configs/_base_/default_runtime.py`, see [configuration tutorial](config.md) for details. + +```Python +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', + vis_backends=vis_backends, + name='visualizer') +``` + +Based on the above example, we can see that the configuration of `Visualizer` consists of two main parts, namely, the type of `Visualizer` and the visualization backend `vis_backends` it uses. + +- Users can directly use `DetLocalVisualizer` to visualize labels or predictions for support tasks. +- MMDet sets the visualization backend `vis_backend` to the local visualization backend `LocalVisBackend` by default, saving all visualization results and other training information in a local folder. + +## Storage + +MMDet uses the local visualization backend [`LocalVisBackend`](mmengine.visualization.LocalVisBackend) by default, and the model loss, learning rate, model evaluation accuracy and visualization The information stored in `VisualizerHook` and `LoggerHook`, including loss, learning rate, evaluation accuracy will be saved to the `{work_dir}/{config_name}/{time}/{vis_data}` folder by default. In addition, MMDet also supports other common visualization backends, such as `TensorboardVisBackend` and `WandbVisBackend`, and you only need to change the `vis_backends` type in the configuration file to the corresponding visualization backend. For example, you can store data to `TensorBoard` and `Wandb` by simply inserting the following code block into the configuration file. + +```Python +# https://mmengine.readthedocs.io/en/latest/api/visualization.html +_base_.visualizer.vis_backends = [ + dict(type='LocalVisBackend'), # + dict(type='TensorboardVisBackend'), + dict(type='WandbVisBackend'),] +``` + +## Plot + +### Plot the prediction results + +MMDet mainly uses [`DetVisualizationHook`](mmdet.engine.hooks.DetVisualizationHook) to plot the prediction results of validation and test, by default `DetVisualizationHook` is off, and the default configuration is as follows. + +```Python +visualization=dict( # user visualization of validation and test results + type='DetVisualizationHook', + draw=False, + interval=1, + show=False) +``` + +The following table shows the parameters supported by `DetVisualizationHook`. + +| Parameters | Description | +| :--------: | :-----------------------------------------------------------------------------------------------------------: | +| draw | The DetVisualizationHook is turned on and off by the enable parameter, which is the default state. | +| interval | Controls how much iteration to store or display the results of a val or test if VisualizationHook is enabled. | +| show | Controls whether to visualize the results of val or test. | + +If you want to enable `DetVisualizationHook` related functions and configurations during training or testing, you only need to modify the configuration, take `configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py` as an example, draw annotations and predictions at the same time, and display the images, the configuration can be modified as follows + +```Python +visualization = _base_.default_hooks.visualization +visualization.update(dict(draw=True, show=True)) +``` + +
+ +
+ +The `test.py` procedure is further simplified by providing the `--show` and `--show-dir` parameters to visualize the annotation and prediction results during the test without modifying the configuration. + +```Shell +# Show test results +python tools/test.py configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_tiny_8xb32-300e_coco/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --show + +# Specify where to store the prediction results +python tools/test.py configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_tiny_8xb32-300e_coco/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --show-dir imgs/ +``` + +
+ +
diff --git a/mmdet_code/mmdetection/docs/zh_cn/Makefile b/mmdet_code/mmdetection/docs/zh_cn/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d4bb2cbb9eddb1bb1b4f366623044af8e4830919 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/mmdet_code/mmdetection/docs/zh_cn/_static/css/readthedocs.css b/mmdet_code/mmdetection/docs/zh_cn/_static/css/readthedocs.css new file mode 100644 index 0000000000000000000000000000000000000000..57ed0ad084827ae75f5c58d3799ff5cfa6e40600 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/_static/css/readthedocs.css @@ -0,0 +1,6 @@ +.header-logo { + background-image: url("../image/mmdet-logo.png"); + background-size: 156px 40px; + height: 40px; + width: 156px; +} diff --git a/mmdet_code/mmdetection/docs/zh_cn/_static/image/mmdet-logo.png b/mmdet_code/mmdetection/docs/zh_cn/_static/image/mmdet-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..da0b5a3f01ba8ba79c63189e09b4689f3fe25472 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/_static/image/mmdet-logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3cbc8783587b4c1edd6300c8026007514b8fee8298d2a7cfa48a53936f47610 +size 32181 diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/conventions.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/conventions.md new file mode 100644 index 0000000000000000000000000000000000000000..9fb1f14c89840f24a068a07469db92c5c5022324 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/conventions.md @@ -0,0 +1,109 @@ +# 默认约定 + +如果你想把 MMDetection 修改为自己的项目,请遵循下面的约定。 + +## 关于图片 shape 顺序的说明 + +在OpenMMLab 2.0中, 为了与 OpenCV 的输入参数相一致,图片处理 pipeline 中关于图像 shape 的输入参数总是以 `(width, height)` 的顺序排列。 +相反,为了计算方便,经过 pipeline 和 model 的字段的顺序是 `(height, width)`。具体来说在每个数据 pipeline 处理的结果中,字段和它们的值含义如下: + +- img_shape: (height, width) +- ori_shape: (height, width) +- pad_shape: (height, width) +- batch_input_shape: (height, width) + +以 `Mosaic` 为例,其初始化参数如下所示: + +```python +@TRANSFORMS.register_module() +class Mosaic(BaseTransform): + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + center_ratio_range: Tuple[float, float] = (0.5, 1.5), + bbox_clip_border: bool = True, + pad_val: float = 114.0, + prob: float = 1.0) -> None: + ... + + # img_scale 顺序应该是 (width, height) + self.img_scale = img_scale + + def transform(self, results: dict) -> dict: + ... + + results['img'] = mosaic_img + # (height, width) + results['img_shape'] = mosaic_img.shape[:2] +``` + +## 损失 + +在 MMDetection 中,`model(**data)` 的返回值是一个字典,包含着所有的损失和评价指标,他们将会由 `model(**data)` 返回。 + +例如,在 bbox head 中, + +```python +class BBoxHead(nn.Module): + ... + def loss(self, ...): + losses = dict() + # 分类损失 + losses['loss_cls'] = self.loss_cls(...) + # 分类准确率 + losses['acc'] = accuracy(...) + # 边界框损失 + losses['loss_bbox'] = self.loss_bbox(...) + return losses +``` + +`'bbox_head.loss()'` 在模型 forward 阶段会被调用。返回的字典中包含了 `'loss_bbox'`,`'loss_cls'`,`'acc'`。只有 `'loss_bbox'`, `'loss_cls'` 会被用于反向传播,`'acc'` 只会被作为评价指标来监控训练过程。 + +我们默认,只有那些键的名称中包含 `'loss'` 的值会被用于反向传播。这个行为可以通过修改 `BaseDetector.train_step()` 来改变。 + +## 空 proposals + +在 MMDetection 中,我们为两阶段方法中空 proposals 的情况增加了特殊处理和单元测试。我们同时需要处理整个 batch 和单一图片中空 proposals 的情况。例如,在 CascadeRoIHead 中, + +```python +# 简单的测试 +... + +# 在整个 batch中 都没有 proposals +if rois.shape[0] == 0: + bbox_results = [[ + np.zeros((0, 5), dtype=np.float32) + for _ in range(self.bbox_head[-1].num_classes) + ]] * num_imgs + if self.with_mask: + mask_classes = self.mask_head[-1].num_classes + segm_results = [[[] for _ in range(mask_classes)] + for _ in range(num_imgs)] + results = list(zip(bbox_results, segm_results)) + else: + results = bbox_results + return results +... + +# 在单张图片中没有 proposals +for i in range(self.num_stages): + ... + if i < self.num_stages - 1: + for j in range(num_imgs): + # 处理空 proposals + if rois[j].shape[0] > 0: + bbox_label = cls_score[j][:, :-1].argmax(dim=1) + refine_roi = self.bbox_head[i].regress_by_class( + rois[j], bbox_label[j], bbox_pred[j], img_metas[j]) + refine_roi_list.append(refine_roi) +``` + +如果你有自定义的 `RoIHead`, 你可以参考上面的方法来处理空 proposals 的情况。 + +## 全景分割数据集 + +在 MMDetection 中,我们支持了 COCO 全景分割数据集 `CocoPanopticDataset`。对于它的实现,我们在这里声明一些默认约定。 + +1. 在 mmdet\<=2.16.0 时,语义分割标注中的前景和背景标签范围与 MMDetection 中的默认规定有所不同。标签 `0` 代表 `VOID` 标签。 + 从 mmdet=2.17.0 开始,为了和框的类别标注保持一致,语义分割标注的类别标签也改为从 `0` 开始,标签 `255` 代表 `VOID` 类。 + 为了达成这一目标,我们在流程 `Pad` 里支持了设置 `seg` 的填充值的功能。 +2. 在评估中,全景分割结果必须是一个与原图大小相同的图。结果图中每个像素的值有如此形式:`instance_id * INSTANCE_OFFSET + category_id`。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_dataset.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_dataset.md new file mode 100644 index 0000000000000000000000000000000000000000..e845f37f2db4b92f1fb600baf4d8d0a8dab1a7c0 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_dataset.md @@ -0,0 +1,425 @@ +# 自定义数据集 + +## 支持新的数据格式 + +为了支持新的数据格式,可以选择将数据转换成现成的格式(COCO 或者 PASCAL)或将其转换成中间格式。当然也可以选择以离线的形式(在训练之前使用脚本转换)或者在线的形式(实现一个新的 dataset 在训练中进行转换)来转换数据。 + +在 MMDetection 中,建议将数据转换成 COCO 格式并以离线的方式进行,因此在完成数据转换后只需修改配置文件中的标注数据的路径和类别即可。 + +### 将新的数据格式转换为现有的数据格式 + +最简单的方法就是将你的数据集转换成现有的数据格式(COCO 或者 PASCAL VOC) + +COCO 格式的 JSON 标注文件有如下必要的字段: + +```python +'images': [ + { + 'file_name': 'COCO_val2014_000000001268.jpg', + 'height': 427, + 'width': 640, + 'id': 1268 + }, + ... +], + +'annotations': [ + { + 'segmentation': [[192.81, + 247.09, + ... + 219.03, + 249.06]], # 如果有 mask 标签且为多边形 XY 点坐标格式,则需要保证至少包括 3 个点坐标,否则为无效多边形 + 'area': 1035.749, + 'iscrowd': 0, + 'image_id': 1268, + 'bbox': [192.81, 224.8, 74.73, 33.43], + 'category_id': 16, + 'id': 42986 + }, + ... +], + +'categories': [ + {'id': 0, 'name': 'car'}, + ] +``` + +在 JSON 文件中有三个必要的键: + +- `images`: 包含多个图片以及它们的信息的数组,例如 `file_name`、`height`、`width` 和 `id`。 +- `annotations`: 包含多个实例标注信息的数组。 +- `categories`: 包含多个类别名字和 ID 的数组。 + +在数据预处理之后,使用现有的数据格式来训练自定义的新数据集有如下两步(以 COCO 为例): + +1. 为自定义数据集修改配置文件。 +2. 检查自定义数据集的标注。 + +这里我们举一个例子来展示上面的两个步骤,这个例子使用包括 5 个类别的 COCO 格式的数据集来训练一个现有的 Cascade Mask R-CNN R50-FPN 检测器 + +#### 1. 为自定义数据集修改配置文件 + +配置文件的修改涉及两个方面: + +1. `dataloaer` 部分。需要在 `train_dataloader.dataset`、`val_dataloader.dataset` 和 `test_dataloader.dataset` 中添加 `metainfo=dict(classes=classes)`, 其中 classes 必须是 tuple 类型。 +2. `model` 部分中的 `num_classes`。需要将默认值(COCO 数据集中为 80)修改为自定义数据集中的类别数。 + +`configs/my_custom_config.py` 内容如下: + +```python + +# 新的配置来自基础的配置以更好地说明需要修改的地方 +_base_ = './cascade_mask_rcnn_r50_fpn_1x_coco.py' + +# 1. 数据集设定 +dataset_type = 'CocoDataset' +classes = ('a', 'b', 'c', 'd', 'e') +data_root='path/to/your/' + +train_dataloader = dict( + batch_size=2, + num_workers=2, + dataset=dict( + type=dataset_type, + # 将类别名字添加至 `metainfo` 字段中 + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='train/annotation_data', + data_prefix=dict(img='train/image_data') + ) + ) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + dataset=dict( + type=dataset_type, + test_mode=True, + # 将类别名字添加至 `metainfo` 字段中 + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='val/annotation_data', + data_prefix=dict(img='val/image_data') + ) + +test_dataloader = dict( + batch_size=1, + num_workers=2, + dataset=dict( + type=dataset_type, + test_mode=True, + # 将类别名字添加至 `metainfo` 字段中 + metainfo=dict(classes=classes), + data_root=data_root, + ann_file='test/annotation_data', + data_prefix=dict(img='test/image_data') + ) + ) + +# 2. 模型设置 + +# 将所有的 `num_classes` 默认值修改为 5(原来为80) +model = dict( + roi_head=dict( + bbox_head=[ + dict( + type='Shared2FCBBoxHead', + # 将所有的 `num_classes` 默认值修改为 5(原来为 80) + num_classes=5), + dict( + type='Shared2FCBBoxHead', + # 将所有的 `num_classes` 默认值修改为 5(原来为 80) + num_classes=5), + dict( + type='Shared2FCBBoxHead', + # 将所有的 `num_classes` 默认值修改为 5(原来为 80) + num_classes=5)], + # 将所有的 `num_classes` 默认值修改为 5(原来为 80) + mask_head=dict(num_classes=5))) +``` + +#### 2. 检查自定义数据集的标注 + +假设你自己的数据集是 COCO 格式,那么需要保证数据的标注没有问题: + +1. 标注文件中 `categories` 的长度要与配置中的 `classes` 元组长度相匹配,它们都表示有几类。(如例子中有 5 个类别) +2. 配置文件中 `classes` 字段应与标注文件里 `categories` 下的 `name` 有相同的元素且顺序一致。MMDetection 会自动将 `categories` 中不连续的 `id` 映射成连续的索引,因此 `categories` 下的 `name`的字符串顺序会影响标签的索引。同时,配置文件中的 `classes` 的字符串顺序也会影响到预测框可视化时的标签。 +3. `annotations` 中的 `category_id` 必须是有效的值。比如所有 `category_id` 的值都应该属于 `categories` 中的 `id`。 + +下面是一个有效标注的例子: + +```python + +'annotations': [ + { + 'segmentation': [[192.81, + 247.09, + ... + 219.03, + 249.06]], # 如果有 mask 标签。 + 'area': 1035.749, + 'iscrowd': 0, + 'image_id': 1268, + 'bbox': [192.81, 224.8, 74.73, 33.43], + 'category_id': 16, + 'id': 42986 + }, + ... +], + +# MMDetection 会自动将 `categories` 中不连续的 `id` 映射成连续的索引。 +'categories': [ + {'id': 1, 'name': 'a'}, {'id': 3, 'name': 'b'}, {'id': 4, 'name': 'c'}, {'id': 16, 'name': 'd'}, {'id': 17, 'name': 'e'}, + ] +``` + +我们使用这种方式来支持 CityScapes 数据集。脚本在 [cityscapes.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/dataset_converters/cityscapes.py) 并且我们提供了微调的 [configs](https://github.com/open-mmlab/mmdetection/blob/main/configs/cityscapes). + +**注意** + +1. 对于实例分割数据集, **MMDetection 目前只支持评估 COCO 格式的 mask AP**. +2. 推荐训练之前进行离线转换,这样就可以继续使用 `CocoDataset` 且只需修改标注文件的路径以及训练的种类。 + +### 调整新的数据格式为中间格式 + +如果不想将标注格式转换为 COCO 或者 PASCAL 格式也是可行的。实际上,我们在 MMEngine 的 [BaseDataset](https://github.com/open-mmlab/mmengine/blob/main/mmengine/dataset/base_dataset.py#L116) 中定义了一种简单的标注格式并且与所有现有的数据格式兼容,也能进行离线或者在线转换。 + +数据集的标注必须为 `json` 或 `yaml`,`yml` 或 `pickle`,`pkl` 格式;标注文件中存储的字典必须包含 `metainfo` 和 `data_list` 两个字段。其中 `metainfo` 是一个字典,里面包含数据集的元信息,例如类别信息;`data_list` 是一个列表,列表中每个元素是一个字典,该字典定义了一个原始数据(raw data),每个原始数据包含一个或若干个训练/测试样本。 + +以下是一个 JSON 标注文件的例子: + +```json +{ + 'metainfo': + { + 'classes': ('person', 'bicycle', 'car', 'motorcycle'), + ... + }, + 'data_list': + [ + { + "img_path": "xxx/xxx_1.jpg", + "height": 604, + "width": 640, + "instances": + [ + { + "bbox": [0, 0, 10, 20], + "bbox_label": 1, + "ignore_flag": 0 + }, + { + "bbox": [10, 10, 110, 120], + "bbox_label": 2, + "ignore_flag": 0 + } + ] + }, + { + "img_path": "xxx/xxx_2.jpg", + "height": 320, + "width": 460, + "instances": + [ + { + "bbox": [10, 0, 20, 20], + "bbox_label": 3, + "ignore_flag": 1 + } + ] + }, + ... + ] +} +``` + +有些数据集可能会提供如:crowd/difficult/ignored bboxes 标注,那么我们使用 `ignore_flag`来包含它们。 + +在得到上述标准的数据标注格式后,可以直接在配置中使用 MMDetection 的 [BaseDetDataset](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/datasets/base_det_dataset.py#L13) ,而无需进行转换。 + +### 自定义数据集例子 + +假设文本文件中表示的是一种全新的标注格式。边界框的标注信息保存在 `annotation.txt` 中,内容如下: + +``` +# +000001.jpg +1280 720 +2 +10 20 40 60 1 +20 40 50 60 2 +# +000002.jpg +1280 720 +3 +50 20 40 60 2 +20 40 30 45 2 +30 40 50 60 3 +``` + +我们可以在 `mmdet/datasets/my_dataset.py` 中创建一个新的 dataset 用以加载数据。 + +```python +import mmengine +from mmdet.base_det_dataset import BaseDetDataset +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class MyDataset(BaseDetDataset): + + METAINFO = { + 'classes': ('person', 'bicycle', 'car', 'motorcycle'), + 'palette': [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230)] + } + + def load_data_list(self, ann_file): + ann_list = mmengine.list_from_file(ann_file) + + data_infos = [] + for i, ann_line in enumerate(ann_list): + if ann_line != '#': + continue + + img_shape = ann_list[i + 2].split(' ') + width = int(img_shape[0]) + height = int(img_shape[1]) + bbox_number = int(ann_list[i + 3]) + + instances = [] + for anns in ann_list[i + 4:i + 4 + bbox_number]: + instance = {} + instance['bbox'] = [float(ann) for ann in anns.split(' ')[:4]] + instance['bbox_label']=int(anns[4]) + instances.append(instance) + + data_infos.append( + dict( + img_path=ann_list[i + 1], + img_id=i, + width=width, + height=height, + instances=instances + )) + + return data_infos +``` + +配置文件中,可以使用 `MyDataset` 进行如下修改 + +```python +dataset_A_train = dict( + type='MyDataset', + ann_file = 'image_list.txt', + pipeline=train_pipeline +) +``` + +## 使用 dataset 包装器自定义数据集 + +MMEngine 也支持非常多的数据集包装器(wrapper)来混合数据集或在训练时修改数据集的分布,其支持如下三种数据集包装: + +- `RepeatDataset`:将整个数据集简单地重复。 +- `ClassBalancedDataset`:以类别均衡的方式重复数据集。 +- `ConcatDataset`:合并数据集。 + +具体使用方式见 [MMEngine 数据集包装器](#TODO)。 + +## 修改数据集的类别 + +根据现有数据集的类型,我们可以修改它们的类别名称来训练其标注的子集。 +例如,如果只想训练当前数据集中的三个类别,那么就可以修改数据集的 `metainfo` 字典,数据集就会自动屏蔽掉其他类别的真实框。 + +```python +classes = ('person', 'bicycle', 'car') +train_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +val_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +test_dataloader = dict( + dataset=dict( + metainfo=dict(classes=classes)) + ) +``` + +**注意** + +- 在 MMDetection v2.5.0 之前,如果类别为集合时数据集将自动过滤掉不包含 GT 的图片,且没办法通过修改配置将其关闭。这是一种不可取的行为而且会引起混淆,因为当类别不是集合时数据集时,只有在 `filter_empty_gt=True` 以及 `test_mode=False` 的情况下才会过滤掉不包含 GT 的图片。在 MMDetection v2.5.0 之后,我们将图片的过滤以及类别的修改进行解耦,数据集只有在 `filter_cfg=dict(filter_empty_gt=True)` 和 `test_mode=False` 的情况下才会过滤掉不包含 GT 的图片,无论类别是否为集合。设置类别只会影响用于训练的标注类别,用户可以自行决定是否过滤不包含 GT 的图片。 +- 直接使用 MMEngine 中的 `BaseDataset` 或者 MMDetection 中的 `BaseDetDataset` 时用户不能通过修改配置来过滤不含 GT 的图片,但是可以通过离线的方式来解决。 +- 当设置数据集中的 `classes` 时,记得修改 `num_classes`。从 v2.9.0 (PR#4508) 之后,我们实现了 [NumClassCheckHook](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/engine/hooks/num_class_check_hook.py) 来检查类别数是否一致。 + +## COCO 全景分割数据集 + +现在我们也支持 COCO Panoptic Dataset,全景注释的格式与 COCO 格式不同,其前景和背景都将存在于注释文件中。COCO Panoptic 格式的注释 JSON 文件具有以下必要的键: + +```python +'images': [ + { + 'file_name': '000000001268.jpg', + 'height': 427, + 'width': 640, + 'id': 1268 + }, + ... +] + +'annotations': [ + { + 'filename': '000000001268.jpg', + 'image_id': 1268, + 'segments_info': [ + { + 'id':8345037, # One-to-one correspondence with the id in the annotation map. + 'category_id': 51, + 'iscrowd': 0, + 'bbox': (x1, y1, w, h), # The bbox of the background is the outer rectangle of its mask. + 'area': 24315 + }, + ... + ] + }, + ... +] + +'categories': [ # including both foreground categories and background categories + {'id': 0, 'name': 'person'}, + ... + ] +``` + +此外,`seg` 必须设置为全景注释图像的路径。 + +```python +dataset_type = 'CocoPanopticDataset' +data_root='path/to/your/' + +train_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='train/image_data/', seg='train/panoptic/image_annotation_data/') + ) +) +val_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='val/image_data/', seg='val/panoptic/image_annotation_data/') + ) +) +test_dataloader = dict( + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img='test/image_data/', seg='test/panoptic/image_annotation_data/') + ) +) +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_losses.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_losses.md new file mode 100644 index 0000000000000000000000000000000000000000..07ccccda128f7604b6bc80bf30b2251498eede5e --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_losses.md @@ -0,0 +1,125 @@ +# 自定义损失函数 + +MMDetection 为用户提供了不同的损失函数。但是默认的配置可能无法适应不同的数据和模型,所以用户可能会希望修改某一个损失函数来适应新的情况。 + +本教程首先详细的解释计算损失的过程然后给出一些关于如何修改每一个步骤的指导。对损失的修改可以被分为微调和加权。 + +## 一个损失的计算过程 + +给定输入(包括预测和目标,以及权重),损失函数会把输入的张量映射到最后的损失标量。映射过程可以分为下面五个步骤: + +1. 设置采样方法为对正负样本进行采样。 + +2. 通过损失核函数获取**元素**或者**样本**损失。 + +3. 通过权重张量来给损失**逐元素**权重。 + +4. 把损失张量归纳为一个**标量**。 + +5. 用一个**张量**给当前损失一个权重。 + +## 设置采样方法(步骤 1) + +对于一些损失函数,需要采样策略来避免正负样本之间的不平衡。 + +例如,在RPN head中使用`CrossEntropyLoss`时,我们需要在`train_cfg`中设置`RandomSampler` + +```python +train_cfg=dict( + rpn=dict( + sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False)) +``` + +对于其他一些具有正负样本平衡机制的损失,例如 Focal Loss、GHMC 和 QualityFocalLoss,不再需要进行采样。 + +## 微调损失 + +微调一个损失主要与步骤 2,4,5 有关,大部分的修改可以在配置文件中指定。这里我们用 [Focal Loss (FL)](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/focal_loss.py) 作为例子。 +下面的代码分别是构建 FL 的方法和它的配置文件,他们是一一对应的。 + +```python +@LOSSES.register_module() +class FocalLoss(nn.Module): + + def __init__(self, + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + reduction='mean', + loss_weight=1.0): +``` + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0) +``` + +### 微调超参数(步骤2) + +`gamma` 和 `beta` 是 Focal Loss 中的两个超参数。如果我们想把 `gamma` 的值设为 1.5,把 `alpha` 的值设为 0.5,我们可以在配置文件中按照如下指定: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=1.5, + alpha=0.5, + loss_weight=1.0) +``` + +### 微调归纳方式(步骤4) + +Focal Loss 默认的归纳方式是 `mean`。如果我们想把归纳方式从 `mean` 改成 `sum`,我们可以在配置文件中按照如下指定: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0, + reduction='sum') +``` + +### 微调损失权重(步骤5) + +这里的损失权重是一个标量,他用来控制多任务学习中不同损失的重要程度,例如,分类损失和回归损失。如果我们想把分类损失的权重设为 0.5,我们可以在配置文件中如下指定: + +```python +loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=0.5) +``` + +## 加权损失(步骤3) + +加权损失就是我们逐元素修改损失权重。更具体来说,我们给损失张量乘以一个与他有相同形状的权重张量。所以,损失中不同的元素可以被赋予不同的比例,所以这里叫做逐元素。损失的权重在不同模型中变化很大,而且与上下文相关,但是总的来说主要有两种损失权重:分类损失的 `label_weights` 和边界框的 `bbox_weights`。你可以在相应的头中的 `get_target` 方法中找到他们。这里我们使用 [ATSSHead](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/dense_heads/atss_head.py#L322) 作为一个例子。它继承了 [AnchorHead](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/dense_heads/anchor_head.py) ,但是我们重写它的 +`get_targets` 方法来产生不同的 `label_weights` 和 `bbox_weights`。 + +``` +class ATSSHead(AnchorHead): + + ... + + def get_targets(self, + anchor_list, + valid_flag_list, + gt_bboxes_list, + img_metas, + gt_bboxes_ignore_list=None, + gt_labels_list=None, + label_channels=1, + unmap_outputs=True): +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_models.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_models.md new file mode 100644 index 0000000000000000000000000000000000000000..5fa77e4195ba3f50dd113b1a25cb2307cdc3218f --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_models.md @@ -0,0 +1,412 @@ +# 自定义模型 + +我们简单地把模型的各个组件分为五类: + +- 主干网络 (backbone):通常是一个用来提取特征图 (feature map) 的全卷积网络 (FCN network),例如:ResNet, MobileNet。 +- Neck:主干网络和 Head 之间的连接部分,例如:FPN, PAFPN。 +- Head:用于具体任务的组件,例如:边界框预测和掩码预测。 +- 区域提取器 (roi extractor):从特征图中提取 RoI 特征,例如:RoI Align。 +- 损失 (loss):在 Head 组件中用于计算损失的部分,例如:FocalLoss, L1Loss, GHMLoss. + +## 开发新的组件 + +### 添加一个新的主干网络 + +这里,我们以 MobileNet 为例来展示如何开发新组件。 + +#### 1. 定义一个新的主干网络(以 MobileNet 为例) + +新建一个文件 `mmdet/models/backbones/mobilenet.py` + +```python +import torch.nn as nn + +from mmdet.registry import MODELS + + +@MODELS.register_module() +class MobileNet(nn.Module): + + def __init__(self, arg1, arg2): + pass + + def forward(self, x): # should return a tuple + pass +``` + +#### 2. 导入该模块 + +你可以添加下述代码到 `mmdet/models/backbones/__init__.py` + +```python +from .mobilenet import MobileNet +``` + +或添加: + +```python +custom_imports = dict( + imports=['mmdet.models.backbones.mobilenet'], + allow_failed_imports=False) +``` + +到配置文件以避免原始代码被修改。 + +#### 3. 在你的配置文件中使用该主干网络 + +```python +model = dict( + ... + backbone=dict( + type='MobileNet', + arg1=xxx, + arg2=xxx), + ... +``` + +### 添加新的 Neck + +#### 1. 定义一个 Neck(以 PAFPN 为例) + +新建一个文件 `mmdet/models/necks/pafpn.py` + +```python +import torch.nn as nn + +from mmdet.registry import MODELS + + +@MODELS.register_module() +class PAFPN(nn.Module): + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False): + pass + + def forward(self, inputs): + # implementation is ignored + pass +``` + +#### 2. 导入该模块 + +你可以添加下述代码到 `mmdet/models/necks/__init__.py` + +```python +from .pafpn import PAFPN +``` + +或添加: + +```python +custom_imports = dict( + imports=['mmdet.models.necks.pafpn'], + allow_failed_imports=False) +``` + +到配置文件以避免原始代码被修改。 + +#### 3. 修改配置文件 + +```python +neck=dict( + type='PAFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5) +``` + +### 添加新的 Head + +我们以 [Double Head R-CNN](https://arxiv.org/abs/1904.06493) 为例来展示如何添加一个新的 Head。 + +首先,添加一个新的 bbox head 到 `mmdet/models/roi_heads/bbox_heads/double_bbox_head.py`。 +Double Head R-CNN 在目标检测上实现了一个新的 bbox head。为了实现 bbox head,我们需要使用如下的新模块中三个函数。 + +```python +from typing import Tuple + +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule, ModuleList +from torch import Tensor + +from mmdet.models.backbones.resnet import Bottleneck +from mmdet.registry import MODELS +from mmdet.utils import ConfigType, MultiConfig, OptConfigType, OptMultiConfig +from .bbox_head import BBoxHead + + +@MODELS.register_module() +class DoubleConvFCBBoxHead(BBoxHead): + r"""Bbox head used in Double-Head R-CNN + + .. code-block:: none + + /-> cls + /-> shared convs -> + \-> reg + roi features + /-> cls + \-> shared fc -> + \-> reg + """ # noqa: W605 + + def __init__(self, + num_convs: int = 0, + num_fcs: int = 0, + conv_out_channels: int = 1024, + fc_out_channels: int = 1024, + conv_cfg: OptConfigType = None, + norm_cfg: ConfigType = dict(type='BN'), + init_cfg: MultiConfig = dict( + type='Normal', + override=[ + dict(type='Normal', name='fc_cls', std=0.01), + dict(type='Normal', name='fc_reg', std=0.001), + dict( + type='Xavier', + name='fc_branch', + distribution='uniform') + ]), + **kwargs) -> None: + kwargs.setdefault('with_avg_pool', True) + super().__init__(init_cfg=init_cfg, **kwargs) + + def forward(self, x_cls: Tensor, x_reg: Tensor) -> Tuple[Tensor]: + +``` + +然后,如有必要,实现一个新的 bbox head。我们打算从 `StandardRoIHead` 来继承新的 `DoubleHeadRoIHead`。我们可以发现 `StandardRoIHead` 已经实现了下述函数。 + +```python +from typing import List, Optional, Tuple + +import torch +from torch import Tensor + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.structures import DetDataSample +from mmdet.structures.bbox import bbox2roi +from mmdet.utils import ConfigType, InstanceList +from ..task_modules.samplers import SamplingResult +from ..utils import empty_instances, unpack_gt_instances +from .base_roi_head import BaseRoIHead + + +@MODELS.register_module() +class StandardRoIHead(BaseRoIHead): + """Simplest base roi head including one bbox head and one mask head.""" + + def init_assigner_sampler(self) -> None: + + def init_bbox_head(self, bbox_roi_extractor: ConfigType, + bbox_head: ConfigType) -> None: + + def init_mask_head(self, mask_roi_extractor: ConfigType, + mask_head: ConfigType) -> None: + + def forward(self, x: Tuple[Tensor], + rpn_results_list: InstanceList) -> tuple: + + def loss(self, x: Tuple[Tensor], rpn_results_list: InstanceList, + batch_data_samples: List[DetDataSample]) -> dict: + + def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict: + + def bbox_loss(self, x: Tuple[Tensor], + sampling_results: List[SamplingResult]) -> dict: + + def mask_loss(self, x: Tuple[Tensor], + sampling_results: List[SamplingResult], bbox_feats: Tensor, + batch_gt_instances: InstanceList) -> dict: + + def _mask_forward(self, + x: Tuple[Tensor], + rois: Tensor = None, + pos_inds: Optional[Tensor] = None, + bbox_feats: Optional[Tensor] = None) -> dict: + + def predict_bbox(self, + x: Tuple[Tensor], + batch_img_metas: List[dict], + rpn_results_list: InstanceList, + rcnn_test_cfg: ConfigType, + rescale: bool = False) -> InstanceList: + + def predict_mask(self, + x: Tuple[Tensor], + batch_img_metas: List[dict], + results_list: InstanceList, + rescale: bool = False) -> InstanceList: + +``` + +Double Head 的修改主要在 bbox_forward 的逻辑中,且它从 `StandardRoIHead` 中继承了其他逻辑。在 `mmdet/models/roi_heads/double_roi_head.py` 中,我们用下述代码实现新的 bbox head: + +```python +from typing import Tuple + +from torch import Tensor + +from mmdet.registry import MODELS +from .standard_roi_head import StandardRoIHead + + +@MODELS.register_module() +class DoubleHeadRoIHead(StandardRoIHead): + """RoI head for `Double Head RCNN `_. + + Args: + reg_roi_scale_factor (float): The scale factor to extend the rois + used to extract the regression features. + """ + + def __init__(self, reg_roi_scale_factor: float, **kwargs): + super().__init__(**kwargs) + self.reg_roi_scale_factor = reg_roi_scale_factor + + def _bbox_forward(self, x: Tuple[Tensor], rois: Tensor) -> dict: + """Box head forward function used in both training and testing. + + Args: + x (tuple[Tensor]): List of multi-level img features. + rois (Tensor): RoIs with the shape (n, 5) where the first + column indicates batch id of each RoI. + + Returns: + dict[str, Tensor]: Usually returns a dictionary with keys: + + - `cls_score` (Tensor): Classification scores. + - `bbox_pred` (Tensor): Box energies / deltas. + - `bbox_feats` (Tensor): Extract bbox RoI features. + """ + bbox_cls_feats = self.bbox_roi_extractor( + x[:self.bbox_roi_extractor.num_inputs], rois) + bbox_reg_feats = self.bbox_roi_extractor( + x[:self.bbox_roi_extractor.num_inputs], + rois, + roi_scale_factor=self.reg_roi_scale_factor) + if self.with_shared_head: + bbox_cls_feats = self.shared_head(bbox_cls_feats) + bbox_reg_feats = self.shared_head(bbox_reg_feats) + cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats) + + bbox_results = dict( + cls_score=cls_score, + bbox_pred=bbox_pred, + bbox_feats=bbox_cls_feats) + return bbox_results +``` + +最终,用户需要把该模块添加到 `mmdet/models/bbox_heads/__init__.py` 和 `mmdet/models/roi_heads/__init__.py` 以使相关的注册表可以找到并加载他们。 + +或者,用户可以添加: + +```python +custom_imports=dict( + imports=['mmdet.models.roi_heads.double_roi_head', 'mmdet.models.roi_heads.bbox_heads.double_bbox_head']) +``` + +到配置文件并实现相同的目的。 + +Double Head R-CNN 的配置文件如下: + +```python +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + roi_head=dict( + type='DoubleHeadRoIHead', + reg_roi_scale_factor=1.3, + bbox_head=dict( + _delete_=True, + type='DoubleConvFCBBoxHead', + num_convs=4, + num_fcs=2, + in_channels=256, + conv_out_channels=1024, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=80, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[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=2.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=2.0)))) + +``` + +从 MMDetection 2.0 版本起,配置系统支持继承配置以使用户可以专注于修改。 +Double Head R-CNN 主要使用了一个新的 `DoubleHeadRoIHead` 和一个新的 `DoubleConvFCBBoxHead`,参数需要根据每个模块的 `__init__` 函数来设置。 + +### 添加新的损失 + +假设你想添加一个新的损失 `MyLoss` 用于边界框回归。 +为了添加一个新的损失函数,用户需要在 `mmdet/models/losses/my_loss.py` 中实现。 +装饰器 `weighted_loss` 可以使损失每个部分加权。 + +```python +import torch +import torch.nn as nn + +from mmdet.registry import LOSSES +from .utils import weighted_loss + + +@weighted_loss +def my_loss(pred, target): + assert pred.size() == target.size() and target.numel() > 0 + loss = torch.abs(pred - target) + return loss + +@LOSSES.register_module() +class MyLoss(nn.Module): + + def __init__(self, reduction='mean', loss_weight=1.0): + super(MyLoss, self).__init__() + self.reduction = reduction + self.loss_weight = loss_weight + + def forward(self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None): + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + loss_bbox = self.loss_weight * my_loss( + pred, target, weight, reduction=reduction, avg_factor=avg_factor) + return loss_bbox +``` + +然后,用户需要把它加到 `mmdet/models/losses/__init__.py`。 + +```python +from .my_loss import MyLoss, my_loss +``` + +或者,你可以添加: + +```python +custom_imports=dict( + imports=['mmdet.models.losses.my_loss']) +``` + +到配置文件来实现相同的目的。 + +如使用,请修改 `loss_xxx` 字段。 +因为 MyLoss 是用于回归的,你需要在 Head 中修改 `loss_xxx` 字段。 + +```python +loss_bbox=dict(type='MyLoss', loss_weight=1.0)) +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_runtime.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_runtime.md new file mode 100644 index 0000000000000000000000000000000000000000..d4a190987899ccefb044e6402b2b67ec998a3136 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_runtime.md @@ -0,0 +1,387 @@ +# 自定义训练配置 + +## 自定义优化相关的配置 + +优化相关的配置现在已全部集成到 `optim_wrapper` 中,通常包含三个域:`optimizer`, `paramwise_cfg`,`clip_grad`,具体细节见 [OptimWrapper](https://mmengine.readthedocs.io/en/latest/tutorials/optim_wrapper.md)。下面这个例子中,使用了 `AdamW` 作为优化器,主干部分的学习率缩小到原来的十分之一,以及添加了梯度裁剪。 + +```python +optim_wrapper = dict( + type='OptimWrapper', + # 优化器 + optimizer=dict( + type='AdamW', + lr=0.0001, + weight_decay=0.05, + eps=1e-8, + betas=(0.9, 0.999)), + + # 参数层面的学习率和正则化设置 + paramwise_cfg=dict( + custom_keys={ + 'backbone': dict(lr_mult=0.1, decay_mult=1.0), + }, + norm_decay_mult=0.0), + + # 梯度裁剪 + clip_grad=dict(max_norm=0.01, norm_type=2)) +``` + +### 自定义 Pytorch 中优化器设置 + +我们已经支持了 Pytorch 中实现的所有优化器,要使用这些优化器唯一要做就是修改配置文件中的 `optimi_wrapper` 中的 `optimzer` 域。比如,如果想要使用 `ADAM` 作为优化器(可能会导致性能下降),所需要做的修改如下。 + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='Adam', lr=0.0003, weight_decay=0.0001)) +``` + +要修改模型的学习率,用户只需要修改 `optimizer` 中的 `lr` 域。用户可以直接参考 PyToch 的 [API doc](https://pytorch.org/docs/stable/optim.html?highlight=optim#module-torch.optim) 来进行参数的设置。 + +### 自定义优化器 + +#### 1. 定义一个新优化器 + +自定义优化器可以定义的方式如下: + +假设你想要添加一个名为 `MyOptimizer` 的优化器,它包含三个参数 `a`,`b`,`c`。你需要新建一个名为 +`mmdet/engine/optimizers` 的文件夹。然后在文件(比如,`mmdet/engine/optimizers/my_optimizer.py`)实现一个新的优化器。 + +```python +from mmdet.registry import OPTIMIZERS +from torch.optim import Optimizer + + +@OPTIMIZERS.register_module() +class MyOptimizer(Optimizer): + + def __init__(self, a, b, c) + +``` + +#### 2. 导入自定义的优化器 + +为了能找到上面的所定义的模块,这个模块必须要先导入到主命名空间中。有两种方式可以实现这一点。 + +- 修改 `mmdet/engine/optimizers/__init__.py` 来导入模块。 + + 新定义的模块必须导入到 `mmdet/engine/optimizers/__init__.py`,这样注册器才能找到该模块并添加它。 + +```python +from .my_optimizer import MyOptimizer +``` + +- 在配置文件使用 `custom_imports` 来手动导入模块。 + +```python +custom_imports = dict(imports=['mmdet.engine.optimizers.my_optimizer'], allow_failed_imports=False) +``` + +`mmdet.engine.optimizers.my_optimizer` 模块将在程序开始时导入,之后 `MyOptimizer` 类会被自动注册。注意:应该导入 `MyOptimizer` 所在的文件,即 `mmdet.engine.optimizers.my_optimizer`,而不是 `mmdet.engine.optimizers.my_optimizer.MyOptimizer`。 + +实际上,用户也可以在别的目录结构下来进行导入模块,只要改模块可以在 `PYTHONPATH` 中找到。 + +#### 3. 在配置文件中指定优化器 + +接下来,你可以在配置文件中的 `optim_wrapper` 域中的中 `optimizer` 域中设置你实现的优化器 `MyOptimizer`。在配置文件中,优化器在 `optimizer` 域中的配置方式如下: + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) +``` + +为了使用你的优化器,可以进行如下修改 + +```python +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='MyOptimizer', a=a_value, b=b_value, c=c_value)) +``` + +### 自定义优化器包装构造类 + +一些模型可能存在一些特定参数的优化设置,比如,BN 层的权重衰减。用户可以通过自定义优化器包装构造类来实现这些精细化的参数调整。 + +```python +from mmengine.optim import DefaultOptiWrapperConstructor + +from mmdet.registry import OPTIM_WRAPPER_CONSTRUCTORS +from .my_optimizer import MyOptimizer + + +@OPTIM_WRAPPER_CONSTRUCTORS.register_module() +class MyOptimizerWrapperConstructor(DefaultOptimWrapperConstructor): + + def __init__(self, + optim_wrapper_cfg: dict, + paramwise_cfg: Optional[dict] = None): + + def __call__(self, model: nn.Module) -> OptimWrapper: + + return optim_wrapper + +``` + +优化器包装构造类的具体实现见[这里](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/optimizer/default_constructor.py#L18),用户以它为模板,来实现新的优化器包装构造类。 + +### 额外的设置 + +一些没有被优化器实现的技巧(比如,参数层面的学习率设置)应该通过优化器包装构造类来实现或者钩子。我们列出了一些常用的设置用于稳定训练或者加速训练。请随意创建 PR,发布更多设置。 + +- __使用梯度裁剪来稳定训练__: + 一些模型需要进行梯度裁剪来稳定训练过程,例子如下: + + ```python + optim_wrapper = dict( + _delete_=True, clip_grad=dict(max_norm=35, norm_type=2)) + ``` + + 如果你的配置已经集成了基础配置(包含了 `optim_wrapper` 的配置),那么你需要添加 `_delete_=True` 来覆盖掉不需要的设置。具体见[配置相关的文档](https://mmdetection.readthedocs.io/en/latest/tutorials/config.html)。 + +- __使用动量调度加速模型收敛__: + 我们支持动量调度器根据学习率修改模型的动量,这可以使模型以更快的方式收敛。动量调度器通常与学习率调度器一起使用,例如 [3D 检测](https://github.com/open-mmlab/mmdetection3d/blob/dev-1.x/configs/_base_/schedules/cyclic-20e.py) 中使用以下配置以加速收敛。 + 更多细节请参考 [CosineAnnealingLR](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py#L43) 和 [CosineAnnealingMomentum](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/momentum_scheduler.py#L71) 的具体实现。 + + ```python + param_scheduler = [ + # 学习率调度器 + # 在前 8 个 epoch, 学习率从 0 增大到 lr * 10 + # 在接下来 12 个 epoch, 学习率从 lr * 10 减小到 lr * 1e-4 + dict( + type='CosineAnnealingLR', + T_max=8, + eta_min=lr * 10, + begin=0, + end=8, + by_epoch=True, + convert_to_iter_based=True), + dict( + type='CosineAnnealingLR', + T_max=12, + eta_min=lr * 1e-4, + begin=8, + end=20, + by_epoch=True, + convert_to_iter_based=True), + # 动量调度器 + # 在前 8 个 epoch, 动量从 0 增大到 0.85 / 0.95 + # 在接下来 12 个 epoch, 学习率从 0.85 / 0.95 增大到 1 + dict( + type='CosineAnnealingMomentum', + T_max=8, + eta_min=0.85 / 0.95, + begin=0, + end=8, + by_epoch=True, + convert_to_iter_based=True), + dict( + type='CosineAnnealingMomentum', + T_max=12, + eta_min=1, + begin=8, + end=20, + by_epoch=True, + convert_to_iter_based=True) + ] + ``` + +## 自定义训练策略 + +默认情况下,我们使用 1x 的学习率调整策略,这会条用 MMEngine 中的 [MultiStepLR](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py#L139)。 +我们支持许多其他学习率调整策略,具体见[这里](https://github.com/open-mmlab/mmengine/blob/main/mmengine/optim/scheduler/lr_scheduler.py),例如 `CosineAnnealingLR` 和 `PolyLR` 策略。下面有些例子 + +- 多项式学习率调整策略: + + ```python + param_scheduler = [ + dict( + type='PolyLR', + power=0.9, + eta_min=1e-4, + begin=0, + end=8, + by_epoch=True)] + ``` + +- 余弦退火学习率调整策略 + + ```python + param_scheduler = [ + dict( + type='CosineAnnealingLR', + T_max=8, + eta_min=lr * 1e-5, + begin=0, + end=8, + by_epoch=True)] + + ``` + +## 自定义训练循环 + +默认情况下,在 `train_cfg` 中使用 `EpochBasedTrainLoop`,并且在每个 epoch 训练之后进行验证,如下所示。 + +```python +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_begin=1, val_interval=1) +``` + +实际上,[`IterBasedTrainLoop`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py#L183%5D) 和\[`EpochBasedTrainLoop`\](https:// github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py#L18) 支持动态区间的方式进行验证,见下例。 + +```python +# 在第 365001 次迭代之前,我们每 5000 次迭代进行一次评估。 +# 在第 365000 次迭代后,我们每 368750 次迭代进行一次评估, +# 这意味着我们在训练结束时进行评估。 + +interval = 5000 +max_iters = 368750 +dynamic_intervals = [(max_iters // interval * interval + 1, max_iters)] +train_cfg = dict( + type='IterBasedTrainLoop', + max_iters=max_iters, + val_interval=interval, + dynamic_intervals=dynamic_intervals) +``` + +## 自定义钩子 + +### 自定义自行实现的钩子 + +#### 1. 实现一个新的钩子 + +MMEngine 提供了许多有用的[钩子](https://mmdetection.readthedocs.io/en/latest/tutorials/hooks.html),但在某些情况下用户可能需要实现新的钩子。MMDetection 在 v3.0 中支持自定义钩子。因此,用户可以直接在 mmdet 或其基于 mmdet 的代码库中实现钩子,并通过仅在训练中修改配置来使用钩子。 +这里我们给出一个在 mmdet 中创建一个新的钩子并在训练中使用它的例子。 + +```python +from mmengine.hooks import Hook +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class MyHook(Hook): + + def __init__(self, a, b): + + def before_run(self, runner) -> None: + + def after_run(self, runner) -> None: + + def before_train(self, runner) -> None: + + def after_train(self, runner) -> None: + + def before_train_epoch(self, runner) -> None: + + def after_train_epoch(self, runner) -> None: + + def before_train_iter(self, + runner, + batch_idx: int, + data_batch: DATA_BATCH = None) -> None: + + def after_train_iter(self, + runner, + batch_idx: int, + data_batch: DATA_BATCH = None, + outputs: Optional[dict] = None) -> None: +``` + +根据钩子的功能,用户需要在 `before_run`、`after_run`、`before_train`、`after_train`、`before_train_epoch`、`after_train_epoch`、`before_train_iter` 和 `after_train_iter`。还有更多可以插入钩子的点,更多细节请参考 [base hook class](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/hook.py#L9)。 + +#### 2. 注册新钩子 + +然后我们需要导入 `MyHook`。假设该文件位于 `mmdet/engine/hooks/my_hook.py` 中,有两种方法可以做到这一点: + +- 修改 `mmdet/engine/hooks/__init__.py` 以导入它。 + + 新定义的模块应该在 `mmdet/engine/hooks/__init__.py` 中导入,以便注册表找到新模块并添加它: + +```python +from .my_hook import MyHook +``` + +- 在配置中使用 `custom_imports` 手动导入它 + +```python +custom_imports = dict(imports=['mmdet.engine.hooks.my_hook'], allow_failed_imports=False) +``` + +#### 3. 修改配置 + +```python +custom_hooks = [ + dict(type='MyHook', a=a_value, b=b_value) +] +``` + +你还可以通过修改键 `priority` 的值为 `NORMAL` 或 `HIGHEST` 来设置挂钩的优先级,如下所示 + +```python +custom_hooks = [ + dict(type='MyHook', a=a_value, b=b_value, priority='NORMAL') +] +``` + +默认情况下,钩子的优先级在注册期间设置为 `NORMAL`。 + +### 使用 MMDetection 中实现的钩子 + +如果 MMDetection 中已经实现了该钩子,你可以直接修改配置以使用该钩子,如下所示 + +#### 例子: `NumClassCheckHook` + +我们实现了一个名为 [NumClassCheckHook](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/engine/hooks/num_class_check_hook.py) 的自定义钩子来检查 `num_classes` 是否在 head 中和 `dataset` 中的 `classes` 的长度相匹配。 + +我们在 [default_runtime.py](https://github.com/open-mmlab/mmdetection/blob/main/configs/_base_/default_runtime.py) 中设置它。 + +```python +custom_hooks = [dict(type='NumClassCheckHook')] +``` + +### 修改默认运行时钩子 + +有一些常见的钩子是通过 `default_hooks` 注册的,它们是 + +- `IterTimerHook`:记录 “data_time” 用于加载数据和 “time” 用于模型训练步骤的钩子。 +- `LoggerHook`:从`Runner`的不同组件收集日志并将它们写入终端、JSON文件、tensorboard和 wandb 等的钩子。 +- `ParamSchedulerHook`:更新优化器中一些超参数的钩子,例如学习率和动量。 +- `CheckpointHook`:定期保存检查点的钩子。 +- `DistSamplerSeedHook`:为采样器和批处理采样器设置种子的钩子。 +- `DetVisualizationHook`:用于可视化验证和测试过程预测结果的钩子。 + +`IterTimerHook`、`ParamSchedulerHook` 和 `DistSamplerSeedHook` 很简单,通常不需要修改,所以这里我们将展示如何使用 `LoggerHook`、`CheckpointHook` 和 `DetVisualizationHook`。 + +#### CheckpointHook + +除了定期保存检查点,[`CheckpointHook`](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py#L19) 提供了其他选项,例如`max_keep_ckpts`、`save_optimizer ` 等。用户可以设置 `max_keep_ckpts` 只保存少量检查点或通过 `save_optimizer` 决定是否存储优化器的状态字典。参数的更多细节在[这里](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py#L19)可以找到。 + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + interval=1, + max_keep_ckpts=3, + save_optimizer=True)) +``` + +#### LoggerHook + +`LoggerHook` 可以设置间隔。详细用法可以在 [docstring](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/logger_hook.py#L18) 中找到。 + +```python +default_hooks = dict(logger=dict(type='LoggerHook', interval=50)) +``` + +#### DetVisualizationHook + +`DetVisualizationHook` 使用 `DetLocalVisualizer` 来可视化预测结果,`DetLocalVisualizer` 支持不同的后端,例如 `TensorboardVisBackend` 和 `WandbVisBackend` (见 [docstring](https://github.com/open-mmlab/mmengine/blob/main/mmengine/visualization/vis_backend.py) 了解更多细节)。用户可以添加多个后端来进行可视化,如下所示。 + +```python +default_hooks = dict( + visualization=dict(type='DetVisualizationHook', draw=True)) + +vis_backends = [dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_transforms.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_transforms.md new file mode 100644 index 0000000000000000000000000000000000000000..aa40717904a9ac34fd5640af6947aa09a85bcd11 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/customize_transforms.md @@ -0,0 +1,47 @@ +# 自定义数据预处理流程 + +1. 在任意文件里写一个新的流程,例如在 `my_pipeline.py`,它以一个字典作为输入并且输出一个字典: + + ```python + import random + from mmcv.transforms import BaseTransform + from mmdet.registry import TRANSFORMS + + + @TRANSFORMS.register_module() + class MyTransform(BaseTransform): + """Add your transform + + Args: + p (float): Probability of shifts. Default 0.5. + """ + + def __init__(self, prob=0.5): + self.prob = prob + + def transform(self, results): + if random.random() > self.prob: + results['dummy'] = True + return results + ``` + +2. 在配置文件里调用并使用你写的数据处理流程,需要确保你的训练脚本能够正确导入新增模块: + + ```python + custom_imports = dict(imports=['path.to.my_pipeline'], allow_failed_imports=False) + + train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='MyTransform', prob=0.2), + dict(type='PackDetInputs') + ] + ``` + +3. 可视化数据增强处理流程的结果 + + 如果想要可视化数据增强处理流程的结果,可以使用 `tools/misc/browse_dataset.py` 直观 + 地浏览检测数据集(图像和标注信息),或将图像保存到指定目录。 + 使用方法请参考[可视化文档](../user_guides/visualization.md) diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/data_flow.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/data_flow.md new file mode 100644 index 0000000000000000000000000000000000000000..ccc734f77fa3206520a47140a4780769e04313ae --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/data_flow.md @@ -0,0 +1 @@ +# 数据流(待更新) diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/datasets.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/datasets.md new file mode 100644 index 0000000000000000000000000000000000000000..16cc9bfc17baaaa718b4557f402d7628270c6642 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/datasets.md @@ -0,0 +1 @@ +# 数据集(待更新) diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/engine.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/engine.md new file mode 100644 index 0000000000000000000000000000000000000000..fa1a2561ea5c87722776745bc874d37496a462bd --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/engine.md @@ -0,0 +1 @@ +# 执行引擎(待更新) diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/evaluation.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..0b4954488bb25497e558098575d62325a0f17aa0 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/evaluation.md @@ -0,0 +1 @@ +# 精度评测(待更新) diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/how_to.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/how_to.md new file mode 100644 index 0000000000000000000000000000000000000000..6705dafdeabeb443fa2a7a5ef4e0af554556fa2d --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/how_to.md @@ -0,0 +1,220 @@ +本教程收集了任何如何使用 MMDetection 进行 xxx 的答案。 如果您遇到有关`如何做`的问题及答案,请随时更新此文档! + +## 使用 MMPretrain 的骨干网络 + +MMDet、MMPretrain、MMSeg 中的模型注册表都继承自 MMEngine 中的根注册表,允许这些存储库直接使用彼此已经实现的模块。 因此用户可以在 MMDetection 中使用来自 MMPretrain 的骨干网络,而无需实现MMPretrain 中已经存在的网络。 + +### 使用在 MMPretrain 中实现的骨干网络 + +假设想将 `MobileNetV3-small` 作为 `RetinaNet` 的骨干网络,则配置文件如下。 + +```python +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict(imports=['mmpretrain.models'], allow_failed_imports=False) +pretrained = 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v3/convert/mobilenet_v3_small-8427ecf0.pth' +model = dict( + backbone=dict( + _delete_=True, # 将 _base_ 中关于 backbone 的字段删除 + type='mmpretrain.MobileNetV3', # 使用 mmpretrain 中的 MobileNetV3 + arch='small', + out_indices=(3, 8, 11), # 修改 out_indices + init_cfg=dict( + type='Pretrained', + checkpoint=pretrained, + prefix='backbone.')), # mmpretrain 中骨干网络的预训练权重含义 prefix='backbone.',为了正常加载权重,需要把这个 prefix 去掉。 + # 修改 in_channels + neck=dict(in_channels=[24, 48, 96], start_level=0)) +``` + +### 通过 MMPretrain 使用 TIMM 中实现的骨干网络 + +由于 MMPretrain 提供了 Py**T**orch **Im**age **M**odels (`timm`) 骨干网络的封装,用户也可以通过 MMPretrain 直接使用 `timm` 中的骨干网络。假设想将 [`EfficientNet-B1`](../../../configs/timm_example/retinanet_timm-efficientnet-b1_fpn_1x_coco.py) 作为 `RetinaNet` 的骨干网络,则配置文件如下。 + +```python +# https://github.com/open-mmlab/mmdetection/blob/main/configs/timm_example/retinanet_timm_efficientnet_b1_fpn_1x_coco.py +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict(imports=['mmpretrain.models'], allow_failed_imports=False) +model = dict( + backbone=dict( + _delete_=True, # 将 _base_ 中关于 backbone 的字段删除 + type='mmpretrain.TIMMBackbone', # 使用 mmpretrain 中 timm 骨干网络 + model_name='efficientnet_b1', + features_only=True, + pretrained=True, + out_indices=(1, 2, 3, 4)), # 修改 out_indices + neck=dict(in_channels=[24, 40, 112, 320])) # 修改 in_channels + +optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) +``` + +`type='mmpretrain.TIMMBackbone'` 表示在 MMDetection 中使用 MMPretrain 中的 `TIMMBackbone` 类,并且使用的模型为` EfficientNet-B1`,其中 `mmpretrain` 表示 MMPretrain 库,而 `TIMMBackbone ` 表示 MMPretrain 中实现的 TIMMBackbone 包装器。 + +关于层次注册器的具体原理可以参考 [MMEngine 文档](https://mmengine.readthedocs.io/zh_cn/latest/tutorials/config.md#跨项目继承配置文件),关于如何使用 MMPretrain 中的其他 backbone,可以参考 [MMPretrain 文档](https://mmpretrain.readthedocs.io/en/latest/user_guides/config.html)。 + +## 使用马赛克数据增强 + +如果你想在训练中使用 `Mosaic`,那么请确保你同时使用 `MultiImageMixDataset`。以 `Faster R-CNN` 算法为例,你可以通过如下做法实现: + +```python +# 直接打开 configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py ,增添如下字段 +data_root = 'data/coco/' +dataset_type = 'CocoDataset' +img_scale=(1333, 800) + +train_pipeline = [ + dict(type='Mosaic', img_scale=img_scale, pad_val=114.0), + dict( + type='RandomAffine', + scaling_ratio_range=(0.1, 2), + border=(-img_scale[0] // 2, -img_scale[1] // 2)), # 图像经过马赛克处理后会放大4倍,所以我们使用仿射变换来恢复图像的大小。 + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs')) +] + +train_dataset = dict( + _delete_ = True, # 删除不必要的设置 + type='MultiImageMixDataset', + dataset=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=[ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True) + ], + filter_empty_gt=False, + ), + pipeline=train_pipeline + ) + +data = dict( + train=train_dataset + ) +``` + +## 在配置文件中冻结骨干网络后在训练中解冻骨干网络 + +如果你在配置文件中已经冻结了骨干网络并希望在几个训练周期后解冻它,你可以通过 hook 来实现这个功能。以用 ResNet 为骨干网络的 Faster R-CNN 为例,你可以冻结一个骨干网络的一个层并在配置文件中添加如下 `custom_hooks`: + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +model = dict( + # freeze one stage of the backbone network. + backbone=dict(frozen_stages=1), +) +custom_hooks = [dict(type="UnfreezeBackboneEpochBasedHook", unfreeze_epoch=1)] +``` + +同时在 `mmdet/core/hook/unfreeze_backbone_epoch_based_hook.py` 当中书写 `UnfreezeBackboneEpochBasedHook` 类 + +```python +from mmengine.model import is_model_wrapper +from mmengine.hooks import Hook +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class UnfreezeBackboneEpochBasedHook(Hook): + """Unfreeze backbone network Hook. + + Args: + unfreeze_epoch (int): The epoch unfreezing the backbone network. + """ + + def __init__(self, unfreeze_epoch=1): + self.unfreeze_epoch = unfreeze_epoch + + def before_train_epoch(self, runner): + # Unfreeze the backbone network. + # Only valid for resnet. + if runner.epoch == self.unfreeze_epoch: + model = runner.model + if is_module_wrapper(model): + model = model.module + backbone = model.backbone + if backbone.frozen_stages >= 0: + if backbone.deep_stem: + backbone.stem.train() + for param in backbone.stem.parameters(): + param.requires_grad = True + else: + backbone.norm1.train() + for m in [backbone.conv1, backbone.norm1]: + for param in m.parameters(): + param.requires_grad = True + + for i in range(1, backbone.frozen_stages + 1): + m = getattr(backbone, f'layer{i}') + m.train() + for param in m.parameters(): + param.requires_grad = True +``` + +## 获得新的骨干网络的通道数 + +如果你想获得一个新骨干网络的通道数,你可以单独构建这个骨干网络并输入一个伪造的图片来获取每一个阶段的输出。 + +以 `ResNet` 为例: + +```python +from mmdet.models import ResNet +import torch +self = ResNet(depth=18) +self.eval() +inputs = torch.rand(1, 3, 32, 32) +level_outputs = self.forward(inputs) +for level_out in level_outputs: + print(tuple(level_out.shape)) + +``` + +以上脚本的输出为: + +```python +(1, 64, 8, 8) +(1, 128, 4, 4) +(1, 256, 2, 2) +(1, 512, 1, 1) +``` + +用户可以通过将脚本中的 `ResNet(depth=18)` 替换为自己的骨干网络配置来得到新的骨干网络的通道数。 + +# MMDetection 中训练 Detectron2 的模型 + +用户可以使用 `Detectron2Wrapper` 从而在 MMDetection 中使用 Detectron2 的模型。 +我们提供了 [Faster R-CNN](../../../configs/misc/d2_faster-rcnn_r50-caffe_fpn_ms-90k_coco.py), +[Mask R-CNN](../../../configs/misc/d2_mask-rcnn_r50-caffe_fpn_ms-90k_coco.py) 和 [RetinaNet](../../../configs/misc/d2_retinanet_r50-caffe_fpn_ms-90k_coco.py) 的示例来在 MMDetection 中训练/测试 Detectron2 的模型。 + +使用过程中需要注意配置文件中算法组件要和 Detectron2 中的相同。模型初始化时,我们首先初始化 [Detectron2](https://github.com/facebookresearch/detectron2/blob/main/detectron2/config/defaults.py) 的默认设置,然后配置文件中的设置将覆盖默认设置,模型将基于更新过的设置来建立。 +输入数据首先转换成 Detectron2 的类型并输入进 Detectron2 的模型中。在推理阶段,Detectron2 的模型结果将会转换回 MMDetection 的类型。 + +## 使用 Detectron2 的预训练权重 + +`Detectron2Wrapper` 中的权重初始化将不使用 MMDetection 的逻辑。用户可以设置 `model.d2_detector.weights=xxx` 来加载预训练的权重。 +例如,我们可以使用 `model.d2_detector.weights='detectron2://ImageNetPretrained/MSRA/R-50.pkl'` 来加载 ResNet-50 的预训练权重,或者使用 +`model.d2_detector.weights='detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x/137260431/model_final_a54504.pkl'` 来加载 Detectron2 中提出的预训练的Mask R-CNN权重。 + +**注意:** 不能直接使用 `load_from` 来加载 Detectron2 的预训练模型,但可以通过 `tools/model_converters/detectron2_to_mmdet.py` 先对该预训练模型进行转换。 + +在测试时,用户应该首先使用 `tools/model_converters/detectron2_to_mmdet.py` 将 Detectron2 的预训练权重转换为 MMDetection 可读取的结构。 + +```shell +python tools/model_converters/detectron2_to_mmdet.py ${Detectron2 ckpt path} ${MMDetectron ckpt path}。 +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/index.rst b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..8e925394a7da2ea4f70b23a2517432b02c8e97fe --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/index.rst @@ -0,0 +1,34 @@ +基础概念 +*************** + +.. toctree:: + :maxdepth: 1 + + data_flow.md + structures.md + models.md + datasets.md + transforms.md + evaluation.md + engine.md + conventions.md + +组件定制 +************************ + +.. toctree:: + :maxdepth: 1 + + customize_models.md + customize_losses.md + customize_dataset.md + customize_transforms.md + customize_runtime.md + +How to +************************ + +.. toctree:: + :maxdepth: 1 + + how_to.md diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/models.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/models.md new file mode 100644 index 0000000000000000000000000000000000000000..c5119d06374fd335e09666f438729b5acf72ea25 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/models.md @@ -0,0 +1 @@ +# 模型(待更新) diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/structures.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/structures.md new file mode 100644 index 0000000000000000000000000000000000000000..c2118c34a3f47ae46a173dc099f8d3c0ccfb5456 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/structures.md @@ -0,0 +1 @@ +# 数据结构(待更新) diff --git a/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/transforms.md b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/transforms.md new file mode 100644 index 0000000000000000000000000000000000000000..07d7db2432a39580acd5f1fe6dcdde593bc8ac05 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/advanced_guides/transforms.md @@ -0,0 +1,43 @@ +# 数据变换(待更新) + +按照惯例,我们使用 `Dataset` 和 `DataLoader` 进行多进程的数据加载。`Dataset` 返回字典类型的数据,数据内容为模型 `forward` 方法的各个参数。由于在目标检测中,输入的图像数据具有不同的大小,我们在 `MMCV` 里引入一个新的 `DataContainer` 类去收集和分发不同大小的输入数据。更多细节请参考[这里](https://github.com/open-mmlab/mmcv/blob/master/mmcv/parallel/data_container.py)。 + +数据的准备流程和数据集是解耦的。通常一个数据集定义了如何处理标注数据(annotations)信息,而一个数据流程定义了准备一个数据字典的所有步骤。一个流程包括一系列的操作,每个操作都把一个字典作为输入,然后再输出一个新的字典给下一个变换操作。 + +我们在下图展示了一个经典的数据处理流程。蓝色块是数据处理操作,随着数据流程的处理,每个操作都可以在结果字典中加入新的键(标记为绿色)或更新现有的键(标记为橙色)。 + +![pipeline figure](../../../resources/data_pipeline.png) + +这些操作可以分为数据加载(data loading)、预处理(pre-processing)、格式变化(formatting)和测试时数据增强(test-time augmentation)。 + +下面的例子是 `Faster R-CNN` 的一个流程: + +```python +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=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', flip_ratio=0.5), + dict(type='Normalize', **img_norm_cfg), + 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=(1333, 800), + flip=False, + transforms=[ + dict(type='Resize', keep_ratio=True), + dict(type='RandomFlip'), + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='ImageToTensor', keys=['img']), + dict(type='Collect', keys=['img']), + ]) +] +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/api.rst b/mmdet_code/mmdetection/docs/zh_cn/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..1b1273219e8ac7af1a9e2e27a3f80d6a18c630e5 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/api.rst @@ -0,0 +1,161 @@ +mmdet.apis +-------------- +.. automodule:: mmdet.apis + :members: + +mmdet.datasets +-------------- + +datasets +^^^^^^^^^^ +.. automodule:: mmdet.datasets + :members: + +api_wrappers +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.datasets.api_wrappers + :members: + +samplers +^^^^^^^^^^ +.. automodule:: mmdet.datasets.samplers + :members: + +transforms +^^^^^^^^^^^^ +.. automodule:: mmdet.datasets.transforms + :members: + +mmdet.engine +-------------- + +hooks +^^^^^^^^^^ +.. automodule:: mmdet.engine.hooks + :members: + +optimizers +^^^^^^^^^^^^^^^ +.. automodule:: mmdet.engine.optimizers + :members: + +runner +^^^^^^^^^^ +.. automodule:: mmdet.engine.runner + :members: + +schedulers +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.engine.schedulers + :members: + +mmdet.evaluation +-------------------- + +functional +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.evaluation.functional + :members: + +metrics +^^^^^^^^^^ +.. automodule:: mmdet.evaluation.metrics + :members: + + +mmdet.models +-------------- + +backbones +^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.backbones + :members: + +data_preprocessors +^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.data_preprocessors + :members: + +dense_heads +^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.dense_heads + :members: + +detectors +^^^^^^^^^^ +.. automodule:: mmdet.models.detectors + :members: + +layers +^^^^^^^^^^ +.. automodule:: mmdet.models.layers + :members: + +losses +^^^^^^^^^^ +.. automodule:: mmdet.models.losses + :members: + +necks +^^^^^^^^^^^^ +.. automodule:: mmdet.models.necks + :members: + +roi_heads +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.roi_heads + :members: + +seg_heads +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.seg_heads + :members: + +task_modules +^^^^^^^^^^^^^ +.. automodule:: mmdet.models.task_modules + :members: + +test_time_augs +^^^^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.models.test_time_augs + :members: + +utils +^^^^^^^^^^ +.. automodule:: mmdet.models.utils + :members: + + +mmdet.structures +-------------------- + +structures +^^^^^^^^^^^^^^^^^ +.. automodule:: mmdet.structures + :members: + +bbox +^^^^^^^^^^ +.. automodule:: mmdet.structures.bbox + :members: + +mask +^^^^^^^^^^ +.. automodule:: mmdet.structures.mask + :members: + +mmdet.testing +---------------- +.. automodule:: mmdet.testing + :members: + +mmdet.visualization +-------------------- +.. automodule:: mmdet.visualization + :members: + +mmdet.utils +-------------- +.. automodule:: mmdet.utils + :members: diff --git a/mmdet_code/mmdetection/docs/zh_cn/article.md b/mmdet_code/mmdetection/docs/zh_cn/article.md new file mode 100644 index 0000000000000000000000000000000000000000..3b698308d6b96bd4df1df356bf2119e9174bc204 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/article.md @@ -0,0 +1,53 @@ +## 中文解读文案汇总(待更新) + +### 1 官方解读文案(v2.x) + +#### 1.1 框架解读 + +- **[轻松掌握 MMDetection 整体构建流程(一)](https://zhuanlan.zhihu.com/p/337375549)** +- **[轻松掌握 MMDetection 整体构建流程(二)](https://zhuanlan.zhihu.com/p/341954021)** +- **[轻松掌握 MMDetection 中 Head 流程](https://zhuanlan.zhihu.com/p/343433169)** + +#### 1.2 算法解读 + +- **[轻松掌握 MMDetection 中常用算法(一):RetinaNet 及配置详解](https://zhuanlan.zhihu.com/p/346198300)** +- **[轻松掌握 MMDetection 中常用算法(二):Faster R-CNN|Mask R-CNN](https://zhuanlan.zhihu.com/p/349807581)** +- [轻松掌握 MMDetection 中常用算法(三):FCOS](https://zhuanlan.zhihu.com/p/358056615) +- [轻松掌握 MMDetection 中常用算法(四):ATSS](https://zhuanlan.zhihu.com/p/358125611) +- [轻松掌握 MMDetection 中常用算法(五):Cascade R-CNN](https://zhuanlan.zhihu.com/p/360952172) +- [轻松掌握 MMDetection 中常用算法(六):YOLOF](https://zhuanlan.zhihu.com/p/370758213) +- [轻松掌握 MMDetection 中常用算法(七):CenterNet](https://zhuanlan.zhihu.com/p/374891478) +- [轻松掌握 MMDetection 中常用算法(八):YOLACT](https://zhuanlan.zhihu.com/p/376347955) +- [轻松掌握 MMDetection 中常用算法(九):AutoAssign](https://zhuanlan.zhihu.com/p/378581552) +- [YOLOX 在 MMDetection 中复现全流程解析](https://zhuanlan.zhihu.com/p/398545304) +- [喂喂喂!你可以减重了!小模型 - MMDetection 新增SSDLite 、 MobileNetV2YOLOV3 两大经典算法](https://zhuanlan.zhihu.com/p/402781143) + +#### 1.3 工具解读 + +- [OpenMMLab 中混合精度训练 AMP 的正确打开方式](https://zhuanlan.zhihu.com/p/375224982) +- [小白都能看懂!手把手教你使用混淆矩阵分析目标检测](https://zhuanlan.zhihu.com/p/443499860) +- [MMDetection 图像缩放 Resize 详细说明 OpenMMLab](https://zhuanlan.zhihu.com/p/381117525) +- [拿什么拯救我的 4G 显卡](https://zhuanlan.zhihu.com/p/430123077) +- [MMDet居然能用MMCls的Backbone?论配置文件的打开方式](https://zhuanlan.zhihu.com/p/436865195) + +#### 1.4 知乎问答 + +- [COCO数据集上1x模式下为什么不采用多尺度训练?](https://www.zhihu.com/question/462170786/answer/1915119662) +- [MMDetection中SOTA论文源码中将训练过程中BN层的eval打开?](https://www.zhihu.com/question/471189603/answer/2195540892) +- [基于PyTorch的MMDetection中训练的随机性来自何处?](https://www.zhihu.com/question/453511684/answer/1839683634) +- [单阶段、双阶段、anchor-based、anchor-free 这四者之间有什么联系吗?](https://www.zhihu.com/question/428972054/answer/1619925296) +- [目标检测的深度学习方法,有推荐的书籍或资料吗?](https://www.zhihu.com/question/391577080/answer/1612593817) +- [大佬们,刚入学研究生,想入门目标检测,有什么学习路线可以入门的?](https://www.zhihu.com/question/343768934/answer/1612580715) +- [目标检测领域还有什么可以做的?](https://www.zhihu.com/question/280703314/answer/1627885518) +- [如何看待Transformer在CV上的应用前景,未来有可能替代CNN吗?](https://www.zhihu.com/question/437495132/answer/1686380553) +- [MMDetection如何学习源码?](https://www.zhihu.com/question/451585041/answer/1832498963) +- [如何具体上手实现目标检测呢?](https://www.zhihu.com/question/341401981/answer/1848561187) + +#### 1.5 其他 + +- **[不得不知的 MMDetection 学习路线(个人经验版)](https://zhuanlan.zhihu.com/p/369826931)** +- [OpenMMLab 社区专访之 YOLOX 复现篇](https://zhuanlan.zhihu.com/p/405913343) + +### 2 社区解读文案(v2.x) + +- [手把手带你实现经典检测网络 Mask R-CNN 的推理](https://zhuanlan.zhihu.com/p/414082071) diff --git a/mmdet_code/mmdetection/docs/zh_cn/conf.py b/mmdet_code/mmdetection/docs/zh_cn/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..e687840897186406911e8e5166a5620606b016a4 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/conf.py @@ -0,0 +1,118 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import subprocess +import sys + +import pytorch_sphinx_theme + +sys.path.insert(0, os.path.abspath('../../')) + +# -- Project information ----------------------------------------------------- + +project = 'MMDetection' +copyright = '2018-2021, OpenMMLab' +author = 'MMDetection Authors' +version_file = '../../mmdet/version.py' + + +def get_version(): + with open(version_file, 'r') as f: + exec(compile(f.read(), version_file, 'exec')) + return locals()['__version__'] + + +# The full version, including alpha/beta/rc tags +release = get_version() + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.napoleon', + 'sphinx.ext.viewcode', + 'myst_parser', + 'sphinx_markdown_tables', + 'sphinx_copybutton', +] + +myst_enable_extensions = ['colon_fence'] +myst_heading_anchors = 3 + +autodoc_mock_imports = [ + 'matplotlib', 'pycocotools', 'terminaltables', 'mmdet.version', 'mmcv.ops' +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +source_suffix = { + '.rst': 'restructuredtext', + '.md': 'markdown', +} + +# The main toctree document. +master_doc = 'index' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +# html_theme = 'sphinx_rtd_theme' +html_theme = 'pytorch_sphinx_theme' +html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()] + +html_theme_options = { + 'menu': [ + { + 'name': 'GitHub', + 'url': 'https://github.com/open-mmlab/mmdetection' + }, + ], + # Specify the language of shared menu + 'menu_lang': + 'cn', +} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] +html_css_files = ['css/readthedocs.css'] + +language = 'zh_CN' + +# -- Extension configuration ------------------------------------------------- +# Ignore >>> when copying code +copybutton_prompt_text = r'>>> |\.\.\. ' +copybutton_prompt_is_regexp = True + + +def builder_inited_handler(app): + subprocess.run(['./stat.py']) + + +def setup(app): + app.connect('builder-inited', builder_inited_handler) diff --git a/mmdet_code/mmdetection/docs/zh_cn/get_started.md b/mmdet_code/mmdetection/docs/zh_cn/get_started.md new file mode 100644 index 0000000000000000000000000000000000000000..52d061ef50f8a2a18a212fa575930f103facf619 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/get_started.md @@ -0,0 +1,230 @@ +# 开始你的第一步 + +## 依赖 + +本节中,我们将演示如何用 PyTorch 准备一个环境。 + +MMDetection 支持在 Linux,Windows 和 macOS 上运行。它需要 Python 3.7 以上,CUDA 9.2 以上和 PyTorch 1.8 及其以上。 + +```{note} +如果你对 PyTorch 有经验并且已经安装了它,你可以直接跳转到[下一小节](#安装流程)。否则,你可以按照下述步骤进行准备。 +``` + +**步骤 0.** 从[官方网站](https://docs.conda.io/en/latest/miniconda.html)下载并安装 Miniconda。 + +**步骤 1.** 创建并激活一个 conda 环境。 + +```shell +conda create --name openmmlab python=3.8 -y +conda activate openmmlab +``` + +**步骤 2.** 基于 [PyTorch 官方说明](https://pytorch.org/get-started/locally/)安装 PyTorch。 + +在 GPU 平台上: + +```shell +conda install pytorch torchvision -c pytorch +``` + +在 CPU 平台上: + +```shell +conda install pytorch torchvision cpuonly -c pytorch +``` + +## 安装流程 + +我们推荐用户参照我们的最佳实践安装 MMDetection。不过,整个过程也是可定制化的,更多信息请参考[自定义安装](#自定义安装)章节。 + +### 最佳实践 + +**步骤 0.** 使用 [MIM](https://github.com/open-mmlab/mim) 安装 [MMEngine](https://github.com/open-mmlab/mmengine) 和 [MMCV](https://github.com/open-mmlab/mmcv)。 + +```shell +pip install -U openmim +mim install mmengine +mim install "mmcv>=2.0.0" +``` + +**注意:** 在 MMCV-v2.x 中,`mmcv-full` 改名为 `mmcv`,如果你想安装不包含 CUDA 算子精简版,可以通过 `mim install "mmcv-lite>=2.0.0rc1"` 来安装。 + +**步骤 1.** 安装 MMDetection。 + +方案 a:如果你开发并直接运行 mmdet,从源码安装它: + +```shell +git clone https://github.com/open-mmlab/mmdetection.git +cd mmdetection +pip install -v -e . +# "-v" 指详细说明,或更多的输出 +# "-e" 表示在可编辑模式下安装项目,因此对代码所做的任何本地修改都会生效,从而无需重新安装。 +``` + +方案 b:如果你将 mmdet 作为依赖或第三方 Python 包,使用 MIM 安装: + +```shell +mim install mmdet +``` + +## 验证安装 + +为了验证 MMDetection 是否安装正确,我们提供了一些示例代码来执行模型推理。 + +**步骤 1.** 我们需要下载配置文件和模型权重文件。 + +```shell +mim download mmdet --config rtmdet_tiny_8xb32-300e_coco --dest . +``` + +下载将需要几秒钟或更长时间,这取决于你的网络环境。完成后,你会在当前文件夹中发现两个文件 `rtmdet_tiny_8xb32-300e_coco.py` 和 `rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth`。 + +**步骤 2.** 推理验证。 + +方案 a:如果你通过源码安装的 MMDetection,那么直接运行以下命令进行验证: + +```shell +python demo/image_demo.py demo/demo.jpg rtmdet_tiny_8xb32-300e_coco.py --weights rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --device cpu +``` + +你会在当前文件夹中的 `outputs/vis` 文件夹中看到一个新的图像 `demo.jpg`,图像中包含有网络预测的检测框。 + +方案 b:如果你通过 MIM 安装的 MMDetection,那么可以打开你的 Python 解析器,复制并粘贴以下代码: + +```python +from mmdet.apis import init_detector, inference_detector + +config_file = 'rtmdet_tiny_8xb32-300e_coco.py' +checkpoint_file = 'rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth' +model = init_detector(config_file, checkpoint_file, device='cpu') # or device='cuda:0' +inference_detector(model, 'demo/demo.jpg') +``` + +你将会看到一个包含 `DetDataSample` 的列表,预测结果在 `pred_instance` 里,包含有检测框,类别和得分。 + +### 自定义安装 + +#### CUDA 版本 + +在安装 PyTorch 时,你需要指定 CUDA 的版本。如果你不清楚应该选择哪一个,请遵循我们的建议: + +- 对于 Ampere 架构的 NVIDIA GPU,例如 GeForce 30 系列以及 NVIDIA A100,CUDA 11 是必需的。 +- 对于更早的 NVIDIA GPU,CUDA 11 是向后兼容 (backward compatible) 的,但 CUDA 10.2 能够提供更好的兼容性,也更加轻量。 + +请确保你的 GPU 驱动版本满足最低的版本需求,参阅 NVIDIA 官方的 [CUDA 工具箱和相应的驱动版本关系表](https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#cuda-major-component-versions__table-cuda-toolkit-driver-versions)。 + +```{note} +如果按照我们的最佳实践,安装 CUDA 运行时库就足够了,这是因为不需要在本地编译 CUDA 代码。但如果你希望从源码编译 MMCV,或是开发其他 CUDA 算子,那么就必须安装完整的 CUDA 工具链,参见 [NVIDIA 官网](https://developer.nvidia.com/cuda-downloads),另外还需要确保该 CUDA 工具链的版本与 PyTorch 安装时的配置相匹配(如用 `conda install` 安装 PyTorch 时指定的 cudatoolkit 版本)。 +``` + +#### 不使用 MIM 安装 MMEngine + +要使用 pip 而不是 MIM 来安装 MMEngine,请遵照 [MMEngine 安装指南](https://mmengine.readthedocs.io/zh_CN/latest/get_started/installation.html)。 + +例如,你可以通过以下命令安装 MMEngine。 + +```shell +pip install mmengine +``` + +#### 不使用 MIM 安装 MMCV + +MMCV 包含 C++ 和 CUDA 扩展,因此其对 PyTorch 的依赖比较复杂。MIM 会自动解析这些依赖,选择合适的 MMCV 预编译包,使安装更简单,但它并不是必需的。 + +要使用 pip 而不是 MIM 来安装 MMCV,请遵照 [MMCV 安装指南](https://mmcv.readthedocs.io/zh_CN/2.x/get_started/installation.html)。它需要您用指定 url 的形式手动指定对应的 PyTorch 和 CUDA 版本。 + +例如,下述命令将会安装基于 PyTorch 1.12.x 和 CUDA 11.6 编译的 MMCV。 + +```shell +pip install "mmcv>=2.0.0" -f https://download.openmmlab.com/mmcv/dist/cu116/torch1.12.0/index.html +``` + +#### 在 CPU 环境中安装 + +MMDetection 可以在 CPU 环境中构建。在 CPU 模式下,可以进行模型训练(需要 MMCV 版本 >= 2.0.0rc1)、测试或者推理。 + +但是,以下功能在该模式下不能使用: + +- Deformable Convolution +- Modulated Deformable Convolution +- ROI pooling +- Deformable ROI pooling +- CARAFE +- SyncBatchNorm +- CrissCrossAttention +- MaskedConv2d +- Temporal Interlace Shift +- nms_cuda +- sigmoid_focal_loss_cuda +- bbox_overlaps + +因此,如果尝试训练/测试/推理包含上述算子的模型,将会报错。下表列出了将会受影响的相关算法。 + +| 操作 | 模型 | +| :-----------------------------------------------------: | :--------------------------------------------------------------------------------------: | +| Deformable Convolution/Modulated Deformable Convolution | DCN、Guided Anchoring、RepPoints、CentripetalNet、VFNet、CascadeRPN、NAS-FCOS、DetectoRS | +| MaskedConv2d | Guided Anchoring | +| CARAFE | CARAFE | +| SyncBatchNorm | ResNeSt | + +#### 在 Google Colab 中安装 + +[Google Colab](https://colab.research.google.com/) 通常已经包含了 PyTorch 环境,因此我们只需要安装 MMEngine,MMCV 和 MMDetection 即可,命令如下: + +**步骤 1.** 使用 [MIM](https://github.com/open-mmlab/mim) 安装 [MMEngine](https://github.com/open-mmlab/mmengine) 和 [MMCV](https://github.com/open-mmlab/mmcv)。 + +```shell +!pip3 install openmim +!mim install mmengine +!mim install "mmcv>=2.0.0,<2.1.0" +``` + +**步骤 2.** 使用源码安装 MMDetection。 + +```shell +!git clone https://github.com/open-mmlab/mmdetection.git +%cd mmdetection +!pip install -e . +``` + +**步骤 3.** 验证安装是否成功。 + +```python +import mmdet +print(mmdet.__version__) +# 预期输出:3.0.0 或其他版本号 +``` + +```{note} +在 Jupyter Notebook 中,感叹号 `!` 用于执行外部命令,而 `%cd` 是一个[魔术命令](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-cd),用于切换 Python 的工作路径。 +``` + +#### 通过 Docker 使用 MMDetection + +我们提供了一个 [Dockerfile](../../docker/Dockerfile) 来构建一个镜像。请确保你的 [docker 版本](https://docs.docker.com/engine/install/) >=19.03。 + +```shell +# 基于 PyTorch 1.9,CUDA 11.1 构建镜像 +# 如果你想要其他版本,只需要修改 Dockerfile +docker build -t mmdetection docker/ +``` + +用以下命令运行 Docker 镜像: + +```shell +docker run --gpus all --shm-size=8g -it -v {DATA_DIR}:/mmdetection/data mmdetection +``` + +### 排除故障 + +如果你在安装过程中遇到一些问题,请先查看 [FAQ](notes/faq.md) 页面。如果没有找到解决方案,你也可以在 GitHub 上[提出一个问题](https://github.com/open-mmlab/mmdetection/issues/new/choose)。 + +### 使用多个 MMDetection 版本进行开发 + +训练和测试的脚本已经在 `PYTHONPATH` 中进行了修改,以确保脚本使用当前目录中的 MMDetection。 + +要使环境中安装默认版本的 MMDetection 而不是当前正在使用的,可以删除出现在相关脚本中的代码: + +```shell +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/index.rst b/mmdet_code/mmdetection/docs/zh_cn/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..58a4d8a52d3f457033f6691411f1078d9491faef --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/index.rst @@ -0,0 +1,67 @@ +Welcome to MMDetection's documentation! +======================================= + +.. toctree:: + :maxdepth: 1 + :caption: 开始你的第一步 + + overview.md + get_started.md + +.. toctree:: + :maxdepth: 2 + :caption: 使用指南 + + user_guides/index.rst + +.. toctree:: + :maxdepth: 2 + :caption: 进阶教程 + + advanced_guides/index.rst + +.. toctree:: + :maxdepth: 1 + :caption: 迁移版本 + + migration/migration.md + +.. toctree:: + :maxdepth: 1 + :caption: 接口文档(英文) + + api.rst + +.. toctree:: + :maxdepth: 1 + :caption: 模型仓库 + + model_zoo.md + +.. toctree:: + :maxdepth: 1 + :caption: 说明 + + notes/contribution_guide.md + notes/projects.md + notes/faq.md + notes/compatibility.md + +.. toctree:: + :maxdepth: 1 + :caption: 文章 + + article.md + +.. toctree:: + :caption: 语言切换 + + switch_language.md + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`search` diff --git a/mmdet_code/mmdetection/docs/zh_cn/make.bat b/mmdet_code/mmdetection/docs/zh_cn/make.bat new file mode 100644 index 0000000000000000000000000000000000000000..922152e96a04a242e6fc40f124261d74890617d8 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/mmdet_code/mmdetection/docs/zh_cn/migration/api_and_registry_migration.md b/mmdet_code/mmdetection/docs/zh_cn/migration/api_and_registry_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..66e1c3408063ca0d40bf28bbf96143a0a5c14938 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/migration/api_and_registry_migration.md @@ -0,0 +1 @@ +# 将 API 和注册器从 MMDetection 2.x 迁移至 3.x diff --git a/mmdet_code/mmdetection/docs/zh_cn/migration/config_migration.md b/mmdet_code/mmdetection/docs/zh_cn/migration/config_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..c4f9c8e3d2df72ee352d7af20072645154004db6 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/migration/config_migration.md @@ -0,0 +1,814 @@ +# 将配置文件从 MMDetection 2.x 迁移至 3.x + +MMDetection 3.x 的配置文件与 2.x 相比有较大变化,这篇文档将介绍如何将 2.x 的配置文件迁移到 3.x。 + +在前面的[配置文件教程](../user_guides/config.md)中,我们以 Mask R-CNN 为例介绍了 MMDetection 3.x 的配置文件结构,这里我们将按同样的结构介绍如何将 2.x 的配置文件迁移至 3.x。 + +## 模型配置 + +模型的配置与 2.x 相比并没有太大变化,对于模型的 backbone,neck,head,以及 train_cfg 和 test_cfg,它们的参数与 2.x 版本的参数保持一致。 + +不同的是,我们在 3.x 版本的模型中新增了 `DataPreprocessor` 模块。 +`DataPreprocessor` 模块的配置位于 `model.data_preprocessor` 中,它用于对输入数据进行预处理,例如对输入图像进行归一化,将不同大小的图片进行 padding 从而组成 batch,将图像从内存中读取到显存中等。这部分配置取代了原本存在于 train_pipeline 和 test_pipeline 中的 `Normalize` 和 `Pad`。 + + + + + + + + + +
原配置 + +```python +# 图像归一化参数 +img_norm_cfg = dict( + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True) +pipeline=[ + ..., + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), # 图像 padding 到 32 的倍数 + ... +] +``` + +
新配置 + +```python +model = dict( + data_preprocessor=dict( + type='DetDataPreprocessor', + # 图像归一化参数 + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + # 图像 padding 参数 + pad_mask=True, # 在实例分割中,需要将 mask 也进行 padding + pad_size_divisor=32) # 图像 padding 到 32 的倍数 +) +``` + +
+ +## 数据集和评测器配置 + +数据集和评测部分的配置相比 2.x 版本有较大的变化。我们将从 Dataloader 和 Dataset,Data transform pipeline,以及评测器配置三个方面介绍如何将 2.x 版本的配置迁移到 3.x 版本。 + +### Dataloader 和 Dataset 配置 + +在新版本中,我们将数据加载的设置与 PyTorch 官方的 DataLoader 保持一致,这样可以使用户更容易理解和上手。 +我们将训练、验证和测试的数据加载设置分别放在 `train_dataloader`,`val_dataloader` 和 `test_dataloader` 中,用户可以分别对这些 dataloader 设置不同的参数,其输入参数与 [PyTorch 的 Dataloader](https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader) 所需要的参数基本一致。 + +通过这种方式,我们将 2.x 版本中不可配置的 `sampler`,`batch_sampler`,`persistent_workers` 等参数都放到了配置文件中,使得用户可以更加灵活地设置数据加载的参数。 + +用户可以通过 `train_dataloader.dataset`,`val_dataloader.dataset` 和 `test_dataloader.dataset` 来设置数据集的配置,它们分别对应 2.x 版本中的 `data.train`,`data.val` 和 `data.test`。 + + + + + + + + + +
原配置 + +```python +data = dict( + samples_per_gpu=2, + workers_per_gpu=2, + train=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_train2017.json', + img_prefix=data_root + 'train2017/', + pipeline=train_pipeline), + val=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline), + test=dict( + type=dataset_type, + ann_file=data_root + 'annotations/instances_val2017.json', + img_prefix=data_root + 'val2017/', + pipeline=test_pipeline)) +``` + +
新配置 + +```python +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, # 避免每次迭代后 dataloader 重新创建子进程 + sampler=dict(type='DefaultSampler', shuffle=True), # 默认的 sampler,同时支持分布式训练和非分布式训练 + batch_sampler=dict(type='AspectRatioBatchSampler'), # 默认的 batch_sampler,用于保证 batch 中的图片具有相似的长宽比,从而可以更好地利用显存 + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline)) +# 在 3.x 版本中可以独立配置验证和测试的 dataloader +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader # 测试 dataloader 的配置与验证 dataloader 的配置相同,这里省略 +``` + +
+ +### Data transform pipeline 配置 + +上文中提到,我们将图像 normalize 和 padding 的配置从 `train_pipeline` 和 `test_pipeline` 中独立出来,放到了 `model.data_preprocessor` 中,因此在 3.x 版本的 pipeline 中,我们不再需要 `Normalize` 和 `Pad` 这两个 transform。 + +同时,我们也对负责数据格式打包的 transform 进行了重构,将 `Collect` 和 `DefaultFormatBundle` 这两个 transform 合并为了 `PackDetInputs`,它负责将 data pipeline 中的数据打包成模型的输入格式,关于输入格式的转换,详见[数据流文档](../advanced_guides/data_flow.md)。 + +下面以 Mask R-CNN 1x 的 train_pipeline 为例,介绍如何将 2.x 版本的配置迁移到 3.x 版本: + + + + + + + + + +
原配置 + +```python +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=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', flip_ratio=0.5), + dict(type='Normalize', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='DefaultFormatBundle'), + dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), +] +``` + +
新配置 + +```python +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +``` + +
+ +对于 test_pipeline,除了将 `Normalize` 和 `Pad` 这两个 transform 去掉之外,我们也将测试时的数据增强(TTA)与普通的测试流程分开,移除了 `MultiScaleFlipAug`。关于新版的 TTA 如何使用,详见[TTA 文档](../advanced_guides/tta.md)。 + +下面同样以 Mask R-CNN 1x 的 test_pipeline 为例,介绍如何将 2.x 版本的配置迁移到 3.x 版本: + + + + + + + + + +
原配置 + +```python +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', **img_norm_cfg), + dict(type='Pad', size_divisor=32), + dict(type='ImageToTensor', keys=['img']), + dict(type='Collect', keys=['img']), + ]) +] +``` + +
新配置 + +```python +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +``` + +
+ +除此之外,我们还对一些数据增强进行了重构,下表列出了 2.x 版本中的 transform 与 3.x 版本中的 transform 的对应关系: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称原配置新配置
Resize + +```python +dict(type='Resize', + img_scale=(1333, 800), + keep_ratio=True) +``` + + + +```python +dict(type='Resize', + scale=(1333, 800), + keep_ratio=True) +``` + +
RandomResize + +```python +dict( + type='Resize', + img_scale=[ + (1333, 640), (1333, 800)], + multiscale_mode='range', + keep_ratio=True) +``` + + + +```python +dict( + type='RandomResize', + scale=[ + (1333, 640), (1333, 800)], + keep_ratio=True) +``` + +
RandomChoiceResize + +```python +dict( + type='Resize', + img_scale=[ + (1333, 640), (1333, 672), + (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + multiscale_mode='value', + keep_ratio=True) +``` + + + +```python +dict( + type='RandomChoiceResize', + scales=[ + (1333, 640), (1333, 672), + (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True) +``` + +
RandomFlip + +```python +dict(type='RandomFlip', + flip_ratio=0.5) +``` + + + +```python +dict(type='RandomFlip', + prob=0.5) +``` + +
+ +### 评测器配置 + +在 3.x 版本中,模型精度评测不再与数据集绑定,而是通过评测器(Evaluator)来完成。 +评测器配置分为 val_evaluator 和 test_evaluator 两部分,其中 val_evaluator 用于验证集评测,test_evaluator 用于测试集评测,对应 2.x 版本中的 evaluation 字段。 +下表列出了 2.x 版本与 3.x 版本中的评测器的对应关系: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
评测指标名称原配置新配置
COCO + +```python +data = dict( + val=dict( + type='CocoDataset', + ann_file=data_root + 'annotations/instances_val2017.json')) +evaluation = dict(metric=['bbox', 'segm']) +``` + + + +```python +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False) +``` + +
Pascal VOC + +```python +data = dict( + val=dict( + type=dataset_type, + ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt')) +evaluation = dict(metric='mAP') +``` + + + +```python +val_evaluator = dict( + type='VOCMetric', + metric='mAP', + eval_mode='11points') +``` + +
OpenImages + +```python +data = dict( + val=dict( + type='OpenImagesDataset', + ann_file=data_root + 'annotations/validation-annotations-bbox.csv', + img_prefix=data_root + 'OpenImages/validation/', + label_file=data_root + 'annotations/class-descriptions-boxable.csv', + hierarchy_file=data_root + + 'annotations/bbox_labels_600_hierarchy.json', + meta_file=data_root + 'annotations/validation-image-metas.pkl', + image_level_ann_file=data_root + + 'annotations/validation-annotations-human-imagelabels-boxable.csv')) +evaluation = dict(interval=1, metric='mAP') +``` + + + +```python +val_evaluator = dict( + type='OpenImagesMetric', + iou_thrs=0.5, + ioa_thrs=0.5, + use_group_of=True, + get_supercategory=True) +``` + +
CityScapes + +```python +data = dict( + val=dict( + type='CityScapesDataset', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + img_prefix=data_root + 'leftImg8bit/val/', + pipeline=test_pipeline)) +evaluation = dict(metric=['bbox', 'segm']) +``` + + + +```python +val_evaluator = [ + dict( + type='CocoMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + metric=['bbox', 'segm']), + dict( + type='CityScapesMetric', + ann_file=data_root + + 'annotations/instancesonly_filtered_gtFine_val.json', + seg_prefix=data_root + '/gtFine/val', + outfile_prefix='./work_dirs/cityscapes_metric/instance') +] +``` + +
+ +## 训练和测试的配置 + + + + + + + + + +
原配置 + +```python +runner = dict( + type='EpochBasedRunner', # 训练循环的类型 + max_epochs=12) # 最大训练轮次 +evaluation = dict(interval=2) # 验证间隔。每 2 个 epoch 验证一次 +``` + +
新配置 + +```python +train_cfg = dict( + type='EpochBasedTrainLoop', # 训练循环的类型,请参考 https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py + max_epochs=12, # 最大训练轮次 + val_interval=2) # 验证间隔。每 2 个 epoch 验证一次 +val_cfg = dict(type='ValLoop') # 验证循环的类型 +test_cfg = dict(type='TestLoop') # 测试循环的类型 +``` + +
+ +## 优化相关配置 + +优化器以及梯度裁剪的配置都移至 optim_wrapper 字段中。下表列出了 2.x 版本与 3.x 版本中的优化器配置的对应关系: + + + + + + + + + +
原配置 + +```python +optimizer = dict( + type='SGD', # 随机梯度下降优化器 + lr=0.02, # 基础学习率 + momentum=0.9, # 带动量的随机梯度下降 + weight_decay=0.0001) # 权重衰减 +optimizer_config = dict(grad_clip=None) # 梯度裁剪的配置,设置为 None 关闭梯度裁剪 +``` + +
新配置 + +```python +optim_wrapper = dict( # 优化器封装的配置 + type='OptimWrapper', # 优化器封装的类型。可以切换至 AmpOptimWrapper 来启用混合精度训练 + optimizer=dict( # 优化器配置。支持 PyTorch 的各种优化器。请参考 https://pytorch.org/docs/stable/optim.html#algorithms + type='SGD', # 随机梯度下降优化器 + lr=0.02, # 基础学习率 + momentum=0.9, # 带动量的随机梯度下降 + weight_decay=0.0001), # 权重衰减 + clip_grad=None, # 梯度裁剪的配置,设置为 None 关闭梯度裁剪。使用方法请见 https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html + ) +``` + +
+ +学习率的配置也从 lr_config 字段中移至 param_scheduler 字段中。param_scheduler 的配置更贴近 PyTorch 的学习率调整策略,更加灵活。下表列出了 2.x 版本与 3.x 版本中的学习率配置的对应关系: + + + + + + + + + +
原配置 + +```python +lr_config = dict( + policy='step', # 在训练过程中使用 multi step 学习率策略 + warmup='linear', # 使用线性学习率预热 + warmup_iters=500, # 到第 500 个 iteration 结束预热 + warmup_ratio=0.001, # 学习率预热的系数 + step=[8, 11], # 在哪几个 epoch 进行学习率衰减 + gamma=0.1) # 学习率衰减系数 +``` + +
新配置 + +```python +param_scheduler = [ + dict( + type='LinearLR', # 使用线性学习率预热 + start_factor=0.001, # 学习率预热的系数 + by_epoch=False, # 按 iteration 更新预热学习率 + begin=0, # 从第一个 iteration 开始 + end=500), # 到第 500 个 iteration 结束 + dict( + type='MultiStepLR', # 在训练过程中使用 multi step 学习率策略 + by_epoch=True, # 按 epoch 更新学习率 + begin=0, # 从第一个 epoch 开始 + end=12, # 到第 12 个 epoch 结束 + milestones=[8, 11], # 在哪几个 epoch 进行学习率衰减 + gamma=0.1) # 学习率衰减系数 +] +``` + +
+ +关于其他的学习率调整策略的迁移,请参考 MMEngine 的[学习率迁移文档](https://mmengine.readthedocs.io/zh_CN/latest/migration/param_scheduler.html)。 + +## 其他配置的迁移 + +### 保存 checkpoint 的配置 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能原配置新配置
设置保存间隔 + +```python +checkpoint_config = dict( + interval=1) +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + interval=1)) +``` + +
保存最佳模型 + +```python +evaluation = dict( + save_best='auto') +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + save_best='auto')) +``` + +
只保留最新的几个模型 + +```python +checkpoint_config = dict( + max_keep_ckpts=3) +``` + + + +```python +default_hooks = dict( + checkpoint=dict( + type='CheckpointHook', + max_keep_ckpts=3)) +``` + +
+ +### 日志的配置 + +3.x 版本中,日志的打印和可视化由 MMEngine 中的 logger 和 visualizer 分别完成。下表列出了 2.x 版本与 3.x 版本中的日志配置的对应关系: + + + + + + + + + + + + + + + + + + + + + + + + +
功能原配置新配置
设置日志打印间隔 + +```python +log_config = dict( + interval=50) +``` + + + +```python +default_hooks = dict( + logger=dict( + type='LoggerHook', + interval=50)) +# 可选: 配置日志打印数值的平滑窗口大小 +log_processor = dict( + type='LogProcessor', + window_size=50) +``` + +
使用 TensorBoard 或 WandB 可视化日志 + +```python +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook'), + dict(type='MMDetWandbHook', + init_kwargs={ + 'project': 'mmdetection', + 'group': 'maskrcnn-r50-fpn-1x-coco' + }, + interval=50, + log_checkpoint=True, + log_checkpoint_metadata=True, + num_eval_images=100) + ]) +``` + + + +```python +vis_backends = [ + dict(type='LocalVisBackend'), + dict(type='TensorboardVisBackend'), + dict(type='WandbVisBackend', + init_kwargs={ + 'project': 'mmdetection', + 'group': 'maskrcnn-r50-fpn-1x-coco' + }) +] +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +``` + +
+ +关于可视化相关的教程,请参考 MMDetection 的[可视化教程](../user_guides/visualization.md)。 + +### Runtime 的配置 + +3.x 版本中 runtime 的配置字段有所调整,具体的对应关系如下: + + + + + + + + + + + + + + + + +
原配置新配置
+ +```python +cudnn_benchmark = False +opencv_num_threads = 0 +mp_start_method = 'fork' +dist_params = dict(backend='nccl') +log_level = 'INFO' +load_from = None +resume_from = None + + +``` + + + +```python +env_cfg = dict( + cudnn_benchmark=False, + mp_cfg=dict(mp_start_method='fork', + opencv_num_threads=0), + dist_cfg=dict(backend='nccl')) +log_level = 'INFO' +load_from = None +resume = False +``` + +
diff --git a/mmdet_code/mmdetection/docs/zh_cn/migration/dataset_migration.md b/mmdet_code/mmdetection/docs/zh_cn/migration/dataset_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..c379b9f1b7b6a4829b1a678c74861b3226d130bb --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/migration/dataset_migration.md @@ -0,0 +1 @@ +# 将数据集从 MMDetection 2.x 迁移至 3.x diff --git a/mmdet_code/mmdetection/docs/zh_cn/migration/migration.md b/mmdet_code/mmdetection/docs/zh_cn/migration/migration.md new file mode 100644 index 0000000000000000000000000000000000000000..d706856fa828f051c7ec9dfdb4c79fccdc03b867 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/migration/migration.md @@ -0,0 +1,12 @@ +# 从 MMDetection 2.x 迁移至 3.x + +MMDetection 3.x 版本是一个重大更新,包含了许多 API 和配置文件的变化。本文档旨在帮助用户从 MMDetection 2.x 版本迁移到 3.x 版本。 +我们将迁移指南分为以下几个部分: + +- [配置文件迁移](./config_migration.md) +- [API 和 Registry 迁移](./api_and_registry_migration.md) +- [数据集迁移](./dataset_migration.md) +- [模型迁移](./model_migration.md) +- [常见问题](./migration_faq.md) + +如果您在迁移过程中遇到任何问题,欢迎在 issue 中提出。我们也欢迎您为本文档做出贡献。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/migration/migration_faq.md b/mmdet_code/mmdetection/docs/zh_cn/migration/migration_faq.md new file mode 100644 index 0000000000000000000000000000000000000000..208a138b25d707a81d491af4fe82aaff024cac2f --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/migration/migration_faq.md @@ -0,0 +1 @@ +# 迁移 FAQ diff --git a/mmdet_code/mmdetection/docs/zh_cn/migration/model_migration.md b/mmdet_code/mmdetection/docs/zh_cn/migration/model_migration.md new file mode 100644 index 0000000000000000000000000000000000000000..d7992440228a811ce75023414f7fd7364516563a --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/migration/model_migration.md @@ -0,0 +1 @@ +# 将模型从 MMDetection 2.x 迁移至 3.x diff --git a/mmdet_code/mmdetection/docs/zh_cn/model_zoo.md b/mmdet_code/mmdetection/docs/zh_cn/model_zoo.md new file mode 100644 index 0000000000000000000000000000000000000000..b5376152d9c17634ab2b32bf1e1cc9baa7a1cff9 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/model_zoo.md @@ -0,0 +1,333 @@ +# 模型库 + +## 镜像地址 + +从 MMDetection V2.0 起,我们只通过阿里云维护模型库。V1.x 版本的模型已经弃用。 + +## 共同设置 + +- 所有模型都是在 `coco_2017_train` 上训练,在 `coco_2017_val` 上测试。 +- 我们使用分布式训练。 +- 所有 pytorch-style 的 ImageNet 预训练主干网络来自 PyTorch 的模型库,caffe-style 的预训练主干网络来自 detectron2 最新开源的模型。 +- 为了与其他代码库公平比较,文档中所写的 GPU 内存是8个 GPU 的 `torch.cuda.max_memory_allocated()` 的最大值,此值通常小于 nvidia-smi 显示的值。 +- 我们以网络 forward 和后处理的时间加和作为推理时间,不包含数据加载时间。所有结果通过 [benchmark.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/benchmark.py) 脚本计算所得。该脚本会计算推理 2000 张图像的平均时间。 + +## ImageNet 预训练模型 + +通过 ImageNet 分类任务预训练的主干网络进行初始化是很常见的操作。所有预训练模型的链接都可以在 [open_mmlab](https://github.com/open-mmlab/mmcv/blob/master/mmcv/model_zoo/open_mmlab.json) 中找到。根据 `img_norm_cfg` 和原始权重,我们可以将所有 ImageNet 预训练模型分为以下几种情况: + +- TorchVision:torchvision 模型权重,包含 ResNet50, ResNet101。`img_norm_cfg` 为 `dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)`。 +- Pycls:[pycls](https://github.com/facebookresearch/pycls) 模型权重,包含 RegNetX。`img_norm_cfg` 为 `dict( mean=[103.530, 116.280, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False)`。 +- MSRA styles:[MSRA](https://github.com/KaimingHe/deep-residual-networks) 模型权重,包含 ResNet50_Caffe,ResNet101_Caffe。`img_norm_cfg` 为 `dict( mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)`。 +- Caffe2 styles:现阶段只包含 ResNext101_32x8d。`img_norm_cfg` 为 `dict(mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395], to_rgb=False)`。 +- Other styles: SSD 的 `img_norm_cfg` 为 `dict(mean=[123.675, 116.28, 103.53], std=[1, 1, 1], to_rgb=True)`,YOLOv3 的 `img_norm_cfg` 为 `dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True)`。 + +MMdetection 常用到的主干网络细节如下表所示: + +| 模型 | 来源 | 链接 | 描述 | +| ---------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ResNet50 | TorchVision | [torchvision 中的 ResNet-50](https://download.pytorch.org/models/resnet50-19c8e357.pth) | 来自 [torchvision 中的 ResNet-50](https://download.pytorch.org/models/resnet50-19c8e357.pth)。 | +| ResNet101 | TorchVision | [torchvision 中的 ResNet-101](https://download.pytorch.org/models/resnet101-5d3b4d8f.pth) | 来自 [torchvision 中的 ResNet-101](https://download.pytorch.org/models/resnet101-5d3b4d8f.pth)。 | +| RegNetX | Pycls | [RegNetX_3.2gf](https://download.openmmlab.com/pretrain/third_party/regnetx_3.2gf-c2599b0f.pth),[RegNetX_800mf](https://download.openmmlab.com/pretrain/third_party/regnetx_800mf-1f4be4c7.pth) 等 | 来自 [pycls](https://github.com/facebookresearch/pycls)。 | +| ResNet50_Caffe | MSRA | [MSRA 中的 ResNet-50](https://download.openmmlab.com/pretrain/third_party/resnet50_caffe-788b5fa3.pth) | 由 [Detectron2 中的 R-50.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-50.pkl) 转化的副本。原始权重文件来自 [MSRA 中的原始 ResNet-50](https://github.com/KaimingHe/deep-residual-networks)。 | +| ResNet101_Caffe | MSRA | [MSRA 中的 ResNet-101](https://download.openmmlab.com/pretrain/third_party/resnet101_caffe-3ad79236.pth) | 由 [Detectron2 中的 R-101.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/MSRA/R-101.pkl) 转化的副本。原始权重文件来自 [MSRA 中的原始 ResNet-101](https://github.com/KaimingHe/deep-residual-networks)。 | +| ResNext101_32x8d | Caffe2 | [Caffe2 ResNext101_32x8d](https://download.openmmlab.com/pretrain/third_party/resnext101_32x8d-1516f1aa.pth) | 由 [Detectron2 中的 X-101-32x8d.pkl](https://dl.fbaipublicfiles.com/detectron2/ImageNetPretrained/FAIR/X-101-32x8d.pkl) 转化的副本。原始 ResNeXt-101-32x8d 由 FB 使用 Caffe2 训练。 | + +## Baselines + +### RPN + +请参考 [RPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/rpn)。 + +### Faster R-CNN + +请参考 [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn)。 + +### Mask R-CNN + +请参考 [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn)。 + +### Fast R-CNN (使用提前计算的 proposals) + +请参考 [Fast R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/fast_rcnn)。 + +### RetinaNet + +请参考 [RetinaNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/retinanet)。 + +### Cascade R-CNN and Cascade Mask R-CNN + +请参考 [Cascade R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/cascade_rcnn)。 + +### Hybrid Task Cascade (HTC) + +请参考 [HTC](https://github.com/open-mmlab/mmdetection/blob/main/configs/htc)。 + +### SSD + +请参考 [SSD](https://github.com/open-mmlab/mmdetection/blob/main/configs/ssd)。 + +### Group Normalization (GN) + +请参考 [Group Normalization](https://github.com/open-mmlab/mmdetection/blob/main/configs/gn)。 + +### Weight Standardization + +请参考 [Weight Standardization](https://github.com/open-mmlab/mmdetection/blob/main/configs/gn+ws)。 + +### Deformable Convolution v2 + +请参考 [Deformable Convolutional Networks](https://github.com/open-mmlab/mmdetection/blob/main/configs/dcn)。 + +### CARAFE: Content-Aware ReAssembly of FEatures + +请参考 [CARAFE](https://github.com/open-mmlab/mmdetection/blob/main/configs/carafe)。 + +### Instaboost + +请参考 [Instaboost](https://github.com/open-mmlab/mmdetection/blob/main/configs/instaboost)。 + +### Libra R-CNN + +请参考 [Libra R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/libra_rcnn)。 + +### Guided Anchoring + +请参考 [Guided Anchoring](https://github.com/open-mmlab/mmdetection/blob/main/configs/guided_anchoring)。 + +### FCOS + +请参考 [FCOS](https://github.com/open-mmlab/mmdetection/blob/main/configs/fcos)。 + +### FoveaBox + +请参考 [FoveaBox](https://github.com/open-mmlab/mmdetection/blob/main/configs/foveabox)。 + +### RepPoints + +请参考 [RepPoints](https://github.com/open-mmlab/mmdetection/blob/main/configs/reppoints)。 + +### FreeAnchor + +请参考 [FreeAnchor](https://github.com/open-mmlab/mmdetection/blob/main/configs/free_anchor)。 + +### Grid R-CNN (plus) + +请参考 [Grid R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/grid_rcnn)。 + +### GHM + +请参考 [GHM](https://github.com/open-mmlab/mmdetection/blob/main/configs/ghm)。 + +### GCNet + +请参考 [GCNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/gcnet)。 + +### HRNet + +请参考 [HRNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/hrnet)。 + +### Mask Scoring R-CNN + +请参考 [Mask Scoring R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/ms_rcnn)。 + +### Train from Scratch + +请参考 [Rethinking ImageNet Pre-training](https://github.com/open-mmlab/mmdetection/blob/main/configs/scratch)。 + +### NAS-FPN + +请参考 [NAS-FPN](https://github.com/open-mmlab/mmdetection/blob/main/configs/nas_fpn)。 + +### ATSS + +请参考 [ATSS](https://github.com/open-mmlab/mmdetection/blob/main/configs/atss)。 + +### FSAF + +请参考 [FSAF](https://github.com/open-mmlab/mmdetection/blob/main/configs/fsaf)。 + +### RegNetX + +请参考 [RegNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/regnet)。 + +### Res2Net + +请参考 [Res2Net](https://github.com/open-mmlab/mmdetection/blob/main/configs/res2net)。 + +### GRoIE + +请参考 [GRoIE](https://github.com/open-mmlab/mmdetection/blob/main/configs/groie)。 + +### Dynamic R-CNN + +请参考 [Dynamic R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/dynamic_rcnn)。 + +### PointRend + +请参考 [PointRend](https://github.com/open-mmlab/mmdetection/blob/main/configs/point_rend)。 + +### DetectoRS + +请参考 [DetectoRS](https://github.com/open-mmlab/mmdetection/blob/main/configs/detectors)。 + +### Generalized Focal Loss + +请参考 [Generalized Focal Loss](https://github.com/open-mmlab/mmdetection/blob/main/configs/gfl)。 + +### CornerNet + +请参考 [CornerNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/cornernet)。 + +### YOLOv3 + +请参考 [YOLOv3](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolo)。 + +### PAA + +请参考 [PAA](https://github.com/open-mmlab/mmdetection/blob/main/configs/paa)。 + +### SABL + +请参考 [SABL](https://github.com/open-mmlab/mmdetection/blob/main/configs/sabl)。 + +### CentripetalNet + +请参考 [CentripetalNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/centripetalnet)。 + +### ResNeSt + +请参考 [ResNeSt](https://github.com/open-mmlab/mmdetection/blob/main/configs/resnest)。 + +### DETR + +请参考 [DETR](https://github.com/open-mmlab/mmdetection/blob/main/configs/detr)。 + +### Deformable DETR + +请参考 [Deformable DETR](https://github.com/open-mmlab/mmdetection/blob/main/configs/deformable_detr)。 + +### AutoAssign + +请参考 [AutoAssign](https://github.com/open-mmlab/mmdetection/blob/main/configs/autoassign)。 + +### YOLOF + +请参考 [YOLOF](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolof)。 + +### Seesaw Loss + +请参考 [Seesaw Loss](https://github.com/open-mmlab/mmdetection/blob/main/configs/seesaw_loss)。 + +### CenterNet + +请参考 [CenterNet](https://github.com/open-mmlab/mmdetection/blob/main/configs/centernet)。 + +### YOLOX + +请参考 [YOLOX](https://github.com/open-mmlab/mmdetection/blob/main/configs/yolox)。 + +### PVT + +请参考 [PVT](https://github.com/open-mmlab/mmdetection/blob/main/configs/pvt)。 + +### SOLO + +请参考 [SOLO](https://github.com/open-mmlab/mmdetection/blob/main/configs/solo)。 + +### QueryInst + +请参考 [QueryInst](https://github.com/open-mmlab/mmdetection/blob/main/configs/queryinst)。 + +### Other datasets + +我们还在 [PASCAL VOC](https://github.com/open-mmlab/mmdetection/blob/main/configs/pascal_voc),[Cityscapes](https://github.com/open-mmlab/mmdetection/blob/main/configs/cityscapes) 和 [WIDER FACE](https://github.com/open-mmlab/mmdetection/blob/main/configs/wider_face) 上对一些方法进行了基准测试。 + +### Pre-trained Models + +我们还通过多尺度训练和更长的训练策略来训练用 ResNet-50 和 [RegNetX-3.2G](https://github.com/open-mmlab/mmdetection/blob/main/configs/regnet) 作为主干网络的 [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn) 和 [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn)。这些模型可以作为下游任务的预训练模型。 + +## 速度基准 + +### 训练速度基准 + +我们提供 [analyze_logs.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/analyze_logs.py) 来得到训练中每一次迭代的平均时间。示例请参考 [Log Analysis](https://mmdetection.readthedocs.io/en/latest/useful_tools.html#log-analysis)。 + +我们与其他流行框架的 Mask R-CNN 训练速度进行比较(数据是从 [detectron2](https://github.com/facebookresearch/detectron2/blob/main/docs/notes/benchmarks.md/) 复制而来)。在 mmdetection 中,我们使用 [mask-rcnn_r50-caffe_fpn_poly-1x_coco_v1.py](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn/mask-rcnn_r50-caffe_fpn_poly-1x_coco_v1.py) 进行基准测试。它与 detectron2 的 [mask_rcnn_R_50_FPN_noaug_1x.yaml](https://github.com/facebookresearch/detectron2/blob/main/configs/Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x.yaml) 设置完全一样。同时,我们还提供了[模型权重](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug_compare_20200518-10127928.pth)和[训练 log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug/mask_rcnn_r50_caffe_fpn_poly_1x_coco_no_aug_20200518_105755.log.json) 作为参考。为了跳过 GPU 预热时间,吞吐量按照100-500次迭代之间的平均吞吐量来计算。 + +| 框架 | 吞吐量 (img/s) | +| -------------------------------------------------------------------------------------- | -------------- | +| [Detectron2](https://github.com/facebookresearch/detectron2) | 62 | +| [MMDetection](https://github.com/open-mmlab/mmdetection) | 61 | +| [maskrcnn-benchmark](https://github.com/facebookresearch/maskrcnn-benchmark/) | 53 | +| [tensorpack](https://github.com/tensorpack/tensorpack/tree/master/examples/FasterRCNN) | 50 | +| [simpledet](https://github.com/TuSimple/simpledet/) | 39 | +| [Detectron](https://github.com/facebookresearch/Detectron) | 19 | +| [matterport/Mask_RCNN](https://github.com/matterport/Mask_RCNN/) | 14 | + +### 推理时间基准 + +我们提供 [benchmark.py](https://github.com/open-mmlab/mmdetection/blob/main/tools/analysis_tools/benchmark.py) 对推理时间进行基准测试。此脚本将推理 2000 张图片并计算忽略前 5 次推理的平均推理时间。可以通过设置 `LOG-INTERVAL` 来改变 log 输出间隔(默认为 50)。 + +```shell +python tools/benchmark.py ${CONFIG} ${CHECKPOINT} [--log-interval $[LOG-INTERVAL]] [--fuse-conv-bn] +``` + +模型库中,所有模型在基准测量推理时间时都没设置 `fuse-conv-bn`, 此设置可以使推理时间更短。 + +## 与 Detectron2 对比 + +我们在速度和精度方面对 mmdetection 和 [Detectron2](https://github.com/facebookresearch/detectron2.git) 进行对比。对比所使用的 detectron2 的 commit id 为 [185c27e](https://github.com/facebookresearch/detectron2/tree/185c27e4b4d2d4c68b5627b3765420c6d7f5a659)(30/4/2020)。 +为了公平对比,我们所有的实验都在同一机器下进行。 + +### 硬件 + +- 8 NVIDIA Tesla V100 (32G) GPUs +- Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz + +### 软件环境 + +- Python 3.7 +- PyTorch 1.4 +- CUDA 10.1 +- CUDNN 7.6.03 +- NCCL 2.4.08 + +### 精度 + +| 模型 | 训练策略 | Detectron2 | mmdetection | 下载 | +| ------------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_ms-1x_coco.py) | 1x | [37.9](https://github.com/facebookresearch/detectron2/blob/main/configs/COCO-Detection/faster_rcnn_R_50_FPN_1x.yaml) | 38.0 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco-5324cff8.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco_20200429_234554.log.json) | +| [Mask R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_coco.py) | 1x | [38.6 & 35.2](https://github.com/facebookresearch/detectron2/blob/master/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml) | 38.8 & 35.4 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco-dbecf295.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco_20200430_054239.log.json) | +| [Retinanet](https://github.com/open-mmlab/mmdetection/blob/main/configs/retinanet/retinanet_r50-caffe_fpn_ms-1x_coco.py) | 1x | [36.5](https://github.com/facebookresearch/detectron2/blob/master/configs/COCO-Detection/retinanet_R_50_FPN_1x.yaml) | 37.0 | [model](https://download.openmmlab.com/mmdetection/v2.0/benchmark/retinanet_r50_caffe_fpn_mstrain_1x_coco/retinanet_r50_caffe_fpn_mstrain_1x_coco-586977a0.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/benchmark/retinanet_r50_caffe_fpn_mstrain_1x_coco/retinanet_r50_caffe_fpn_mstrain_1x_coco_20200430_014748.log.json) | + +### 训练速度 + +训练速度使用 s/iter 来度量。结果越低越好。 + +| 模型 | Detectron2 | mmdetection | +| ------------ | ---------- | ----------- | +| Faster R-CNN | 0.210 | 0.216 | +| Mask R-CNN | 0.261 | 0.265 | +| Retinanet | 0.200 | 0.205 | + +### 推理速度 + +推理速度通过单张 GPU 下的 fps(img/s) 来度量,越高越好。 +为了与 Detectron2 保持一致,我们所写的推理时间除去了数据加载时间。 +对于 Mask RCNN,我们去除了后处理中 RLE 编码的时间。 +我们在括号中给出了官方给出的速度。由于硬件差异,官方给出的速度会比我们所测试得到的速度快一些。 + +| 模型 | Detectron2 | mmdetection | +| ------------ | ----------- | ----------- | +| Faster R-CNN | 25.6 (26.3) | 22.2 | +| Mask R-CNN | 22.5 (23.3) | 19.6 | +| Retinanet | 17.8 (18.2) | 20.6 | + +### 训练内存 + +| 模型 | Detectron2 | mmdetection | +| ------------ | ---------- | ----------- | +| Faster R-CNN | 3.0 | 3.8 | +| Mask R-CNN | 3.4 | 3.9 | +| Retinanet | 3.9 | 3.4 | diff --git a/mmdet_code/mmdetection/docs/zh_cn/notes/compatibility.md b/mmdet_code/mmdetection/docs/zh_cn/notes/compatibility.md new file mode 100644 index 0000000000000000000000000000000000000000..e9ebdd97e84c5ab109dbb64f978e741c1fb42c15 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/notes/compatibility.md @@ -0,0 +1,177 @@ +# MMDetection v2.x 兼容性说明 + +## MMDetection 2.25.0 + +为了加入 Mask2Former 实例分割模型,对 Mask2Former 的配置文件进行了重命名 [PR #7571](https://github.com/open-mmlab/mmdetection/pull/7571): + + + + + + + + + + + +
在 v2.25.0 之前v2.25.0 及之后
+ +``` +'mask2former_xxx_coco.py' 代表全景分割的配置文件 +``` + + + +``` +'mask2former_xxx_coco.py' 代表实例分割的配置文件 +'mask2former_xxx_coco-panoptic.py' 代表全景分割的配置文件 +``` + +
+ +## MMDetection 2.21.0 + +为了支持 CPU 训练,MMCV 中进行批处理的 scatter 的代码逻辑已经被修改。我们推荐使用 MMCV v1.4.4 或更高版本, +更多信息请参考 [MMCV PR #1621](https://github.com/open-mmlab/mmcv/pull/1621). + +## MMDetection 2.18.1 + +### MMCV compatibility + +为了修复 BaseTransformerLayer 中的权重引用问题, MultiheadAttention 中 batch first 的逻辑有所改变。 +我们推荐使用 MMCV v1.3.17 或更高版本。 更多信息请参考 [MMCV PR #1418](https://github.com/open-mmlab/mmcv/pull/1418) 。 + +## MMDetection 2.18.0 + +### DIIHead 兼容性 + +为了支持 QueryInst,在 DIIHead 的返回元组中加入了 attn_feats。 + +## MMDetection v2.14.0 + +### MMCV 版本 + +为了修复 EvalHook 优先级过低的问题,MMCV v1.3.8 中所有 hook 的优先级都重新进行了调整,因此 MMDetection v2.14.0 需要依赖最新的 MMCV v1.3.8 版本。 相关信息请参考[PR #1120](https://github.com/open-mmlab/mmcv/pull/1120) ,相关问题请参考[#5343](https://github.com/open-mmlab/mmdetection/issues/5343) 。 + +### SSD 兼容性 + +在 v2.14.0 中,为了使 SSD 能够被更灵活地使用,[PR #5291](https://github.com/open-mmlab/mmdetection/pull/5291) 重构了 SSD 的 backbone、neck 和 head。用户可以使用 tools/model_converters/upgrade_ssd_version.py 转换旧版本训练的模型。 + +```shell +python tools/model_converters/upgrade_ssd_version.py ${OLD_MODEL_PATH} ${NEW_MODEL_PATH} + +``` + +- OLD_MODEL_PATH:旧版 SSD 模型的路径。 +- NEW_MODEL_PATH:保存转换后模型权重的路径。 + +## MMDetection v2.12.0 + +在 v2.12.0 到 v2.18.0(或以上)版本的这段时间,为了提升通用性和便捷性,MMDetection 正在进行大规模重构。在升级到 v2.12.0 后 MMDetection 不可避免地带来了一些 BC Breaking,包括 MMCV 的版本依赖、模型初始化方式、模型 registry 和 mask AP 的评估。 + +### MMCV 版本 + +MMDetection v2.12.0 依赖 MMCV v1.3.3 中新增加的功能,包括:使用 `BaseModule` 统一参数初始化,模型 registry,以及[Deformable DETR](https://arxiv.org/abs/2010.04159) 中的 `MultiScaleDeformableAttn` CUDA 算子。 +注意,尽管 MMCV v1.3.2 已经包含了 MMDet 所需的功能,但是存在一些已知的问题。我们建议用户跳过 MMCV v1.3.2 使用 v1.3.3 版本。 + +### 统一模型初始化 + +为了统一 OpenMMLab 项目中的参数初始化方式,MMCV 新增加了 `BaseModule` 类,使用 `init_cfg` 参数对模块进行统一且灵活的初始化配置管理。 +现在用户需要在训练脚本中显式调用 `model.init_weights()` 来初始化模型(例如 [这行代码](https://github.com/open-mmlab/mmdetection/blob/master/tools/train.py#L162) ,在这之前则是在 detector 中进行处理的。 +**下游项目必须相应地更新模型初始化方式才能使用 MMDetection v2.12.0**。请参阅 [PR #4750](https://github.com/open-mmlab/mmdetection/pull/4750) 了解详情。 + +### 统一模型 registry + +为了能够使用在其他 OpenMMLab 项目中实现的 backbone,MMDetection v2.12.0 继承了在 MMCV (#760) 中创建的模型 registry。 +这样,只要 OpenMMLab 项目实现了某个 backbone,并且该项目也使用 MMCV 中的 registry,那么用户只需修改配置即可在 MMDetection 中使用该 backbone,不再需要将代码复制到 MMDetection 中。 更多详细信息,请参阅 [PR #5059](https://github.com/open-mmlab/mmdetection/pull/5059) 。 + +### Mask AP 评估 + +在 [PR #4898](https://github.com/open-mmlab/mmdetection/pull/4898) 和 v2.12.0 之前,对小、中、大目标的 mask AP 的评估是基于其边界框区域而不是真正的 mask 区域。 +这导致 `APs` 和 `APm` 变得更高但 `APl` 变得更低,但是不会影响整体的 mask AP。 [PR #4898](https://github.com/open-mmlab/mmdetection/pull/4898) 删除了 mask AP 计算中的 `bbox` ,改为使用 mask 区域。 +新的计算方式不会影响整体的 mask AP 评估,与 [Detectron2](https://github.com/facebookresearch/detectron2/)一致。 + +## 与 MMDetection v1.x 的兼容性 + +MMDetection v2.0 经过了大规模重构并解决了许多遗留问题。 MMDetection v2.0 不兼容 v1.x 版本,在这两个版本中使用相同的模型权重运行推理会产生不同的结果。 因此,MMDetection v2.0 重新对所有模型进行了 benchmark,并在 model zoo 中提供了新模型的权重和训练记录。 + +新旧版本的主要的区别有四方面:坐标系、代码库约定、训练超参和模块设计。 + +### 坐标系 + +新坐标系与 [Detectron2](https://github.com/facebookresearch/detectron2/) 一致, +将最左上角的像素的中心视为坐标原点 (0, 0) 而不是最左上角像素的左上角。 因此 COCO 边界框和分割标注中的坐标被解析为范围 `[0,width]` 和 `[0,height]` 中的坐标。 这个修改影响了所有与 bbox 及像素选择相关的计算,变得更加自然且更加准确。 + +- 在新坐标系中,左上角和右下角为 (x1, y1) (x2, y2) 的框的宽度及高度计算公式为 `width = x2 - x1` 和 `height = y2 - y1`。 + 在 MMDetection v1.x 和之前的版本中,高度和宽度都多了 `+ 1` 的操作。 + 本次修改包括三部分: + + 1. box 回归中的检测框变换以及编码/解码。 + 2. IoU 计算。这会影响 ground truth 和检测框之间的匹配以及 NMS 。但对兼容性的影响可以忽略不计。 + 3. Box 的角点坐标为浮点型,不再取整。这能使得检测结果更为准确,也使得检测框和 RoI 的最小尺寸不再为 1,但影响很小。 + +- Anchor 的中心与特征图的网格点对齐,类型变为 float。 + 在 MMDetection v1.x 和之前的版本中,anchors 是 `int` 类型且没有居中对齐。 + 这会影响 RPN 中的 Anchor 生成和所有基于 Anchor 的方法。 + +- ROIAlign 更好地与图像坐标系对齐。新的实现来自 [Detectron2](https://github.com/facebookresearch/detectron2/tree/master/detectron2/layers/csrc/ROIAlign) 。 + 当 RoI 用于提取 RoI 特征时,与 MMDetection v1.x 相比默认情况下相差半个像素。 + 能够通过设置 `aligned=False` 而不是 `aligned=True` 来维持旧版本的设置。 + +- Mask 的裁剪和粘贴更准确。 + + 1. 我们使用新的 RoIAlign 来提取 mask 目标。 在 MMDetection v1.x 中,bounding box 在提取 mask 目标之前被取整,裁剪过程是 numpy 实现的。 而在新版本中,裁剪的边界框不经过取整直接输入 RoIAlign。 此实现大大加快了训练速度(每次迭代约加速 0.1 秒,1x schedule 训练 Mask R50 时加速约 2 小时)并且理论上会更准确。 + 2. 在 MMDetection v2.0 中,修改后的 `paste_mask()` 函数应该比之前版本更准确。 此更改参考了 [Detectron2](https://github.com/facebookresearch/detectron2/blob/master/detectron2/structures/masks.py) 中的修改,可以将 COCO 上的 mask AP 提高约 0.5%。 + +### 代码库约定 + +- MMDetection v2.0 更改了类别标签的顺序,减少了回归和 mask 分支里的无用参数并使得顺序更加自然(没有 +1 和 -1)。 + 这会影响模型的所有分类层,使其输出的类别标签顺序发生改变。回归分支和 mask head 的最后一层不再为 K 个类别保留 K+1 个通道,类别顺序与分类分支一致。 + + - 在 MMDetection v2.0 中,标签 “K” 表示背景,标签 \[0, K-1\] 对应于 K = num_categories 个对象类别。 + + - 在 MMDetection v1.x 及之前的版本中,标签 “0” 表示背景,标签 \[1, K\] 对应 K 个类别。 + + - **注意**:softmax RPN 的类顺序在 version\<=2.4.0 中仍然和 1.x 中的一样,而 sigmoid RPN 不受影响。从 MMDetection v2.5.0 开始,所有 head 中的类顺序是统一的。 + +- 不使用 R-CNN 中的低质量匹配。在 MMDetection v1.x 和之前的版本中,`max_iou_assigner` 会在 RPN 和 R-CNN 训练时给每个 ground truth 匹配低质量框。我们发现这会导致最佳的 GT 框不会被分配给某些边界框, + 因此,在MMDetection v2.0 的 R-CNN 训练中默认不允许低质量匹配。这有时可能会稍微改善 box AP(约为 0.1%)。 + +- 单独的宽高比例系数。在 MMDetection v1.x 和以前的版本中,`keep_ratio=True` 时比例系数是单个浮点数,这并不准确,因为宽度和高度的比例系数会有一定的差异。 MMDetection v2.0 对宽度和高度使用单独的比例系数,对 AP 的提升约为 0.1%。 + +- 修改了 config 文件名称的规范。 由于 model zoo 中模型不断增多, MMDetection v2.0 采用新的命名规则: + + ```shell + [model]_(model setting)_[backbone]_[neck]_(norm setting)_(misc)_(gpu x batch)_[schedule]_[dataset].py + ``` + + 其中 (`misc`) 包括 DCN 和 GCBlock 等。更多详细信息在 [配置文件说明文档](config.md) 中说明 + +- MMDetection v2.0 使用新的 ResNet Caffe backbone 来减少加载预训练模型时的警告。新 backbone 中的大部分权重与以前的相同,但没有 `conv.bias`,且它们使用不同的 `img_norm_cfg`。因此,新的 backbone 不会报 `unexpected keys` 的警告。 + +### 训练超参 + +训练超参的调整不会影响模型的兼容性,但会略微提高性能。主要有: + +- 通过设置 `nms_post=1000` 和 `max_num=1000`,将 nms 之后的 proposal 数量从 2000 更改为 1000。使 mask AP 和 bbox AP 提高了约 0.2%。 + +- Mask R-CNN、Faster R-CNN 和 RetinaNet 的默认回归损失从 smooth L1 损失更改为 L1 损失,使得 box AP 整体上都有所提升(约 0.6%)。但是,将 L1-loss 用在 Cascade R-CNN 和 HTC 等其他方法上并不能提高性能,因此我们保留这些方法的原始设置。 + +- 为简单起见,RoIAlign 层的 `sampling_ratio` 设置为 0。略微提升了 AP(约 0.2% 绝对值)。 + +- 为了提升训练速度,默认设置在训练过程中不再使用梯度裁剪。大多数模型的性能不会受到影响。对于某些模型(例如 RepPoints),我们依旧使用梯度裁剪来稳定训练过程从而获得更好的性能。 + +- 因为不再默认使用梯度裁剪,默认 warmup 比率从 1/3 更改为 0.001,以使模型训练预热更加平缓。不过我们重新进行基准测试时发现这种影响可以忽略不计。 + +### 将模型从 v1.x 升级至 v2.0 + +用户可以使用脚本 `tools/model_converters/upgrade_model_version.py` 来将 MMDetection 1.x 训练的模型转换为 MMDetection v2.0。转换后的模型可以在 MMDetection v2.0 中运行,但性能略有下降(小于 1% AP)。 +详细信息可以在 `configs/legacy` 中找到。 + +## pycocotools 兼容性 + +`mmpycocotools` 是 OpenMMLab 维护的 `pycocotools` 的复刻版,适用于 MMDetection 和 Detectron2。 +在 [PR #4939](https://github.com/open-mmlab/mmdetection/pull/4939) 之前,由于 `pycocotools` 和 `mmpycocotool` 具有相同的包名,如果用户已经安装了 `pyccocotools`(在相同环境下先安装了 Detectron2 ),那么 MMDetection 的安装过程会跳过安装 `mmpycocotool`。 导致 MMDetection 缺少 `mmpycocotools` 而报错。 +但如果在 Detectron2 之前安装 MMDetection,则可以在相同的环境下工作。 +[PR #4939](https://github.com/open-mmlab/mmdetection/pull/4939) 弃用 mmpycocotools,使用官方 pycocotools。 +在 [PR #4939](https://github.com/open-mmlab/mmdetection/pull/4939) 之后,用户能够在相同环境下安装 MMDetection 和 Detectron2,不再需要关注安装顺序。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/notes/faq.md b/mmdet_code/mmdetection/docs/zh_cn/notes/faq.md new file mode 100644 index 0000000000000000000000000000000000000000..2b4237c741140e04ae0076d60637662b0e6aa117 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/notes/faq.md @@ -0,0 +1,260 @@ +# 常见问题解答 + +我们在这里列出了使用时的一些常见问题及其相应的解决方案。 如果您发现有一些问题被遗漏,请随时提 PR 丰富这个列表。 如果您无法在此获得帮助,请使用 [issue模板](https://github.com/open-mmlab/mmdetection/blob/main/.github/ISSUE_TEMPLATE/error-report.md/)创建问题,但是请在模板中填写所有必填信息,这有助于我们更快定位问题。 + +## PyTorch 2.0 支持 + +MMDetection 目前绝大部分算法已经支持了 PyTorch 2.0 及其 `torch.compile` 功能, 用户只需要安装 MMDetection 3.0.0rc7 及其以上版本即可。如果你在使用中发现有不支持的算法,欢迎给我们反馈。我们也非常欢迎社区贡献者来 benchmark 对比 `torch.compile` 功能所带来的速度提升。 + +如果你想启动 `torch.compile` 功能,只需要在 `train.py` 或者 `test.py` 后面加上 `--cfg-options compile=True`。 以 RTMDet 为例,你可以使用以下命令启动 `torch.compile` 功能: + +```shell +# 单卡 +python tools/train.py configs/rtmdet/rtmdet_s_8xb32-300e_coco.py --cfg-options compile=True + +# 单机 8 卡 +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True + +# 单机 8 卡 + AMP 混合精度训练 +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True --amp +``` + +需要特别注意的是,PyTorch 2.0 对于动态 shape 支持不是非常完善,目标检测算法中大部分不仅输入 shape 是动态的,而且 loss 计算和后处理过程中也是动态的,这会导致在开启 `torch.compile` 功能后训练速度会变慢。基于此,如果你想启动 `torch.compile` 功能,则应该遵循如下原则: + +1. 输入到网络的图片是固定 shape 的,而非多尺度的 +2. 设置 `torch._dynamo.config.cache_size_limit` 参数。TorchDynamo 会将 Python 字节码转换并缓存,已编译的函数会被存入缓存中。当下一次检查发现需要重新编译时,该函数会被重新编译并缓存。但是如果重编译次数超过预设的最大值(64),则该函数将不再被缓存或重新编译。前面说过目标检测算法中的 loss 计算和后处理部分也是动态计算的,这些函数需要在每次迭代中重新编译。因此将 `torch._dynamo.config.cache_size_limit` 参数设置得更小一些可以有效减少编译时间 + +在 MMDetection 中可以通过环境变量 `DYNAMO_CACHE_SIZE_LIMIT` 设置 `torch._dynamo.config.cache_size_limit` 参数,以 RTMDet 为例,命令如下所示: + +```shell +# 单卡 +export DYNAMO_CACHE_SIZE_LIMIT = 4 +python tools/train.py configs/rtmdet/rtmdet_s_8xb32-300e_coco.py --cfg-options compile=True + +# 单机 8 卡 +export DYNAMO_CACHE_SIZE_LIMIT = 4 +./tools/dist_train.sh configs/rtmdet/rtmdet_s_8xb32-300e_coco.py 8 --cfg-options compile=True +``` + +关于 PyTorch 2.0 的 dynamo 常见问题,可以参考 [这里](https://pytorch.org/docs/stable/dynamo/faq.html) + +## 安装 + +- MMCV 与 MMDetection 的兼容问题: "ConvWS is already registered in conv layer"; "AssertionError: MMCV==xxx is used but incompatible. Please install mmcv>=xxx, \<=xxx." + + MMDetection,MMEngine 和 MMCV 的版本兼容关系如下。请选择合适的版本避免安装错误 。 + + | MMDetection 版本 | MMCV 版本 | MMEngine 版本 | + | :--------------: | :---------------------: | :----------------------: | + | main | mmcv>=2.0.0, \<2.2.0 | mmengine>=0.7.1, \<1.0.0 | + | 3.3.0 | mmcv>=2.0.0, \<2.2.0 | mmengine>=0.7.1, \<1.0.0 | + | 3.2.0 | mmcv>=2.0.0, \<2.2.0 | mmengine>=0.7.1, \<1.0.0 | + | 3.1.0 | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | + | 3.0.0 | mmcv>=2.0.0, \<2.1.0 | mmengine>=0.7.1, \<1.0.0 | + | 3.0.0rc6 | mmcv>=2.0.0rc4, \<2.1.0 | mmengine>=0.6.0, \<1.0.0 | + | 3.0.0rc5 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | + | 3.0.0rc4 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | + | 3.0.0rc3 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.3.0, \<1.0.0 | + | 3.0.0rc2 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | + | 3.0.0rc1 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | + | 3.0.0rc0 | mmcv>=2.0.0rc1, \<2.1.0 | mmengine>=0.1.0, \<1.0.0 | + + **注意:** + + 1. 如果你希望安装 mmdet-v2.x, MMDetection 和 MMCV 版本兼容表可以在 [这里](https://mmdetection.readthedocs.io/en/stable/faq.html#installation) 找到,请选择合适的版本避免安装错误。 + 2. 在 MMCV-v2.x 中,`mmcv-full` 改名为 `mmcv`,如果你想安装不包含 CUDA 算子的版本,可以选择安装 MMCV 精简版 `mmcv-lite`。 + +- "No module named 'mmcv.ops'"; "No module named 'mmcv.\_ext'". + + 原因是安装了 `mmcv-lite` 而不是 `mmcv`。 + + 1. `pip uninstall mmcv-lite` 卸载安装的 `mmcv-lite` + + 2. 安装 `mmcv` 根据 [安装说明](https://mmcv.readthedocs.io/zh_CN/2.x/get_started/installation.html)。 + +- 在 Windows 环境下安装过程中遇到 "Microsoft Visual C++ 14.0 or graeter is required" error . + + 这个错误发生在 pycotools 的 'pycocotools.\_mask' 扩展构建过程,其原因是缺少了对应 C++ 环境依赖。你需要到微软官方下载[对应工具](https://visualstudio.microsoft.com/zh-hans/visual-cpp-build-tools/),选择“使用 C++ 的桌面开发”选项安装最小依赖,随后重新安装 pycocotools。 + +- 使用 albumentations + +如果你希望使用 `albumentations`,我们建议使用 `pip install -r requirements/albu.txt` +或者 `pip install -U albumentations --no-binary qudida,albumentations` 进行安装。 +如果简单地使用 `pip install albumentations>=0.3.2` 进行安装, +则会同时安装 `opencv-python-headless`(即便已经安装了 `opencv-python` 也会再次安装)。 +我们建议在安装 `albumentations` 后检查环境,以确保没有同时安装 `opencv-python` 和 `opencv-python-headless`, +因为同时安装可能会导致一些问题。更多细节请参考[官方文档](https://albumentations.ai/docs/getting_started/installation/#note-on-opencv-dependencies) 。 + +- 在某些算法中出现 ModuleNotFoundError 错误 + +一些算法或者数据需要额外的依赖,例如 Instaboost、 Panoptic Segmentation、 LVIS dataset 等。请注意错误信息并安装相应的包,例如: + +```shell +# 安装 instaboost 依赖 +pip install instaboostfast +# 安装 panoptic segmentation 依赖 +pip install git+https://github.com/cocodataset/panopticapi.git +# 安装 LVIS dataset 依赖 +pip install git+https://github.com/lvis-dataset/lvis-api.git +``` + +## 代码 + +- 修改一些代码后是否需要重新安装 mmdet + +如果你遵循最佳实践,即使用 `pip install -v -e .` 安装的 mmdet,则对本地代码所作的任何修改都会生效,无需重新安装 + +- 如何使用多个 MMDetection 版本进行开发 + +你可以拥有多个文件夹,例如 mmdet-3.0,mmdet-3.1。 + +要使环境中安装默认的 MMDetection 而不是当前正在在使用的,可以删除出现在相关脚本中的代码: + +```shell +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH +``` + +## PyTorch/CUDA 环境相关 + +- "RTX 30 series card fails when building MMCV or MMDet" + + 1. 临时解决方案为使用命令 `MMCV_WITH_OPS=1 MMCV_CUDA_ARGS='-gencode=arch=compute_80,code=sm_80' pip install -e .` 进行编译。 常见报错信息为 `nvcc fatal : Unsupported gpu architecture 'compute_86'` 意思是你的编译器不支持 sm_86 架构(包括英伟达 30 系列的显卡)的优化,至 CUDA toolkit 11.0 依旧未支持. 这个命令是通过增加宏 `MMCV_CUDA_ARGS='-gencode=arch=compute_80,code=sm_80` 让 nvcc 编译器为英伟达 30 系列显卡进行 `sm_80` 的优化,虽然这有可能会无法发挥出显卡所有性能。 + + 2. 有开发者已经在 [pytorch/pytorch#47585](https://github.com/pytorch/pytorch/pull/47585) 更新了 PyTorch 默认的编译 flag, 但是我们对此并没有进行测试。 + +- "invalid device function" 或者 "no kernel image is available for execution". + + 1. 检查您正常安装了 CUDA runtime (一般在`/usr/local/`),或者使用 `nvcc --version` 检查本地版本,有时安装 PyTorch 会顺带安装一个 CUDA runtime,并且实际优先使用 conda 环境中的版本,你可以使用 `conda list cudatoolkit` 查看其版本。 + + 2. 编译 extension 的 CUDA Toolkit 版本与运行时的 CUDA Toolkit 版本是否相符, + + - 如果您从源码自己编译的,使用 `python mmdet/utils/collect_env.py` 检查编译编译 extension 的 CUDA Toolkit 版本,然后使用 `conda list cudatoolkit` 检查当前 conda 环境是否有 CUDA Toolkit,若有检查版本是否匹配, 如不匹配,更换 conda 环境的 CUDA Toolkit,或者使用匹配的 CUDA Toolkit 中的 nvcc 编译即可,如环境中无 CUDA Toolkit,可以使用 `nvcc -V`。 + + 等命令查看当前使用的 CUDA runtime。 + + - 如果您是通过 pip 下载的预编译好的版本,请确保与当前 CUDA runtime 一致。 + + 3. 运行 `python mmdet/utils/collect_env.py` 检查是否为正确的 GPU 架构编译的 PyTorch, torchvision, 与 MMCV。 你或许需要设置 `TORCH_CUDA_ARCH_LIST` 来重新安装 MMCV,可以参考 [GPU 架构表](https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#gpu-feature-list), + 例如, 运行 `TORCH_CUDA_ARCH_LIST=7.0 pip install mmcv` 为 Volta GPU 编译 MMCV。这种架构不匹配的问题一般会出现在使用一些旧型号的 GPU 时候出现, 例如, Tesla K80。 + +- "undefined symbol" 或者 "cannot open xxx.so". + + 1. 如果这些 symbol 属于 CUDA/C++ (如 libcudart.so 或者 GLIBCXX),使用 `python mmdet/utils/collect_env.py`检查 CUDA/GCC runtime 与编译 MMCV 的 CUDA 版本是否相同。 + 2. 如果这些 symbols 属于 PyTorch,(例如, symbols containing caffe, aten, and TH), 检查当前 Pytorch 版本是否与编译 MMCV 的版本一致。 + 3. 运行 `python mmdet/utils/collect_env.py` 检查 PyTorch, torchvision, MMCV 等的编译环境与运行环境一致。 + +- setuptools.sandbox.UnpickleableException: DistutilsSetupError("each element of 'ext_modules' option must be an Extension instance or 2-tuple") + + 1. 如果你在使用 miniconda 而不是 anaconda,检查是否正确的安装了 Cython 如 [#3379](https://github.com/open-mmlab/mmdetection/issues/3379). + 2. 检查环境中的 `setuptools`, `Cython`, and `PyTorch` 相互之间版本是否匹配。 + +- "Segmentation fault". + + 1. 检查 GCC 的版本,通常是因为 PyTorch 版本与 GCC 版本不匹配 (例如 GCC \< 4.9 ),我们推荐用户使用 GCC 5.4,我们也不推荐使用 GCC 5.5, 因为有反馈 GCC 5.5 会导致 "segmentation fault" 并且切换到 GCC 5.4 就可以解决问题。 + + 2. 检查是否正确安装了 CUDA 版本的 PyTorch 。 + + ```shell + python -c 'import torch; print(torch.cuda.is_available())' + ``` + + 是否返回True。 + + 3. 如果 `torch` 的安装是正确的,检查是否正确编译了 MMCV。 + + ```shell + python -c 'import mmcv; import mmcv.ops' + ``` + + 4. 如果 MMCV 与 PyTorch 都被正确安装了,则使用 `ipdb`, `pdb` 设置断点,直接查找哪一部分的代码导致了 `segmentation fault`。 + +## Training 相关 + +- "Loss goes Nan" + + 1. 检查数据的标注是否正常, 长或宽为 0 的框可能会导致回归 loss 变为 nan,一些小尺寸(宽度或高度小于 1)的框在数据增强(例如,instaboost)后也会导致此问题。 因此,可以检查标注并过滤掉那些特别小甚至面积为 0 的框,并关闭一些可能会导致 0 面积框出现数据增强。 + 2. 降低学习率:由于某些原因,例如 batch size 大小的变化, 导致当前学习率可能太大。 您可以降低为可以稳定训练模型的值。 + 3. 延长 warm up 的时间:一些模型在训练初始时对学习率很敏感,您可以把 `warmup_iters` 从 500 更改为 1000 或 2000。 + 4. 添加 gradient clipping: 一些模型需要梯度裁剪来稳定训练过程。 默认的 `grad_clip` 是 `None`, 你可以在 config 设置 `optimizer_config=dict(_delete_=True, grad_clip=dict(max_norm=35, norm_type=2))` 如果你的 config 没有继承任何包含 `optimizer_config=dict(grad_clip=None)`, 你可以直接设置`optimizer_config=dict(grad_clip=dict(max_norm=35, norm_type=2))`. + +- "GPU out of memory" + + 1. 存在大量 ground truth boxes 或者大量 anchor 的场景,可能在 assigner 会 OOM。 您可以在 assigner 的配置中设置 `gpu_assign_thr=N`,这样当超过 N 个 GT boxes 时,assigner 会通过 CPU 计算 IOU。 + + 2. 在 backbone 中设置 `with_cp=True`。 这使用 PyTorch 中的 `sublinear strategy` 来降低 backbone 占用的 GPU 显存。 + + 3. 使用 `config/fp16` 中的示例尝试混合精度训练。`loss_scale` 可能需要针对不同模型进行调整。 + + 4. 你也可以尝试使用 `AvoidCUDAOOM` 来避免该问题。首先它将尝试调用 `torch.cuda.empty_cache()`。如果失败,将会尝试把输入类型转换到 FP16。如果仍然失败,将会把输入从 GPUs 转换到 CPUs 进行计算。这里提供了两个使用的例子: + + ```python + from mmdet.utils import AvoidCUDAOOM + + output = AvoidCUDAOOM.retry_if_cuda_oom(some_function)(input1, input2) + ``` + + 你也可也使用 `AvoidCUDAOOM` 作为装饰器让代码遇到 OOM 的时候继续运行: + + ```python + from mmdet.utils import AvoidCUDAOOM + + @AvoidCUDAOOM.retry_if_cuda_oom + def function(*args, **kwargs): + ... + return xxx + ``` + +- "RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one" + + 1. 这个错误出现在存在参数没有在 forward 中使用,容易在 DDP 中运行不同分支时发生。 + 2. 你可以在 config 设置 `find_unused_parameters = True` 进行训练 (会降低训练速度)。 + 3. 你也可以通过在 config 中的 `optimizer_config` 里设置 `detect_anomalous_params=True` 查找哪些参数没有用到,但是需要 MMCV 的版本 >= 1.4.1。 + +- 训练中保存最好模型 + + 可以通过配置 `default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=1, save_best='auto')`开启。在 `auto` 参数情况下会根据返回的验证结果中的第一个 key 作为选择最优模型的依据,你也可以直接设置评估结果中的 key 来手动设置,例如 `save_best='coco/bbox_mAP'`。 + +- 在 Resume 训练中使用 `ExpMomentumEMAHook` + + 如果在训练中使用了 `ExpMomentumEMAHook`,那么 resume 时候不能仅仅通过命令行参数 `--resume-from` 或 `--cfg-options resume_from` 实现恢复模型参数功能例如 `python tools/train.py configs/yolox/yolox_s_8x8_300e_coco.py --resume-from ./work_dir/yolox_s_8x8_300e_coco/epoch_x.pth`。以 `yolox_s` 算法为例,由于 `ExpMomentumEMAHook` 需要重新加载权重,你可以通过如下做法实现: + + ```python + # 直接打开 configs/yolox/yolox_s_8x8_300e_coco.py 修改所有 resume_from 字段 + resume_from=./work_dir/yolox_s_8x8_300e_coco/epoch_x.pth + custom_hooks=[... + dict( + type='ExpMomentumEMAHook', + resume_from=./work_dir/yolox_s_8x8_300e_coco/epoch_x.pth, + momentum=0.0001, + priority=49) + ] + ``` + +## Evaluation 相关 + +- 使用 COCO Dataset 的测评接口时, 测评结果中 AP 或者 AR = -1 + 1. 根据COCO数据集的定义,一张图像中的中等物体与小物体面积的阈值分别为 9216(96\*96)与 1024(32\*32)。 + 2. 如果在某个区间没有检测框 AP 与 AR 认定为 -1. + +## Model 相关 + +- **ResNet style 参数说明** + + ResNet style 可选参数允许 `pytorch` 和 `caffe`,其差别在于 Bottleneck 模块。Bottleneck 是 `1x1-3x3-1x1` 堆叠结构,在 `caffe` 模式模式下 stride=2 参数放置在第一个 `1x1` 卷积处,而 `pyorch` 模式下 stride=2 放在第二个 `3x3` 卷积处。一个简单示例如下: + + ```python + if self.style == 'pytorch': + self.conv1_stride = 1 + self.conv2_stride = stride + else: + self.conv1_stride = stride + self.conv2_stride = 1 + ``` + +- **ResNeXt 参数说明** + + ResNeXt 来自论文 [`Aggregated Residual Transformations for Deep Neural Networks`](https://arxiv.org/abs/1611.05431). 其引入分组卷积,并且通过变量基数来控制组的数量达到精度和复杂度的平衡,其有两个超参 `baseWidth` 和 `cardinality `来控制内部 Bottleneck 模块的基本宽度和分组数参数。以 MMDetection 中配置名为 `mask_rcnn_x101_64x4d_fpn_mstrain-poly_3x_coco.py` 为例,其中 `mask_rcnn` 代表算法采用 Mask R-CNN,`x101` 代表骨架网络采用 ResNeXt-101,`64x4d`代表 Bottleneck 一共分成 64 组,每组的基本宽度是 4。 + +- **骨架网络 eval 模式说明** + + 因为检测模型通常比较大且输入图片分辨率很高,这会导致检测模型的 batch 很小,通常是 2,这会使得 BatchNorm 在训练过程计算的统计量方差非常大,不如主干网络预训练时得到的统计量稳定,因此在训练是一般都会使用 `norm_eval=True` 模式,直接使用预训练主干网络中的 BatchNorm 统计量,少数使用大 batch 的算法是 `norm_eval=False` 模式,例如 NASFPN。对于没有 ImageNet 预训练的骨架网络,如果 batch 比较小,可以考虑使用 `SyncBN`。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/notes/projects.md b/mmdet_code/mmdetection/docs/zh_cn/notes/projects.md new file mode 100644 index 0000000000000000000000000000000000000000..6b9d300d33bb46b9ae816fb865bef9b27310c7e8 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/notes/projects.md @@ -0,0 +1,48 @@ +# 基于 MMDetection 的项目 + +有许多开源项目都是基于 MMDetection 搭建的,我们在这里列举一部分作为样例,展示如何基于 MMDetection 搭建您自己的项目。 +由于这个页面列举的项目并不完全,我们欢迎社区提交 Pull Request 来更新这个文档。 + +## MMDetection 的拓展项目 + +一些项目拓展了 MMDetection 的边界,如将 MMDetection 拓展支持 3D 检测或者将 MMDetection 用于部署。 +它们展示了 MMDetection 的许多可能性,所以我们在这里也列举一些。 + +- [OTEDetection](https://github.com/opencv/mmdetection): OpenVINO training extensions for object detection. +- [MMDetection3d](https://github.com/open-mmlab/mmdetection3d): OpenMMLab's next-generation platform for general 3D object detection. + +## 研究项目 + +同样有许多研究论文是基于 MMDetection 进行的。许多论文都发表在了顶级的会议或期刊上,或者对社区产生了深远的影响。 +为了向社区提供一个可以参考的论文列表,帮助大家开发或者比较新的前沿算法,我们在这里也遵循会议的时间顺序列举了一些论文。 +MMDetection 中已经支持的算法不在此列。 + +- Involution: Inverting the Inherence of Convolution for Visual Recognition, CVPR21. [\[paper\]](https://arxiv.org/abs/2103.06255)[\[github\]](https://github.com/d-li14/involution) +- Multiple Instance Active Learning for Object Detection, CVPR 2021. [\[paper\]](https://openaccess.thecvf.com/content/CVPR2021/papers/Yuan_Multiple_Instance_Active_Learning_for_Object_Detection_CVPR_2021_paper.pdf)[\[github\]](https://github.com/yuantn/MI-AOD) +- Adaptive Class Suppression Loss for Long-Tail Object Detection, CVPR 2021. [\[paper\]](https://arxiv.org/abs/2104.00885)[\[github\]](https://github.com/CASIA-IVA-Lab/ACSL) +- Generalizable Pedestrian Detection: The Elephant In The Room, CVPR2021. [\[paper\]](https://arxiv.org/abs/2003.08799)[\[github\]](https://github.com/hasanirtiza/Pedestron) +- Group Fisher Pruning for Practical Network Compression, ICML2021. [\[paper\]](https://github.com/jshilong/FisherPruning/blob/main/resources/paper.pdf)[\[github\]](https://github.com/jshilong/FisherPruning) +- Overcoming Classifier Imbalance for Long-tail Object Detection with Balanced Group Softmax, CVPR2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/papers/Li_Overcoming_Classifier_Imbalance_for_Long-Tail_Object_Detection_With_Balanced_Group_CVPR_2020_paper.pdf)[\[github\]](https://github.com/FishYuLi/BalancedGroupSoftmax) +- Coherent Reconstruction of Multiple Humans from a Single Image, CVPR2020. [\[paper\]](https://jiangwenpl.github.io/multiperson/)[\[github\]](https://github.com/JiangWenPL/multiperson) +- Look-into-Object: Self-supervised Structure Modeling for Object Recognition, CVPR 2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/papers/Zhou_Look-Into-Object_Self-Supervised_Structure_Modeling_for_Object_Recognition_CVPR_2020_paper.pdf)[\[github\]](https://github.com/JDAI-CV/LIO) +- Video Panoptic Segmentation, CVPR2020. [\[paper\]](https://arxiv.org/abs/2006.11339)[\[github\]](https://github.com/mcahny/vps) +- D2Det: Towards High Quality Object Detection and Instance Segmentation, CVPR2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/html/Cao_D2Det_Towards_High_Quality_Object_Detection_and_Instance_Segmentation_CVPR_2020_paper.html)[\[github\]](https://github.com/JialeCao001/D2Det) +- CentripetalNet: Pursuing High-quality Keypoint Pairs for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.09119)[\[github\]](https://github.com/KiveeDong/CentripetalNet) +- Learning a Unified Sample Weighting Network for Object Detection, CVPR 2020. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2020/html/Cai_Learning_a_Unified_Sample_Weighting_Network_for_Object_Detection_CVPR_2020_paper.html)[\[github\]](https://github.com/caiqi/sample-weighting-network) +- Scale-equalizing Pyramid Convolution for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2005.03101) [\[github\]](https://github.com/jshilong/SEPC) +- Revisiting the Sibling Head in Object Detector, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.07540)[\[github\]](https://github.com/Sense-X/TSD) +- PolarMask: Single Shot Instance Segmentation with Polar Representation, CVPR2020. [\[paper\]](https://arxiv.org/abs/1909.13226)[\[github\]](https://github.com/xieenze/PolarMask) +- Hit-Detector: Hierarchical Trinity Architecture Search for Object Detection, CVPR2020. [\[paper\]](https://arxiv.org/abs/2003.11818)[\[github\]](https://github.com/ggjy/HitDet.pytorch) +- ZeroQ: A Novel Zero Shot Quantization Framework, CVPR2020. [\[paper\]](https://arxiv.org/abs/2001.00281)[\[github\]](https://github.com/amirgholami/ZeroQ) +- CBNet: A Novel Composite Backbone Network Architecture for Object Detection, AAAI2020. [\[paper\]](https://aaai.org/Papers/AAAI/2020GB/AAAI-LiuY.1833.pdf)[\[github\]](https://github.com/VDIGPKU/CBNet) +- RDSNet: A New Deep Architecture for Reciprocal Object Detection and Instance Segmentation, AAAI2020. [\[paper\]](https://arxiv.org/abs/1912.05070)[\[github\]](https://github.com/wangsr126/RDSNet) +- Training-Time-Friendly Network for Real-Time Object Detection, AAAI2020. [\[paper\]](https://arxiv.org/abs/1909.00700)[\[github\]](https://github.com/ZJULearning/ttfnet) +- Cascade RPN: Delving into High-Quality Region Proposal Network with Adaptive Convolution, NeurIPS 2019. [\[paper\]](https://arxiv.org/abs/1909.06720)[\[github\]](https://github.com/thangvubk/Cascade-RPN) +- Reasoning R-CNN: Unifying Adaptive Global Reasoning into Large-scale Object Detection, CVPR2019. [\[paper\]](http://openaccess.thecvf.com/content_CVPR_2019/papers/Xu_Reasoning-RCNN_Unifying_Adaptive_Global_Reasoning_Into_Large-Scale_Object_Detection_CVPR_2019_paper.pdf)[\[github\]](https://github.com/chanyn/Reasoning-RCNN) +- Learning RoI Transformer for Oriented Object Detection in Aerial Images, CVPR2019. [\[paper\]](https://arxiv.org/abs/1812.00155)[\[github\]](https://github.com/dingjiansw101/AerialDetection) +- SOLO: Segmenting Objects by Locations. [\[paper\]](https://arxiv.org/abs/1912.04488)[\[github\]](https://github.com/WXinlong/SOLO) +- SOLOv2: Dynamic, Faster and Stronger. [\[paper\]](https://arxiv.org/abs/2003.10152)[\[github\]](https://github.com/WXinlong/SOLO) +- Dense Peppoints: Representing Visual Objects with Dense Point Sets. [\[paper\]](https://arxiv.org/abs/1912.11473)[\[github\]](https://github.com/justimyhxu/Dense-RepPoints) +- IterDet: Iterative Scheme for Object Detection in Crowded Environments. [\[paper\]](https://arxiv.org/abs/2005.05708)[\[github\]](https://github.com/saic-vul/iterdet) +- Cross-Iteration Batch Normalization. [\[paper\]](https://arxiv.org/abs/2002.05712)[\[github\]](https://github.com/Howal/Cross-iterationBatchNorm) +- A Ranking-based, Balanced Loss Function Unifying Classification and Localisation in Object Detection, NeurIPS2020 [\[paper\]](https://arxiv.org/abs/2009.13592)[\[github\]](https://github.com/kemaloksuz/aLRPLoss) diff --git a/mmdet_code/mmdetection/docs/zh_cn/overview.md b/mmdet_code/mmdetection/docs/zh_cn/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..5269aed896df8863594295fcf4b64633faf9db1a --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/overview.md @@ -0,0 +1,54 @@ +# 概述 + +本章向您介绍 MMDetection 的整体框架,并提供详细的教程链接。 + +## 什么是 MMDetection + +![图片](https://user-images.githubusercontent.com/12907710/137271636-56ba1cd2-b110-4812-8221-b4c120320aa9.png) + +MMDetection 是一个目标检测工具箱,包含了丰富的目标检测、实例分割、全景分割算法以及相关的组件和模块,下面是它的整体框架: + +MMDetection 由 7 个主要部分组成,apis、structures、datasets、models、engine、evaluation 和 visualization。 + +- **apis** 为模型推理提供高级 API。 +- **structures** 提供 bbox、mask 和 DetDataSample 等数据结构。 +- **datasets** 支持用于目标检测、实例分割和全景分割的各种数据集。 + - **transforms** 包含各种数据增强变换。 + - **samplers** 定义了不同的数据加载器采样策略。 +- **models** 是检测器最重要的部分,包含检测器的不同组件。 + - **detectors** 定义所有检测模型类。 + - **data_preprocessors** 用于预处理模型的输入数据。 + - **backbones** 包含各种骨干网络。 + - **necks** 包含各种模型颈部组件。 + - **dense_heads** 包含执行密集预测的各种检测头。 + - **roi_heads** 包含从 RoI 预测的各种检测头。 + - **seg_heads** 包含各种分割头。 + - **losses** 包含各种损失函数。 + - **task_modules** 为检测任务提供模块,例如 assigners、samplers、box coders 和 prior generators。 + - **layers** 提供了一些基本的神经网络层。 +- **engine** 是运行时组件的一部分。 + - **runner** 为 [MMEngine 的执行器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/runner.html)提供扩展。 + - **schedulers** 提供用于调整优化超参数的调度程序。 + - **optimizers** 提供优化器和优化器封装。 + - **hooks** 提供执行器的各种钩子。 +- **evaluation** 为评估模型性能提供不同的指标。 +- **visualization** 用于可视化检测结果。 + +## 如何使用本指南 + +以下是 MMDetection 的详细指南: + +1. 安装说明见[开始你的第一步](get_started.md)。 + +2. MMDetection 的基本使用方法请参考以下教程。 + + - [训练和测试](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/index.html#train-test) + + - [实用工具](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/index.html#useful-tools) + +3. 参考以下教程深入了解: + + - [基础概念](https://mmdetection.readthedocs.io/zh_CN/latest/advanced_guides/index.html#basic-concepts) + - [组件定制](https://mmdetection.readthedocs.io/zh_CN/latest/advanced_guides/index.html#component-customization) + +4. 对于 MMDetection 2.x 版本的用户,我们提供了[迁移指南](./migration/migration.md),帮助您完成新版本的适配。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/stat.py b/mmdet_code/mmdetection/docs/zh_cn/stat.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea5fbd25b89e5d3d0925e85a63e2d56d1f58678 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/stat.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +import functools as func +import glob +import os.path as osp +import re + +import numpy as np + +url_prefix = 'https://github.com/open-mmlab/mmdetection/blob/main/' + +files = sorted(glob.glob('../configs/*/README.md')) + +stats = [] +titles = [] +num_ckpts = 0 + +for f in files: + url = osp.dirname(f.replace('../', url_prefix)) + + with open(f, 'r') as content_file: + content = content_file.read() + + title = content.split('\n')[0].replace('# ', '').strip() + ckpts = set(x.lower().strip() + for x in re.findall(r'\[model\]\((https?.*)\)', content)) + + if len(ckpts) == 0: + continue + + _papertype = [x for x in re.findall(r'\[([A-Z]+)\]', content)] + assert len(_papertype) > 0 + papertype = _papertype[0] + + paper = set([(papertype, title)]) + + titles.append(title) + num_ckpts += len(ckpts) + + statsmsg = f""" +\t* [{papertype}] [{title}]({url}) ({len(ckpts)} ckpts) +""" + stats.append((paper, ckpts, statsmsg)) + +allpapers = func.reduce(lambda a, b: a.union(b), [p for p, _, _ in stats]) +msglist = '\n'.join(x for _, _, x in stats) + +papertypes, papercounts = np.unique([t for t, _ in allpapers], + return_counts=True) +countstr = '\n'.join( + [f' - {t}: {c}' for t, c in zip(papertypes, papercounts)]) + +modelzoo = f""" +# Model Zoo Statistics + +* Number of papers: {len(set(titles))} +{countstr} + +* Number of checkpoints: {num_ckpts} + +{msglist} +""" + +with open('modelzoo_statistics.md', 'w') as f: + f.write(modelzoo) diff --git a/mmdet_code/mmdetection/docs/zh_cn/switch_language.md b/mmdet_code/mmdetection/docs/zh_cn/switch_language.md new file mode 100644 index 0000000000000000000000000000000000000000..b2c4ad9db394a147483388b245ffb3c72f81642e --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/switch_language.md @@ -0,0 +1,3 @@ +## English + +## 简体中文 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/config.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/config.md new file mode 100644 index 0000000000000000000000000000000000000000..3a670bf8adacee2ddf3e463b5fd7d2ecc7ff6541 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/config.md @@ -0,0 +1,589 @@ +# 学习配置文件 + +MMDetection 和其他 OpenMMLab 仓库使用 [MMEngine 的配置文件系统](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html)。 配置文件使用了模块化和继承设计,以便于进行各类实验。 + +## 配置文件的内容 + +MMDetection 采用模块化设计,所有功能的模块都可以通过配置文件进行配置。 以 Mask R-CNN 为例,我们将根据不同的功能模块介绍配置文件中的各个字段: + +### 模型配置 + +在 mmdetection 的配置中,我们使用 `model` 字段来配置检测算法的组件。 除了 `backbone`、`neck` 等神经网络组件外,还需要 `data_preprocessor`、`train_cfg` 和 `test_cfg`。 `data_preprocessor` 负责对 dataloader 输出的每一批数据进行预处理。 模型配置中的 `train_cfg` 和 `test_cfg` 用于设置训练和测试组件的超参数。 + +```python +model = dict( + type='MaskRCNN', # 检测器名 + data_preprocessor=dict( # 数据预处理器的配置,通常包括图像归一化和 padding + type='DetDataPreprocessor', # 数据预处理器的类型,参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.data_preprocessors.DetDataPreprocessor + mean=[123.675, 116.28, 103.53], # 用于预训练骨干网络的图像归一化通道均值,按 R、G、B 排序 + std=[58.395, 57.12, 57.375], # 用于预训练骨干网络的图像归一化通道标准差,按 R、G、B 排序 + bgr_to_rgb=True, # 是否将图片通道从 BGR 转为 RGB + pad_mask=True, # 是否填充实例分割掩码 + pad_size_divisor=32), # padding 后的图像的大小应该可以被 ``pad_size_divisor`` 整除 + backbone=dict( # 主干网络的配置文件 + type='ResNet', # 主干网络的类别,可用选项请参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.backbones.ResNet + depth=50, # 主干网络的深度,对于 ResNet 和 ResNext 通常设置为 50 或 101 + num_stages=4, # 主干网络状态(stages)的数目,这些状态产生的特征图作为后续的 head 的输入 + out_indices=(0, 1, 2, 3), # 每个状态产生的特征图输出的索引 + frozen_stages=1, # 第一个状态的权重被冻结 + norm_cfg=dict( # 归一化层(norm layer)的配置项 + type='BN', # 归一化层的类别,通常是 BN 或 GN + requires_grad=True), # 是否训练归一化里的 gamma 和 beta + norm_eval=True, # 是否冻结 BN 里的统计项 + style='pytorch', # 主干网络的风格,'pytorch' 意思是步长为2的层为 3x3 卷积, 'caffe' 意思是步长为2的层为 1x1 卷积 + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), # 加载通过 ImageNet 预训练的模型 + neck=dict( + type='FPN', # 检测器的 neck 是 FPN,我们同样支持 'NASFPN', 'PAFPN' 等,更多细节可以参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.necks.FPN + in_channels=[256, 512, 1024, 2048], # 输入通道数,这与主干网络的输出通道一致 + out_channels=256, # 金字塔特征图每一层的输出通道 + num_outs=5), # 输出的范围(scales) + rpn_head=dict( + type='RPNHead', # rpn_head 的类型是 'RPNHead', 我们也支持 'GARPNHead' 等,更多细节可以参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.dense_heads.RPNHead + in_channels=256, # 每个输入特征图的输入通道,这与 neck 的输出通道一致 + feat_channels=256, # head 卷积层的特征通道 + anchor_generator=dict( # 锚点(Anchor)生成器的配置 + type='AnchorGenerator', # 大多数方法使用 AnchorGenerator 作为锚点生成器, SSD 检测器使用 `SSDAnchorGenerator`。更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/prior_generators/anchor_generator.py#L18 + scales=[8], # 锚点的基本比例,特征图某一位置的锚点面积为 scale * base_sizes + ratios=[0.5, 1.0, 2.0], # 高度和宽度之间的比率 + strides=[4, 8, 16, 32, 64]), # 锚生成器的步幅。这与 FPN 特征步幅一致。 如果未设置 base_sizes,则当前步幅值将被视为 base_sizes + bbox_coder=dict( # 在训练和测试期间对框进行编码和解码 + type='DeltaXYWHBBoxCoder', # 框编码器的类别,'DeltaXYWHBBoxCoder' 是最常用的,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/coders/delta_xywh_bbox_coder.py#L13 + 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', # 分类分支的损失类型,我们也支持 FocalLoss 等,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/cross_entropy_loss.py#L201 + use_sigmoid=True, # RPN 通常进行二分类,所以通常使用 sigmoid 函数 + los_weight=1.0), # 分类分支的损失权重 + loss_bbox=dict( # 回归分支的损失函数配置 + type='L1Loss', # 损失类型,我们还支持许多 IoU Losses 和 Smooth L1-loss 等,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/losses/smooth_l1_loss.py#L56 + loss_weight=1.0)), # 回归分支的损失权重 + roi_head=dict( # RoIHead 封装了两步(two-stage)/级联(cascade)检测器的第二步 + type='StandardRoIHead', # RoI head 的类型,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/standard_roi_head.py#L17 + bbox_roi_extractor=dict( # 用于 bbox 回归的 RoI 特征提取器 + type='SingleRoIExtractor', # RoI 特征提取器的类型,大多数方法使用 SingleRoIExtractor,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/roi_extractors/single_level_roi_extractor.py#L13 + roi_layer=dict( # RoI 层的配置 + type='RoIAlign', # RoI 层的类别, 也支持 DeformRoIPoolingPack 和 ModulatedDeformRoIPoolingPack,更多细节请参考 https://mmcv.readthedocs.io/en/latest/api.html#mmcv.ops.RoIAlign + output_size=7, # 特征图的输出大小 + sampling_ratio=0), # 提取 RoI 特征时的采样率。0 表示自适应比率 + out_channels=256, # 提取特征的输出通道 + featmap_strides=[4, 8, 16, 32]), # 多尺度特征图的步幅,应该与主干的架构保持一致 + bbox_head=dict( # RoIHead 中 box head 的配置 + type='Shared2FCBBoxHead', # bbox head 的类别,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py#L220 + in_channels=256, # bbox head 的输入通道。 这与 roi_extractor 中的 out_channels 一致 + fc_out_channels=1024, # FC 层的输出特征通道 + roi_feat_size=7, # 候选区域(Region of Interest)特征的大小 + num_classes=80, # 分类的类别数量 + bbox_coder=dict( # 第二阶段使用的框编码器 + type='DeltaXYWHBBoxCoder', # 框编码器的类别,大多数情况使用 'DeltaXYWHBBoxCoder' + target_means=[0.0, 0.0, 0.0, 0.0], # 用于编码和解码框的均值 + target_stds=[0.1, 0.1, 0.2, 0.2]), # 编码和解码的标准差。因为框更准确,所以值更小,常规设置时 [0.1, 0.1, 0.2, 0.2]。 + reg_class_agnostic=False, # 回归是否与类别无关 + loss_cls=dict( # 分类分支的损失函数配 + type='CrossEntropyLoss', # 分类分支的损失类型,我们也支持 FocalLoss 等 + use_sigmoid=False, # 是否使用 sigmoid + loss_weight=1.0), # 分类分支的损失权重 + loss_bbox=dict( # 回归分支的损失函数配置 + type='L1Loss', # 损失类型,我们还支持许多 IoU Losses 和 Smooth L1-loss 等 + loss_weight=1.0)), # 回归分支的损失权重 + mask_roi_extractor=dict( # 用于 mask 生成的 RoI 特征提取器 + type='SingleRoIExtractor', # RoI 特征提取器的类型,大多数方法使用 SingleRoIExtractor + roi_layer=dict( # 提取实例分割特征的 RoI 层配置 + type='RoIAlign', # RoI 层的类型,也支持 DeformRoIPoolingPack 和 ModulatedDeformRoIPoolingPack + output_size=14, # 特征图的输出大小 + sampling_ratio=0), # 提取 RoI 特征时的采样率 + out_channels=256, # 提取特征的输出通道 + featmap_strides=[4, 8, 16, 32]), # 多尺度特征图的步幅 + mask_head=dict( # mask 预测 head 模型 + type='FCNMaskHead', # mask head 的类型,更多细节请参考 https://mmdetection.readthedocs.io/en/latest/api.html#mmdet.models.roi_heads.FCNMaskHead + num_convs=4, # mask head 中的卷积层数 + in_channels=256, # 输入通道,应与 mask roi extractor 的输出通道一致 + conv_out_channels=256, # 卷积层的输出通道 + num_classes=80, # 要分割的类别数 + loss_mask=dict( # mask 分支的损失函数配置 + type='CrossEntropyLoss', # 用于分割的损失类型 + use_mask=True, # 是否只在正确的类中训练 mask + loss_weight=1.0))), # mask 分支的损失权重 + train_cfg = dict( # rpn 和 rcnn 训练超参数的配置 + rpn=dict( # rpn 的训练配置 + assigner=dict( # 分配器(assigner)的配置 + type='MaxIoUAssigner', # 分配器的类型,MaxIoUAssigner 用于许多常见的检测器,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/assigners/max_iou_assigner.py#L14 + pos_iou_thr=0.7, # IoU >= 0.7(阈值) 被视为正样本 + neg_iou_thr=0.3, # IoU < 0.3(阈值) 被视为负样本 + min_pos_iou=0.3, # 将框作为正样本的最小 IoU 阈值 + match_low_quality=True, # 是否匹配低质量的框(更多细节见 API 文档) + ignore_iof_thr=-1), # 忽略 bbox 的 IoF 阈值 + sampler=dict( # 正/负采样器(sampler)的配置 + type='RandomSampler', # 采样器类型,还支持 PseudoSampler 和其他采样器,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/samplers/random_sampler.py#L14 + num=256, # 样本数量。 + pos_fraction=0.5, # 正样本占总样本的比例 + neg_pos_ub=-1, # 基于正样本数量的负样本上限 + add_gt_as_proposals=False), # 采样后是否添加 GT 作为 proposal + allowed_border=-1, # 填充有效锚点后允许的边框 + pos_weight=-1, # 训练期间正样本的权重 + debug=False), # 是否设置调试(debug)模式 + rpn_proposal=dict( # 在训练期间生成 proposals 的配置 + nms_across_levels=False, # 是否对跨层的 box 做 NMS。仅适用于 `GARPNHead` ,naive rpn 不支持 nms cross levels + nms_pre=2000, # NMS 前的 box 数 + nms_post=1000, # NMS 要保留的 box 的数量,只在 GARPNHHead 中起作用 + max_per_img=1000, # NMS 后要保留的 box 数量 + nms=dict( # NMS 的配置 + type='nms', # NMS 的类别 + iou_threshold=0.7 # NMS 的阈值 + ), + min_bbox_size=0), # 允许的最小 box 尺寸 + rcnn=dict( # roi head 的配置。 + assigner=dict( # 第二阶段分配器的配置,这与 rpn 中的不同 + type='MaxIoUAssigner', # 分配器的类型,MaxIoUAssigner 目前用于所有 roi_heads。更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/assigners/max_iou_assigner.py#L14 + pos_iou_thr=0.5, # IoU >= 0.5(阈值)被认为是正样本 + neg_iou_thr=0.5, # IoU < 0.5(阈值)被认为是负样本 + min_pos_iou=0.5, # 将 box 作为正样本的最小 IoU 阈值 + match_low_quality=False, # 是否匹配低质量下的 box(有关更多详细信息,请参阅 API 文档) + ignore_iof_thr=-1), # 忽略 bbox 的 IoF 阈值 + sampler=dict( + type='RandomSampler', # 采样器的类型,还支持 PseudoSampler 和其他采样器,更多细节请参考 https://github.com/open-mmlab/mmdetection/blob/main/mmdet/models/task_modules/samplers/random_sampler.py#L14 + num=512, # 样本数量 + pos_fraction=0.25, # 正样本占总样本的比例 + neg_pos_ub=-1, # 基于正样本数量的负样本上限 + add_gt_as_proposals=True + ), # 采样后是否添加 GT 作为 proposal + mask_size=28, # mask 的大小 + pos_weight=-1, # 训练期间正样本的权重 + debug=False)), # 是否设置调试模式 + test_cfg = dict( # 用于测试 rpn 和 rcnn 超参数的配置 + rpn=dict( # 测试阶段生成 proposals 的配置 + nms_across_levels=False, # 是否对跨层的 box 做 NMS。仅适用于 `GARPNHead`,naive rpn 不支持做 NMS cross levels + nms_pre=1000, # NMS 前的 box 数 + nms_post=1000, # NMS 要保留的 box 的数量,只在 `GARPNHHead` 中起作用 + max_per_img=1000, # NMS 后要保留的 box 数量 + nms=dict( # NMS 的配置 + type='nms', # NMS 的类型 + iou_threshold=0.7 # NMS 阈值 + ), + min_bbox_size=0), # box 允许的最小尺寸 + rcnn=dict( # roi heads 的配置 + score_thr=0.05, # bbox 的分数阈值 + nms=dict( # 第二步的 NMS 配置 + type='nms', # NMS 的类型 + iou_thr=0.5), # NMS 的阈值 + max_per_img=100, # 每张图像的最大检测次数 + mask_thr_binary=0.5))) # mask 预处的阈值 +``` + +### 数据集和评测器配置 + +在使用[执行器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/runner.html) 进行训练、测试、验证时,我们需要配置 [Dataloader](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/dataset.html)。构建数据 dataloader 需要设置数据集(dataset)和数据处理流程(data pipeline)。 由于这部分的配置较为复杂,我们使用中间变量来简化 dataloader 配置的编写。 + +```python +dataset_type = 'CocoDataset' # 数据集类型,这将被用来定义数据集。 +data_root = 'data/coco/' # 数据的根路径。 + +train_pipeline = [ # 训练数据处理流程 + dict(type='LoadImageFromFile'), # 第 1 个流程,从文件路径里加载图像。 + dict( + type='LoadAnnotations', # 第 2 个流程,对于当前图像,加载它的注释信息。 + with_bbox=True, # 是否使用标注框(bounding box), 目标检测需要设置为 True。 + with_mask=True, # 是否使用 instance mask,实例分割需要设置为 True。 + poly2mask=False), # 是否将 polygon mask 转化为 instance mask, 设置为 False 以加速和节省内存。 + dict( + type='Resize', # 变化图像和其标注大小的流程。 + scale=(1333, 800), # 图像的最大尺寸 + keep_ratio=True # 是否保持图像的长宽比。 + ), + dict( + type='RandomFlip', # 翻转图像和其标注的数据增广流程。 + prob=0.5), # 翻转图像的概率。 + dict(type='PackDetInputs') # 将数据转换为检测器输入格式的流程 +] +test_pipeline = [ # 测试数据处理流程 + dict(type='LoadImageFromFile'), # 第 1 个流程,从文件路径里加载图像。 + dict(type='Resize', scale=(1333, 800), keep_ratio=True), # 变化图像大小的流程。 + dict( + type='PackDetInputs', # 将数据转换为检测器输入格式的流程 + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( # 训练 dataloader 配置 + batch_size=2, # 单个 GPU 的 batch size + num_workers=2, # 单个 GPU 分配的数据加载线程数 + persistent_workers=True, # 如果设置为 True,dataloader 在迭代完一轮之后不会关闭数据读取的子进程,可以加速训练 + sampler=dict( # 训练数据的采样器 + type='DefaultSampler', # 默认的采样器,同时支持分布式和非分布式训练。请参考 https://mmengine.readthedocs.io/zh_CN/latest/api/generated/mmengine.dataset.DefaultSampler.html#mmengine.dataset.DefaultSampler + shuffle=True), # 随机打乱每个轮次训练数据的顺序 + batch_sampler=dict(type='AspectRatioBatchSampler'), # 批数据采样器,用于确保每一批次内的数据拥有相似的长宽比,可用于节省显存 + dataset=dict( # 训练数据集的配置 + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', # 标注文件路径 + data_prefix=dict(img='train2017/'), # 图片路径前缀 + filter_cfg=dict(filter_empty_gt=True, min_size=32), # 图片和标注的过滤配置 + pipeline=train_pipeline)) # 这是由之前创建的 train_pipeline 定义的数据处理流程。 +val_dataloader = dict( # 验证 dataloader 配置 + batch_size=1, # 单个 GPU 的 Batch size。如果 batch-szie > 1,组成 batch 时的额外填充会影响模型推理精度 + num_workers=2, # 单个 GPU 分配的数据加载线程数 + persistent_workers=True, # 如果设置为 True,dataloader 在迭代完一轮之后不会关闭数据读取的子进程,可以加速训练 + drop_last=False, # 是否丢弃最后未能组成一个批次的数据 + sampler=dict( + type='DefaultSampler', + shuffle=False), # 验证和测试时不打乱数据顺序 + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, # 开启测试模式,避免数据集过滤图片和标注 + pipeline=test_pipeline)) +test_dataloader = val_dataloader # 测试 dataloader 配置 +``` + +[评测器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/evaluation.html) 用于计算训练模型在验证和测试数据集上的指标。评测器的配置由一个或一组评价指标(Metric)配置组成: + +```python +val_evaluator = dict( # 验证过程使用的评测器 + type='CocoMetric', # 用于评估检测和实例分割的 AR、AP 和 mAP 的 coco 评价指标 + ann_file=data_root + 'annotations/instances_val2017.json', # 标注文件路径 + metric=['bbox', 'segm'], # 需要计算的评价指标,`bbox` 用于检测,`segm` 用于实例分割 + format_only=False) +test_evaluator = val_evaluator # 测试过程使用的评测器 +``` + +由于测试数据集没有标注文件,因此 MMDetection 中的 test_dataloader 和 test_evaluator 配置通常等于val。 如果要保存在测试数据集上的检测结果,则可以像这样编写配置: + +```python +# 在测试集上推理, +# 并将检测结果转换格式以用于提交结果 +test_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file=data_root + 'annotations/image_info_test-dev2017.json', + data_prefix=dict(img='test2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/image_info_test-dev2017.json', + metric=['bbox', 'segm'], + format_only=True, # 只将模型输出转换为 coco 的 JSON 格式并保存 + outfile_prefix='./work_dirs/coco_detection/test') # 要保存的 JSON 文件的前缀 +``` + +### 训练和测试的配置 + +MMEngine 的 Runner 使用 Loop 来控制训练,验证和测试过程。 +用户可以使用这些字段设置最大训练轮次和验证间隔。 + +```python +train_cfg = dict( + type='EpochBasedTrainLoop', # 训练循环的类型,请参考 https://github.com/open-mmlab/mmengine/blob/main/mmengine/runner/loops.py + max_epochs=12, # 最大训练轮次 + val_interval=1) # 验证间隔。每个 epoch 验证一次 +val_cfg = dict(type='ValLoop') # 验证循环的类型 +test_cfg = dict(type='TestLoop') # 测试循环的类型 +``` + +### 优化相关配置 + +`optim_wrapper` 是配置优化相关设置的字段。优化器封装(OptimWrapper)不仅提供了优化器的功能,还支持梯度裁剪、混合精度训练等功能。更多内容请看[优化器封装教程](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/optim_wrapper.html) 。 + +```python +optim_wrapper = dict( # 优化器封装的配置 + type='OptimWrapper', # 优化器封装的类型。可以切换至 AmpOptimWrapper 来启用混合精度训练 + optimizer=dict( # 优化器配置。支持 PyTorch 的各种优化器。请参考 https://pytorch.org/docs/stable/optim.html#algorithms + type='SGD', # 随机梯度下降优化器 + lr=0.02, # 基础学习率 + momentum=0.9, # 带动量的随机梯度下降 + weight_decay=0.0001), # 权重衰减 + clip_grad=None, # 梯度裁剪的配置,设置为 None 关闭梯度裁剪。使用方法请见 https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html + ) +``` + +`param_scheduler` 字段用于配置参数调度器(Parameter Scheduler)来调整优化器的超参数(例如学习率和动量)。 用户可以组合多个调度器来创建所需的参数调整策略。 在 [参数调度器教程](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/param_scheduler.html) 和 [参数调度器 API 文档](https://mmengine.readthedocs.io/zh_CN/latest/api/generated/mmengine.optim._ParamScheduler.html#mmengine.optim._ParamScheduler) 中查找更多信息。 + +```python +param_scheduler = [ + dict( + type='LinearLR', # 使用线性学习率预热 + start_factor=0.001, # 学习率预热的系数 + by_epoch=False, # 按 iteration 更新预热学习率 + begin=0, # 从第一个 iteration 开始 + end=500), # 到第 500 个 iteration 结束 + dict( + type='MultiStepLR', # 在训练过程中使用 multi step 学习率策略 + by_epoch=True, # 按 epoch 更新学习率 + begin=0, # 从第一个 epoch 开始 + end=12, # 到第 12 个 epoch 结束 + milestones=[8, 11], # 在哪几个 epoch 进行学习率衰减 + gamma=0.1) # 学习率衰减系数 +] +``` + +### 钩子配置 + +用户可以在训练、验证和测试循环上添加钩子,以便在运行期间插入一些操作。配置中有两种不同的钩子字段,一种是 `default_hooks`,另一种是 `custom_hooks`。 + +`default_hooks` 是一个字典,用于配置运行时必须使用的钩子。这些钩子具有默认优先级,如果未设置,runner 将使用默认值。如果要禁用默认钩子,用户可以将其配置设置为 `None`。更多内容请看 [钩子教程](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/hook.html) 。 + +```python +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', interval=1), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='DetVisualizationHook')) +``` + +`custom_hooks` 是一个列表。用户可以在这个字段中加入自定义的钩子。 + +```python +custom_hooks = [] +``` + +### 运行相关配置 + +```python +default_scope = 'mmdet' # 默认的注册器域名,默认从此注册器域中寻找模块。请参考 https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/registry.html + +env_cfg = dict( + cudnn_benchmark=False, # 是否启用 cudnn benchmark + mp_cfg=dict( # 多进程设置 + mp_start_method='fork', # 使用 fork 来启动多进程。'fork' 通常比 'spawn' 更快,但可能存在隐患。请参考 https://github.com/pytorch/pytorch/issues/1355 + opencv_num_threads=0), # 关闭 opencv 的多线程以避免系统超负荷 + dist_cfg=dict(backend='nccl'), # 分布式相关设置 +) + +vis_backends = [dict(type='LocalVisBackend')] # 可视化后端,请参考 https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/visualization.html +visualizer = dict( + type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer') +log_processor = dict( + type='LogProcessor', # 日志处理器用于处理运行时日志 + window_size=50, # 日志数值的平滑窗口 + by_epoch=True) # 是否使用 epoch 格式的日志。需要与训练循环的类型保存一致。 + +log_level = 'INFO' # 日志等级 +load_from = None # 从给定路径加载模型检查点作为预训练模型。这不会恢复训练。 +resume = False # 是否从 `load_from` 中定义的检查点恢复。 如果 `load_from` 为 None,它将恢复 `work_dir` 中的最新检查点。 +``` + +## Iter-based 配置 + +MMEngine 的 Runner 除了基于轮次的训练循环(epoch)外,还提供了基于迭代(iteration)的训练循环。 +要使用基于迭代的训练,用户应该修改 `train_cfg`、`param_scheduler`、`train_dataloader`、`default_hooks` 和 `log_processor`。 +以下是将基于 epoch 的 RetinaNet 配置更改为基于 iteration 的示例:configs/retinanet/retinanet_r50_fpn_90k_coco.py + +```python +# iter-based 训练配置 +train_cfg = dict( + _delete_=True, # 忽略继承的配置文件中的值(可选) + type='IterBasedTrainLoop', # iter-based 训练循环 + max_iters=90000, # 最大迭代次数 + val_interval=10000) # 每隔多少次进行一次验证 + + +# 将参数调度器修改为 iter-based +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=90000, + by_epoch=False, + milestones=[60000, 80000], + gamma=0.1) +] + +# 切换至 InfiniteSampler 来避免 dataloader 重启 +train_dataloader = dict(sampler=dict(type='InfiniteSampler')) + +# 将模型检查点保存间隔设置为按 iter 保存 +default_hooks = dict(checkpoint=dict(by_epoch=False, interval=10000)) + +# 将日志格式修改为 iter-based +log_processor = dict(by_epoch=False) +``` + +## 配置文件继承 + +在 `config/_base_` 文件夹下有 4 个基本组件类型,分别是:数据集(dataset),模型(model),训练策略(schedule)和运行时的默认设置(default runtime)。许多方法,例如 Faster R-CNN、Mask R-CNN、Cascade R-CNN、RPN、SSD 能够很容易地构建出来。由 `_base_` 下的组件组成的配置,被我们称为 _原始配置(primitive)_。 + +对于同一文件夹下的所有配置,推荐**只有一个**对应的**原始配置**文件。所有其他的配置文件都应该继承自这个**原始配置**文件。这样就能保证配置文件的最大继承深度为 3。 + +为了便于理解,我们建议贡献者继承现有方法。例如,如果在 Faster R-CNN 的基础上做了一些修改,用户首先可以通过指定 `_base_ = ../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py` 来继承基础的 Faster R-CNN 结构,然后修改配置文件中的必要参数以完成继承。 + +如果你在构建一个与任何现有方法不共享结构的全新方法,那么可以在 `configs` 文件夹下创建一个新的例如 `xxx_rcnn` 文件夹。 + +更多细节请参考 [MMEngine 配置文件教程](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html) 。 + +通过设置 `_base_` 字段,我们可以设置当前配置文件继承自哪些文件。 + +当 `_base_` 为文件路径字符串时,表示继承一个配置文件的内容。 + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' +``` + +当 `_base_` 是多个文件路径的列表时,表示继承多个文件。 + +```python +_base_ = [ + '../_base_/models/mask-rcnn_r50_fpn.py', + '../_base_/datasets/coco_instance.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +``` + +如果需要检查配置文件,可以通过运行 `python tools/misc/print_config.py /PATH/TO/CONFIG` 来查看完整的配置。 + +### 忽略基础配置文件里的部分内容 + +有时,您也许会设置 `_delete_=True` 去忽略基础配置文件里的一些域内容。 您也许可以参照 [MMEngine 配置文件教程](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html) 来获得一些简单的指导。 + +在 MMDetection 里,例如为了改变 Mask R-CNN 的主干网络的某些内容: + +```python +model = dict( + type='MaskRCNN', + 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', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict(...), + rpn_head=dict(...), + roi_head=dict(...)) +``` + +基础配置的 `Mask R-CNN` 使用 `ResNet-50`,在需要将主干网络改成 `HRNet` 的时候,因为 `HRNet` 和 `ResNet` 中有不同的字段,需要使用 `_delete_=True` 将新的键去替换 `backbone` 域内所有老的键。 + +```python +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + _delete_=True, + type='HRNet', + extra=dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128)), + stage4=dict( + num_modules=3, + num_branches=4, + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256))), + init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://msra/hrnetv2_w32')), + neck=dict(...)) +``` + +### 使用配置文件里的中间变量 + +配置文件里会使用一些中间变量,例如数据集里的 `train_pipeline`/`test_pipeline`。我们在定义新的 `train_pipeline`/`test_pipeline` 之后,需要将它们传递到 `data` 里。例如,我们想在训练或测试时,改变 Mask R-CNN 的多尺度策略 (multi scale strategy),`train_pipeline`/`test_pipeline` 是我们想要修改的中间变量。 + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', scale=[(1333, 640), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) +val_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +test_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +``` + +我们首先定义新的 `train_pipeline`/`test_pipeline` 然后传递到 `data` 里。 + +同样的,如果我们想从 `SyncBN` 切换到 `BN` 或者 `MMSyncBN`,我们需要修改配置文件里的每一个 `norm_cfg`。 + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' +norm_cfg = dict(type='BN', requires_grad=True) +model = dict( + backbone=dict(norm_cfg=norm_cfg), + neck=dict(norm_cfg=norm_cfg), + ...) +``` + +### 复用 \_base\_ 文件中的变量 + +如果用户希望在当前配置中复用 base 文件中的变量,则可以通过使用 `{{_base_.xxx}}` 的方式来获取对应变量的拷贝。例如: + +```python +_base_ = './mask-rcnn_r50_fpn_1x_coco.py' + +a = {{_base_.model}} # 变量 a 等于 _base_ 中定义的 model +``` + +## 通过脚本参数修改配置 + +当运行 `tools/train.py` 和 `tools/test.py` 时,可以通过 `--cfg-options` 来修改配置文件。 + +- 更新字典链中的配置 + + 可以按照原始配置文件中的 dict 键顺序地指定配置预选项。例如,使用 `--cfg-options model.backbone.norm_eval=False` 将模型主干网络中的所有 BN 模块都改为 `train` 模式。 + +- 更新配置列表中的键 + + 在配置文件里,一些字典型的配置被包含在列表中。例如,数据训练流程 `data.train.pipeline` 通常是一个列表,比如 `[dict(type='LoadImageFromFile'), ...]`。如果需要将 `'LoadImageFromFile'` 改成 `'LoadImageFromWebcam'`,需要写成下述形式: `--cfg-options data.train.pipeline.0.type=LoadImageFromNDArray`. + +- 更新列表或元组的值 + + 如果要更新的值是列表或元组。例如,配置文件通常设置 `model.data_preprocessor.mean=[123.675, 116.28, 103.53]`. 如果需要改变这个键,可以通过 `--cfg-options model.data_preprocessor.mean="[127,127,127]"` 来重新设置。需要注意,引号 " 是支持列表或元组数据类型所必需的,并且在指定值的引号内**不允许**有空格。 + +## 配置文件名称风格 + +我们遵循以下样式来命名配置文件。建议贡献者遵循相同的风格。 + +``` +{algorithm name}_{model component names [component1]_[component2]_[...]}_{training settings}_{training dataset information}_{testing dataset information}.py +``` + +文件名分为五个部分。 每个部分用`_`连接,每个部分内的单词应该用`-`连接。 + +- `{algorithm name}`: 算法的名称。 它可以是检测器名称,例如 `faster-rcnn`、`mask-rcnn` 等。也可以是半监督或知识蒸馏算法,例如 `soft-teacher`、`lad` 等等 +- `{component names}`: 算法中使用的组件名称,如 backbone、neck 等。例如 `r50-caffe_fpn_gn-head` 表示在算法中使用 caffe 版本的 ResNet50、FPN 和 使用了 Group Norm 的检测头。 +- `{training settings}`: 训练设置的信息,例如 batch 大小、数据增强、损失、参数调度方式和训练最大轮次/迭代。 例如:`4xb4-mixup-giou-coslr-100e` 表示使用 8 个 gpu 每个 gpu 4 张图、mixup 数据增强、GIoU loss、余弦退火学习率,并训练 100 个 epoch。 + 缩写介绍: + - `{gpu x batch_per_gpu}`: GPU 数和每个 GPU 的样本数。`bN` 表示每个 GPU 上的 batch 大小为 N。例如 `4x4b` 是 4 个 GPU 每个 GPU 4 张图的缩写。如果没有注明,默认为 8 卡每卡 2 张图。 + - `{schedule}`: 训练方案,选项是 `1x`、 `2x`、 `20e` 等。`1x` 和 `2x` 分别代表 12 epoch 和 24 epoch,`20e` 在级联模型中使用,表示 20 epoch。对于 `1x`/`2x`,初始学习率在第 8/16 和第 11/22 epoch 衰减 10 倍;对于 `20e` ,初始学习率在第 16 和第 19 epoch 衰减 10 倍。 +- `{training dataset information}`: 训练数据集,例如 `coco`, `coco-panoptic`, `cityscapes`, `voc-0712`, `wider-face`。 +- `{testing dataset information}` (可选): 测试数据集,用于训练和测试在不同数据集上的模型配置。 如果没有注明,则表示训练和测试的数据集类型相同。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/dataset_prepare.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/dataset_prepare.md new file mode 100644 index 0000000000000000000000000000000000000000..1caad856af0891016aebe317bb3be4581fabf080 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/dataset_prepare.md @@ -0,0 +1,362 @@ +## 数据集准备 + +### 基础检测数据集准备 + +MMDetection 支持多个公共数据集,包括 [COCO](https://cocodataset.org/), [Pascal VOC](http://host.robots.ox.ac.uk/pascal/VOC), [Cityscapes](https://www.cityscapes-dataset.com/) 和 [其他更多数据集](https://github.com/open-mmlab/mmdetection/tree/main/configs/_base_/datasets)。 + +一些公共数据集,比如 Pascal VOC 及其镜像数据集,或者 COCO 等数据集都可以从官方网站或者镜像网站获取。注意:在检测任务中,Pascal VOC 2012 是 Pascal VOC 2007 的无交集扩展,我们通常将两者一起使用。 我们建议将数据集下载,然后解压到项目外部的某个文件夹内,然后通过符号链接的方式,将数据集根目录链接到 `$MMDETECTION/data` 文件夹下, 如果你的文件夹结构和下方不同的话,你需要在配置文件中改变对应的路径。 + +我们提供了下载 COCO 等数据集的脚本,你可以运行 `python tools/misc/download_dataset.py --dataset-name coco2017` 下载 COCO 数据集。 对于中国境内的用户,我们也推荐通过开源数据平台 [OpenDataLab](https://opendatalab.com/?source=OpenMMLab%20GitHub) 来下载数据,以获得更好的下载体验。 + +更多用法请参考[数据集下载](./useful_tools.md#dataset-download) + +```text +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ ├── cityscapes +│ │ ├── annotations +│ │ ├── leftImg8bit +│ │ │ ├── train +│ │ │ ├── val +│ │ ├── gtFine +│ │ │ ├── train +│ │ │ ├── val +│ ├── VOCdevkit +│ │ ├── VOC2007 +│ │ ├── VOC2012 +``` + +有些模型需要额外的 [COCO-stuff](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip) 数据集,比如 HTC,DetectoRS 和 SCNet,你可以下载并解压它们到 `coco` 文件夹下。文件夹会是如下结构: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +``` + +PanopticFPN 等全景分割模型需要额外的 [COCO Panoptic](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip) 数据集,你可以下载并解压它们到 `coco/annotations` 文件夹下。文件夹会是如下结构: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── panoptic_train2017.json +│ │ │ ├── panoptic_train2017 +│ │ │ ├── panoptic_val2017.json +│ │ │ ├── panoptic_val2017 +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +``` + +Cityscape 数据集的标注格式需要转换,以与 COCO 数据集标注格式保持一致,使用 `tools/dataset_converters/cityscapes.py` 来完成转换: + +```shell +pip install cityscapesscripts + +python tools/dataset_converters/cityscapes.py \ + ./data/cityscapes \ + --nproc 8 \ + --out-dir ./data/cityscapes/annotations +``` + +### COCO Caption 数据集准备 + +COCO Caption 采用的是 COCO2014 数据集作为图片,并且使用了 karpathy 的标注, + +首先你需要下载 COCO2014 数据集 + +```shell +python tools/misc/download_dataset.py --dataset-name coco2014 --unzip +``` + +数据集会下载到当前路径的 `data/coco` 下。然后下载 karpathy 的标注 + +```shell +cd data/coco/annotations +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_train.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_val_gt.json +wget https://storage.googleapis.com/sfr-vision-language-research/datasets/coco_karpathy_test_gt.json +``` + +最终直接可用于训练和测试的数据集文件夹结构如下: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── coco_karpathy_train.json +│ │ │ ├── coco_karpathy_test.json +│ │ │ ├── coco_karpathy_val.json +│ │ │ ├── coco_karpathy_val_gt.json +│ │ │ ├── coco_karpathy_test_gt.json +│ │ ├── train2014 +│ │ ├── val2014 +│ │ ├── test2014 +``` + +### COCO semantic 数据集准备 + +COCO 语义分割有两种类型标注,主要差别在于类别名定义不一样,因此处理方式也有两种,第一种是直接使用 stuffthingmaps 数据集,第二种是使用 panoptic 数据集。 + +**(1) 使用 stuffthingmaps 数据集** + +该数据集的下载地址为 [stuffthingmaps_trainval2017](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip),请下载后解压到 `data/coco` 文件夹下。 + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +``` + +该数据集不同于标准的 COCO 类别标注,其包括 172 个类: 80 thing 类、91 stuff 类和 1 个 'unlabeled',其每个类别的说明见 https://github.com/nightrome/cocostuff/blob/master/labels.md + +虽然只标注了 172 个类别,但是 `stuffthingmaps` 中最大标签 id 是 182,中间有些类别是没有标注的,并且第 0 类的 `unlabeled` 类别被移除。因此最终的 `stuffthingmaps` 图片中每个位置的值对应的类别关系见 https://github.com/kazuto1011/deeplab-pytorch/blob/master/data/datasets/cocostuff/labels.txt + +考虑到训练高效和方便用户,在开启训练或者评估前,我们需要将没有标注的 12 个类移除,这 12 个类的名字为: `street sign、hat、shoe、eye glasses、plate、mirror、window、desk、door、blender、hair brush`,最终可用于训练和评估的类别信息见 `mmdet/datasets/coco_semantic.py` + +你可以使用 `tools/dataset_converters/coco_stuff164k.py` 来完成将下载的 `stuffthingmaps` 转换为直接可以训练和评估的数据集,转换后的数据集文件夹结构如下: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── stuffthingmaps +│ │ ├── stuffthingmaps_semseg +``` + +`stuffthingmaps_semseg` 即为新生成的可以直接训练和测试的 COCO 语义分割数据集。 + +**(2) 使用 panoptic 数据集** + +通过 panoptic 标注生成的语义分割数据集类别数相比使用 `stuffthingmaps` 数据集生成的会少一些。首先你需要准备全景分割标注,然后使用如下脚本完成转换 + +```shell +python tools/dataset_converters/prepare_coco_semantic_annos_from_panoptic_annos.py data/coco +``` + +转换后的数据集文件夹结构如下: + +```text +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── panoptic_train2017.json +│ │ │ ├── panoptic_train2017 +│ │ │ ├── panoptic_val2017.json +│ │ │ ├── panoptic_val2017 +│ │ │ ├── panoptic_semseg_train2017 +│ │ │ ├── panoptic_semseg_val2017 +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +``` + +`panoptic_semseg_train2017` 和 `panoptic_semseg_val2017` 即为新生成的可以直接训练和测试的 COCO 语义分割数据集。注意其类别信息就是 COCO 全景分割的类别信息,包括 thing 和 stuff。 + +### RefCOCO 数据集准备 + +[RefCOCO](https://github.com/lichengunc/refer)系列数据集的图像和注释可以通过运行 `tools/misc/download_dataset.py` 下载: + +```shell +python tools/misc/download_dataset.py --dataset-name refcoco --save-dir data/coco --unzip +``` + +然后,目录应该是这样的: + +```text +data +├── coco +│ ├── refcoco +│   │   ├── instances.json +│   │   ├── refs(google).p +│   │   └── refs(unc).p +│   ├── refcoco+ +│   │   ├── instances.json +│   │   └── refs(unc).p +│   ├── refcocog +│   │   ├── instances.json +│   │   ├── refs(google).p +│   │   └── refs(umd).p +| |── train2014 +``` + +### ADE20K 数据集准备 + +[ADE20K](http://groups.csail.mit.edu/vision/datasets/ADE20K/)数据集的图像和注释可以通过运行 `tools/misc/download_dataset.py` 下载: + +```shell +python tools/misc/download_dataset.py --dataset-name ade20k_2016 --save-dir data --unzip +``` + +然后将注释移至`data/ADEChallengeData2016`目录,并运行预处理脚本以产生coco格式注释: + +```shell +mv data/annotations_instance data/ADEChallengeData2016/ +mv data/categoryMapping.txt data/ADEChallengeData2016/ +mv data/imgCatIds.json data/ADEChallengeData2016/ +python tools/dataset_converters/ade20k2coco.py data/ADEChallengeData2016 --task panoptic +python tools/dataset_converters/ade20k2coco.py data/ADEChallengeData2016 --task instance +``` + +然后,目录应该是这样的: + +```text +data +├── ADEChallengeData2016 +│   ├── ade20k_instance_train.json +│   ├── ade20k_instance_val.json +│   ├── ade20k_panoptic_train +| | ├── ADE_train_00000001.png +| | ├── ADE_train_00000002.png +| | ├── ... +│   ├── ade20k_panoptic_train.json +│   ├── ade20k_panoptic_val +| | ├── ADE_val_00000001.png +| | ├── ADE_val_00000002.png +| | ├── ... +│   ├── ade20k_panoptic_val.json +│   ├── annotations +| | ├── training +| | | ├── ADE_train_00000001.png +| | | ├── ADE_train_00000002.png +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.png +| | | ├── ADE_val_00000002.png +| | | ├── ... +│   ├── annotations_instance +| | ├── training +| | | ├── ADE_train_00000001.png +| | | ├── ADE_train_00000002.png +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.png +| | | ├── ADE_val_00000002.png +| | | ├── ... +│   ├── categoryMapping.txt +│   ├── images +│   | ├── training +| | | ├── ADE_train_00000001.jpg +| | | ├── ADE_train_00000002.jpg +| | | ├── ... +| | ├── validation +| | | ├── ADE_val_00000001.jpg +| | | ├── ADE_val_00000002.jpg +| | | ├── ... +│   ├── imgCatIds.json +│   ├── objectInfo150.txt +| |── sceneCategories.txt +``` + +上述文件夹包括ADE20K的语义分割、实例分割和泛在分割的所有数据。 + +### 从 OpenDataLab 中下载 + +[OpenDataLab](https://opendatalab.com/) 为人工智能研究者提供免费开源的数据集,通过 OpenDataLab,研究者可以获得格式统一的各领域经典数据集。通过平台的搜索功能,研究者可以迅速便捷地找到自己所需数据集;通过平台的统一格式,研究者可以便捷地对跨数据集任务进行开发。 + +目前,MIM 支持使用一条命令行从 OpenDataLab 中下载 VOC 和 COCO 数据集,后续将支持更多数据集。你也可以直接访问 OpenDataLab 平台下载你所需的数据集,然后将其转化为 MMDetection 所要求的格式。 + +如果使用 MIM 下载,请确保版本大于 v0.3.8,你可以使用如下命令更新: + +```Bash +pip install -U openmim +``` + +```Bash +# install OpenXLab CLI tools +pip install -U openxlab +# log in OpenXLab, registry +openxlab login + +# download voc2007 and preprocess by MIM +mim download mmdet --dataset voc2007 + +# download voc2012 and preprocess by MIM +mim download mmdet --dataset voc2012 + +# download coco2017 and preprocess by MIM +mim download mmdet --dataset coco2017 +``` + +### ODinW 数据集准备 + +ODinW 数据集来自 GLIP 论文,用于评估预训练模型泛化性能。一共包括 ODinW-13 和 ODinW-35 两个版本,其中 ODinW-35 包括了 ODinW-13 的所有数据。 目前数据托管在 [huggingface](https://huggingface.co/GLIPModel/GLIP) + +请确保你提前安装好了 [git lfs](https://git-lfs.com), 然后按照如下命令下载 + +```shell +cd mmdetection + +git lfs install +# 我们不需要下载权重 +GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/GLIPModel/GLIP + +cd GLIP +git lfs pull --include="odinw_35" +``` + +下载完成后,目录结构如下所示: + +```text +mmdetection +├── GLIP +| ├── odinw_35 +| | ├── AerialMaritimeDrone.zip +| | ├── AmericanSignLanguageLetters.zip +... +``` + +你可以采用如下命令全部解压并移动到 `mmdetection/data` 路径下: + +```shell +#!/bin/bash + +folder="./GLIP/odinw_35/" + +find "$folder" -type f -name "*.zip" | while read -r file; do + unzip "$file" -d "$(dirname "$file")" +done + +mv GLIP/odinw_35 data/ +``` + +最终结构如下所示: + +```text +mmdetection +├── tools +├── configs +├── data +| ├── odinw_35 +| | ├── AerialMaritimeDrone +... +│ ├── coco +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/deploy.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/deploy.md new file mode 100644 index 0000000000000000000000000000000000000000..f796b004f0babb4b965cf96dd7f28cfb10c4caf0 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/deploy.md @@ -0,0 +1,174 @@ +# 模型部署 + +[MMDeploy](https://github.com/open-mmlab/mmdeploy) 是 OpenMMLab 的部署仓库,负责包括 MMPretrain、MMDetection 等在内的各算法库的部署工作。 +你可以从[这里](https://mmdeploy.readthedocs.io/zh_CN/1.x/04-supported-codebases/mmdet.html)获取 MMDeploy 对 MMDetection 部署支持的最新文档。 + +本文的结构如下: + +- [安装](#安装) +- [模型转换](#模型转换) +- [模型规范](#模型规范) +- [模型推理](#模型推理) + - [后端模型推理](#后端模型推理) + - [SDK 模型推理](#sdk-模型推理) +- [模型支持列表](#模型支持列表) +- + +## 安装 + +请参考[此处](https://mmdetection.readthedocs.io/en/latest/get_started.html)安装 mmdet。然后,按照[说明](https://mmdeploy.readthedocs.io/zh_CN/1.x/get_started.html#mmdeploy)安装 mmdeploy。 + +```{note} +如果安装的是 mmdeploy 预编译包,那么也请通过 'git clone https://github.com/open-mmlab/mmdeploy.git --depth=1' 下载 mmdeploy 源码。因为它包含了部署时要用到的配置文件 +``` + +## 模型转换 + +假设在安装步骤中,mmdetection 和 mmdeploy 代码库在同级目录下,并且当前的工作目录为 mmdetection 的根目录,那么以 [Faster R-CNN](https://github.com/open-mmlab/mmdetection/blob/main/configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py) 模型为例,你可以从[此处](https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth)下载对应的 checkpoint,并使用以下代码将之转换为 onnx 模型: + +```python +from mmdeploy.apis import torch2onnx +from mmdeploy.backend.sdk.export_info import export2SDK + +img = 'demo/demo.jpg' +work_dir = 'mmdeploy_models/mmdet/onnx' +save_file = 'end2end.onnx' +deploy_cfg = '../mmdeploy/configs/mmdet/detection/detection_onnxruntime_dynamic.py' +model_cfg = 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model_checkpoint = 'faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' +device = 'cpu' + +# 1. convert model to onnx +torch2onnx(img, work_dir, save_file, deploy_cfg, model_cfg, + model_checkpoint, device) + +# 2. extract pipeline info for inference by MMDeploy SDK +export2SDK(deploy_cfg, model_cfg, work_dir, pth=model_checkpoint, + device=device) +``` + +转换的关键之一是使用正确的配置文件。项目中已内置了各后端部署[配置文件](https://github.com/open-mmlab/mmdeploy/tree/1.x/configs/mmdet)。 +文件的命名模式是: + +``` +{task}/{task}_{backend}-{precision}_{static | dynamic}_{shape}.py +``` + +其中: + +- **{task}:** mmdet 中的任务 + + mmdet 任务有2种:物体检测(detection)、实例分割(instance-seg)。例如,`RetinaNet`、`Faster R-CNN`、`DETR`等属于前者。`Mask R-CNN`、`SOLO`等属于后者。更多`模型-任务`的划分,请参考章节[模型支持列表](#模型支持列表)。 + + **请务必**使用 `detection/detection_*.py` 转换检测模型,使用 `instance-seg/instance-seg_*.py` 转换实例分割模型。 + +- **{backend}:** 推理后端名称。比如,onnxruntime、tensorrt、pplnn、ncnn、openvino、coreml 等等 + +- **{precision}:** 推理精度。比如,fp16、int8。不填表示 fp32 + +- **{static | dynamic}:** 动态、静态 shape + +- **{shape}:** 模型输入的 shape 或者 shape 范围 + +在上例中,你也可以把 `Faster R-CNN` 转为其他后端模型。比如使用`detection_tensorrt-fp16_dynamic-320x320-1344x1344.py`,把模型转为 tensorrt-fp16 模型。 + +```{tip} +当转 tensorrt 模型时, --device 需要被设置为 "cuda" +``` + +## 模型规范 + +在使用转换后的模型进行推理之前,有必要了解转换结果的结构。 它存放在 `--work-dir` 指定的路路径下。 + +上例中的`mmdeploy_models/mmdet/onnx`,结构如下: + +``` +mmdeploy_models/mmdet/onnx +├── deploy.json +├── detail.json +├── end2end.onnx +└── pipeline.json +``` + +重要的是: + +- **end2end.onnx**: 推理引擎文件。可用 ONNX Runtime 推理 +- ***xxx*.json**: mmdeploy SDK 推理所需的 meta 信息 + +整个文件夹被定义为**mmdeploy SDK model**。换言之,**mmdeploy SDK model**既包括推理引擎,也包括推理 meta 信息。 + +## 模型推理 + +## 后端模型推理 + +以上述模型转换后的 `end2end.onnx` 为例,你可以使用如下代码进行推理: + +```python +from mmdeploy.apis.utils import build_task_processor +from mmdeploy.utils import get_input_shape, load_config +import torch + +deploy_cfg = '../mmdeploy/configs/mmdet/detection/detection_onnxruntime_dynamic.py' +model_cfg = 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +device = 'cpu' +backend_model = ['mmdeploy_models/mmdet/onnx/end2end.onnx'] +image = 'demo/demo.jpg' + +# read deploy_cfg and model_cfg +deploy_cfg, model_cfg = load_config(deploy_cfg, model_cfg) + +# build task and backend model +task_processor = build_task_processor(model_cfg, deploy_cfg, device) +model = task_processor.build_backend_model(backend_model) + +# process input image +input_shape = get_input_shape(deploy_cfg) +model_inputs, _ = task_processor.create_input(image, input_shape) + +# do model inference +with torch.no_grad(): + result = model.test_step(model_inputs) + +# visualize results +task_processor.visualize( + image=image, + model=model, + result=result[0], + window_name='visualize', + output_file='output_detection.png') +``` + +## SDK 模型推理 + +你也可以参考如下代码,对 SDK model 进行推理: + +```python +from mmdeploy_python import Detector +import cv2 + +img = cv2.imread('demo/demo.jpg') + +# create a detector +detector = Detector(model_path='mmdeploy_models/mmdet/onnx', + device_name='cpu', device_id=0) +# perform inference +bboxes, labels, masks = detector(img) + +# visualize inference result +indices = [i for i in range(len(bboxes))] +for index, bbox, label_id in zip(indices, bboxes, labels): + [left, top, right, bottom], score = bbox[0:4].astype(int), bbox[4] + if score < 0.3: + continue + + cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0)) + +cv2.imwrite('output_detection.png', img) +``` + +除了python API,mmdeploy SDK 还提供了诸如 C、C++、C#、Java等多语言接口。 +你可以参考[样例](https://github.com/open-mmlab/mmdeploy/tree/1.x/demo)学习其他语言接口的使用方法。 + +## 模型支持列表 + +请参考[这里](https://mmdeploy.readthedocs.io/zh_CN/1.x/04-supported-codebases/mmdet.html#id6) diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/finetune.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/finetune.md new file mode 100644 index 0000000000000000000000000000000000000000..66bad94e6013b3f0e3ac08c13d48f8ca7aa8f132 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/finetune.md @@ -0,0 +1,96 @@ +# 模型微调 + +在 COCO 数据集上预训练的检测器可以作为其他数据集(例如 CityScapes 和 KITTI 数据集)优质的预训练模型。 +本教程将指导用户如何把 [ModelZoo](../model_zoo.md) 中提供的模型用于其他数据集中并使得当前所训练的模型获得更好性能。 + +以下是在新数据集中微调模型需要的两个步骤。 + +- 按 [教程2:自定义数据集](../advanced_guides/customize_dataset.md) 中的方法对新数据集添加支持中的方法对新数据集添加支持 +- 按照本教程中所讨论方法,修改配置信息 + +接下来将会以 Cityscapes Dataset 上的微调过程作为例子,具体讲述用户需要在配置中修改的五个部分。 + +## 继承基础配置 + +为了减轻编写整个配置的负担并减少漏洞的数量, MMDetection V3.0 支持从多个现有配置中继承配置信息。微调 MaskRCNN 模型的时候,新的配置信息需要使用从 `_base_/models/mask_rcnn_r50_fpn.py` 中继承的配置信息来构建模型的基本结构。当使用 Cityscapes 数据集时,新的配置信息可以简便地从`_base_/datasets/cityscapes_instance.py` 中继承。对于训练过程的运行设置部分,例如 `logger settings`,配置文件可以从 `_base_/default_runtime.py` 中继承。对于训练计划的配置则可以从`_base_/schedules/schedule_1x.py` 中继承。这些配置文件存放于 `configs` 目录下,用户可以选择全部内容的重新编写而不是使用继承方法。 + +```python +_base_ = [ + '../_base_/models/mask_rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py', + '../_base_/schedules/schedule_1x.py' +] +``` + +## Head 的修改 + +接下来新的配置还需要根据新数据集的类别数量对 Head 进行修改。只需要对 roi_head 中的 `num_classes`进行修改。修改后除了最后的预测模型的 Head 之外,预训练模型的权重的大部分都会被重新使用。 + +```python +model = dict( + roi_head=dict( + bbox_head=dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[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='SmoothL1Loss', beta=1.0, loss_weight=1.0)), + mask_head=dict( + type='FCNMaskHead', + num_convs=4, + in_channels=256, + conv_out_channels=256, + num_classes=8, + loss_mask=dict( + type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) +``` + +## 数据集的修改 + +用户可能还需要准备数据集并编写有关数据集的配置,可在 [Customize Datasets](../advanced_guides/customize_dataset.md) 中获取更多信息。目前 MMDetection V3.0 的配置文件已经支持 VOC、WIDERFACE、COCO、LIVS、OpenImages、DeepFashion、Objects365 和 Cityscapes Dataset 的数据集信息。 + +## 训练策略的修改 + +微调超参数与默认的训练策略不同。它通常需要更小的学习率和更少的训练回合。 + +```python +# 优化器 +# batch size 为 8 时的 lr 配置 +optim_wrapper = dict(optimizer=dict(lr=0.01)) + +# 学习率 +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=8, + by_epoch=True, + milestones=[7], + gamma=0.1) +] + +# 设置 max epoch +train_cfg = dict(max_epochs=8) + +# 设置 log config +default_hooks = dict(logger=dict(interval=100)), + +``` + +## 使用预训练模型 + +如果要使用预训练模型,可以在 `load_from` 中查阅新的配置信息,用户需要在训练开始之前下载好需要的模型权重,从而避免在训练过程中浪费了宝贵时间。 + +```python +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth' # noqa +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/index.rst b/mmdet_code/mmdetection/docs/zh_cn/user_guides/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..5abc50ad1cd991bb024503c067d0c99f7e79233d --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/index.rst @@ -0,0 +1,34 @@ +训练 & 测试 +************** + +MMDetection 在 `Model Zoo `_ 中提供了数百个预训练的检测模型, +并支持多种标准数据集格式,包括 Pascal VOC、COCO、CityScapes、LVIS 等。本文档将展示如何使用这些模型和数据集来执行常见的训练和测试任务: + +.. toctree:: + :maxdepth: 1 + + config.md + inference.md + dataset_prepare.md + test.md + train.md + new_model.md + finetune.md + test_results_submission.md + init_cfg.md + single_stage_as_rpn.md + semi_det.md + + +实用工具 +************ + +.. toctree:: + :maxdepth: 1 + + useful_tools.md + useful_hooks.md + visualization.md + robustness_benchmarking.md + deploy.md + label_studio.md diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/inference.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/inference.md new file mode 100644 index 0000000000000000000000000000000000000000..a0fb08faeb0f0d5dba3901ff29e96da3d6476de7 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/inference.md @@ -0,0 +1,438 @@ +# 使用已有模型在标准数据集上进行推理 + +MMDetection 提供了许多预训练好的检测模型,可以在 [Model Zoo](https://mmdetection.readthedocs.io/zh_CN/latest/model_zoo.html) 查看具体有哪些模型。 + +推理具体指使用训练好的模型来检测图像上的目标,本文将会展示具体步骤。 + +在 MMDetection 中,一个模型被定义为一个[配置文件](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/config.html) 和对应被存储在 checkpoint 文件内的模型参数的集合。 + +首先,我们建议从 [RTMDet](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet) 开始,其 [配置](https://github.com/open-mmlab/mmdetection/blob/main/configs/rtmdet/rtmdet_l_8xb32-300e_coco.py) 文件和 [checkpoint](https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_l_8xb32-300e_coco/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth) 文件在此。 +我们建议将 checkpoint 文件下载到 `checkpoints` 文件夹内。 + +## 推理的高层编程接口——推理器 + +在 OpenMMLab 中,所有的推理操作都被统一到了推理器 `Inferencer` 中。推理器被设计成为一个简洁易用的 API,它在不同的 OpenMMLab 库中都有着非常相似的接口。 +下面介绍的演示样例都放在 [demo/inference_demo.ipynb](https://github.com/open-mmlab/mmdetection/blob/main/demo/inference_demo.ipynb) 中方便大家尝试。 + +### 基础用法 + +使用 `DetInferencer`,您只需 3 行代码就可以获得推理结果。 + +```python +from mmdet.apis import DetInferencer + +# 初始化模型 +inferencer = DetInferencer('rtmdet_tiny_8xb32-300e_coco') + +# 推理示例图片 +inferencer('demo/demo.jpg', show=True) +``` + +可视化结果将被显示在一个新窗口中: + +
+ +
+ +```{note} +如果你在没有 GUI 的服务器上,或者通过禁用 X11 转发的 SSH 隧道运行以上命令,`show` 选项将不起作用。然而,你仍然可以通过设置 `out_dir` 参数将可视化数据保存到文件。阅读 [储存结果](#储存结果) 了解详情。 +``` + +### 初始化 + +每个推理器必须使用一个模型进行初始化。初始化时,可以手动选择推理设备。 + +#### 模型初始化 + +- 要用 MMDetection 的预训练模型进行推理,只需要把它的名字传给参数 `model`,权重将自动从 OpenMMLab 的模型库中下载和加载。 + + ```python + inferencer = DetInferencer(model='rtmdet_tiny_8xb32-300e_coco') + ``` + + 在 MMDetection 中有一个非常容易的方法,可以列出所有模型名称。 + + ```python + # models 是一个模型名称列表,它们将自动打印 + models = DetInferencer.list_models('mmdet') + ``` + + 你可以通过将权重的路径或 URL 传递给 `weights` 来让推理器加载自定义的权重。 + + ```python + inferencer = DetInferencer(model='rtmdet_tiny_8xb32-300e_coco', weights='path/to/rtmdet.pth') + ``` + +- 要加载自定义的配置和权重,你可以把配置文件的路径传给 `model`,把权重的路径传给 `weights`。 + + ```python + inferencer = DetInferencer(model='path/to/rtmdet_config.py', weights='path/to/rtmdet.pth') + ``` + +- 默认情况下,[MMEngine](https://github.com/open-mmlab/mmengine/) 会在训练模型时自动将配置文件转储到权重文件中。如果你有一个在 MMEngine 上训练的权重,你也可以将权重文件的路径传递给 `weights`,而不需要指定 `model`: + + ```python + # 如果无法在权重中找到配置文件,则会引发错误。目前 MMDetection 模型库中只有 ddq-detr-4scale_r50 的权重可以这样加载。 + inferencer = DetInferencer(weights='https://download.openmmlab.com/mmdetection/v3.0/ddq/ddq-detr-4scale_r50_8xb2-12e_coco/ddq-detr-4scale_r50_8xb2-12e_coco_20230809_170711-42528127.pth') + ``` + +- 传递配置文件到 `model` 而不指定 `weights` 则会产生一个随机初始化的模型。 + +#### 推理设备 + +每个推理器实例都会跟一个设备绑定。默认情况下,最佳设备是由 [MMEngine](https://github.com/open-mmlab/mmengine/) 自动决定的。你也可以通过指定 `device` 参数来改变设备。例如,你可以使用以下代码在 GPU 1 上创建一个推理器。 + +```python +inferencer = DetInferencer(model='rtmdet_tiny_8xb32-300e_coco', device='cuda:1') +``` + +如要在 CPU 上创建一个推理器: + +```python +inferencer = DetInferencer(model='rtmdet_tiny_8xb32-300e_coco', device='cpu') +``` + +请参考 [torch.device](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) 了解 `device` 参数支持的所有形式。 + +### 推理 + +当推理器初始化后,你可以直接传入要推理的原始数据,从返回值中获取推理结果。 + +#### 输入 + +输入可以是以下任意一种格式: + +- str: 图像的路径/URL。 + + ```python + inferencer('demo/demo.jpg') + ``` + +- array: 图像的 numpy 数组。它应该是 BGR 格式。 + + ```python + import mmcv + array = mmcv.imread('demo/demo.jpg') + inferencer(array) + ``` + +- list: 基本类型的列表。列表中的每个元素都将单独处理。 + + ```python + inferencer(['img_1.jpg', 'img_2.jpg]) + # 列表内混合类型也是允许的 + inferencer(['img_1.jpg', array]) + ``` + +- str: 目录的路径。目录中的所有图像都将被处理。 + + ```python + inferencer('path/to/your_imgs/') + ``` + +#### 输出 + +默认情况下,每个推理器都以字典格式返回预测结果。 + +- `visualization` 包含可视化的预测结果。但默认情况下,它是一个空列表,除非 `return_vis=True`。 + +- `predictions` 包含以 json-可序列化格式返回的预测结果。 + +```python +{ + 'predictions' : [ + # 每个实例都对应于一个输入图像 + { + 'labels': [...], # 整数列表,长度为 (N, ) + 'scores': [...], # 浮点列表,长度为 (N, ) + 'bboxes': [...], # 2d 列表,形状为 (N, 4),格式为 [min_x, min_y, max_x, max_y] + }, + ... + ], + 'visualization' : [ + array(..., dtype=uint8), + ] + } +``` + +如果你想要从模型中获取原始输出,可以将 `return_datasamples` 设置为 `True` 来获取原始的 [DataSample](advanced_guides/structures.md),它将存储在 `predictions` 中。 + +#### 储存结果 + +除了从返回值中获取预测结果,你还可以通过设置 `out_dir` 和 `no_save_pred`/`no_save_vis` 参数将预测结果和可视化结果导出到文件中。 + +```python +inferencer('demo/demo.jpg', out_dir='outputs/', no_save_pred=False) +``` + +结果目录结构如下: + +```text +outputs +├── preds +│ └── demo.json +└── vis + └── demo.jpg +``` + +#### 批量推理 + +你可以通过设置 `batch_size` 来自定义批量推理的批大小。默认批大小为 1。 + +### API + +这里列出了推理器详尽的参数列表。 + +- **DetInferencer.\_\_init\_\_():** + +| 参数 | 类型 | 默认值 | 描述 | +| --------------- | ---------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `model` | str , 可选 | None | 配置文件的路径或 metafile 中定义的模型名称。例如,可以是 'rtmdet-s' 或 'rtmdet_s_8xb32-300e_coco' 或 'configs/rtmdet/rtmdet_s_8xb32-300e_coco.py'。如果未指定模型,用户必须提供 MMEngine 保存的包含配置字符串的 "weights"。 | +| `weights` | str, 可选 | None | 模型权重文件的路径。如果未指定且 `model` 是 metafile 中的模型名称,权重将从 metafile 中加载。 | +| `device` | str, 可选 | None | 推理使用的设备,接受 `torch.device` 允许的所有字符串。例如,'cuda:0' 或 'cpu'。如果为 None,将自动使用可用设备。 默认为 None。 | +| `scope` | str, 可选 | 'mmdet' | 模型的”域名“。 | +| `palette` | str | 'none' | 用于可视化的配色。优先顺序为 palette -> config -> checkpoint。 | +| `show_progress` | bool | True | 控制是否在推理过程中显示进度条。 | + +- **DetInferencer.\_\_call\_\_()** + +| 参数 | 类型 | 默认值 | 描述 | +| -------------------- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `inputs` | str/list/tuple/np.array | **必需** | 它可以是一个图片/文件夹的路径,一个 numpy 数组,或者是一个包含图片路径或 numpy 数组的列表/元组 | +| `batch_size` | int | 1 | 推理的批大小。 | +| `return_vis` | bool | False | 是否返回可视化结果。 | +| `show` | bool | False | 是否在弹出窗口中显示可视化结果。 | +| `wait_time` | float | 0 | 弹窗展示可视化结果的时间间隔。 | +| `no_save_vis` | bool | False | 是否将可视化结果保存到 `out_dir`。默认为保存。 | +| `draw_pred` | bool | True | 是否绘制预测的边界框。 | +| `pred_score_thr` | float | 0.3 | 显示预测框的最低置信度。 | +| `return_datasamples` | bool | False | 是否将结果作为 `DetDataSample` 返回。 如果为 False,则结果将被打包到一个 dict 中。 | +| `print_result` | bool | False | 是否将推理结果打印到控制台。 | +| `no_save_pred` | bool | True | 是否将推理结果保存到 `out_dir`。默认为不保存。 | +| `out_dir` | str | '' | 结果的输出目录。 | +| `texts` | str/list\[str\],可选 | None | 文本提示词。 | +| `stuff_texts` | str/list\[str\],可选 | None | 物体文本提示词。 | +| `custom_entities` | bool | False | 是否使用自定义实体。只用于 GLIP 算法。 | +| \*\*kwargs | | | 传递给 :meth:`preprocess`、:meth:`forward`、:meth:`visualize` 和 :meth:`postprocess` 的其他关键字参数。kwargs 中的每个关键字都应在相应的 `preprocess_kwargs`、`forward_kwargs`、`visualize_kwargs` 和 `postprocess_kwargs` 中。 | + +## 演示脚本样例 + +我们还提供了四个演示脚本,它们是使用高层编程接口实现的。[源码在此](https://github.com/open-mmlab/mmdetection/blob/main/demo) 。 + +### 图片样例 + +这是在单张图片上进行推理的脚本。 + +```shell +python demo/image_demo.py \ + ${IMAGE_FILE} \ + ${CONFIG_FILE} \ + [--weights ${WEIGHTS}] \ + [--device ${GPU_ID}] \ + [--pred-score-thr ${SCORE_THR}] +``` + +运行样例: + +```shell +python demo/image_demo.py demo/demo.jpg \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + --weights checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --device cpu +``` + +### 摄像头样例 + +这是使用摄像头实时图片的推理脚本。 + +```shell +python demo/webcam_demo.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--camera-id ${CAMERA-ID}] \ + [--score-thr ${SCORE_THR}] +``` + +运行样例: + +```shell +python demo/webcam_demo.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth +``` + +### 视频样例 + +这是在视频样例上进行推理的脚本。 + +```shell +python demo/video_demo.py \ + ${VIDEO_FILE} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--score-thr ${SCORE_THR}] \ + [--out ${OUT_FILE}] \ + [--show] \ + [--wait-time ${WAIT_TIME}] +``` + +运行样例: + +```shell +python demo/video_demo.py demo/demo.mp4 \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --out result.mp4 +``` + +#### 视频样例,显卡加速版本 + +这是在视频样例上进行推理的脚本,使用显卡加速。 + +```shell +python demo/video_gpuaccel_demo.py \ + ${VIDEO_FILE} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--device ${GPU_ID}] \ + [--score-thr ${SCORE_THR}] \ + [--nvdecode] \ + [--out ${OUT_FILE}] \ + [--show] \ + [--wait-time ${WAIT_TIME}] + +``` + +运行样例: + +```shell +python demo/video_gpuaccel_demo.py demo/demo.mp4 \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --nvdecode --out result.mp4 +``` + +### 大图推理样例 + +这是在大图上进行切片推理的脚本。 + +```shell +python demo/large_image_demo.py \ + ${IMG_PATH} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --device ${GPU_ID} \ + --show \ + --tta \ + --score-thr ${SCORE_THR} \ + --patch-size ${PATCH_SIZE} \ + --patch-overlap-ratio ${PATCH_OVERLAP_RATIO} \ + --merge-iou-thr ${MERGE_IOU_THR} \ + --merge-nms-type ${MERGE_NMS_TYPE} \ + --batch-size ${BATCH_SIZE} \ + --debug \ + --save-patch +``` + +运行样例: + +```shell +# inferecnce without tta +wget -P checkpoint https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r101_fpn_2x_coco/faster_rcnn_r101_fpn_2x_coco_bbox_mAP-0.398_20200504_210455-1d2dac9c.pth + +python demo/large_image_demo.py \ + demo/large_image.jpg \ + configs/faster_rcnn/faster-rcnn_r101_fpn_2x_coco.py \ + checkpoint/faster_rcnn_r101_fpn_2x_coco_bbox_mAP-0.398_20200504_210455-1d2dac9c.pth + +# inference with tta +wget -P checkpoint https://download.openmmlab.com/mmdetection/v2.0/retinanet/retinanet_r50_fpn_1x_coco/retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth + +python demo/large_image_demo.py \ + demo/large_image.jpg \ + configs/retinanet/retinanet_r50_fpn_1x_coco.py \ + checkpoint/retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth --tta +``` + +## 多模态算法的推理和验证 + +随着多模态视觉算法的不断发展,MMDetection 也完成了对这类算法的支持。这一小节我们通过 GLIP 算法和模型来演示如何使用对应多模态算法的 demo 和 eval 脚本。同时 MMDetection 也在 projects 下完成了 [gradio_demo 项目](../../../projects/gradio_demo/),用户可以参照[文档](../../../projects/gradio_demo/README.md)在本地快速体验 MMDetection 中支持的各类图片输入的任务。 + +### 模型准备 + +首先需要安装多模态依赖: + +```shell +# if source +pip install -r requirements/multimodal.txt + +# if wheel +mim install mmdet[multimodal] +``` + +MMDetection 已经集成了 glip 算法和模型,可以直接使用链接下载使用: + +```shell +cd mmdetection +wget https://download.openmmlab.com/mmdetection/v3.0/glip/glip_tiny_a_mmdet-b3654169.pth +``` + +### 推理演示 + +下载完成后我们就可以利用 `demo` 下的多模态推理脚本完成推理: + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts bench +``` + +demo 效果如下图所示: + +
+ +
+ +如果想进行多种类型的识别,需要使用 `xx. xx` 的格式在 `--texts` 字段后声明目标类型: + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts 'bench. car' +``` + +结果如下图所示: + +
+ +
+ +推理脚本还支持输入一个句子作为 `--texts` 字段的输入: + +```shell +python demo/image_demo.py demo/demo.jpg glip_tiny_a_mmdet-b3654169.pth --texts 'There are a lot of cars here.' +``` + +结果可以参考下图: + +
+ +
+ +### 验证演示 + +MMDetection 支持后的 GLIP 算法对比官方版本没有精度上的损失, benchmark 如下所示: + +| Model | official mAP | mmdet mAP | +| ----------------------- | :----------: | :-------: | +| glip_A_Swin_T_O365.yaml | 42.9 | 43.0 | +| glip_Swin_T_O365.yaml | 44.9 | 44.9 | +| glip_Swin_L.yaml | 51.4 | 51.3 | + +用户可以使用 `test.py` 脚本对模型精度进行验证,使用如下所示: + +```shell +# 1 gpu +python tools/test.py configs/glip/glip_atss_swin-t_fpn_dyhead_pretrain_obj365.py glip_tiny_a_mmdet-b3654169.pth + +# 8 GPU +./tools/dist_test.sh configs/glip/glip_atss_swin-t_fpn_dyhead_pretrain_obj365.py glip_tiny_a_mmdet-b3654169.pth 8 +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/init_cfg.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/init_cfg.md new file mode 100644 index 0000000000000000000000000000000000000000..b58b19d5ab0f4db06cc7467dc9b5e97e39416e19 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/init_cfg.md @@ -0,0 +1,161 @@ +# 权重初始化 + +在训练过程中,适当的初始化策略有利于加快训练速度或获得更⾼的性能。 [MMCV](https://github.com/open-mmlab/mmcv/blob/master/mmcv/cnn/utils/weight_init.py) 提供了一些常⽤的初始化模块的⽅法,如 `nn.Conv2d`。 MMdetection 中的模型初始化主要使⽤ `init_cfg`。⽤⼾可以通过以下两个步骤来初始化模型: + +1. 在 `model_cfg` 中为模型或其组件定义 `init_cfg`,但⼦组件的 `init_cfg` 优先级更⾼,会覆盖⽗模块的 `init_cfg` 。 +2. 像往常一样构建模型,然后显式调⽤ `model.init_weights()` ⽅法,此时模型参数将会被按照配置文件写法进行初始化。 + +MMdetection 初始化工作流的高层 API 调用流程是: + +model_cfg(init_cfg) -> build_from_cfg -> model -> init_weight() -> initialize(self, self.init_cfg) -> children's init_weight() + +### 描述 + +它的数据类型是 dict 或者 list\[dict\],包含了下列键值: + +- `type` (str),包含 `INTIALIZERS` 中的初始化器名称,后面跟着初始化器的参数。 +- `layer`(str 或 list\[str\]),包含 Pytorch 或 MMCV 中基本层的名称,以及将被初始化的可学习参数,例如 `'Conv2d'`,`'DeformConv2d'`。 +- `override` (dict 或 list\[dict\]),包含不继承⾃ `BaseModule` 且其初始化配置与 `layer` 键中的其他层不同的⼦模块。 `type` 中定义的初始化器将适⽤于 `layer` 中定义的所有层,因此如果⼦模块不是 `BaseModule` 的派⽣类但可以与 `layer` 中的层相同的⽅式初始化,则不需要使⽤ `override`。`override` 包含了: + - `type` 后跟初始化器的参数; + - `name` 用以指⽰将被初始化的⼦模块。 + +### 初始化参数 + +从 `mmcv.runner.BaseModule` 或 `mmdet.models` 继承一个新模型。这里我们用 FooModel 来举个例子。 + +```python +import torch.nn as nn +from mmcv.runner import BaseModule + +class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=None): + super(FooModel, self).__init__(init_cfg) + ... +``` + +- 直接在代码中使⽤ `init_cfg` 初始化模型 + + ```python + import torch.nn as nn + from mmcv.runner import BaseModule + # or directly inherit mmdet models + + class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=XXX): + super(FooModel, self).__init__(init_cfg) + ... + ``` + +- 在 `mmcv.Sequential` 或 `mmcv.ModuleList` 代码中直接使⽤ `init_cfg` 初始化模型 + + ```python + from mmcv.runner import BaseModule, ModuleList + + class FooModel(BaseModule) + def __init__(self, + arg1, + arg2, + init_cfg=None): + super(FooModel, self).__init__(init_cfg) + ... + self.conv1 = ModuleList(init_cfg=XXX) + ``` + +- 使⽤配置⽂件中的 `init_cfg` 初始化模型 + + ```python + model = dict( + ... + model = dict( + type='FooModel', + arg1=XXX, + arg2=XXX, + init_cfg=XXX), + ... + ``` + +### init_cfg 的使用 + +1. 用 `layer` 键初始化模型 + + 如果我们只定义了 `layer`, 它只会在 `layer` 键中初始化网络层。 + + 注意: `layer` 键对应的值是 Pytorch 的带有 weights 和 bias 属性的类名(因此不⽀持 `MultiheadAttention` 层)。 + +- 定义⽤于初始化具有相同配置的模块的 `layer` 键。 + + ```python + init_cfg = dict(type='Constant', layer=['Conv1d', 'Conv2d', 'Linear'], val=1) + # ⽤相同的配置初始化整个模块 + ``` + +- 定义⽤于初始化具有不同配置的层的 `layer` 键。 + + ```python + init_cfg = [dict(type='Constant', layer='Conv1d', val=1), + dict(type='Constant', layer='Conv2d', val=2), + dict(type='Constant', layer='Linear', val=3)] + # nn.Conv1d 将被初始化为 dict(type='Constant', val=1) + # nn.Conv2d 将被初始化为 dict(type='Constant', val=2) + # nn.Linear 将被初始化为 dict(type='Constant', val=3) + ``` + +2. 使⽤ `override` 键初始化模型 + +- 当使⽤属性名初始化某些特定部分时,我们可以使⽤ `override` 键, `override` 中的值将忽略 init_cfg 中的值。 + + ```python + # layers: + # self.feat = nn.Conv1d(3, 1, 3) + # self.reg = nn.Conv2d(3, 3, 3) + # self.cls = nn.Linear(1,2) + + init_cfg = dict(type='Constant', + layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(type='Constant', name='reg', val=3, bias=4)) + # self.feat and self.cls 将被初始化为 dict(type='Constant', val=1, bias=2) + # 叫 'reg' 的模块将被初始化为 dict(type='Constant', val=3, bias=4) + ``` + +- 如果 init_cfg 中的 `layer` 为 None,则只会初始化 override 中有 name 的⼦模块,⽽ override 中的 type 和其他参数可以省略。 + + ```python + # layers: + # self.feat = nn.Conv1d(3, 1, 3) + # self.reg = nn.Conv2d(3, 3, 3) + # self.cls = nn.Linear(1,2) + + init_cfg = dict(type='Constant', val=1, bias=2, override=dict(name='reg')) + + # self.feat and self.cls 将被 Pytorch 初始化 + # 叫 'reg' 的模块将被 dict(type='Constant', val=1, bias=2) 初始化 + ``` + +- 如果我们不定义 `layer` 或 `override` 键,它不会初始化任何东西。 + +- 无效的使用 + + ```python + # override 没有 name 键的话是无效的 + init_cfg = dict(type='Constant', layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(type='Constant', val=3, bias=4)) + + # override 有 name 键和其他参数但是没有 type 键也是无效的 + init_cfg = dict(type='Constant', layer=['Conv1d','Conv2d'], val=1, bias=2, + override=dict(name='reg', val=3, bias=4)) + ``` + +3. 使⽤预训练模型初始化模型 + + ```python + init_cfg = dict(type='Pretrained', + checkpoint='torchvision://resnet50') + ``` + +更多细节可以参考 [MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/initialize.html) 的文档 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/label_studio.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/label_studio.md new file mode 100644 index 0000000000000000000000000000000000000000..202122f685402e41bbfb270b445a7b1c04ccf1a8 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/label_studio.md @@ -0,0 +1,255 @@ +# 使用 MMDetection 和 Label-Studio 进行半自动化目标检测标注 + +标注数据是一个费时费力的任务,本文介绍了如何使用 MMDetection 中的 RTMDet 算法联合 Label-Studio 软件进行半自动化标注。具体来说,使用 RTMDet 预测图片生成标注,然后使用 Label-Studio 进行微调标注,社区用户可以参考此流程和方法,将其应用到其他领域。 + +- RTMDet:RTMDet 是 OpenMMLab 自研的高精度单阶段的目标检测算法,开源于 MMDetection 目标检测工具箱中,其开源协议为 Apache 2.0,工业界的用户可以不受限的免费使用。 +- [Label Studio](https://github.com/heartexlabs/label-studio) 是一款优秀的标注软件,覆盖图像分类、目标检测、分割等领域数据集标注的功能。 + +本文将使用[喵喵数据集](https://download.openmmlab.com/mmyolo/data/cat_dataset.zip)的图片,进行半自动化标注。 + +## 环境配置 + +首先需要创建一个虚拟环境,然后安装 PyTorch 和 MMCV。在本文中,我们将指定 PyTorch 和 MMCV 的版本。接下来安装 MMDetection、Label-Studio 和 label-studio-ml-backend,具体步骤如下: + +创建虚拟环境: + +```shell +conda create -n rtmdet python=3.9 -y +conda activate rtmdet +``` + +安装 PyTorch + +```shell +# Linux and Windows CPU only +pip install torch==1.10.1+cpu torchvision==0.11.2+cpu torchaudio==0.10.1 -f https://download.pytorch.org/whl/cpu/torch_stable.html +# Linux and Windows CUDA 11.3 +pip install torch==1.10.1+cu113 torchvision==0.11.2+cu113 torchaudio==0.10.1 -f https://download.pytorch.org/whl/cu113/torch_stable.html +# OSX +pip install torch==1.10.1 torchvision==0.11.2 torchaudio==0.10.1 +``` + +安装 MMCV + +```shell +pip install -U openmim +mim install "mmcv>=2.0.0" +# 安装 mmcv 的过程中会自动安装 mmengine +``` + +安装 MMDetection + +```shell +git clone https://github.com/open-mmlab/mmdetection +cd mmdetection +pip install -v -e . +``` + +安装 Label-Studio 和 label-studio-ml-backend + +```shell +# 安装 label-studio 需要一段时间,如果找不到版本请使用官方源 +pip install label-studio==1.7.2 +pip install label-studio-ml==1.0.9 +``` + +下载rtmdet权重 + +```shell +cd path/to/mmetection +mkdir work_dirs +cd work_dirs +wget https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_m_8xb32-300e_coco/rtmdet_m_8xb32-300e_coco_20220719_112220-229f527c.pth +``` + +## 启动服务 + +启动 RTMDet 后端推理服务: + +```shell +cd path/to/mmetection + +label-studio-ml start projects/LabelStudio/backend_template --with \ +config_file=configs/rtmdet/rtmdet_m_8xb32-300e_coco.py \ +checkpoint_file=./work_dirs/rtmdet_m_8xb32-300e_coco_20220719_112220-229f527c.pth \ +device=cpu \ +--port 8003 +# device=cpu 为使用 CPU 推理,如果使用 GPU 推理,将 cpu 替换为 cuda:0 +``` + +![](https://cdn.vansin.top/picgo20230330131601.png) + +此时,RTMDet 后端推理服务已经启动,后续在 Label-Studio Web 系统中配置 http://localhost:8003 后端推理服务即可。 + +现在启动 Label-Studio 网页服务: + +```shell +label-studio start +``` + +![](https://cdn.vansin.top/picgo20230330132913.png) + +打开浏览器访问 [http://localhost:8080/](http://localhost:8080/) 即可看到 Label-Studio 的界面。 + +![](https://cdn.vansin.top/picgo20230330133118.png) + +我们注册一个用户,然后创建一个 RTMDet-Semiautomatic-Label 项目。 + +![](https://cdn.vansin.top/picgo20230330133333.png) + +我们通过下面的方式下载好示例的喵喵图片,点击 Data Import 导入需要标注的猫图片。 + +```shell +cd path/to/mmetection +mkdir data && cd data + +wget https://download.openmmlab.com/mmyolo/data/cat_dataset.zip && unzip cat_dataset.zip +``` + +![](https://cdn.vansin.top/picgo20230330133628.png) + +![](https://cdn.vansin.top/picgo20230330133715.png) + +然后选择 Object Detection With Bounding Boxes 模板 + +![](https://cdn.vansin.top/picgo20230330133807.png) + +```shell +airplane +apple +backpack +banana +baseball_bat +baseball_glove +bear +bed +bench +bicycle +bird +boat +book +bottle +bowl +broccoli +bus +cake +car +carrot +cat +cell_phone +chair +clock +couch +cow +cup +dining_table +dog +donut +elephant +fire_hydrant +fork +frisbee +giraffe +hair_drier +handbag +horse +hot_dog +keyboard +kite +knife +laptop +microwave +motorcycle +mouse +orange +oven +parking_meter +person +pizza +potted_plant +refrigerator +remote +sandwich +scissors +sheep +sink +skateboard +skis +snowboard +spoon +sports_ball +stop_sign +suitcase +surfboard +teddy_bear +tennis_racket +tie +toaster +toilet +toothbrush +traffic_light +train +truck +tv +umbrella +vase +wine_glass +zebra +``` + +然后将上述类别复制添加到 Label-Studio,然后点击 Save。 + +![](https://cdn.vansin.top/picgo20230330134027.png) + +然后在设置中点击 Add Model 添加 RTMDet 后端推理服务。 + +![](https://cdn.vansin.top/picgo20230330134320.png) + +点击 Validate and Save,然后点击 Start Labeling。 + +![](https://cdn.vansin.top/picgo20230330134424.png) + +看到如下 Connected 就说明后端推理服务添加成功。 + +![](https://cdn.vansin.top/picgo20230330134554.png) + +## 开始半自动化标注 + +点击 Label 开始标注 + +![](https://cdn.vansin.top/picgo20230330134804.png) + +我们可以看到 RTMDet 后端推理服务已经成功返回了预测结果并显示在图片上,我们可以发现这个喵喵预测的框有点大。 + +![](https://cdn.vansin.top/picgo20230403104419.png) + +我们手工拖动框,修正一下框的位置,得到以下修正过后的标注,然后点击 Submit,本张图片就标注完毕了。 + +![](https://cdn.vansin.top/picgo/20230403105923.png) + +我们 submit 完毕所有图片后,点击 exprot 导出 COCO 格式的数据集,就能把标注好的数据集的压缩包导出来了。 + +![](https://cdn.vansin.top/picgo20230330135921.png) + +用 vscode 打开解压后的文件夹,可以看到标注好的数据集,包含了图片和 json 格式的标注文件。 + +![](https://cdn.vansin.top/picgo20230330140321.png) + +到此半自动化标注就完成了,我们可以用这个数据集在 MMDetection 训练精度更高的模型了,训练出更好的模型,然后再用这个模型继续半自动化标注新采集的图片,这样就可以不断迭代,扩充高质量数据集,提高模型的精度。 + +## 使用 MMYOLO 作为后端推理服务 + +如果想在 MMYOLO 中使用 Label-Studio,可以参考在启动后端推理服务时,将 config_file 和 checkpoint_file 替换为 MMYOLO 的配置文件和权重文件即可。 + +```shell +cd path/to/mmetection + +label-studio-ml start projects/LabelStudio/backend_template --with \ +config_file= path/to/mmyolo_config.py \ +checkpoint_file= path/to/mmyolo_weights.pth \ +device=cpu \ +--port 8003 +# device=cpu 为使用 CPU 推理,如果使用 GPU 推理,将 cpu 替换为 cuda:0 +``` + +旋转目标检测和实例分割还在支持中,敬请期待。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/new_model.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/new_model.md new file mode 100644 index 0000000000000000000000000000000000000000..424c4f90f348b6d635644180954f58f5bac85da0 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/new_model.md @@ -0,0 +1,289 @@ +# 在标准数据集上训练自定义模型(待更新) + +在本文中,你将知道如何在标准数据集上训练、测试和推理自定义模型。我们将在 cityscapes 数据集上以自定义 Cascade Mask R-CNN R50 模型为例演示整个过程,为了方便说明,我们将 neck 模块中的 `FPN` 替换为 `AugFPN`,并且在训练中的自动增强类中增加 `Rotate` 或 `TranslateX`。 + +基本步骤如下所示: + +1. 准备标准数据集 +2. 准备你的自定义模型 +3. 准备配置文件 +4. 在标准数据集上对模型进行训练、测试和推理 + +## 准备标准数据集 + +在本文中,我们使用 cityscapes 标准数据集为例进行说明。 + +推荐将数据集根路径采用符号链接方式链接到 `$MMDETECTION/data`。 + +如果你的文件结构不同,你可能需要在配置文件中进行相应的路径更改。标准的文件组织格式如下所示: + +```none +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── annotations +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ ├── cityscapes +│ │ ├── annotations +│ │ ├── leftImg8bit +│ │ │ ├── train +│ │ │ ├── val +│ │ ├── gtFine +│ │ │ ├── train +│ │ │ ├── val +│ ├── VOCdevkit +│ │ ├── VOC2007 +│ │ ├── VOC2012 +``` + +你也可以通过如下方式设定数据集根路径 + +```bash +export MMDET_DATASETS=$data_root +``` + +我们将会使用环境便变量 `$MMDET_DATASETS` 作为数据集的根目录,因此你无需再修改相应配置文件的路径信息。 + +你需要使用脚本 `tools/dataset_converters/cityscapes.py` 将 cityscapes 标注转化为 coco 标注格式。 + +```shell +pip install cityscapesscripts +python tools/dataset_converters/cityscapes.py ./data/cityscapes --nproc 8 --out-dir ./data/cityscapes/annotations +``` + +目前在 `cityscapes `文件夹中的配置文件所对应模型是采用 COCO 预训练权重进行初始化的。 + +如果你的网络不可用或者比较慢,建议你先手动下载对应的预训练权重,否则可能在训练开始时候出现错误。 + +## 准备你的自定义模型 + +第二步是准备你的自定义模型或者训练相关配置。假设你想在已有的 Cascade Mask R-CNN R50 检测模型基础上,新增一个新的 neck 模块 `AugFPN` 去代替默认的 `FPN`,以下是具体实现: + +### 1 定义新的 neck (例如 AugFPN) + +首先创建新文件 `mmdet/models/necks/augfpn.py`. + +```python +import torch.nn as nn +from mmdet.registry import MODELS + +@MODELS.register_module() +class AugFPN(nn.Module): + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False): + pass + + def forward(self, inputs): + # implementation is ignored + pass +``` + +### 2 导入模块 + +你可以采用两种方式导入模块,第一种是在 `mmdet/models/necks/__init__.py` 中添加如下内容 + +```python +from .augfpn import AugFPN +``` + +第二种是增加如下代码到对应配置中,这种方式的好处是不需要改动代码 + +```python +custom_imports = dict( + imports=['mmdet.models.necks.augfpn'], + allow_failed_imports=False) +``` + +### 3 修改配置 + +```python +neck=dict( + type='AugFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5) +``` + +关于自定义模型其余相关细节例如实现新的骨架网络,头部网络、损失函数,以及运行时训练配置例如定义新的优化器、使用梯度裁剪、定制训练调度策略和钩子等,请参考文档 [自定义模型](tutorials/customize_models.md) 和 [自定义运行时训练配置](tutorials/customize_runtime.md)。 + +## 准备配置文件 + +第三步是准备训练配置所需要的配置文件。假设你打算基于 cityscapes 数据集,在 Cascade Mask R-CNN R50 中新增 `AugFPN` 模块,同时增加 `Rotate` 或者 `Translate` 数据增强策略,假设你的配置文件位于 `configs/cityscapes/` 目录下,并且取名为 `cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py`,则配置信息如下: + +```python +# 继承 base 配置,然后进行针对性修改 +_base_ = [ + '../_base_/models/cascade-mask-rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', '../_base_/default_runtime.py' +] + +model = dict( + # 设置 `init_cfg` 为 None,表示不加载 ImageNet 预训练权重, + # 后续可以设置 `load_from` 参数用来加载 COCO 预训练权重 + backbone=dict(init_cfg=None), + # 使用新增的 `AugFPN` 模块代替默认的 `FPN` + neck=dict( + type='AugFPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5), + # 我们也需要将 num_classes 从 80 修改为 8 来匹配 cityscapes 数据集标注 + # 这个修改包括 `bbox_head` 和 `mask_head`. + roi_head=dict( + bbox_head=[ + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # 将 COCO 类别修改为 cityscapes 类别 + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.1, 0.1, 0.2, 0.2]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, + loss_weight=1.0)), + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # 将 COCO 类别修改为 cityscapes 类别 + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.05, 0.05, 0.1, 0.1]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, + loss_weight=1.0)), + dict( + type='Shared2FCBBoxHead', + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + # 将 COCO 类别修改为 cityscapes 类别 + num_classes=8, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.033, 0.033, 0.067, 0.067]), + reg_class_agnostic=True, + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) + ], + mask_head=dict( + type='FCNMaskHead', + num_convs=4, + in_channels=256, + conv_out_channels=256, + # 将 COCO 类别修改为 cityscapes 类别 + num_classes=8, + loss_mask=dict( + type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) + +# 覆写 `train_pipeline`,然后新增 `AutoAugment` 训练配置 +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='AutoAugment', + policies=[ + [dict( + type='Rotate', + level=5, + img_border_value=(124, 116, 104), + prob=0.5) + ], + [dict(type='Rotate', level=7, img_border_value=(124, 116, 104)), + dict( + type='TranslateX', + level=5, + prob=0.5, + img_border_value=(124, 116, 104)) + ], + ]), + dict( + type='RandomResize', + scale=[(2048, 800), (2048, 1024)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs'), +] + +# 设置每张显卡的批处理大小,同时设置新的训练 pipeline +data = dict( + samples_per_gpu=1, + workers_per_gpu=3, + train=dict(dataset=dict(pipeline=train_pipeline))) + +# 设置优化器 +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)) + +# 设置定制的学习率策略 +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=10, + by_epoch=True, + milestones=[8], + gamma=0.1) +] + +# 训练,验证,测试配置 +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=10, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# 我们采用 COCO 预训练过的 Cascade Mask R-CNN R50 模型权重作为初始化权重,可以得到更加稳定的性能 +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco/cascade_mask_rcnn_r50_fpn_1x_coco_20200203-9d4dcb24.pth' +``` + +## 训练新模型 + +为了能够使用新增配置来训练模型,你可以运行如下命令: + +```shell +python tools/train.py configs/cityscapes/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py +``` + +如果想了解更多用法,可以参考 [例子1](1_exist_data_model.md)。 + +## 测试和推理 + +为了能够测试训练好的模型,你可以运行如下命令: + +```shell +python tools/test.py configs/cityscapes/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes.py work_dirs/cascade-mask-rcnn_r50_augfpn_autoaug-10e_cityscapes/epoch_10.pth +``` + +如果想了解更多用法,可以参考 [例子1](1_exist_data_model.md)。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/robustness_benchmarking.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/robustness_benchmarking.md new file mode 100644 index 0000000000000000000000000000000000000000..e95c79a91f1a3bb2bbaedf9838b6293ae53f1b15 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/robustness_benchmarking.md @@ -0,0 +1,109 @@ +# 检测器鲁棒性检查 + +## 介绍 + +我们提供了在 [Benchmarking Robustness in Object Detection: Autonomous Driving when Winter is Coming](https://arxiv.org/abs/1907.07484) 中定义的「图像损坏基准测试」上测试目标检测和实例分割模型的工具。 +此页面提供了如何使用该基准测试的基本教程。 + +```latex +@article{michaelis2019winter, + title={Benchmarking Robustness in Object Detection: + Autonomous Driving when Winter is Coming}, + author={Michaelis, Claudio and Mitzkus, Benjamin and + Geirhos, Robert and Rusak, Evgenia and + Bringmann, Oliver and Ecker, Alexander S. and + Bethge, Matthias and Brendel, Wieland}, + journal={arXiv:1907.07484}, + year={2019} +} +``` + +![image corruption example](../../../resources/corruptions_sev_3.png) + +## 关于基准测试 + +要将结果提交到基准测试,请访问[基准测试主页](https://github.com/bethgelab/robust-detection-benchmark) + +基准测试是仿照 [imagenet-c 基准测试](https://github.com/hendrycks/robustness),由 Dan Hendrycks 和 Thomas Dietterich 在[Benchmarking Neural Network Robustness to Common Corruptions and Perturbations](https://arxiv.org/abs/1903.12261)(ICLR 2019)中发表。 + +图像损坏变换功能包含在此库中,但可以使用以下方法单独安装: + +```shell +pip install imagecorruptions +``` + +与 imagenet-c 相比,我们必须进行一些更改以处理任意大小的图像和灰度图像。 +我们还修改了“运动模糊”和“雪”损坏,以解除对于 linux 特定库的依赖, +否则必须单独安装这些库。有关详细信息,请参阅 [imagecorruptions](https://github.com/bethgelab/imagecorruptions)。 + +## 使用预训练模型进行推理 + +我们提供了一个测试脚本来评估模型在基准测试中提供的各种损坏变换组合下的性能。 + +### 在数据集上测试 + +- [x] 单张 GPU 测试 +- [ ] 多张 GPU 测试 +- [ ] 可视化检测结果 + +您可以使用以下命令在基准测试中使用 15 种损坏变换来测试模型性能。 + +```shell +# single-gpu testing +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] +``` + +也可以选择其它不同类型的损坏变换。 + +```shell +# noise +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions noise + +# blur +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions blur + +# wetaher +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions weather + +# digital +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions digital +``` + +或者使用一组自定义的损坏变换,例如: + +```shell +# gaussian noise, zoom blur and snow +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --corruptions gaussian_noise zoom_blur snow +``` + +最后,我们也可以选择施加在图像上的损坏变换的严重程度。 +严重程度从 1 到 5 逐级增强,0 表示不对图像施加损坏变换,即原始图像数据。 + +```shell +# severity 1 +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --severities 1 + +# severities 0,2,4 +python tools/analysis_tools/test_robustness.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [--out ${RESULT_FILE}] [--eval ${EVAL_METRICS}] --severities 0 2 4 +``` + +## 模型测试结果 + +下表是各模型在 COCO 2017val 上的测试结果。 + +| Model | Backbone | Style | Lr schd | box AP clean | box AP corr. | box % | mask AP clean | mask AP corr. | mask % | +| :-----------------: | :-----------------: | :-----: | :-----: | :----------: | :----------: | :---: | :-----------: | :-----------: | :----: | +| Faster R-CNN | R-50-FPN | pytorch | 1x | 36.3 | 18.2 | 50.2 | - | - | - | +| Faster R-CNN | R-101-FPN | pytorch | 1x | 38.5 | 20.9 | 54.2 | - | - | - | +| Faster R-CNN | X-101-32x4d-FPN | pytorch | 1x | 40.1 | 22.3 | 55.5 | - | - | - | +| Faster R-CNN | X-101-64x4d-FPN | pytorch | 1x | 41.3 | 23.4 | 56.6 | - | - | - | +| Faster R-CNN | R-50-FPN-DCN | pytorch | 1x | 40.0 | 22.4 | 56.1 | - | - | - | +| Faster R-CNN | X-101-32x4d-FPN-DCN | pytorch | 1x | 43.4 | 26.7 | 61.6 | - | - | - | +| Mask R-CNN | R-50-FPN | pytorch | 1x | 37.3 | 18.7 | 50.1 | 34.2 | 16.8 | 49.1 | +| Mask R-CNN | R-50-FPN-DCN | pytorch | 1x | 41.1 | 23.3 | 56.7 | 37.2 | 20.7 | 55.7 | +| Cascade R-CNN | R-50-FPN | pytorch | 1x | 40.4 | 20.1 | 49.7 | - | - | - | +| Cascade Mask R-CNN | R-50-FPN | pytorch | 1x | 41.2 | 20.7 | 50.2 | 35.7 | 17.6 | 49.3 | +| RetinaNet | R-50-FPN | pytorch | 1x | 35.6 | 17.8 | 50.1 | - | - | - | +| Hybrid Task Cascade | X-101-64x4d-FPN-DCN | pytorch | 1x | 50.6 | 32.7 | 64.7 | 43.8 | 28.1 | 64.0 | + +由于对图像的损坏变换存在随机性,测试结果可能略有不同。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/semi_det.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/semi_det.md new file mode 100644 index 0000000000000000000000000000000000000000..a223523705cd25941aecf5f7ef4bc8119a926d70 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/semi_det.md @@ -0,0 +1,320 @@ +# 半监督目标检测 + +半监督目标检测同时利用标签数据和无标签数据进行训练,一方面可以减少模型对检测框数量的依赖,另一方面也可以利用大量的未标记数据进一步提高模型。 + +按照以下流程进行半监督目标检测: + +- [半监督目标检测](#半监督目标检测) + - [准备和拆分数据集](#准备和拆分数据集) + - [配置多分支数据流程](#配置多分支数据流程) + - [配置半监督数据加载](#配置半监督数据加载) + - [配置半监督模型](#配置半监督模型) + - [配置MeanTeacherHook](#配置meanteacherhook) + - [配置TeacherStudentValLoop](#配置teacherstudentvalloop) + +## 准备和拆分数据集 + +我们提供了数据集下载脚本,默认下载 coco2017 数据集,并且自动解压。 + +```shell +python tools/misc/download_dataset.py +``` + +解压后的数据集目录如下: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +半监督目标检测在 coco 数据集上有两种比较通用的实验设置: + +(1)将 `train2017` 按照固定百分比(1%,2%,5% 和 10%)划分出一部分数据作为标签数据集,剩余的训练集数据作为无标签数据集,同时考虑划分不同的训练集数据作为标签数据集对半监督训练的结果影响较大,所以采用五折交叉验证来评估算法性能。我们提供了数据集划分脚本: + +```shell +python tools/misc/split_coco.py +``` + +该脚本默认会按照 1%,2%,5% 和 10% 的标签数据占比划分 `train2017`,每一种划分会随机重复 5 次,用于交叉验证。生成的半监督标注文件名称格式如下: + +- 标签数据集标注名称格式:`instances_train2017.{fold}@{percent}.json` + +- 无标签数据集名称标注:`instances_train2017.{fold}@{percent}-unlabeled.json` + +其中,`fold` 用于交叉验证,`percent` 表示标签数据的占比。 划分后的数据集目录结构如下: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── semi_anns +│ │ │ ├── instances_train2017.1@1.json +│ │ │ ├── instances_train2017.1@1-unlabeled.json +│ │ │ ├── instances_train2017.1@2.json +│ │ │ ├── instances_train2017.1@2-unlabeled.json +│ │ │ ├── instances_train2017.1@5.json +│ │ │ ├── instances_train2017.1@5-unlabeled.json +│ │ │ ├── instances_train2017.1@10.json +│ │ │ ├── instances_train2017.1@10-unlabeled.json +│ │ │ ├── instances_train2017.2@1.json +│ │ │ ├── instances_train2017.2@1-unlabeled.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +(2)将 `train2017` 作为标签数据集,`unlabeled2017` 作为无标签数据集。由于 `image_info_unlabeled2017.json` 没有 `categories` 信息,无法初始化 `CocoDataset` ,所以需要将 `instances_train2017.json` 的 `categories` 写入 `image_info_unlabeled2017.json` ,另存为 `instances_unlabeled2017.json`,相关脚本如下: + +```python +from mmengine.fileio import load, dump + +anns_train = load('instances_train2017.json') +anns_unlabeled = load('image_info_unlabeled2017.json') +anns_unlabeled['categories'] = anns_train['categories'] +dump(anns_unlabeled, 'instances_unlabeled2017.json') +``` + +处理后的数据集目录如下: + +```plain +mmdetection +├── data +│ ├── coco +│ │ ├── annotations +│ │ │ ├── image_info_unlabeled2017.json +│ │ │ ├── instances_train2017.json +│ │ │ ├── instances_unlabeled2017.json +│ │ │ ├── instances_val2017.json +│ │ ├── test2017 +│ │ ├── train2017 +│ │ ├── unlabeled2017 +│ │ ├── val2017 +``` + +## 配置多分支数据流程 + +半监督学习有两个主要的方法,分别是 +[一致性正则化](https://research.nvidia.com/sites/default/files/publications/laine2017iclr_paper.pdf) +和[伪标签](https://www.researchgate.net/profile/Dong-Hyun-Lee/publication/280581078_Pseudo-Label_The_Simple_and_Efficient_Semi-Supervised_Learning_Method_for_Deep_Neural_Networks/links/55bc4ada08ae092e9660b776/Pseudo-Label-The-Simple-and-Efficient-Semi-Supervised-Learning-Method-for-Deep-Neural-Networks.pdf) 。 +一致性正则化往往需要一些精心的设计,而伪标签的形式比较简单,更容易拓展到下游任务。我们主要采用了基于伪标签的教师学生联合训练的半监督目标检测框架,对于标签数据和无标签数据需要配置不同的数据流程: +(1)标签数据的数据流程: + +```python +# pipeline used to augment labeled data, +# which will be sent to student model for supervised training. +sup_pipeline = [ + dict(type='LoadImageFromFile',backend_args = backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict(type='MultiBranch', sup=dict(type='PackDetInputs')) +] +``` + +(2)无标签的数据流程: + +```python +# pipeline used to augment unlabeled data weakly, +# which will be sent to teacher model for predicting pseudo instances. +weak_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data strongly, +# which will be sent to student model for unsupervised training. +strong_pipeline = [ + dict(type='RandomResize', scale=scale, keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomOrder', + transforms=[ + dict(type='RandAugment', aug_space=color_space, aug_num=1), + dict(type='RandAugment', aug_space=geometric, aug_num=1), + ]), + dict(type='RandomErasing', n_patches=(1, 5), ratio=(0, 0.2)), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix')), +] + +# pipeline used to augment unlabeled data into different views +unsup_pipeline = [ + dict(type='LoadImageFromFile', backend_args = backend_args), + dict(type='LoadEmptyAnnotations'), + dict( + type='MultiBranch', + unsup_teacher=weak_pipeline, + unsup_student=strong_pipeline, + ) +] +``` + +## 配置半监督数据加载 + +(1)构建半监督数据集。使用 `ConcatDataset` 拼接标签数据集和无标签数据集。 + +```python +labeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=sup_pipeline) + +unlabeled_dataset = dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_unlabeled2017.json', + data_prefix=dict(img='unlabeled2017/'), + filter_cfg=dict(filter_empty_gt=False), + pipeline=unsup_pipeline) + +train_dataloader = dict( + batch_size=batch_size, + num_workers=num_workers, + persistent_workers=True, + sampler=dict( + type='GroupMultiSourceSampler', + batch_size=batch_size, + source_ratio=[1, 4]), + dataset=dict( + type='ConcatDataset', datasets=[labeled_dataset, unlabeled_dataset])) +``` + +(2)使用多源数据集采样器。 使用 `GroupMultiSourceSampler` 从 `labeled_dataset` 和 `labeled_dataset` 采样数据组成 batch , `source_ratio` 控制 batch 中标签数据和无标签数据的占比。`GroupMultiSourceSampler` 还保证了同一个 batch 中的图片具有相近的长宽比例,如果不需要保证batch内图片的长宽比例,可以使用 `MultiSourceSampler`。`GroupMultiSourceSampler` 采样示意图如下: + +
+ +
+ +`sup=1000` 表示标签数据集的规模为 1000 ,`sup_h=200` 表示标签数据集中长宽比大于等于1的图片规模为 200,`sup_w=800` 表示标签数据集中长宽比小于1的图片规模为 800 ,`unsup=9000` 表示无标签数据集的规模为 9000 ,`unsup_h=1800` 表示无标签数据集中长宽比大于等于1的图片规模为 1800,`unsup_w=7200` 表示标签数据集中长宽比小于1的图片规模为 7200 ,`GroupMultiSourceSampler` 每次按照标签数据集和无标签数据集的图片的总体长宽比分布随机选择一组,然后按照 `source_ratio` 从两个数据集中采样组成 batch ,因此标签数据集和无标签数据集重复采样次数不同。 + +## 配置半监督模型 + +我们选择 `Faster R-CNN` 作为 `detector` 进行半监督训练,以半监督目标检测算法 `SoftTeacher` 为例,模型的配置可以继承 `_base_/models/faster-rcnn_r50_fpn.py`,将检测器的骨干网络替换成 `caffe` 风格。 +注意,与监督训练的配置文件不同的是,`Faster R-CNN` 作为 `detector`,是作为 `model`的一个属性,而不是 `model` 。此外,还需要将`data_preprocessor`设置为`MultiBranchDataPreprocessor`,用于处理不同数据流程图片的填充和归一化。 +最后,可以通过 `semi_train_cfg` 和 `semi_test_cfg` 配置半监督训练和测试需要的参数。 + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', '../_base_/default_runtime.py', + '../_base_/datasets/semi_coco_detection.py' +] + +detector = _base_.model +detector.data_preprocessor = dict( + type='DetDataPreprocessor', + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False, + pad_size_divisor=32) +detector.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=False), + norm_eval=True, + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe')) + +model = dict( + _delete_=True, + type='SoftTeacher', + detector=detector, + data_preprocessor=dict( + type='MultiBranchDataPreprocessor', + data_preprocessor=detector.data_preprocessor), + semi_train_cfg=dict( + freeze_teacher=True, + sup_weight=1.0, + unsup_weight=4.0, + pseudo_label_initial_score_thr=0.5, + rpn_pseudo_thr=0.9, + cls_pseudo_thr=0.9, + reg_pseudo_thr=0.02, + jitter_times=10, + jitter_scale=0.06, + min_pseudo_bbox_wh=(1e-2, 1e-2)), + semi_test_cfg=dict(predict_on='teacher')) +``` + +此外,我们也支持其他检测模型进行半监督训练,比如,`RetinaNet` 和 `Cascade R-CNN`。由于 `SoftTeacher` 仅支持 `Faster R-CNN`,所以需要将其替换为 `SemiBaseDetector`,示例如下: + +```python +_base_ = [ + '../_base_/models/retinanet_r50_fpn.py', '../_base_/default_runtime.py', + '../_base_/datasets/semi_coco_detection.py' +] + +detector = _base_.model + +model = dict( + _delete_=True, + type='SemiBaseDetector', + detector=detector, + data_preprocessor=dict( + type='MultiBranchDataPreprocessor', + data_preprocessor=detector.data_preprocessor), + semi_train_cfg=dict( + freeze_teacher=True, + sup_weight=1.0, + unsup_weight=1.0, + cls_pseudo_thr=0.9, + min_pseudo_bbox_wh=(1e-2, 1e-2)), + semi_test_cfg=dict(predict_on='teacher')) +``` + +沿用 `SoftTeacher` 的半监督训练配置,将 `batch_size` 改为 2 ,`source_ratio` 改为 `[1, 1]`,`RetinaNet`,`Faster R-CNN`, `Cascade R-CNN` 以及 `SoftTeacher` 在 10% coco 训练集上的监督训练和半监督训练的实验结果如下: + +| Model | Detector | BackBone | Style | sup-0.1-coco mAP | semi-0.1-coco mAP | +| :--------------: | :-----------: | :------: | :---: | :--------------: | :---------------: | +| SemiBaseDetector | RetinaNet | R-50-FPN | caffe | 23.5 | 27.7 | +| SemiBaseDetector | Faster R-CNN | R-50-FPN | caffe | 26.7 | 28.4 | +| SemiBaseDetector | Cascade R-CNN | R-50-FPN | caffe | 28.0 | 29.7 | +| SoftTeacher | Faster R-CNN | R-50-FPN | caffe | 26.7 | 31.1 | + +## 配置MeanTeacherHook + +通常,教师模型采用对学生模型指数滑动平均(EMA)的方式进行更新,进而教师模型随着学生模型的优化而优化,可以通过配置 `custom_hooks` 实现: + +```python +custom_hooks = [dict(type='MeanTeacherHook')] +``` + +## 配置TeacherStudentValLoop + +由于教师学生联合训练框架存在两个模型,我们可以用 `TeacherStudentValLoop` 替换 `ValLoop`,在训练的过程中同时检验两个模型的精度。 + +```python +val_cfg = dict(type='TeacherStudentValLoop') +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/single_stage_as_rpn.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/single_stage_as_rpn.md new file mode 100644 index 0000000000000000000000000000000000000000..39db35c26830871755ef072d4a3d9ffe6dd628fb --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/single_stage_as_rpn.md @@ -0,0 +1,171 @@ +# 将单阶段检测器作为 RPN + +候选区域网络 (Region Proposal Network, RPN) 作为 [Faster R-CNN](https://arxiv.org/abs/1506.01497) 的一个子模块,将为 Faster R-CNN 的第二阶段产生候选区域。在 MMDetection 里大多数的二阶段检测器使用 [`RPNHead`](../../../mmdet/models/dense_heads/rpn_head.py)作为候选区域网络来产生候选区域。然而,任何的单阶段检测器都可以作为候选区域网络,是因为他们对边界框的预测可以被视为是一种候选区域,并且因此能够在 R-CNN 中得到改进。因此在 MMDetection v3.0 中会支持将单阶段检测器作为 RPN 使用。 + +接下来我们通过一个例子,即如何在 [Faster R-CNN](../../../configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py) 中使用一个无锚框的单阶段的检测器模型 [FCOS](../../../configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py) 作为 RPN ,详细阐述具体的全部流程。 + +主要流程如下: + +1. 在 Faster R-CNN 中使用 `FCOSHead` 作为 `RPNHead` +2. 评估候选区域 +3. 用预先训练的 FCOS 训练定制的 Faster R-CNN + +## 在 Faster R-CNN 中使用 `FCOSHead` 作为` RPNHead` + +为了在 Faster R-CNN 中使用 `FCOSHead` 作为 `RPNHead` ,我们应该创建一个名为 `configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py` 的配置文件,并且在 `configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py` 中将 `rpn_head` 的设置替换为 `bbox_head` 的设置,此外我们仍然使用 FCOS 的瓶颈设置,步幅为`[8,16,32,64,128]`,并且更新 `bbox_roi_extractor` 的 `featmap_stride` 为 ` [8,16,32,64,128]`。为了避免损失变慢,我们在前1000次迭代而不是前500次迭代中应用预热,这意味着 lr 增长得更慢。相关配置如下: + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +model = dict( + # 从 configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py 复制 + neck=dict( + start_level=1, + add_extra_convs='on_output', # 使用 P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # 忽略未使用的旧设置 + type='FCOSHead', + num_classes=1, # 对于 rpn, num_classes = 1,如果 num_classes > 1,它将在 TwoStageDetector 中自动设置为1 + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + roi_head=dict( # featmap_strides 的更新取决于于颈部的步伐 + bbox_roi_extractor=dict(featmap_strides=[8, 16, 32, 64, 128]))) +# 学习率 +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), # 慢慢增加 lr,否则损失变成 NAN + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[8, 11], + gamma=0.1) +] +``` + +然后,我们可以使用下面的命令来训练我们的定制模型。更多训练命令,请参考[这里](train.md)。 + +```python +# 使用8个 GPU 进行训练 +bash +tools/dist_train.sh +configs/faster_rcnn/faster-rcnn_r50_fpn_fcos-rpn_1x_coco.py +--work-dir /work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco +``` + +## 评估候选区域 + +候选区域的质量对检测器的性能有重要影响,因此,我们也提供了一种评估候选区域的方法。和上面一样创建一个新的名为 `configs/rpn/fcos-rpn_r50_fpn_1x_coco.py` 的配置文件,并且在 `configs/rpn/fcos-rpn_r50_fpn_1x_coco.py` 中将 `rpn_head` 的设置替换为 `bbox_head` 的设置。 + +```python +_base_ = [ + '../_base_/models/rpn_r50_fpn.py', '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +val_evaluator = dict(metric='proposal_fast') +test_evaluator = val_evaluator +model = dict( + # 从 configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py 复制 + neck=dict( + start_level=1, + add_extra_convs='on_output', # 使用 P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # 忽略未使用的旧设置 + type='FCOSHead', + num_classes=1, # 对于 rpn, num_classes = 1,如果 num_classes >为1,它将在 rpn 中自动设置为1 + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) +``` + +假设我们在训练之后有检查点 `./work_dirs/faster-rcnn_r50_fpn_fcos-rpn_1x_coco/epoch_12.pth` ,然后,我们可以使用下面的命令来评估建议的质量。 + +```python +# 使用8个 GPU 进行测试 +bash +tools/dist_test.sh +configs/rpn/fcos-rpn_r50_fpn_1x_coco.py +--work_dirs /faster-rcnn_r50_fpn_fcos-rpn_1x_coco/epoch_12.pth +``` + +## 用预先训练的 FCOS 训练定制的 Faster R-CNN + +预训练不仅加快了训练的收敛速度,而且提高了检测器的性能。因此,我们在这里给出一个例子来说明如何使用预先训练的 FCOS 作为 RPN 来加速训练和提高精度。假设我们想在 Faster R-CNN 中使用 `FCOSHead` 作为 `rpn_head`,并加载预先训练权重来进行训练 [`fcos_r50-caffe_fpn_gn-head_1x_coco`](https://download.openmmlab.com/mmdetection/v2.0/fcos/fcos_r50_caffe_fpn_gn-head_1x_coco/fcos_r50_caffe_fpn_gn-head_1x_coco-821213aa.pth)。 配置文件 `configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_fcos- rpn_1x_copy .py` 的内容如下所示。注意,`fcos_r50-caffe_fpn_gn-head_1x_coco` 使用 ResNet50 的 caffe 版本,因此需要更新 `data_preprocessor` 中的像素平均值和 std。 + +```python +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +model = dict( + data_preprocessor=dict( + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False), + backbone=dict( + norm_cfg=dict(type='BN', requires_grad=False), + style='caffe', + init_cfg=None), # the checkpoint in ``load_from`` contains the weights of backbone + neck=dict( + start_level=1, + add_extra_convs='on_output', # 使用 P5 + relu_before_extra_convs=True), + rpn_head=dict( + _delete_=True, # 忽略未使用的旧设置 + type='FCOSHead', + num_classes=1, # 对于 rpn, num_classes = 1,如果 num_classes > 1,它将在 TwoStageDetector 中自动设置为1 + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + roi_head=dict( # update featmap_strides due to the strides in neck + bbox_roi_extractor=dict(featmap_strides=[8, 16, 32, 64, 128]))) +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/fcos/fcos_r50_caffe_fpn_gn-head_1x_coco/fcos_r50_caffe_fpn_gn-head_1x_coco-821213aa.pth' +``` + +训练命令如下。 + +```python +bash +tools/dist_train.sh +configs/faster_rcnn/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco.py \ +--work-dir /work_dirs/faster-rcnn_r50-caffe_fpn_fcos-rpn_1x_coco +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/test.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/test.md new file mode 100644 index 0000000000000000000000000000000000000000..2ada04d2a0127e93d6f8d364f39b5b40c67ef2f6 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/test.md @@ -0,0 +1,285 @@ +# 测试现有模型 + +我们提供了测试脚本,能够测试一个现有模型在所有数据集(COCO,Pascal VOC,Cityscapes 等)上的性能。我们支持在如下环境下测试: + +- 单 GPU 测试 +- CPU 测试 +- 单节点多 GPU 测试 +- 多节点测试 + +根据以上测试环境,选择合适的脚本来执行测试过程。 + +```shell +# 单 GPU 测试 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# CPU 测试:禁用 GPU 并运行单 GPU 测试脚本 +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# 单节点多 GPU 测试 +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--out ${RESULT_FILE}] +``` + +`tools/dist_test.sh` 也支持多节点测试,不过需要依赖 PyTorch 的 [启动工具](https://pytorch.org/docs/stable/distributed.html#launch-utility) 。 + +可选参数: + +- `RESULT_FILE`: 结果文件名称,需以 .pkl 形式存储。如果没有声明,则不将结果存储到文件。 +- `--show`: 如果开启,检测结果将被绘制在图像上,以一个新窗口的形式展示。它只适用于单 GPU 的测试,是用于调试和可视化的。请确保使用此功能时,你的 GUI 可以在环境中打开。否则,你可能会遇到这么一个错误 `cannot connect to X server`。 +- `--show-dir`: 如果指明,检测结果将会被绘制在图像上并保存到指定目录。它只适用于单 GPU 的测试,是用于调试和可视化的。即使你的环境中没有 GUI,这个选项也可使用。 +- `--cfg-options`: 如果指明,这里的键值对将会被合并到配置文件中。 + +### 样例 + +假设你已经下载了 checkpoint 文件到 `checkpoints/` 文件下了。 + +1. 测试 RTMDet 并可视化其结果。按任意键继续下张图片的测试。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet) 。 + + ```shell + python tools/test.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --show + ``` + +2. 测试 RTMDet,并为了之后的可视化保存绘制的图像。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/main/configs/rtmdet) 。 + + ```shell + python tools/test.py \ + configs/rtmdet/rtmdet_l_8xb32-300e_coco.py \ + checkpoints/rtmdet_l_8xb32-300e_coco_20220719_112030-5a0be7c4.pth \ + --show-dir rtmdet_l_8xb32-300e_coco_results + ``` + +3. 在 Pascal VOC 数据集上测试 Faster R-CNN,不保存测试结果,测试 `mAP`。配置文件和 checkpoint 文件 [在此](../../../configs/pascal_voc) 。 + + ```shell + python tools/test.py \ + configs/pascal_voc/faster-rcnn_r50_fpn_1x_voc0712.py \ + checkpoints/faster_rcnn_r50_fpn_1x_voc0712_20200624-c9895d40.pth + ``` + +4. 使用 8 块 GPU 测试 Mask R-CNN,测试 `bbox` 和 `mAP` 。配置文件和 checkpoint 文件 [在此](../../../configs/mask_rcnn) 。 + + ```shell + ./tools/dist_test.sh \ + configs/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 \ + --out results.pkl + ``` + +5. 使用 8 块 GPU 测试 Mask R-CNN,测试**每类**的 `bbox` 和 `mAP`。配置文件和 checkpoint 文件 [在此](../../../configs/mask_rcnn) 。 + + ```shell + ./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 + ``` + + 该命令生成两个JSON文件 `./work_dirs/coco_instance/test.bbox.json` 和 `./work_dirs/coco_instance/test.segm.json`。 + +6. 在 COCO test-dev 数据集上,使用 8 块 GPU 测试 Mask R-CNN,并生成 JSON 文件提交到官方评测服务器,配置文件和 checkpoint 文件 [在此](../../../configs/mask_rcnnn) 。你可以在 [config](./././configs/_base_/datasets/coco_instance.py) 的注释中用 test_evaluator 和 test_dataloader 替换原来的 test_evaluator 和 test_dataloader,然后运行: + + ```shell + ./tools/dist_test.sh \ + configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py \ + checkpoints/mask_rcnn_r50_fpn_1x_cityscapes_20200227-afe51d5a.pth \ + 8 + ``` + + 这行命令生成两个 JSON 文件 `mask_rcnn_test-dev_results.bbox.json` 和 `mask_rcnn_test-dev_results.segm.json`。 + +7. 在 Cityscapes 数据集上,使用 8 块 GPU 测试 Mask R-CNN,生成 txt 和 png 文件,并上传到官方评测服务器。配置文件和 checkpoint 文件 [在此](../../../configs/cityscapes) 。 你可以在 [config](./././configs/_base_/datasets/cityscapes_instance.py) 的注释中用 test_evaluator 和 test_dataloader 替换原来的 test_evaluator 和 test_dataloader,然后运行: + + ```shell + ./tools/dist_test.sh \ + configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py \ + checkpoints/mask_rcnn_r50_fpn_1x_cityscapes_20200227-afe51d5a.pth \ + 8 + ``` + + 生成的 png 和 txt 文件在 `./work_dirs/cityscapes_metric` 文件夹下。 + +### 不使用 Ground Truth 标注进行测试 + +MMDetection 支持在不使用 ground-truth 标注的情况下对模型进行测试,这需要用到 `CocoDataset`。如果你的数据集格式不是 COCO 格式的,请将其转化成 COCO 格式。如果你的数据集格式是 VOC 或者 Cityscapes,你可以使用 [tools/dataset_converters](https://github.com/open-mmlab/mmdetection/tree/main/tools/dataset_converters) 内的脚本直接将其转化成 COCO 格式。如果是其他格式,可以使用 [images2coco 脚本](https://github.com/open-mmlab/mmdetection/tree/master/tools/dataset_converters/images2coco.py) 进行转换。 + +```shell +python tools/dataset_converters/images2coco.py \ + ${IMG_PATH} \ + ${CLASSES} \ + ${OUT} \ + [--exclude-extensions] +``` + +参数: + +- `IMG_PATH`: 图片根路径。 +- `CLASSES`: 类列表文本文件名。文本中每一行存储一个类别。 +- `OUT`: 输出 json 文件名。 默认保存目录和 `IMG_PATH` 在同一级。 +- `exclude-extensions`: 待排除的文件后缀名。 + +在转换完成后,使用如下命令进行测试 + +```shell +# 单 GPU 测试 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--show] + +# CPU 测试:禁用 GPU 并运行单 GPU 测试脚本 +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--show] + +# 单节点多 GPU 测试 +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--show] +``` + +假设 [model zoo](https://mmdetection.readthedocs.io/en/latest/modelzoo_statistics.html) 中的 checkpoint 文件被下载到了 `checkpoints/` 文件夹下, +我们可以使用以下命令,用 8 块 GPU 在 COCO test-dev 数据集上测试 Mask R-CNN,并且生成 JSON 文件。 + +```sh +./tools/dist_test.sh \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ + 8 +``` + +这行命令生成两个 JSON 文件 `./work_dirs/coco_instance/test.bbox.json` 和 `./work_dirs/coco_instance/test.segm.json`。 + +### 批量推理 + +MMDetection 在测试模式下,既支持单张图片的推理,也支持对图像进行批量推理。默认情况下,我们使用单张图片的测试,你可以通过修改测试数据配置文件中的 `samples_per_gpu` 来开启批量测试。 +开启批量推理的配置文件修改方法为: + +```shell +data = dict(train_dataloader=dict(...), val_dataloader=dict(...), test_dataloader=dict(batch_size=2, ...)) +``` + +或者你可以通过将 `--cfg-options` 设置为 `--cfg-options test_dataloader.batch_size=` 来开启它。 + +## 测试时增强 (TTA) + +测试时增强 (TTA) 是一种在测试阶段使用的数据增强策略。它对同一张图片应用不同的增强,例如翻转和缩放,用于模型推理,然后将每个增强后的图像的预测结果合并,以获得更准确的预测结果。为了让用户更容易使用 TTA,MMEngine 提供了 [BaseTTAModel](https://mmengine.readthedocs.io/en/latest/api/generated/mmengine.model.BaseTTAModel.html#mmengine.model.BaseTTAModel) 类,允许用户根据自己的需求通过简单地扩展 BaseTTAModel 类来实现不同的 TTA 策略。 + +在 MMDetection 中,我们提供了 [DetTTAModel](../../../mmdet/models/test_time_augs/det_tta.py) 类,它继承自 BaseTTAModel。 + +### 使用案例 + +使用 TTA 需要两个步骤。首先,你需要在配置文件中添加 `tta_model` 和 `tta_pipeline`: + +```shell +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict( + type='nms', + iou_threshold=0.5), + max_per_img=100)) + +tta_pipeline = [ + dict(type='LoadImageFromFile', + backend_args=None), + dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=(1333, 800), keep_ratio=True) + ], [ # It uses 2 flipping transformations (flipping and not flipping). + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ]])] +``` + +第二步,运行测试脚本时,设置 `--tta` 参数,如下所示: + +```shell +# 单 GPU 测试 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--tta] + +# CPU 测试:禁用 GPU 并运行单 GPU 测试脚本 +export CUDA_VISIBLE_DEVICES=-1 +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + [--out ${RESULT_FILE}] \ + [--tta] + +# 多 GPU 测试 +bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + ${GPU_NUM} \ + [--tta] +``` + +你也可以自己修改 TTA 配置,例如添加缩放增强: + +```shell +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict( + type='nms', + iou_threshold=0.5), + max_per_img=100)) + +img_scales = [(1333, 800), (666, 400), (2000, 1200)] +tta_pipeline = [ + dict(type='LoadImageFromFile', + backend_args=None), + dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=s, keep_ratio=True) for s in img_scales + ], [ + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ]])] +``` + +以上数据增强管道将首先对图像执行 3 个多尺度转换,然后执行 2 个翻转转换(翻转和不翻转),最后使用 PackDetInputs 将图像打包到最终结果中。 +这里有更多的 TTA 使用案例供您参考: + +- [RetinaNet](../../../configs/retinanet/retinanet_tta.py) +- [CenterNet](../../../configs/centernet/centernet_tta.py) +- [YOLOX](../../../configs/rtmdet/rtmdet_tta.py) +- [RTMDet](../../../configs/yolox/yolox_tta.py) + +更多高级用法和 TTA 的数据流,请参考 [MMEngine](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/test_time_augmentation.html#data-flow)。我们将在后续支持实例分割 TTA。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/test_results_submission.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/test_results_submission.md new file mode 100644 index 0000000000000000000000000000000000000000..7a07658517011b30f68da722159223995245a316 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/test_results_submission.md @@ -0,0 +1,174 @@ +# 提交测试结果 + +## 全景分割测试结果提交 + +下面几节介绍如何在 COCO 测试开发集上生成泛视分割模型的预测结果,并将预测提交到 [COCO评估服务器](https://competitions.codalab.org/competitions/19507) + +### 前提条件 + +- 下载 [COCO测试数据集图像](http://images.cocodataset.org/zips/test2017.zip),[测试图像信息](http://images.cocodataset.org/annotations/image_info_test2017.zip),和[全景训练/相关注释](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip),然后解压缩它们,把 `test2017` 放到 `data/coco/`,把 json 文件和注释文件放到 `data/coco/annotations/` 。 + +```shell +# 假设 data/coco/ 不存在 +mkdir -pv data/coco/ +# 下载 test2017 +wget -P data/coco/ http://images.cocodataset.org/zips/test2017.zip +wget -P data/coco/ http://images.cocodataset.org/annotations/image_info_test2017.zip +wget -P data/coco/ http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip +# 解压缩它们 +unzip data/coco/test2017.zip -d data/coco/ +unzip data/coco/image_info_test2017.zip -d data/coco/ +unzip data/coco/panoptic_annotations_trainval2017.zip -d data/coco/ +# 删除 zip 文件(可选) +rm -rf data/coco/test2017.zip data/coco/image_info_test2017.zip data/coco/panoptic_annotations_trainval2017.zip +``` + +- 运行以下代码更新测试图像信息中的类别信息。由于 `image_info_test-dev2017.json` 的类别信息中缺少属性 `isthing` ,我们需要用 `panoptic_val2017.json` 中的类别信息更新它。 + +```shell +python tools/misc/gen_coco_panoptic_test_info.py data/coco/annotations +``` + +在完成上述准备之后,你的 `data` 目录结构应该是这样: + +```text +data +`-- coco + |-- annotations + | |-- image_info_test-dev2017.json + | |-- image_info_test2017.json + | |-- panoptic_image_info_test-dev2017.json + | |-- panoptic_train2017.json + | |-- panoptic_train2017.zip + | |-- panoptic_val2017.json + | `-- panoptic_val2017.zip + `-- test2017 +``` + +### coco 测试开发的推理 + +要在 coco test-dev 上进行推断,我们应该首先更新 `test_dataloder` 和 `test_evaluator` 的设置。有两种方法可以做到这一点:1. 在配置文件中更新它们;2. 在命令行中更新它们。 + +#### 在配置文件中更新它们 + +相关的设置在 `configs/_base_/datasets/ coco_panoptical .py` 的末尾,如下所示。 + +```python +test_dataloader = dict( + batch_size=1, + num_workers=1, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/panoptic_image_info_test-dev2017.json', + data_prefix=dict(img='test2017/'), + test_mode=True, + pipeline=test_pipeline)) +test_evaluator = dict( + type='CocoPanopticMetric', + format_only=True, + ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', + outfile_prefix='./work_dirs/coco_panoptic/test') +``` + +以下任何一种方法都可以用于更新 coco test-dev 集上的推理设置 + +情况1:直接取消注释 `configs/_base_/datasets/ coco_panoptical .py` 中的设置。 + +情况2:将以下设置复制到您现在使用的配置文件中。 + +```python +test_dataloader = dict( + dataset=dict( + ann_file='annotations/panoptic_image_info_test-dev2017.json', + data_prefix=dict(img='test2017/', _delete_=True))) +test_evaluator = dict( + format_only=True, + ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', + outfile_prefix='./work_dirs/coco_panoptic/test') +``` + +然后通过以下命令对 coco test-dev et 进行推断。 + +```shell +python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} +``` + +#### 在命令行中更新它们 + +coco test-dev 上更新相关设置和推理的命令如下所示。 + +```shell +# 用一个 gpu 测试 +CUDA_VISIBLE_DEVICES=0 python tools/test.py \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results +# 用四个 gpu 测试 +CUDA_VISIBLE_DEVICES=0,1,3,4 bash tools/dist_test.sh \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + 8 \ # eights gpus + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results +# 用 slurm 测试 +GPUS=8 tools/slurm_test.sh \ + ${Partition} \ + ${JOB_NAME} \ + ${CONFIG_FILE} \ + ${CHECKPOINT_FILE} \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=${WORK_DIR}/results +``` + +例子:假设我们使用预先训练的带有 ResNet-50 骨干网的 MaskFormer 对 `test2017` 执行推断。 + +```shell +# 单 gpu 测试 +CUDA_VISIBLE_DEVICES=0 python tools/test.py \ + configs/maskformer/maskformer_r50_mstrain_16x1_75e_coco.py \ + checkpoints/maskformer_r50_mstrain_16x1_75e_coco_20220221_141956-bc2699cb.pth \ + --cfg-options \ + test_dataloader.dataset.ann_file=annotations/panoptic_image_info_test-dev2017.json \ + test_dataloader.dataset.data_prefix.img=test2017 \ + test_dataloader.dataset.data_prefix._delete_=True \ + test_evaluator.format_only=True \ + test_evaluator.ann_file=data/coco/annotations/panoptic_image_info_test-dev2017.json \ + test_evaluator.outfile_prefix=work_dirs/maskformer/results +``` + +### 重命名文件并压缩结果 + +推理之后,全景分割结果(一个 json 文件和一个存储掩码的目录)将在 `WORK_DIR` 中。我们应该按照 [COCO's Website](https://cocodataset.org/#upload)上的命名约定重新命名它们。最后,我们需要将 json 和存储掩码的目录压缩到 zip 文件中,并根据命名约定重命名该 zip 文件。注意, zip 文件应该**直接**包含上述两个文件。 + +重命名文件和压缩结果的命令: + +```shell +# 在 WORK_DIR 中,我们有 panoptic 分割结果: 'panoptic' 和 'results. panoptical .json'。 +cd ${WORK_DIR} +# 将 '[algorithm_name]' 替换为您使用的算法名称 +mv ./panoptic ./panoptic_test-dev2017_[algorithm_name]_results +mv ./results.panoptic.json ./panoptic_test-dev2017_[algorithm_name]_results.json +zip panoptic_test-dev2017_[algorithm_name]_results.zip -ur panoptic_test-dev2017_[algorithm_name]_results panoptic_test-dev2017_[algorithm_name]_results.json +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_analysis_tools.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_analysis_tools.md new file mode 100644 index 0000000000000000000000000000000000000000..5330af1d1fa20597e4e8c7f8b7954632a743b424 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_analysis_tools.md @@ -0,0 +1,87 @@ +**我们在 `tools/` 目录下提供了很多有用的工具。** + +## MOT 测试时参数搜索 + +`tools/analysis_tools/mot/mot_param_search.py` 可以搜索 MOT 模型中 `tracker` 的参数。 +它与 `tools/test.py` 的使用方式相同,但配置上**有所不同**。 + +下面是修改配置的示例: + +1. 定义要记录的期望评估指标。 + + 例如,你可以将 `evaluator` 定义为: + + ```python + test_evaluator=dict(type='MOTChallengeMetrics', metric=['HOTA', 'CLEAR', 'Identity']) + ``` + + 当然,你也可以自定义 `test_evaluator` 中 `metric` 的内容。你可以自由选择 `['HOTA', 'CLEAR', 'Identity']` 中的一个或多个指标。 + +2. 定义要搜索的参数及其取值。 + + 假设你有一个 `tracker` 的配置如下: + + ```python + model=dict( + tracker=dict( + type='BaseTracker', + obj_score_thr=0.5, + match_iou_thr=0.5 + ) + ) + ``` + + 如果你想要搜索 `tracker` 的参数,只需将其值改为一个列表,如下所示: + + ```python + model=dict( + tracker=dict( + type='BaseTracker', + obj_score_thr=[0.4, 0.5, 0.6], + match_iou_thr=[0.4, 0.5, 0.6, 0.7] + ) + ) + ``` + + 然后,脚本将测试一共12种情况并且记录结果。 + +## MOT 误差可视化 + +`tools/analysis_tools/mot/mot_error_visualize.py` 可以为多目标跟踪可视化错误。 + +该脚本需要推断的结果作为输入。默认情况下,**红色**边界框表示误检(false positive),**黄色**边界框表示漏检(false negative),**蓝色**边界框表示ID切换(ID switch)。 + +``` +python tools/analysis_tools/mot/mot_error_visualize.py \ + ${CONFIG_FILE}\ + --input ${INPUT} \ + --result-dir ${RESULT_DIR} \ + [--output-dir ${OUTPUT}] \ + [--fps ${FPS}] \ + [--show] \ + [--backend ${BACKEND}] +``` + +`RESULT_DIR` 中包含了所有视频的推断结果,推断结果是一个 `txt` 文件。 + +可选参数: + +- `OUTPUT`:可视化演示的输出。如果未指定,`--show` 是必选的,用于即时显示视频。 +- `FPS`:输出视频的帧率。 +- `--show`:是否即时显示视频。 +- `BACKEND`:用于可视化边界框的后端。选项包括 `cv2` 和 `plt`。 + +## 浏览数据集 + +`tools/analysis_tools/mot/browse_dataset.py` 可以可视化训练数据集,以检查数据集配置是否正确。 + +**示例:** + +```shell +python tools/analysis_tools/browse_dataset.py ${CONFIG_FILE} [--show-interval ${SHOW_INTERVAL}] +``` + +可选参数: + +- `SHOW_INTERVAL`: 显示的间隔时间(秒)。 +- `--show`: 是否即时显示图像。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_config.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_config.md new file mode 100644 index 0000000000000000000000000000000000000000..4a20da775ae1093d0c260ecdb8c5f649c63d985c --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_config.md @@ -0,0 +1,109 @@ +# 学习更多与配置相关的事 + +我们用 python 文档作为我们的配置系统。你可以在 `MMDetection/configs` 底下找到所有已提供的配置文件。 + +我们把模块化和继承化设计融入我们的配置系统,这使我们很方便去进行各种实验。如果你想查看相关的配置文件,你可以跑 `python tools/misc/print_config.py /PATH/TO/CONFIG` 去看完整的详细配置。 + +## 完整配置的简要说明 + +一个完整的配置通常包含以下主要的字段: + +`model`:一个模型的基本配置,包含 `data_preprocessor`、`detector`、`motion` 之类的模块,还有 `train_cfg`、`test_cfg` 等等; + +`train_dataloader`:训练数据集的配置,通常包含 `batch_size`、 `num_workers`、 `sampler`、 `dataset` 等等; + +`val_dataloader`:验证数据集的配置,与训练数据集的配置类似; + +`test_dataloader`:测试数据集的配置,与训练数据集的配置类似; + +`val_evaluator`:验证评估器的配置,例如 `type='MOTChallengeMetrics'` 是 MOT 任务里面的测量标准; + +`test_evaluator`:测试评估器的配置,与验证评估器的配置类似; + +`train_cfg`:训练循环的配置,例如 `type='EpochBasedTrainLoop'` ; + +`val_cfg`:验证循环的配置,例如 `type='VideoValLoop'` ; + +`test_cfg`:测试循环的配置,例如 `type='VideoTestLoop'` ; + +`default_hooks`:默认鱼钩的配置,包含计时器、日志、参数调度程序、检查点、样本种子、可视化; + +`vis_backends`:可视化后端的配置,默认使用 `type='LocalVisBackend'` ; + +`visualizer`:可视化工具的配置,例如MOT任务使用 `type='TrackLocalVisualizer'` ; + +`param_scheduler`:参数调度程序的配置,通常里面设置学习率调度程序; + +`optim_wrapper`:优化器封装的配置,包含优化相关的信息,例如优化器、梯度剪裁等; + +`load_from`:加载预训练模型的路径; + +`resume`:布尔值,如果是 `True` ,会从 `load_from` 加载模型的检查点,训练会恢复至检查点的迭代次数。 + +## 通过脚本参数修改配置 + +当使用 `tools/train.py` 或 `tools/test_trackin.py` 执行任务时,可以指定 `--cfg-options` 来就地修改配置。我们举几个例子如下。有关更多详细信息,请参阅[MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html)。 + +### 更新 dict 链的配置键 + +可以按照原始配置中 `dict` 键的顺序指定配置选项,例如,设置 `--cfg-options model.detector.backbone.norm_eval=False` 会将模型主干中的所有 `BN` 模块更改为训练模式。 + +### 更新配置列表中的关键字 + +一些配置的 `dict` 关键字会以列表的形式组成,例如,测试管道中的 `test_dataloader.dataset.pipeline` 以列表形式出现,即 `[dict(type='LoadImageFromFile'), ...]`。如果你想在测试管道中将 `LoadImageFromFile` 更改为 `LoadImageFromWebcam`,可以设置 `--cfg-options test_dataloader.dataset.pipeline.0.type=LoadImageFromWebcam`。 + +### 更新列表/元组的值 + +要被更新的可能是一个列表或一个元组,例如,你可以通过指定 `--cfg options model.data_processor.mean=[0,0,0]` 来更改 `data_preprocessor` 的平均值的关键字。请注意,指定值内不允许有空格。 + +## 配置文件结构 + +`config/_base_` 下有三种基本组件类型,即数据集、模型和默认运行时间。可以用它们来轻松构建许多方法,例如 `SORT`,`DeepSORT`。由 `_base_` 中的组件组成的配置称为基元。 + +对于同一文件夹下的配置文件,建议只有一个基元配置文件。其他配置文件都应该从基元配置文件继承基本结构,这样,继承级别的最大值为 3。 + +为了便于理解,我们建议贡献者继承现有的方法。例如,如果在 `Faster R-CNN` 的基础上进行了一些修改,用户可以首先通过指定 `_base_ = ../_base_/models/faster-rcnn_r50-dc5.py` 来继承基本的 `Faster R-CNN` 结构,然后修改配置文件中的必要字段。 + +如果你正在构建一个与任何现有方法都不共享结构的全新方法,则可以在 `configs` 下创建一个新文件夹 method_name。 + +有关详细文档,请参阅[MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html)。 + +## 配置命名风格 + +我们根据以下风格去命名配置文件,建议贡献者遵从相同风格。 + +`{method}_{module}_{train_cfg}_{train_data}_{test_data}` + +`{method}`: 方法名称,例如 `sort`; + +`{module}`: 方法的基本模块,例如 `faster-rcnn_r50_fpn`; + +`{train_cfg}`: 训练配置通常包含批量大小、迭代次数等,例如 `8xb4-80e`; + +`{train_data}`: 训练数据集,例如 `mot17halftrain`; + +`{test_data}`: 测试数据集,例如 `test-mot17halfval`。 + +## 常问问题 + +### 忽略基本配置中的某些字段 + +有时候你可以设置 `_delete_=True` 去忽略基本配置中的一些字段,你可以参考[MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/config.html)进行简单说明。 + +### 跟踪数据结构介绍 + +#### 优点和新功能 + +在 `mmdetection` 跟踪任务中,我们使用视频来组织数据集,并使用 `TrackDataSample` 来描述数据集信息。 + +基于视频组织,我们提供了 `transform UniformRefFrameSample` 来对关键帧和参考帧进行采样,并使用 `TransformBroadcaster` 进行剪辑训练。 + +在某种程度上,`TrackDataSample` 可以被视为多个 `DetDataSample` 的包装器。它包含一个 `video_data_samples`,这是一个以 `DetDataSample` 组成的列表,里面每个 `DetDataSample` 对应一个帧。此外,它的元信息包括关键帧的索引和参考帧的索引,用与剪辑训练。 + +得益于基于视频的数据组织,整个视频可以直接被测试。这种方式更简洁直观。如果你的 GPU 内存无法容纳整个视频,我们还提供基于图像的测试方法。 + +## 要做的事 + +`StrongSORT`、`Mask2Former` 等算法不支持基于视频的测试,这些算法对 GPU 内存提出了挑战,我们将来会优化这个问题。 + +现在,我们不支持像 `MOT Challenge dataset` 这样的基于视频的数据集和像 `Crowdhuman` 用于 `QDTrack` 算法这样的基于图像的数据集进行联合训练。我们将来会优化这个问题。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_dataset_prepare.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_dataset_prepare.md new file mode 100644 index 0000000000000000000000000000000000000000..0db495b54c90ee6263d877e7ce87910b35d1ae5c --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_dataset_prepare.md @@ -0,0 +1,245 @@ +## 数据集准备 + +本页面提供了现有基准数据集的准备说明,包括: + +- 多目标跟踪 + + - [MOT Challenge](https://motchallenge.net/) + - [CrowdHuman](https://www.crowdhuman.org/) + +- 视频实例分割 + + - [YouTube-VIS](https://youtube-vos.org/dataset/vis/) + +### 1. 下载数据集 + +请从官方网站下载数据集,并将数据集的根目录建立软链接到 `$MMDETECTION/data` 目录下。 + +#### 1.1 多目标跟踪 + +- 对于多目标跟踪任务的训练和测试,需要下载MOT Challenge数据集之一(例如MOT17、MOT20),CrowdHuman数据集可以作为补充数据集。 + +- 对于中国的用户,可以从 [OpenDataLab](https://opendatalab.com/) 上高速下载如下数据集: + + - [MOT17](https://opendatalab.com/MOT17/download) + - [MOT20](https://opendatalab.com/MOT20/download) + - [CrowdHuman](https://opendatalab.com/CrowdHuman/download) + +#### 1.2 视频实例分割 + +- 对于视频实例分割任务的训练和测试,只需要选择一个YouTube-VIS数据集(例如YouTube-VIS 2019、YouTube-VIS 2021)即可。 +- 可以从 [YouTubeVOS](https://codalab.lisn.upsaclay.fr/competitions/6064) 上下载YouTube-VIS 2019数据集。 +- 可以从 [YouTubeVOS](https://codalab.lisn.upsaclay.fr/competitions/7680) 上下载YouTube-VIS 2021数据集。 + +#### 1.3 数据结构 + +如果您的文件夹结构与以下结构不同,则可能需要在配置文件中更改相应的路径。 + +``` +mmdetection +├── mmdet +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── annotations +│ │ +| ├── MOT15/MOT16/MOT17/MOT20 +| | ├── train +| | | ├── MOT17-02-DPM +| | | | ├── det +| │ │ │ ├── gt +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── test +| | | ├── MOT17-01-DPM +| | | | ├── det +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +│ │ +│ ├── crowdhuman +│ │ ├── annotation_train.odgt +│ │ ├── annotation_val.odgt +│ │ ├── train +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_train01.zip +│ │ │ ├── CrowdHuman_train02.zip +│ │ │ ├── CrowdHuman_train03.zip +│ │ ├── val +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_val.zip +│ │ +``` + +### 2. 转换注释 + +在这种情况下,您需要将官方注释(Annotations)转换为COCO格式。我们提供了相应的脚本,使用方法如下: + +```shell +# MOT17 +# 其他 MOT Challenge 数据集的处理方式与 MOT17 相同。 +python ./tools/dataset_converters/mot2coco.py -i ./data/MOT17/ -o ./data/MOT17/annotations --split-train --convert-det +python ./tools/dataset_converters/mot2reid.py -i ./data/MOT17/ -o ./data/MOT17/reid --val-split 0.2 --vis-threshold 0.3 + +# CrowdHuman +python ./tools/dataset_converters/crowdhuman2coco.py -i ./data/crowdhuman -o ./data/crowdhuman/annotations + +# YouTube-VIS 2019 +python ./tools/dataset_converters/youtubevis2coco.py -i ./data/youtube_vis_2019 -o ./data/youtube_vis_2019/annotations --version 2019 + +# YouTube-VIS 2021 +python ./tools/dataset_converters/youtubevis2coco.py -i ./data/youtube_vis_2021 -o ./data/youtube_vis_2021/annotations --version 2021 + +``` + +运行这些脚本后,文件夹结构将如下所示: + +``` +mmdetection +├── mmtrack +├── tools +├── configs +├── data +│ ├── coco +│ │ ├── train2017 +│ │ ├── val2017 +│ │ ├── test2017 +│ │ ├── annotations +│ │ +| ├── MOT15/MOT16/MOT17/MOT20 +| | ├── train +| | | ├── MOT17-02-DPM +| | | | ├── det +| │ │ │ ├── gt +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── test +| | | ├── MOT17-01-DPM +| | | | ├── det +| │ │ │ ├── img1 +| │ │ │ ├── seqinfo.ini +│ │ │ ├── ...... +| | ├── annotations +| | ├── reid +│ │ │ ├── imgs +│ │ │ ├── meta +│ │ +│ ├── crowdhuman +│ │ ├── annotation_train.odgt +│ │ ├── annotation_val.odgt +│ │ ├── train +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_train01.zip +│ │ │ ├── CrowdHuman_train02.zip +│ │ │ ├── CrowdHuman_train03.zip +│ │ ├── val +│ │ │ ├── Images +│ │ │ ├── CrowdHuman_val.zip +│ │ ├── annotations +│ │ │ ├── crowdhuman_train.json +│ │ │ ├── crowdhuman_val.json +│ │ +│ ├── youtube_vis_2019 +│ │ │── train +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── valid +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── test +│ │ │ │── JPEGImages +│ │ │ │── ...... +│ │ │── train.json (the official annotation files) +│ │ │── valid.json (the official annotation files) +│ │ │── test.json (the official annotation files) +│ │ │── annotations (the converted annotation file) +│ │ +│ ├── youtube_vis_2021 +│ │ │── train +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── valid +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── test +│ │ │ │── JPEGImages +│ │ │ │── instances.json (the official annotation files) +│ │ │ │── ...... +│ │ │── annotations (the converted annotation file) +``` + +#### MOT15/MOT16/MOT17/MOT20中的注释和reid文件夹 + +以 MOT17 数据集为例,其他数据集的结构类似。 + +在 `data/MOT17/annotations` 文件夹中有8个JSON文件: + +`train_cocoformat.json`: 包含MOT17数据集训练集的注释信息的JSON文件。 + +`train_detections.pkl`: 包含MOT17数据集训练集的公共检测结果的Pickle文件。 + +`test_cocoformat.json`: 包含MOT17数据集测试集的注释信息的JSON文件。 + +`test_detections.pkl`: 包含MOT17数据集测试集的公共检测结果的Pickle文件。 + +`half-train_cocoformat.json`、`half-train_detections.pkl`、`half-val_cocoformat.json` 和 `half-val_detections.pkl` 与 `train_cocoformat.json` 和 `train_detections.pkl` 具有类似的含义。`half` 表示将训练集中的每个视频分成两半。前一半的视频被标记为 `half-train` 集,后一半的视频被标记为 `half-val` 集。 + +`data/MOT17/reid` 文件夹的结构如下所示: + +``` +reid +├── imgs +│ ├── MOT17-02-FRCNN_000002 +│ │ ├── 000000.jpg +│ │ ├── 000001.jpg +│ │ ├── ... +│ ├── MOT17-02-FRCNN_000003 +│ │ ├── 000000.jpg +│ │ ├── 000001.jpg +│ │ ├── ... +├── meta +│ ├── train_80.txt +│ ├── val_20.txt +``` + +`train_80.txt` 中的 `80` 表示训练数据集在整个ReID数据集中的比例为80%。而验证数据集的比例为20%。 + +关于训练,我们提供了一个注释列表 `train_80.txt`。列表中的每一行包含一个文件名及其对应的真实标签。格式如下所示: + +``` +MOT17-05-FRCNN_000110/000018.jpg 0 +MOT17-13-FRCNN_000146/000014.jpg 1 +MOT17-05-FRCNN_000088/000004.jpg 2 +MOT17-02-FRCNN_000009/000081.jpg 3 +``` + +`MOT17-05-FRCNN_000110` 表示 `MOT17-05-FRCNN` 视频中的第110个人。 + +对于验证集,注释列表 `val_20.txt` 的格式与上述相同。 + +`reid/imgs` 中的图像是通过相应的 `gt.txt` 从 `MOT17/train` 中的原始图像中裁剪而来。真实标签的值应在 `[0, num_classes - 1]` 的范围内。 + +#### CrowdHuman 中的 annotations 文件夹 + +`data/crowdhuman/annotations` 文件夹下有两个JSON文件: + +`crowdhuman_train.json`:包含 CrowdHuman 数据集训练集的注释信息的JSON文件。 +`crowdhuman_val.json`:包含 CrowdHuman 数据集验证集的注释信息的JSON文件。 + +#### youtube_vis_2019/youtube_vis2021 中的 annotations 文件夹 + +There are 3 JSON files in `data/youtube_vis_2019/annotations` or `data/youtube_vis_2021/annotations`: + +`youtube_vis_2019_train.json`/`youtube_vis_2021_train.json`:包含 youtube_vis_2019/youtube_vis2021 数据集训练集的注释信息的JSON文件。 + +`youtube_vis_2019_valid.json`/`youtube_vis_2021_valid.json`:包含 youtube_vis_2019/youtube_vis2021 数据集验证集的注释信息的JSON文件。 + +`youtube_vis_2019_test.json`/`youtube_vis_2021_test.json`:包含 youtube_vis_2019/youtube_vis2021 数据集测试集的注释信息的JSON文件。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_interference.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_interference.md new file mode 100644 index 0000000000000000000000000000000000000000..1b1fc08aeebeb5575a831429373c0591c34e1895 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_interference.md @@ -0,0 +1,55 @@ +# 推理 + +我们提供了一些演示脚本去推理一个给出的视频,或者是推理包含一系列连续照片的文件夹。想要获取该代码资源,请点击 [这里](https://github.com/open-mmlab/mmdetection/tree/tracking/demo)。 + +若输入为文件夹格式,你需要标明这点。并且,图片命名应该**易于整理**,以便于你根据文件名字中包含的数字信息来重新调整图片的顺序。我们现在只支持 `.jpg`,`.jpeg` 和 `.png` 格式的图片。 + +## MOT models 的推理 + +该脚本能够使用多任务跟踪或者视频实例分割方法来推理一段输入的视频/一张图片。 + +```shell +python demo/mot_demo.py \ + ${INPUTS} + ${CONFIG_FILE} \ + [--checkpoint ${CHECKPOINT_FILE}] \ + [--detector ${DETECTOR_FILE}] \ + [--reid ${REID_FILE}] \ + [--score-thr ${SCORE_THR}] \ + [--device ${DEVICE}] \ + [--out ${OUTPUT}] \ + [--show] +``` + +`INPUTS` 和 `OUTPUT` 参数支持 _mp4 视频_ 格式和_文件夹_格式。 + +**特别注意**:对于 `DeepSORT`、`SORT`、`StrongSORT`,他们需要单独加载 `reid` 和 `detector` 的权重。因此,我们会使用 `--detector` 和 `--reid` 来加载权重参数。其他的例如 `ByteTrack`、`OCSORT`、`QDTrack`、`MaskTrackRCNN` 以及 `Mask2Former` 这样的算法则使用 `--checkpoint` 来加载权重参数。 + +可选参数: + +- `CHECKPOINT_FILE`: 可选择 checkpoint。 +- `DETECTOR_FILE`: 可选择 detector。 +- `REID_FILE`: 可选择 reid。 +- `SCORE_THR`: bboxes 的得分阈值。 +- `DEVICE`: 推理所需配置。可以选择 `cpu`,`cuda:0`,或者其他。 +- `OUTPUT`: 输出结果可视化的示例。如果未指定, `--show` 将强制显示动态视频。 +- `--show`: 是否即时显示视频。 + +**运行 mot model 的示例:** + +```shell +# 示例 1:不指定 --checkpoint 使用 --detector +python demo/mot_demo.py \ + demo/demo_mot.mp4 \ + configs/sort/sort_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py \ + --detector \ + https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-half-64ee2ed4.pth \ + --out mot.mp4 + +# 示例 2:使用 --checkpoint +python demo/mot_demo.py \ + demo/demo_mot.mp4 \ + configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py \ + --checkpoint https://download.openmmlab.com/mmtracking/mot/qdtrack/mot_dataset/qdtrack_faster-rcnn_r50_fpn_4e_mot17_20220315_145635-76f295ef.pth \ + --out mot.mp4 +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_train_test_zh_cn.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_train_test_zh_cn.md new file mode 100644 index 0000000000000000000000000000000000000000..0542b9afcb07f05891980eb657337318c439d091 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_train_test_zh_cn.md @@ -0,0 +1,229 @@ +# 学习训练和测试 + +## 训练 + +本节将介绍如何在支持的数据集上训练现有模型。 +支持以下训练环境: + +- CPU +- 单 GPU +- 单节点多 GPU +- 多节点 + +您还可以使用 Slurm 管理作业。 + +重要: + +- 在训练过程中,您可以通过修改 `train_cfg` 来改变评估间隔。 + `train_cfg = dict(val_interval=10)`。这意味着每 10 个 epoch 对模型进行一次评估。 +- 所有配置文件中的默认学习率为 8 个 GPU。 + 根据[线性扩展规则](https://arxiv.org/abs/1706.02677)、 + 如果在每个 GPU 上使用不同的 GPU 或图像,则需要设置与批次大小成比例的学习率、 + 例如,8 个 GPU * 1 个图像/GPU 的学习率为 `lr=0.01`,16 个 GPU * 2 个图像/GPU 的学习率为 lr=0.04。 +- 在训练过程中,日志文件和检查点将保存到工作目录、 + 该目录由 CLI 参数 `--work-dir`指定。它默认使用 `./work_dirs/CONFIG_NAME`。 +- 如果需要混合精度训练,只需指定 CLI 参数 `--amp`。 + +#### 1.在 CPU 上训练 + +该模型默认放在 cuda 设备上。 +仅当没有 cuda 设备时,该模型才会放在 CPU 上。 +因此,如果要在 CPU 上训练模型,则需要先 `export CUDA_VISIBLE_DEVICES=-1` 以禁用 GPU 可见性。 +更多细节参见 [MMEngine](https://github.com/open-mmlab/mmengine/blob/ca282aee9e402104b644494ca491f73d93a9544f/mmengine/runner/runner.py#L849-L850). + +```shell 脚本 +CUDA_VISIBLE_DEVICES=-1 python tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +在 CPU 上训练 MOT 模型 QDTrack 的示例: + +```shell 脚本 +CUDA_VISIBLE_DEVICES=-1 python tools/train.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +``` + +#### 2. 在单 GPU 上训练 + +如果您想在单 GPU 上训练模型, 您可以按照如下方法直接使用 `tools/train.py`. + +```shell 脚本 +python tools/train.py ${CONFIG_FILE} [optional arguments] +``` + +您可以使用 `export CUDA_VISIBLE_DEVICES=$GPU_ID` 命令选择GPU. + +在单 GPU 上训练 MOT 模型 QDTrack 的示例: + +```shell 脚本 +CUDA_VISIBLE_DEVICES=2 python tools/train.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +``` + +#### 3. 在单节点多 GPU 上进行训练 + +我们提供了 `tools/dist_train.sh`,用于在多个 GPU 上启动训练。 +基本用法如下。 + +```shell 脚本 +bash ./tools/dist_train.sh ${CONFIG_FILE} ${GPU_NUM} [optional arguments] +``` + +如果您想在一台机器上启动多个作业、 +例如,在拥有 8 个 GPU 的机器上启动 2 个 4-GPU 训练作业、 +需要为每个作业指定不同的端口(默认为 29500),以避免通信冲突。 + +例如,可以在命令中设置端口如下。 + +```shell 脚本 +CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4 +CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4 +``` + +在单节点多 GPU 上训练 MOT 模型 QDTrack 的示例: + +```shell脚本 +bash ./tools/dist_train.sh configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py 8 +``` + +#### 4. 在多个节点上训练 + +如果使用以太网连接多台机器,只需运行以下命令即可: + +在第一台机器上 + +```shell 脚本 +NNODES=2 NODE_RANK=0 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR bash tools/dist_train.sh $CONFIG $GPUS +``` + +在第二台机器上: + +```shell script +NNODES=2 NODE_RANK=1 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR bash tools/dist_train.sh $CONFIG $GPUS +``` + +如果没有 InfiniBand 等高速网络,速度通常会很慢。 + +#### 5. 使用 Slurm 进行训练 + +[Slurm](https://slurm.schedmd.com/)是一个用于计算集群的优秀作业调度系统。 +在 Slurm 管理的集群上,您可以使用 `slurm_train.sh` 生成训练作业。 +它支持单节点和多节点训练。 + +基本用法如下。 + +```shell 脚本 +bash ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR} ${GPUS} +``` + +使用 Slurm 训练 MOT 模型 QDTrack 的示例: + +```shell脚本 +PORT=29501 \ +GPUS_PER_NODE=8 \ +SRUN_ARGS="--quotatype=reserved" \ +bash ./tools/slurm_train.sh \ +mypartition \ +mottrack +configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py +./work_dirs/QDTrack \ +8 +``` + +## 测试 + +本节将介绍如何在支持的数据集上测试现有模型。 +支持以下测试环境: + +- CPU +- 单 GPU +- 单节点多 GPU +- 多节点 + +您还可以使用 Slurm 管理作业。 + +重要: + +- 在 MOT 中,某些算法(如 `DeepSORT`、`SORT`、`StrongSORT`)需要分别加载 `reid` 的权重和 `detector` 的权重。 + 其他算法,如`ByteTrack`、`OCSORT`和`QDTrack`则不需要。因此,我们提供了 `--checkpoint`、`--detector` 和 `--reid`来加载权重。 +- 我们提供了两种评估和测试模型的方法,即基于视频的测试和基于图像的测试。 有些算法如 `StrongSORT`, `Mask2former` 只支持基于视频的测试. 如果您的 GPU 内存无法容纳整个视频,您可以通过设置采样器类型来切换测试方式。 + 例如 + 基于视频的测试:`sampler=dict(type='DefaultSampler', shuffle=False, round_up=False)` + 基于图像的测试:`sampler=dict(type='TrackImgSampler')` +- 您可以通过修改 evaluator 中的关键字 `outfile_prefix` 来设置结果保存路径。 + 例如,`val_evaluator = dict(outfile_prefix='results/sort_mot17')`。 + 否则,将创建一个临时文件,并在评估后删除。 +- 如果您只想要格式化的结果而不需要评估,可以设置 `format_only=True`。 + 例如,`test_evaluator = dict(type='MOTChallengeMetric', metric=['HOTA', 'CLEAR', 'Identity'], outfile_prefix='sort_mot17_results', format_only=True)` + +#### 1. 在 CPU 上测试 + +模型默认在 cuda 设备上运行。 +只有在没有 cuda 设备的情况下,模型才会在 CPU 上运行。 +因此,如果要在 CPU 上测试模型,您需要 `export CUDA_VISIBLE_DEVICES=-1` 先禁用 GPU 可见性。 + +更多细节请参考[MMEngine](https://github.com/open-mmlab/mmengine/blob/ca282aee9e402104b644494ca491f73d93a9544f/mmengine/runner/runner.py#L849-L850). + +```shell 脚本 +CUDA_VISIBLE_DEVICES=-1 python tools/test_tracking.py ${CONFIG_FILE} [optional arguments] +``` + +在 CPU 上测试 MOT 模型 SORT 的示例: + +```shell 脚本 +CUDA_VISIBLE_DEVICES=-1 python tools/test_tracking.py configs/sort/sort_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py --detector ${CHECKPOINT_FILE} +``` + +#### 2. 在单 GPU 上测试 + +如果您想在单 GPU 上测试模型,可以直接使用 `tools/test_tracking.py`,如下所示。 + +```shell 脚本 +python tools/test_tracking.py ${CONFIG_FILE} [optional arguments] +``` + +您可以使用 `export CUDA_VISIBLE_DEVICES=$GPU_ID` 来选择 GPU。 + +在单 GPU 上测试 MOT 模型 QDTrack 的示例: + +```shell 脚本 +CUDA_VISIBLE_DEVICES=2 python tools/test_tracking.py configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py --detector ${CHECKPOINT_FILE} +``` + +#### 3. 在单节点多 GPU 上进行测试 + +我们提供了 `tools/dist_test_tracking.sh`,用于在多个 GPU 上启动测试。 +基本用法如下。 + +```shell 脚本 +bash ./tools/dist_test_tracking.sh ${CONFIG_FILE} ${GPU_NUM} [optional arguments] +``` + +在单节点多 GPU 上测试 MOT 模型 DeepSort 的示例: + +```shell 脚本 +bash ./tools/dist_test_tracking.sh configs/qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_test-mot17halfval.py 8 --detector ${CHECKPOINT_FILE} --reid ${CHECKPOINT_FILE} +``` + +#### 4. 在多个节点上测试 + +您可以在多个节点上进行测试,这与 "在多个节点上进行训练 "类似。 + +#### 5. 使用 Slurm 进行测试 + +在 Slurm 管理的集群上,您可以使用 `slurm_test_tracking.sh` 生成测试作业。 +它支持单节点和多节点测试。 + +基本用法如下。 + +```shell 脚本 +[GPUS=${GPUS}] bash tools/slurm_test_tracking.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} [optional arguments] +``` + +使用 Slurm 测试 VIS 模型 Mask2former 的示例: + +```shell 脚本 +GPUS=8 +bash tools/slurm_test_tracking.sh \ +mypartition \ +vis \ +configs/mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py \ +--checkpoint ${CHECKPOINT_FILE} +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_visualization.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..0d10952aa1fbcfdee1ed7d53d4aef330b043c027 --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/tracking_visualization.md @@ -0,0 +1,51 @@ +# 了解可视化 + +## 本地的可视化 + +这一节将会展示如何使用本地的工具可视化 detection/tracking 的运行结果。 + +如果你想要画出预测结果的图像,你可以如下示例,将 `TrackVisualizationHook` 中的 draw 的参数设置为 `draw=True`。 + +```shell +default_hooks = dict(visualization=dict(type='TrackVisualizationHook', draw=True)) +``` + +`TrackVisualizationHook` 共有如下参数: + +- `draw`: 是否绘制预测结果。如果选择 False,将不会显示图像。该参数默认设置为 False。 +- `interval`: 可视化的间隔。默认值为 30。 +- `score_thr`: 确定是否可视化边界框和掩码的阈值。默认值是 0.3。 +- `show`: 是否展示绘制的图像。默认不显示。 +- `wait_time`: 展示的时间间隔(秒)。默认为 0。 +- `test_out_dir`: 测试过程中绘制图像保存的目录。 +- `backend_args`: 用于实例化文件客户端的参数。默认值为 `None `。 + +在 `TrackVisualizationHook` 中,将调用 `TrackLocalVisualizer` 来实现 MOT 和 VIS 任务的可视化。具体细节如下。 + +你可以通过 MMEngine 获取 [Visualization](https://github.com/open-mmlab/mmengine/blob/main/docs/zh_cn/advanced_tutorials/visualization.md) 和 [Hook](https://github.com/open-mmlab/mmengine/blob/main/docs/zh_cn/tutorials/hook.md) 的更多细节。 + +### Tracking 的可视化 + +我们使用 `TrackLocalVisualizer` 这个类以实现跟踪任务可视化。调用方式如下: + +```python +visualizer = dict(type='TrackLocalVisualizer') +``` + +visualizer 共有如下的参数: + +- `name`: 所选实例的名称。默认值为 ‘visualizer’。 + +- `image`: 用于绘制的原始图像。格式需要为 RGB。默认为 None。 + +- `vis_backends`: 可视化后端配置列表。默认为 None。 + +- `save_dir`: 所有后端存储的保存文件目录。如果为 None,后端将不会保存任何数据。 + +- `line_width`: 边框宽度。默认值为 3。 + +- `alpha`: 边界框和掩码的透明度。默认为 0.8。 + +这里提供了一个 DeepSORT 的可视化示例: + +![test_img_89](https://user-images.githubusercontent.com/99722489/186062929-6d0e4663-0d8e-4045-9ec8-67e0e41da876.png) diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/train.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/train.md new file mode 100644 index 0000000000000000000000000000000000000000..8feb1aa6912fdff9032a1aba35d2fcaace45dd7f --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/train.md @@ -0,0 +1,451 @@ +# 在标准数据集上训练预定义的模型 + +MMDetection 也为训练检测模型提供了开盖即食的工具。本节将展示在标准数据集(比如 COCO)上如何训练一个预定义的模型。 + +### 数据集 + +训练需要准备好数据集,细节请参考 [数据集准备](#%E6%95%B0%E6%8D%AE%E9%9B%86%E5%87%86%E5%A4%87) 。 + +**注意**: +目前,`configs/cityscapes` 文件夹下的配置文件都是使用 COCO 预训练权值进行初始化的。如果网络连接不可用或者速度很慢,你可以提前下载现存的模型。否则可能在训练的开始会有错误发生。 + +### 学习率自动缩放 + +**注意**:在配置文件中的学习率是在 8 块 GPU,每块 GPU 有 2 张图像(批大小为 8\*2=16)的情况下设置的。其已经设置在 `config/_base_/schedules/schedule_1x.py` 中的 `auto_scale_lr.base_batch_size`。学习率会基于批次大小为 `16`时的值进行自动缩放。同时,为了不影响其他基于 mmdet 的 codebase,启用自动缩放标志 `auto_scale_lr.enable` 默认设置为 `False`。 + +如果要启用此功能,需在命令添加参数 `--auto-scale-lr`。并且在启动命令之前,请检查下即将使用的配置文件的名称,因为配置名称指示默认的批处理大小。 +在默认情况下,批次大小是 `8 x 2 = 16`,例如:`faster_rcnn_r50_caffe_fpn_90k_coco.py` 或者 `pisa_faster_rcnn_x101_32x4d_fpn_1x_coco.py`;若不是默认批次,你可以在配置文件看到像 `_NxM_` 字样的,例如:`cornernet_hourglass104_mstest_32x3_210e_coco.py` 的批次大小是 `32 x 3 = 96`, 或者 `scnet_x101_64x4d_fpn_8x1_20e_coco.py` 的批次大小是 `8 x 1 = 8`。 + +**请记住:如果使用不是默认批次大小为 `16`的配置文件,请检查配置文件中的底部,会有 `auto_scale_lr.base_batch_size`。如果找不到,可以在其继承的 `_base_=[xxx]` 文件中找到。另外,如果想使用自动缩放学习率的功能,请不要修改这些值。** + +学习率自动缩放基本用法如下: + +```shell +python tools/train.py \ + ${CONFIG_FILE} \ + --auto-scale-lr \ + [optional arguments] +``` + +执行命令之后,会根据机器的GPU数量和训练的批次大小对学习率进行自动缩放,缩放方式详见 [线性扩展规则](https://arxiv.org/abs/1706.02677) ,比如:在 4 块 GPU 并且每张 GPU 上有 2 张图片的情况下 `lr=0.01`,那么在 16 块 GPU 并且每张 GPU 上有 4 张图片的情况下, LR 会自动缩放至 `lr=0.08`。 + +如果不启用该功能,则需要根据 [线性扩展规则](https://arxiv.org/abs/1706.02677) 来手动计算并修改配置文件里面 `optimizer.lr` 的值。 + +### 使用单 GPU 训练 + +我们提供了 `tools/train.py` 来开启在单张 GPU 上的训练任务。基本使用如下: + +```shell +python tools/train.py \ + ${CONFIG_FILE} \ + [optional arguments] +``` + +在训练期间,日志文件和 checkpoint 文件将会被保存在工作目录下,它需要通过配置文件中的 `work_dir` 或者 CLI 参数中的 `--work-dir` 来指定。 + +默认情况下,模型将在每轮训练之后在 validation 集上进行测试,测试的频率可以通过设置配置文件来指定: + +```python +# 每 12 轮迭代进行一次测试评估 +train_cfg = dict(val_interval=12) +``` + +这个工具接受以下参数: + +- `--work-dir ${WORK_DIR}`: 覆盖工作目录. +- `--resume`:自动从work_dir中的最新检查点恢复. +- `--resume ${CHECKPOINT_FILE}`: 从某个 checkpoint 文件继续训练. +- `--cfg-options 'Key=value'`: 覆盖使用的配置文件中的其他设置. + +**注意**: +`resume` 和 `load-from` 的区别: + +`resume` 既加载了模型的权重和优化器的状态,也会继承指定 checkpoint 的迭代次数,不会重新开始训练。`load-from` 则是只加载模型的权重,它的训练是从头开始的,经常被用于微调模型。其中load-from需要写入配置文件中,而resume作为命令行参数传入。 + +### 使用 CPU 训练 + +使用 CPU 训练的流程和使用单 GPU 训练的流程一致,我们仅需要在训练流程开始前禁用 GPU。 + +```shell +export CUDA_VISIBLE_DEVICES=-1 +``` + +之后运行单 GPU 训练脚本即可。 + +**注意**: + +我们不推荐用户使用 CPU 进行训练,这太过缓慢。我们支持这个功能是为了方便用户在没有 GPU 的机器上进行调试。 + +### 在多 GPU 上训练 + +我们提供了 `tools/dist_train.sh` 来开启在多 GPU 上的训练。基本使用如下: + +```shell +bash ./tools/dist_train.sh \ + ${CONFIG_FILE} \ + ${GPU_NUM} \ + [optional arguments] +``` + +可选参数和单 GPU 训练的可选参数一致。 + +#### 同时启动多个任务 + +如果你想在一台机器上启动多个任务的话,比如在一个有 8 块 GPU 的机器上启动 2 个需要 4 块GPU的任务,你需要给不同的训练任务指定不同的端口(默认为 29500)来避免冲突。 + +如果你使用 `dist_train.sh` 来启动训练任务,你可以使用命令来设置端口。 + +```shell +CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4 +CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4 +``` + +### 使用多台机器训练 + +如果您想使用由 ethernet 连接起来的多台机器, 您可以使用以下命令: + +在第一台机器上: + +```shell +NNODES=2 NODE_RANK=0 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS +``` + +在第二台机器上: + +```shell +NNODES=2 NODE_RANK=1 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS +``` + +但是,如果您不使用高速网路连接这几台机器的话,训练将会非常慢。 + +### 使用 Slurm 来管理任务 + +Slurm 是一个常见的计算集群调度系统。在 Slurm 管理的集群上,你可以使用 `slurm.sh` 来开启训练任务。它既支持单节点训练也支持多节点训练。 + +基本使用如下: + +```shell +[GPUS=${GPUS}] ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR} +``` + +以下是在一个名称为 _dev_ 的 Slurm 分区上,使用 16 块 GPU 来训练 Mask R-CNN 的例子,并且将 `work-dir` 设置在了某些共享文件系统下。 + +```shell +GPUS=16 ./tools/slurm_train.sh dev mask_r50_1x configs/mask_rcnn_r50_fpn_1x_coco.py /nfs/xxxx/mask_rcnn_r50_fpn_1x +``` + +你可以查看 [源码](https://github.com/open-mmlab/mmdetection/blob/main/tools/slurm_train.sh) 来检查全部的参数和环境变量. + +在使用 Slurm 时,端口需要以下方的某个方法之一来设置。 + +1. 通过 `--options` 来设置端口。我们非常建议用这种方法,因为它无需改变原始的配置文件。 + + ```shell + CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} --cfg-options 'dist_params.port=29500' + CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} --cfg-options 'dist_params.port=29501' + ``` + +2. 修改配置文件来设置不同的交流端口。 + + 在 `config1.py` 中,设置: + + ```python + dist_params = dict(backend='nccl', port=29500) + ``` + + 在 `config2.py` 中,设置: + + ```python + dist_params = dict(backend='nccl', port=29501) + ``` + + 然后你可以使用 `config1.py` 和 `config2.py` 来启动两个任务了。 + + ```shell + CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} + CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} + ``` + +# 在自定义数据集上进行训练 + +通过本文档,你将会知道如何使用自定义数据集对预先定义好的模型进行推理,测试以及训练。我们使用 [balloon dataset](https://github.com/matterport/Mask_RCNN/tree/master/samples/balloon) 作为例子来描述整个过程。 + +基本步骤如下: + +1. 准备自定义数据集 +2. 准备配置文件 +3. 在自定义数据集上进行训练,测试和推理。 + +## 准备自定义数据集 + +MMDetection 一共支持三种形式应用新数据集: + +1. 将数据集重新组织为 COCO 格式。 +2. 将数据集重新组织为一个中间格式。 +3. 实现一个新的数据集。 + +我们通常建议使用前面两种方法,因为它们通常来说比第三种方法要简单。 + +在本文档中,我们展示一个例子来说明如何将数据转化为 COCO 格式。 + +**注意**:在 MMDetection 3.0 之后,数据集和指标已经解耦(除了 CityScapes)。因此,用户在验证阶段使用任意的评价指标来评价模型在任意数据集上的性能。比如,用 VOC 评价指标来评价模型在 COCO 数据集的性能,或者同时使用 VOC 评价指标和 COCO 评价指标来评价模型在 OpenImages 数据集上的性能。 + +### COCO标注格式 + +用于实例分割的 COCO 数据集格式如下所示,其中的键(key)都是必要的,参考[这里](https://cocodataset.org/#format-data)来获取更多细节。 + +```json +{ + "images": [image], + "annotations": [annotation], + "categories": [category] +} + + +image = { + "id": int, + "width": int, + "height": int, + "file_name": str, +} + +annotation = { + "id": int, + "image_id": int, + "category_id": int, + "segmentation": RLE or [polygon], + "area": float, + "bbox": [x,y,width,height], # (x, y) 为 bbox 左上角的坐标 + "iscrowd": 0 or 1, +} + +categories = [{ + "id": int, + "name": str, + "supercategory": str, +}] +``` + +现在假设我们使用 balloon dataset。 + +下载了数据集之后,我们需要实现一个函数将标注格式转化为 COCO 格式。然后我们就可以使用已经实现的 `CocoDataset` 类来加载数据并进行训练以及评测。 + +如果你浏览过新数据集,你会发现格式如下: + +```json +{'base64_img_data': '', + 'file_attributes': {}, + 'filename': '34020010494_e5cb88e1c4_k.jpg', + 'fileref': '', + 'regions': {'0': {'region_attributes': {}, + 'shape_attributes': {'all_points_x': [1020, + 1000, + 994, + 1003, + 1023, + 1050, + 1089, + 1134, + 1190, + 1265, + 1321, + 1361, + 1403, + 1428, + 1442, + 1445, + 1441, + 1427, + 1400, + 1361, + 1316, + 1269, + 1228, + 1198, + 1207, + 1210, + 1190, + 1177, + 1172, + 1174, + 1170, + 1153, + 1127, + 1104, + 1061, + 1032, + 1020], + 'all_points_y': [963, + 899, + 841, + 787, + 738, + 700, + 663, + 638, + 621, + 619, + 643, + 672, + 720, + 765, + 800, + 860, + 896, + 942, + 990, + 1035, + 1079, + 1112, + 1129, + 1134, + 1144, + 1153, + 1166, + 1166, + 1150, + 1136, + 1129, + 1122, + 1112, + 1084, + 1037, + 989, + 963], + 'name': 'polygon'}}}, + 'size': 1115004} +``` + +标注文件时是 JSON 格式的,其中所有键(key)组成了一张图片的所有标注。 + +其中将 balloon dataset 转化为 COCO 格式的代码如下所示。 + +```python +import os.path as osp + +import mmcv + +from mmengine.fileio import dump, load +from mmengine.utils import track_iter_progress + + +def convert_balloon_to_coco(ann_file, out_file, image_prefix): + data_infos = load(ann_file) + + annotations = [] + images = [] + obj_count = 0 + for idx, v in enumerate(track_iter_progress(data_infos.values())): + filename = v['filename'] + img_path = osp.join(image_prefix, filename) + height, width = mmcv.imread(img_path).shape[:2] + + images.append( + dict(id=idx, file_name=filename, height=height, width=width)) + + for _, obj in v['regions'].items(): + assert not obj['region_attributes'] + obj = obj['shape_attributes'] + px = obj['all_points_x'] + py = obj['all_points_y'] + poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)] + poly = [p for x in poly for p in x] + + x_min, y_min, x_max, y_max = (min(px), min(py), max(px), max(py)) + + data_anno = dict( + image_id=idx, + id=obj_count, + category_id=0, + bbox=[x_min, y_min, x_max - x_min, y_max - y_min], + area=(x_max - x_min) * (y_max - y_min), + segmentation=[poly], + iscrowd=0) + annotations.append(data_anno) + obj_count += 1 + + coco_format_json = dict( + images=images, + annotations=annotations, + categories=[{ + 'id': 0, + 'name': 'balloon' + }]) + dump(coco_format_json, out_file) + + +if __name__ == '__main__': + convert_balloon_to_coco(ann_file='data/balloon/train/via_region_data.json', + out_file='data/balloon/train/annotation_coco.json', + image_prefix='data/balloon/train') + convert_balloon_to_coco(ann_file='data/balloon/val/via_region_data.json', + out_file='data/balloon/val/annotation_coco.json', + image_prefix='data/balloon/val') +``` + +使用如上的函数,用户可以成功将标注文件转化为 JSON 格式,之后可以使用 `CocoDataset` 对模型进行训练,并用 `CocoMetric` 评测。 + +## 准备配置文件 + +第二步需要准备一个配置文件来成功加载数据集。假设我们想要用 balloon dataset 来训练配备了 FPN 的 Mask R-CNN ,如下是我们的配置文件。假设配置文件命名为 `mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py`,相应保存路径为 `configs/balloon/`,配置文件内容如下所示。详细的配置文件方法可以参考[学习配置文件 — MMDetection 3.0.0 文档](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/config.html#base)。 + +```python +# 新配置继承了基本配置,并做了必要的修改 +_base_ = '../mask_rcnn/mask-rcnn_r50-caffe_fpn_ms-poly-1x_coco.py' + +# 我们还需要更改 head 中的 num_classes 以匹配数据集中的类别数 +model = dict( + roi_head=dict( + bbox_head=dict(num_classes=1), mask_head=dict(num_classes=1))) + +# 修改数据集相关配置 +data_root = 'data/balloon/' +metainfo = { + 'classes': ('balloon', ), + 'palette': [ + (220, 20, 60), + ] +} +train_dataloader = dict( + batch_size=1, + dataset=dict( + data_root=data_root, + metainfo=metainfo, + ann_file='train/annotation_coco.json', + data_prefix=dict(img='train/'))) +val_dataloader = dict( + dataset=dict( + data_root=data_root, + metainfo=metainfo, + ann_file='val/annotation_coco.json', + data_prefix=dict(img='val/'))) +test_dataloader = val_dataloader + +# 修改评价指标相关配置 +val_evaluator = dict(ann_file=data_root + 'val/annotation_coco.json') +test_evaluator = val_evaluator + +# 使用预训练的 Mask R-CNN 模型权重来做初始化,可以提高模型性能 +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth' + +``` + +## 训练一个新的模型 + +为了使用新的配置方法来对模型进行训练,你只需要运行如下命令。 + +```shell +python tools/train.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py +``` + +参考 [在标准数据集上训练预定义的模型](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/train.html#id1) 来获取更多详细的使用方法。 + +## 测试以及推理 + +为了测试训练完毕的模型,你只需要运行如下命令。 + +```shell +python tools/test.py configs/balloon/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon.py work_dirs/mask-rcnn_r50-caffe_fpn_ms-poly-1x_balloon/epoch_12.pth +``` + +参考 [测试现有模型](https://mmdetection.readthedocs.io/zh_CN/latest/user_guides/test.html) 来获取更多详细的使用方法。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/useful_hooks.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/useful_hooks.md new file mode 100644 index 0000000000000000000000000000000000000000..07a59df2a8b25e7ca6a8ff0512542560e98b314e --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/useful_hooks.md @@ -0,0 +1,107 @@ +# 实用的钩子 + +MMDetection 和 MMEngine 为用户提供了多种多样实用的钩子(Hook),包括 `MemoryProfilerHook`、`NumClassCheckHook` 等等。 +这篇教程介绍了 MMDetection 中实现的钩子功能及使用方式。若使用 MMEngine 定义的钩子请参考 [MMEngine 的钩子API文档](https://github.com/open-mmlab/mmengine/tree/main/docs/en/tutorials/hook.md). + +## CheckInvalidLossHook + +## NumClassCheckHook + +## MemoryProfilerHook + +[内存分析钩子](https://github.com/open-mmlab/mmdetection/blob/main/mmdet/engine/hooks/memory_profiler_hook.py) +记录了包括虚拟内存、交换内存、当前进程在内的所有内存信息,它能够帮助捕捉系统的使用状况与发现隐藏的内存泄露问题。为了使用这个钩子,你需要先通过 `pip install memory_profiler psutil` 命令安装 `memory_profiler` 和 `psutil`。 + +### 使用 + +为了使用这个钩子,使用者需要添加如下代码至 config 文件 + +```python +custom_hooks = [ + dict(type='MemoryProfilerHook', interval=50) +] +``` + +### 结果 + +在训练中,你会看到 `MemoryProfilerHook` 记录的如下信息: + +```text +The system has 250 GB (246360 MB + 9407 MB) of memory and 8 GB (5740 MB + 2452 MB) of swap memory in total. Currently 9407 MB (4.4%) of memory and 5740 MB (29.9%) of swap memory were consumed. And the current training process consumed 5434 MB of memory. +``` + +```text +2022-04-21 08:49:56,881 - mmengine - INFO - Memory information available_memory: 246360 MB, used_memory: 9407 MB, memory_utilization: 4.4 %, available_swap_memory: 5740 MB, used_swap_memory: 2452 MB, swap_memory_utilization: 29.9 %, current_process_memory: 5434 MB +``` + +## SetEpochInfoHook + +## SyncNormHook + +## SyncRandomSizeHook + +## YOLOXLrUpdaterHook + +## YOLOXModeSwitchHook + +## 如何实现自定义钩子 + +通常,从模型训练的开始到结束,共有20个点位可以执行钩子。我们可以实现自定义钩子在不同点位执行,以便在训练中实现自定义操作。 + +- global points: `before_run`, `after_run` +- points in training: `before_train`, `before_train_epoch`, `before_train_iter`, `after_train_iter`, `after_train_epoch`, `after_train` +- points in validation: `before_val`, `before_val_epoch`, `before_val_iter`, `after_val_iter`, `after_val_epoch`, `after_val` +- points at testing: `before_test`, `before_test_epoch`, `before_test_iter`, `after_test_iter`, `after_test_epoch`, `after_test` +- other points: `before_save_checkpoint`, `after_save_checkpoint` + +比如,我们要实现一个检查 loss 的钩子,当损失为 NaN 时自动结束训练。我们可以把这个过程分为三步: + +1. 在 MMEngine 实现一个继承于 `Hook` 类的新钩子,并实现 `after_train_iter` 方法用于检查每 `n` 次训练迭代后损失是否变为 NaN 。 +2. 使用 `@HOOKS.register_module()` 注册实现好了的自定义钩子,如下列代码所示。 +3. 在配置文件中添加 `custom_hooks = [dict(type='MemoryProfilerHook', interval=50)]` + +```python +from typing import Optional + +import torch +from mmengine.hooks import Hook +from mmengine.runner import Runner + +from mmdet.registry import HOOKS + + +@HOOKS.register_module() +class CheckInvalidLossHook(Hook): + """Check invalid loss hook. + + This hook will regularly check whether the loss is valid + during training. + + Args: + interval (int): Checking interval (every k iterations). + Default: 50. + """ + + def __init__(self, interval: int = 50) -> None: + self.interval = interval + + def after_train_iter(self, + runner: Runner, + batch_idx: int, + data_batch: Optional[dict] = None, + outputs: Optional[dict] = None) -> None: + """Regularly check whether the loss is valid every n iterations. + + Args: + runner (:obj:`Runner`): The runner of the training process. + batch_idx (int): The index of the current batch in the train loop. + data_batch (dict, Optional): Data from dataloader. + Defaults to None. + outputs (dict, Optional): Outputs from model. Defaults to None. + """ + if self.every_n_train_iters(runner, self.interval): + assert torch.isfinite(outputs['loss']), \ + runner.logger.info('loss become infinite or NaN!') +``` + +请参考 [自定义训练配置](../advanced_guides/customize_runtime.md) 了解更多与自定义钩子相关的内容。 diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/useful_tools.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/useful_tools.md new file mode 100644 index 0000000000000000000000000000000000000000..8416472c90ea9f44c36753605c4996be0363200b --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/useful_tools.md @@ -0,0 +1,636 @@ +除了训练和测试脚本,我们还在 `tools/` 目录下提供了许多有用的工具。 + +## 日志分析 + +`tools/analysis_tools/analyze_logs.py` 可利用指定的训练 log 文件绘制 loss/mAP 曲线图, +第一次运行前请先运行 `pip install seaborn` 安装必要依赖. + +```shell +python tools/analysis_tools/analyze_logs.py plot_curve [--keys ${KEYS}] [--eval-interval ${EVALUATION_INTERVAL}] [--title ${TITLE}] [--legend ${LEGEND}] [--backend ${BACKEND}] [--style ${STYLE}] [--out ${OUT_FILE}] +``` + +![loss curve image](../../../resources/loss_curve.png) + +样例: + +- 绘制分类损失曲线图 + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log.json --keys loss_cls --legend loss_cls + ``` + +- 绘制分类损失、回归损失曲线图,保存图片为对应的 pdf 文件 + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log.json --keys loss_cls loss_bbox --out losses.pdf + ``` + +- 在相同图像中比较两次运行结果的 bbox mAP + + ```shell + python tools/analysis_tools/analyze_logs.py plot_curve log1.json log2.json --keys bbox_mAP --legend run1 run2 + ``` + +- 计算平均训练速度 + + ```shell + python tools/analysis_tools/analyze_logs.py cal_train_time log.json [--include-outliers] + ``` + + 输出以如下形式展示 + + ```text + -----Analyze train time of work_dirs/some_exp/20190611_192040.log.json----- + slowest epoch 11, average time is 1.2024 + fastest epoch 1, average time is 1.1909 + time std over epochs is 0.0028 + average iter time: 1.1959 s/iter + ``` + +## 结果分析 + +使用 `tools/analysis_tools/analyze_results.py` 可计算每个图像 mAP,随后根据真实标注框与预测框的比较结果,展示或保存最高与最低 top-k 得分的预测图像。 + +**使用方法** + +```shell +python tools/analysis_tools/analyze_results.py \ + ${CONFIG} \ + ${PREDICTION_PATH} \ + ${SHOW_DIR} \ + [--show] \ + [--wait-time ${WAIT_TIME}] \ + [--topk ${TOPK}] \ + [--show-score-thr ${SHOW_SCORE_THR}] \ + [--cfg-options ${CFG_OPTIONS}] +``` + +各个参数选项的作用: + +- `config`: model config 文件的路径。 +- `prediction_path`: 使用 `tools/test.py` 输出的 pickle 格式结果文件。 +- `show_dir`: 绘制真实标注框与预测框的图像存放目录。 +- `--show`:决定是否展示绘制 box 后的图片,默认值为 `False`。 +- `--wait-time`: show 时间的间隔,若为 0 表示持续显示。 +- `--topk`: 根据最高或最低 `topk` 概率排序保存的图片数量,若不指定,默认设置为 `20`。 +- `--show-score-thr`: 能够展示的概率阈值,默认为 `0`。 +- `--cfg-options`: 如果指定,可根据指定键值对覆盖更新配置文件的对应选项 + +**样例**: +假设你已经通过 `tools/test.py` 得到了 pickle 格式的结果文件,路径为 './result.pkl'。 + +1. 测试 Faster R-CNN 并可视化结果,保存图片至 `results/` + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --show +``` + +2. 测试 Faster R-CNN 并指定 top-k 参数为 50,保存结果图片至 `results/` + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --topk 50 +``` + +3. 如果你想过滤低概率的预测结果,指定 `show-score-thr` 参数 + +```shell +python tools/analysis_tools/analyze_results.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + result.pkl \ + results \ + --show-score-thr 0.3 +``` + +## 多模型检测结果融合 + +`tools/analysis_tools/fuse_results.py` 可使用 Weighted Boxes Fusion(WBF) 方法将多个模型的检测结果进行融合。(当前仅支持 COCO 格式) + +**使用方法** + +```shell +python tools/analysis_tools/fuse_results.py \ + ${PRED_RESULTS} \ + [--annotation ${ANNOTATION}] \ + [--weights ${WEIGHTS}] \ + [--fusion-iou-thr ${FUSION_IOU_THR}] \ + [--skip-box-thr ${SKIP_BOX_THR}] \ + [--conf-type ${CONF_TYPE}] \ + [--eval-single ${EVAL_SINGLE}] \ + [--save-fusion-results ${SAVE_FUSION_RESULTS}] \ + [--out-dir ${OUT_DIR}] +``` + +各个参数选项的作用: + +- `pred-results`: 多模型测试结果的保存路径。(目前仅支持 json 格式) +- `--annotation`: 真实标注框的保存路径。 +- `--weights`: 模型融合权重。默认设置下,每个模型的权重均为1。 +- `--fusion-iou-thr`: 在WBF算法中,匹配成功的 IoU 阈值,默认值为`0.55`。 +- `--skip-box-thr`: WBF算法中需剔除的置信度阈值,置信度小于该值的 bbox 会被剔除,默认值为`0`。 +- `--conf-type`: 如何计算融合后 bbox 的置信度。有以下四种选项: + - `avg`: 取平均值,默认为此选项。 + - `max`: 取最大值。 + - `box_and_model_avg`: box和模型尺度的加权平均值。 + - `absent_model_aware_avg`: 考虑缺失模型的加权平均值。 +- `--eval-single`: 是否评估每个单一模型,默认值为`False`。 +- `--save-fusion-results`: 是否保存融合结果,默认值为`False`。 +- `--out-dir`: 融合结果保存的路径。 + +**样例**: +假设你已经通过 `tools/test.py` 得到了3个模型的 json 格式的结果文件,路径分别为 './faster-rcnn_r50-caffe_fpn_1x_coco.json', './retinanet_r50-caffe_fpn_1x_coco.json', './cascade-rcnn_r50-caffe_fpn_1x_coco.json',真实标注框的文件路径为'./annotation.json'。 + +1. 融合三个模型的预测结果并评估其效果 + +```shell +python tools/analysis_tools/fuse_results.py \ + ./faster-rcnn_r50-caffe_fpn_1x_coco.json \ + ./retinanet_r50-caffe_fpn_1x_coco.json \ + ./cascade-rcnn_r50-caffe_fpn_1x_coco.json \ + --annotation ./annotation.json \ + --weights 1 2 3 \ +``` + +2. 同时评估每个单一模型与融合结果 + +```shell +python tools/analysis_tools/fuse_results.py \ + ./faster-rcnn_r50-caffe_fpn_1x_coco.json \ + ./retinanet_r50-caffe_fpn_1x_coco.json \ + ./cascade-rcnn_r50-caffe_fpn_1x_coco.json \ + --annotation ./annotation.json \ + --weights 1 2 3 \ + --eval-single +``` + +3. 融合三个模型的预测结果并保存 + +```shell +python tools/analysis_tools/fuse_results.py \ + ./faster-rcnn_r50-caffe_fpn_1x_coco.json \ + ./retinanet_r50-caffe_fpn_1x_coco.json \ + ./cascade-rcnn_r50-caffe_fpn_1x_coco.json \ + --annotation ./annotation.json \ + --weights 1 2 3 \ + --save-fusion-results \ + --out-dir outputs/fusion +``` + +## 可视化 + +### 可视化数据集 + +`tools/analysis_tools/browse_dataset.py` 可帮助使用者检查所使用的检测数据集(包括图像和标注),或保存图像至指定目录。 + +```shell +python tools/analysis_tools/browse_dataset.py ${CONFIG} [-h] [--skip-type ${SKIP_TYPE[SKIP_TYPE...]}] [--output-dir ${OUTPUT_DIR}] [--not-show] [--show-interval ${SHOW_INTERVAL}] +``` + +### 可视化模型 + +在可视化之前,需要先转换模型至 ONNX 格式,[可参考此处](#convert-mmdetection-model-to-onnx-experimental)。 +注意,现在只支持 RetinaNet,之后的版本将会支持其他模型 +转换后的模型可以被其他工具可视化[Netron](https://github.com/lutzroeder/netron)。 + +### 可视化预测结果 + +如果你想要一个轻量 GUI 可视化检测结果,你可以参考 [DetVisGUI project](https://github.com/Chien-Hung/DetVisGUI/tree/mmdetection)。 + +## 误差分析 + +`tools/analysis_tools/coco_error_analysis.py` 使用不同标准分析每个类别的 COCO 评估结果。同时将一些有帮助的信息体现在图表上。 + +```shell +python tools/analysis_tools/coco_error_analysis.py ${RESULT} ${OUT_DIR} [-h] [--ann ${ANN}] [--types ${TYPES[TYPES...]}] +``` + +样例: + +假设你已经把 [Mask R-CNN checkpoint file](https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_fpn_1x_coco/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth) 放置在文件夹 'checkpoint' 中(其他模型请在 [model zoo](./model_zoo.md) 中获取)。 + +为了保存 bbox 结果信息,我们需要用下列方式修改 `test_evaluator` : + +1. 查找当前 config 文件相对应的 'configs/base/datasets' 数据集信息。 +2. 用当前数据集 config 中的 test_evaluator 以及 test_dataloader 替换原始文件的 test_evaluator 以及 test_dataloader。 +3. 使用以下命令得到 bbox 或 segmentation 的 json 格式文件。 + +```shell +python tools/test.py \ + configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py \ + checkpoint/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \ +``` + +1. 得到每一类的 COCO bbox 误差结果,并保存分析结果图像至指定目录。(在 [config](../../../configs/_base_/datasets/coco_instance.py) 中默认目录是 './work_dirs/coco_instance/test') + +```shell +python tools/analysis_tools/coco_error_analysis.py \ + results.bbox.json \ + results \ + --ann=data/coco/annotations/instances_val2017.json \ +``` + +2. 得到每一类的 COCO 分割误差结果,并保存分析结果图像至指定目录。 + +```shell +python tools/analysis_tools/coco_error_analysis.py \ + results.segm.json \ + results \ + --ann=data/coco/annotations/instances_val2017.json \ + --types='segm' +``` + +## 模型服务部署 + +如果你想使用 [`TorchServe`](https://pytorch.org/serve/) 搭建一个 `MMDetection` 模型服务,可以参考以下步骤: + +### 1. 安装 TorchServe + +假设你已经成功安装了包含 `PyTorch` 和 `MMDetection` 的 `Python` 环境,那么你可以运行以下命令来安装 `TorchServe` 及其依赖项。有关更多其他安装选项,请参考[快速入门](https://github.com/pytorch/serve/blob/master/README.md#serve-a-model)。 + +```shell +python -m pip install torchserve torch-model-archiver torch-workflow-archiver nvgpu +``` + +**注意**: 如果你想在 docker 中使用`TorchServe`,请参考[torchserve docker](https://github.com/pytorch/serve/blob/master/docker/README.md)。 + +### 2. 把 MMDetection 模型转换至 TorchServe + +```shell +python tools/deployment/mmdet2torchserve.py ${CONFIG_FILE} ${CHECKPOINT_FILE} \ +--output-folder ${MODEL_STORE} \ +--model-name ${MODEL_NAME} +``` + +### 3. 启动 `TorchServe` + +```shell +torchserve --start --ncs \ + --model-store ${MODEL_STORE} \ + --models ${MODEL_NAME}.mar +``` + +### 4. 测试部署效果 + +```shell +curl -O curl -O https://raw.githubusercontent.com/pytorch/serve/master/docs/images/3dogs.jpg +curl http://127.0.0.1:8080/predictions/${MODEL_NAME} -T 3dogs.jpg +``` + +你可以得到下列 json 信息: + +```json +[ + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 294.63409423828125, + 203.99111938476562, + 417.048583984375, + 281.62744140625 + ], + "score": 0.9987992644309998 + }, + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 404.26019287109375, + 126.0080795288086, + 574.5091552734375, + 293.6662292480469 + ], + "score": 0.9979367256164551 + }, + { + "class_label": 16, + "class_name": "dog", + "bbox": [ + 197.2144775390625, + 93.3067855834961, + 307.8505554199219, + 276.7560119628906 + ], + "score": 0.993338406085968 + } +] +``` + +#### 结果对比 + +你也可以使用 `test_torchserver.py` 来比较 `TorchServe` 和 `PyTorch` 的结果,并可视化: + +```shell +python tools/deployment/test_torchserver.py ${IMAGE_FILE} ${CONFIG_FILE} ${CHECKPOINT_FILE} ${MODEL_NAME} +[--inference-addr ${INFERENCE_ADDR}] [--device ${DEVICE}] [--score-thr ${SCORE_THR}] [--work-dir ${WORK_DIR}] +``` + +样例: + +```shell +python tools/deployment/test_torchserver.py \ +demo/demo.jpg \ +configs/yolo/yolov3_d53_8xb8-320-273e_coco.py \ +checkpoint/yolov3_d53_320_273e_coco-421362b6.pth \ +yolov3 \ +--work-dir ./work-dir +``` + +### 5. 停止 `TorchServe` + +```shell +torchserve --stop +``` + +## 模型复杂度 + +`tools/analysis_tools/get_flops.py` 工具可用于计算指定模型的 FLOPs、参数量大小(改编自 [flops-counter.pytorch](https://github.com/sovrasov/flops-counter.pytorch) )。 + +```shell +python tools/analysis_tools/get_flops.py ${CONFIG_FILE} [--shape ${INPUT_SHAPE}] +``` + +获得的结果如下: + +```text +============================== +Input shape: (3, 1280, 800) +Flops: 239.32 GFLOPs +Params: 37.74 M +============================== +``` + +**注意**:这个工具还只是实验性质,我们不保证这个数值是绝对正确的。你可以将他用于简单的比较,但如果用于科技论文报告需要再三检查确认。 + +1. FLOPs 与输入的形状大小相关,参数量没有这个关系,默认的输入形状大小为 (1, 3, 1280, 800) 。 +2. 一些算子并不计入 FLOPs,比如 GN 或其他自定义的算子。你可以参考 [`mmcv.cnn.get_model_complexity_info()`](https://github.com/open-mmlab/mmcv/blob/2.x/mmcv/cnn/utils/flops_counter.py) 查看更详细的说明。 +3. 两阶段检测的 FLOPs 大小取决于 proposal 的数量。 + +## 模型转换 + +### MMDetection 模型转换至 ONNX 格式 + +我们提供了一个脚本用于转换模型至 [ONNX](https://github.com/onnx/onnx) 格式。同时还支持比较 Pytorch 与 ONNX 模型的输出结果以便对照。更详细的内容可以参考 [mmdeploy](https://github.com/open-mmlab/mmdeploy)。 + +### MMDetection 1.x 模型转换至 MMDetection 2.x 模型 + +`tools/model_converters/upgrade_model_version.py` 可将旧版本的 MMDetection checkpoints 转换至新版本。但要注意此脚本不保证在新版本加入非兼容更新后还能正常转换,建议您直接使用新版本的 checkpoints。 + +```shell +python tools/model_converters/upgrade_model_version.py ${IN_FILE} ${OUT_FILE} [-h] [--num-classes NUM_CLASSES] +``` + +### RegNet 模型转换至 MMDetection 模型 + +`tools/model_converters/regnet2mmdet.py` 将 pycls 编码的预训练 RegNet 模型转换为 MMDetection 风格。 + +```shell +python tools/model_converters/regnet2mmdet.py ${SRC} ${DST} [-h] +``` + +### Detectron ResNet 模型转换至 Pytorch 模型 + +`tools/model_converters/detectron2pytorch.py` 将 detectron 的原始预训练 RegNet 模型转换为 MMDetection 风格。 + +```shell +python tools/model_converters/detectron2pytorch.py ${SRC} ${DST} ${DEPTH} [-h] +``` + +### 制作发布用模型 + +`tools/model_converters/publish_model.py` 可用来制作一个发布用的模型。 + +在发布模型至 AWS 之前,你可能需要: + +1. 将模型转换至 CPU 张量 +2. 删除优化器状态 +3. 计算 checkpoint 文件的 hash 值,并将 hash 号码记录至文件名。 + +```shell +python tools/model_converters/publish_model.py ${INPUT_FILENAME} ${OUTPUT_FILENAME} +``` + +样例: + +```shell +python tools/model_converters/publish_model.py work_dirs/faster_rcnn/latest.pth faster_rcnn_r50_fpn_1x_20190801.pth +``` + +最后输出的文件名如下所示: `faster_rcnn_r50_fpn_1x_20190801-{hash id}.pth`. + +## 数据集转换 + +`tools/data_converters/` 提供了将 Cityscapes 数据集与 Pascal VOC 数据集转换至 COCO 数据集格式的工具 + +```shell +python tools/dataset_converters/cityscapes.py ${CITYSCAPES_PATH} [-h] [--img-dir ${IMG_DIR}] [--gt-dir ${GT_DIR}] [-o ${OUT_DIR}] [--nproc ${NPROC}] +python tools/dataset_converters/pascal_voc.py ${DEVKIT_PATH} [-h] [-o ${OUT_DIR}] +``` + +## 数据集下载 + +`tools/misc/download_dataset.py` 可以下载各类形如 COCO, VOC, LVIS 数据集。 + +```shell +python tools/misc/download_dataset.py --dataset-name coco2017 +python tools/misc/download_dataset.py --dataset-name voc2007 +python tools/misc/download_dataset.py --dataset-name lvis +``` + +对于中国境内的用户,我们也推荐使用开源数据平台 [OpenDataLab](https://opendatalab.com/?source=OpenMMLab%20GitHub) 来获取这些数据集,以获得更好的下载体验: + +- [COCO2017](https://opendatalab.com/COCO_2017/download?source=OpenMMLab%20GitHub) +- [VOC2007](https://opendatalab.com/PASCAL_VOC2007/download?source=OpenMMLab%20GitHub) +- [VOC2012](https://opendatalab.com/PASCAL_VOC2012/download?source=OpenMMLab%20GitHub) +- [LVIS](https://opendatalab.com/LVIS/download?source=OpenMMLab%20GitHub) + +## 基准测试 + +### 鲁棒性测试基准 + +`tools/analysis_tools/test_robustness.py` 及 `tools/analysis_tools/robustness_eval.py` 帮助使用者衡量模型的鲁棒性。其核心思想来源于 [Benchmarking Robustness in Object Detection: Autonomous Driving when Winter is Coming](https://arxiv.org/abs/1907.07484)。如果你想了解如何在污损图像上评估模型的效果,以及参考该基准的一组标准模型,请参照 [robustness_benchmarking.md](robustness_benchmarking.md)。 + +### FPS 测试基准 + +`tools/analysis_tools/benchmark.py` 可帮助使用者计算 FPS,FPS 计算包括了模型向前传播与后处理过程。为了得到更精确的计算值,现在的分布式计算模式只支持一个 GPU。 + +```shell +python -m torch.distributed.launch --nproc_per_node=1 --master_port=${PORT} tools/analysis_tools/benchmark.py \ + ${CONFIG} \ + [--checkpoint ${CHECKPOINT}] \ + [--repeat-num ${REPEAT_NUM}] \ + [--max-iter ${MAX_ITER}] \ + [--log-interval ${LOG_INTERVAL}] \ + --launcher pytorch +``` + +样例:假设你已经下载了 `Faster R-CNN` 模型 checkpoint 并放置在 `checkpoints/` 目录下。 + +```shell +python -m torch.distributed.launch --nproc_per_node=1 --master_port=29500 tools/analysis_tools/benchmark.py \ + configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py \ + checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \ + --launcher pytorch +``` + +## 更多工具 + +### 以某个评估标准进行评估 + +`tools/analysis_tools/eval_metric.py` 根据配置文件中的评估方式对 pkl 结果文件进行评估。 + +```shell +python tools/analysis_tools/eval_metric.py ${CONFIG} ${PKL_RESULTS} [-h] [--format-only] [--eval ${EVAL[EVAL ...]}] + [--cfg-options ${CFG_OPTIONS [CFG_OPTIONS ...]}] + [--eval-options ${EVAL_OPTIONS [EVAL_OPTIONS ...]}] +``` + +### 打印全部 config + +`tools/misc/print_config.py` 可将所有配置继承关系展开,完全打印相应的配置文件。 + +```shell +python tools/misc/print_config.py ${CONFIG} [-h] [--options ${OPTIONS [OPTIONS...]}] +``` + +## 超参数优化 + +### YOLO Anchor 优化 + +`tools/analysis_tools/optimize_anchors.py` 提供了两种方法优化 YOLO 的 anchors。 + +其中一种方法使用 K 均值 anchor 聚类(k-means anchor cluster),源自 [darknet](https://github.com/AlexeyAB/darknet/blob/master/src/detector.c#L1421)。 + +```shell +python tools/analysis_tools/optimize_anchors.py ${CONFIG} --algorithm k-means --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} --output-dir ${OUTPUT_DIR} +``` + +另一种方法使用差分进化算法优化 anchors。 + +```shell +python tools/analysis_tools/optimize_anchors.py ${CONFIG} --algorithm differential_evolution --input-shape ${INPUT_SHAPE [WIDTH HEIGHT]} --output-dir ${OUTPUT_DIR} +``` + +样例: + +```shell +python tools/analysis_tools/optimize_anchors.py configs/yolo/yolov3_d53_8xb8-320-273e_coco.py --algorithm differential_evolution --input-shape 608 608 --device cuda --output-dir work_dirs +``` + +你可能会看到如下结果: + +``` +loading annotations into memory... +Done (t=9.70s) +creating index... +index created! +2021-07-19 19:37:20,951 - mmdet - INFO - Collecting bboxes from annotation... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 117266/117266, 15874.5 task/s, elapsed: 7s, ETA: 0s + +2021-07-19 19:37:28,753 - mmdet - INFO - Collected 849902 bboxes. +differential_evolution step 1: f(x)= 0.506055 +differential_evolution step 2: f(x)= 0.506055 +...... + +differential_evolution step 489: f(x)= 0.386625 +2021-07-19 19:46:40,775 - mmdet - INFO Anchor evolution finish. Average IOU: 0.6133754253387451 +2021-07-19 19:46:40,776 - mmdet - INFO Anchor differential evolution result:[[10, 12], [15, 30], [32, 22], [29, 59], [61, 46], [57, 116], [112, 89], [154, 198], [349, 336]] +2021-07-19 19:46:40,798 - mmdet - INFO Result saved in work_dirs/anchor_optimize_result.json +``` + +## 混淆矩阵 + +混淆矩阵是对检测结果的概览。 +`tools/analysis_tools/confusion_matrix.py` 可对预测结果进行分析,绘制成混淆矩阵表。 +首先,运行 `tools/test.py` 保存 `.pkl` 预测结果。 +之后再运行: + +``` +python tools/analysis_tools/confusion_matrix.py ${CONFIG} ${DETECTION_RESULTS} ${SAVE_DIR} --show +``` + +最后你可以得到如图的混淆矩阵: + +![confusion_matrix_example](https://user-images.githubusercontent.com/12907710/140513068-994cdbf4-3a4a-48f0-8fd8-2830d93fd963.png) + +## COCO 分离和遮挡实例分割性能评估 + +对于最先进的目标检测器来说,检测被遮挡的物体仍然是一个挑战。 +我们实现了论文 [A Tri-Layer Plugin to Improve Occluded Detection](https://arxiv.org/abs/2210.10046) 中提出的指标来计算分离和遮挡目标的召回率。 + +使用此评价指标有两种方法: + +### 离线评测 + +我们提供了一个脚本对存储后的检测结果文件计算指标。 + +首先,使用 `tools/test.py` 脚本存储检测结果: + +```shell +python tools/test.py ${CONFIG} ${MODEL_PATH} --out results.pkl +``` + +然后,运行 `tools/analysis_tools/coco_occluded_separated_recall.py` 脚本来计算分离和遮挡目标的掩码的召回率: + +```shell +python tools/analysis_tools/coco_occluded_separated_recall.py results.pkl --out occluded_separated_recall.json +``` + +输出如下: + +``` +loading annotations into memory... +Done (t=0.51s) +creating index... +index created! +processing detection results... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5000/5000, 109.3 task/s, elapsed: 46s, ETA: 0s +computing occluded mask recall... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5550/5550, 780.5 task/s, elapsed: 7s, ETA: 0s +COCO occluded mask recall: 58.79% +COCO occluded mask success num: 3263 +computing separated mask recall... +[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 3522/3522, 778.3 task/s, elapsed: 5s, ETA: 0s +COCO separated mask recall: 31.94% +COCO separated mask success num: 1125 + ++-----------+--------+-------------+ +| mask type | recall | num correct | ++-----------+--------+-------------+ +| occluded | 58.79% | 3263 | +| separated | 31.94% | 1125 | ++-----------+--------+-------------+ +Evaluation results have been saved to occluded_separated_recall.json. +``` + +### 在线评测 + +我们实现继承自 `CocoMetic` 的 `CocoOccludedSeparatedMetric`。 +要在训练期间评估分离和遮挡掩码的召回率,只需在配置中将 evaluator 类型替换为 `CocoOccludedSeparatedMetric`: + +```python +val_evaluator = dict( + type='CocoOccludedSeparatedMetric', # 修改此处 + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False) +test_evaluator = val_evaluator +``` + +如果您使用了此指标,请引用论文: + +```latex +@article{zhan2022triocc, + title={A Tri-Layer Plugin to Improve Occluded Detection}, + author={Zhan, Guanqi and Xie, Weidi and Zisserman, Andrew}, + journal={British Machine Vision Conference}, + year={2022} +} +``` diff --git a/mmdet_code/mmdetection/docs/zh_cn/user_guides/visualization.md b/mmdet_code/mmdetection/docs/zh_cn/user_guides/visualization.md new file mode 100644 index 0000000000000000000000000000000000000000..f90ab6d49fd5857a1a1f4ec695d4b42bcbb76acc --- /dev/null +++ b/mmdet_code/mmdetection/docs/zh_cn/user_guides/visualization.md @@ -0,0 +1,93 @@ +# 可视化 + +在阅读本教程之前,建议先阅读 MMEngine 的 [Visualization](https://github.com/open-mmlab/mmengine/blob/main/docs/en/advanced_tutorials/visualization.md) 文档,以对 `Visualizer` 的定义和用法有一个初步的了解。 + +简而言之,`Visualizer` 在 MMEngine 中实现以满足日常可视化需求,并包含以下三个主要功能: + +- 实现通用的绘图 API,例如 [`draw_bboxes`](mmengine.visualization.Visualizer.draw_bboxes) 实现了绘制边界框的功能,[`draw_lines`](mmengine.visualization.Visualizer.draw_lines) 实现了绘制线条的功能。 +- 支持将可视化结果、学习率曲线、损失函数曲线以及验证精度曲线写入到各种后端中,包括本地磁盘以及常见的深度学习训练日志工具,例如 [TensorBoard](https://www.tensorflow.org/tensorboard) 和 [Wandb](https://wandb.ai/site)。 +- 支持在代码的任何位置调用以可视化或记录模型在训练或测试期间的中间状态,例如特征图和验证结果。 + +基于 MMEngine 的 `Visualizer`,MMDet 提供了各种预构建的可视化工具,用户可以通过简单地修改以下配置文件来使用它们。 + +- `tools/analysis_tools/browse_dataset.py` 脚本提供了一个数据集可视化功能,可以在数据经过数据转换后绘制图像和相应的注释,具体描述请参见[`browse_dataset.py`](useful_tools.md#Visualization)。 + +- MMEngine实现了`LoggerHook`,使用`Visualizer`将学习率、损失和评估结果写入由`Visualizer`设置的后端。因此,通过修改配置文件中的`Visualizer`后端,例如修改为`TensorBoardVISBackend`或`WandbVISBackend`,可以实现日志记录到常用的训练日志工具,如`TensorBoard`或`WandB`,从而方便用户使用这些可视化工具来分析和监控训练过程。 + +- 在MMDet中实现了`VisualizerHook`,它使用`Visualizer`将验证或预测阶段的预测结果可视化或存储到由`Visualizer`设置的后端。因此,通过修改配置文件中的`Visualizer`后端,例如修改为`TensorBoardVISBackend`或`WandbVISBackend`,可以将预测图像存储到`TensorBoard`或`Wandb`中。 + +## 配置 + +由于使用了注册机制,在MMDet中我们可以通过修改配置文件来设置`Visualizer`的行为。通常,我们会在`configs/_base_/default_runtime.py`中为可视化器定义默认配置,详细信息请参见[配置教程](config.md)。 + +```Python +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='DetLocalVisualizer', + vis_backends=vis_backends, + name='visualizer') +``` + +基于上面的例子,我们可以看到`Visualizer`的配置由两个主要部分组成,即`Visualizer`类型和其使用的可视化后端`vis_backends`。 + +- 用户可直接使用`DetLocalVisualizer`来可视化支持任务的标签或预测结果。 +- MMDet默认将可视化后端`vis_backend`设置为本地可视化后端`LocalVisBackend`,将所有可视化结果和其他训练信息保存在本地文件夹中。 + +## 存储 + +MMDet默认使用本地可视化后端[`LocalVisBackend`](mmengine.visualization.LocalVisBackend),`VisualizerHook`和`LoggerHook`中存储的模型损失、学习率、模型评估精度和可视化信息,包括损失、学习率、评估精度将默认保存到`{work_dir}/{config_name}/{time}/{vis_data}`文件夹中。此外,MMDet还支持其他常见的可视化后端,例如`TensorboardVisBackend`和`WandbVisBackend`,您只需要在配置文件中更改`vis_backends`类型为相应的可视化后端即可。例如,只需在配置文件中插入以下代码块即可将数据存储到`TensorBoard`和`Wandb`中。 + +```Python +# https://mmengine.readthedocs.io/en/latest/api/visualization.html +_base_.visualizer.vis_backends = [ + dict(type='LocalVisBackend'), # + dict(type='TensorboardVisBackend'), + dict(type='WandbVisBackend'),] +``` + +## 绘图 + +### 绘制预测结果 + +MMDet主要使用[`DetVisualizationHook`](mmdet.engine.hooks.DetVisualizationHook)来绘制验证和测试的预测结果,默认情况下`DetVisualizationHook`是关闭的,其默认配置如下。 + +```Python +visualization=dict( #用户可视化验证和测试结果 + type='DetVisualizationHook', + draw=False, + interval=1, + show=False) +``` + +以下表格展示了`DetVisualizationHook`支持的参数。 + +| 参数 | 描述 | +| :------: | :------------------------------------------------------------------------------: | +| draw | DetVisualizationHook通过enable参数打开和关闭,默认状态为关闭。 | +| interval | 控制在DetVisualizationHook启用时存储或显示验证或测试结果的间隔,单位为迭代次数。 | +| show | 控制是否可视化验证或测试的结果。 | + +如果您想在训练或测试期间启用 `DetVisualizationHook` 相关功能和配置,您只需要修改配置文件,以 `configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py` 为例,同时绘制注释和预测,并显示图像,配置文件可以修改如下: + +```Python +visualization = _base_.default_hooks.visualization +visualization.update(dict(draw=True, show=True)) +``` + +
+ +
+ +`test.py`程序提供了`--show`和`--show-dir`参数,可以在测试过程中可视化注释和预测结果,而不需要修改配置文件,从而进一步简化了测试过程。 + +```Shell +# 展示测试结果 +python tools/test.py configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_tiny_8xb32-300e_coco/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --show + +# 指定存储预测结果的位置 +python tools/test.py configs/rtmdet/rtmdet_tiny_8xb32-300e_coco.py https://download.openmmlab.com/mmdetection/v3.0/rtmdet/rtmdet_tiny_8xb32-300e_coco/rtmdet_tiny_8xb32-300e_coco_20220902_112414-78e30dcc.pth --show-dir imgs/ +``` + +
+ +
diff --git a/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_detection.py b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..45041f6d236be95eb7592035d31f155c61bfcb25 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_detection.py @@ -0,0 +1,104 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms import LoadImageFromFile +from mmengine.dataset.sampler import DefaultSampler + +from mmdet.datasets import AspectRatioBatchSampler, CocoDataset +from mmdet.datasets.transforms import (LoadAnnotations, PackDetInputs, + RandomFlip, Resize) +from mmdet.evaluation import CocoMetric + +# dataset settings +dataset_type = CocoDataset +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadAnnotations, with_bbox=True), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=RandomFlip, prob=0.5), + dict(type=PackDetInputs) +] +test_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type=LoadAnnotations, with_bbox=True), + dict( + type=PackDetInputs, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=DefaultSampler, shuffle=True), + batch_sampler=dict(type=AspectRatioBatchSampler), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type=DefaultSampler, shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type=CocoMetric, + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type=DefaultSampler, shuffle=False), +# dataset=dict( +# type=dataset_type, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type=CocoMetric, +# metric='bbox', +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_detection/test') diff --git a/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_instance.py b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..b9575432e26b7e861c4dfcf535773b7a1990eeab --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_instance.py @@ -0,0 +1,106 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms.loading import LoadImageFromFile +from mmengine.dataset.sampler import DefaultSampler + +from mmdet.datasets.coco import CocoDataset +from mmdet.datasets.samplers.batch_sampler import AspectRatioBatchSampler +from mmdet.datasets.transforms.formatting import PackDetInputs +from mmdet.datasets.transforms.loading import LoadAnnotations +from mmdet.datasets.transforms.transforms import RandomFlip, Resize +from mmdet.evaluation.metrics.coco_metric import CocoMetric + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadAnnotations, with_bbox=True, with_mask=True), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=RandomFlip, prob=0.5), + dict(type=PackDetInputs) +] +test_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type=LoadAnnotations, with_bbox=True, with_mask=True), + dict( + type=PackDetInputs, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=DefaultSampler, shuffle=True), + batch_sampler=dict(type=AspectRatioBatchSampler), + dataset=dict( + type=CocoDataset, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type=DefaultSampler, shuffle=False), + dataset=dict( + type=CocoDataset, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type=CocoMetric, + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=2, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type=DefaultSampler, shuffle=False), +# dataset=dict( +# type=CocoDataset, +# data_root=data_root, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type=CocoMetric, +# metric=['bbox', 'segm'], +# format_only=True, +# ann_file=data_root + 'annotations/image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_instance/test') diff --git a/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_instance_semantic.py b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_instance_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf5b2cfab8a98a6c97e23a8df663e8f1e90b355 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_instance_semantic.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms.loading import LoadImageFromFile +from mmengine.dataset.sampler import DefaultSampler + +from mmdet.datasets.coco import CocoDataset +from mmdet.datasets.samplers.batch_sampler import AspectRatioBatchSampler +from mmdet.datasets.transforms.formatting import PackDetInputs +from mmdet.datasets.transforms.loading import LoadAnnotations +from mmdet.datasets.transforms.transforms import RandomFlip, Resize +from mmdet.evaluation.metrics.coco_metric import CocoMetric + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadAnnotations, with_bbox=True, with_mask=True, with_seg=True), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=RandomFlip, prob=0.5), + dict(type=PackDetInputs) +] +test_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + # If you don't have a gt annotation, delete the pipeline + dict(type=LoadAnnotations, with_bbox=True, with_mask=True, with_seg=True), + dict( + type=PackDetInputs, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=DefaultSampler, shuffle=True), + batch_sampler=dict(type=AspectRatioBatchSampler), + dataset=dict( + type=CocoDataset, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/', seg='stuffthingmaps/train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) + +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type=DefaultSampler, shuffle=False), + dataset=dict( + type=CocoDataset, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) + +test_dataloader = val_dataloader + +val_evaluator = dict( + type=CocoMetric, + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_panoptic.py b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..29d655ff619c74c5976d5f06c0c623a0d3459997 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/coco_panoptic.py @@ -0,0 +1,105 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms.loading import LoadImageFromFile +from mmengine.dataset.sampler import DefaultSampler + +from mmdet.datasets.coco_panoptic import CocoPanopticDataset +from mmdet.datasets.samplers.batch_sampler import AspectRatioBatchSampler +from mmdet.datasets.transforms.formatting import PackDetInputs +from mmdet.datasets.transforms.loading import LoadPanopticAnnotations +from mmdet.datasets.transforms.transforms import RandomFlip, Resize +from mmdet.evaluation.metrics.coco_panoptic_metric import CocoPanopticMetric + +# dataset settings +dataset_type = 'CocoPanopticDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadPanopticAnnotations, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=RandomFlip, prob=0.5), + dict(type=PackDetInputs) +] +test_pipeline = [ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=(1333, 800), keep_ratio=True), + dict(type=LoadPanopticAnnotations, backend_args=backend_args), + dict( + type=PackDetInputs, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=DefaultSampler, shuffle=True), + batch_sampler=dict(type=AspectRatioBatchSampler), + dataset=dict( + type=CocoPanopticDataset, + data_root=data_root, + ann_file='annotations/panoptic_train2017.json', + data_prefix=dict( + img='train2017/', seg='annotations/panoptic_train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type=DefaultSampler, shuffle=False), + dataset=dict( + type=CocoPanopticDataset, + data_root=data_root, + ann_file='annotations/panoptic_val2017.json', + data_prefix=dict(img='val2017/', seg='annotations/panoptic_val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type=CocoPanopticMetric, + ann_file=data_root + 'annotations/panoptic_val2017.json', + seg_prefix=data_root + 'annotations/panoptic_val2017/', + backend_args=backend_args) +test_evaluator = val_evaluator + +# inference on test dataset and +# format the output results for submission. +# test_dataloader = dict( +# batch_size=1, +# num_workers=1, +# persistent_workers=True, +# drop_last=False, +# sampler=dict(type=DefaultSampler, shuffle=False), +# dataset=dict( +# type=CocoPanopticDataset, +# data_root=data_root, +# ann_file='annotations/panoptic_image_info_test-dev2017.json', +# data_prefix=dict(img='test2017/'), +# test_mode=True, +# pipeline=test_pipeline)) +# test_evaluator = dict( +# type=CocoPanopticMetric, +# format_only=True, +# ann_file=data_root + 'annotations/panoptic_image_info_test-dev2017.json', +# outfile_prefix='./work_dirs/coco_panoptic/test') diff --git a/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/mot_challenge.py b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/mot_challenge.py new file mode 100644 index 0000000000000000000000000000000000000000..a71520a84e52a812f83862920040d96746829285 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/configs/_base_/datasets/mot_challenge.py @@ -0,0 +1,101 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.transforms import (LoadImageFromFile, RandomResize, + TransformBroadcaster) + +from mmdet.datasets import MOTChallengeDataset +from mmdet.datasets.samplers import TrackImgSampler +from mmdet.datasets.transforms import (LoadTrackAnnotations, PackTrackInputs, + PhotoMetricDistortion, RandomCrop, + RandomFlip, Resize, + UniformRefFrameSample) +from mmdet.evaluation import MOTChallengeMetric + +# dataset settings +dataset_type = MOTChallengeDataset +data_root = 'data/MOT17/' +img_scale = (1088, 1088) + +backend_args = None +# data pipeline +train_pipeline = [ + dict( + type=UniformRefFrameSample, + num_ref_imgs=1, + frame_range=10, + filter_key_img=True), + dict( + type=TransformBroadcaster, + share_random_params=True, + transforms=[ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=LoadTrackAnnotations), + dict( + type=RandomResize, + scale=img_scale, + ratio_range=(0.8, 1.2), + keep_ratio=True, + clip_object_border=False), + dict(type=PhotoMetricDistortion) + ]), + dict( + type=TransformBroadcaster, + # different cropped positions for different frames + share_random_params=False, + transforms=[ + dict(type=RandomCrop, crop_size=img_scale, bbox_clip_border=False) + ]), + dict( + type=TransformBroadcaster, + share_random_params=True, + transforms=[ + dict(type=RandomFlip, prob=0.5), + ]), + dict(type=PackTrackInputs) +] + +test_pipeline = [ + dict( + type=TransformBroadcaster, + transforms=[ + dict(type=LoadImageFromFile, backend_args=backend_args), + dict(type=Resize, scale=img_scale, keep_ratio=True), + dict(type=LoadTrackAnnotations) + ]), + dict(type=PackTrackInputs) +] + +# dataloader +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type=TrackImgSampler), # image-based sampling + dataset=dict( + type=dataset_type, + data_root=data_root, + visibility_thr=-1, + ann_file='annotations/half-train_cocoformat.json', + data_prefix=dict(img_path='train'), + metainfo=dict(classes=('pedestrian', )), + pipeline=train_pipeline)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + # Now we support two ways to test, image_based and video_based + # if you want to use video_based sampling, you can use as follows + # sampler=dict(type='DefaultSampler', shuffle=False, round_up=False), + sampler=dict(type=TrackImgSampler), # image-based sampling + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/half-val_cocoformat.json', + data_prefix=dict(img_path='train'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# evaluator +val_evaluator = dict( + type=MOTChallengeMetric, metric=['HOTA', 'CLEAR', 'Identity']) +test_evaluator = val_evaluator diff --git a/mmdet_code/mmdetection/mmdet/datasets/__init__.py b/mmdet_code/mmdetection/mmdet/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..670c207cacf9ed0f9fee88bada119ee3aaa85eae --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/__init__.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .ade20k import (ADE20KInstanceDataset, ADE20KPanopticDataset, + ADE20KSegDataset) +from .base_det_dataset import BaseDetDataset +from .base_semseg_dataset import BaseSegDataset +from .base_video_dataset import BaseVideoDataset +from .cityscapes import CityscapesDataset +from .coco import CocoDataset +from .coco_caption import CocoCaptionDataset +from .coco_panoptic import CocoPanopticDataset +from .coco_semantic import CocoSegDataset +from .crowdhuman import CrowdHumanDataset +from .dataset_wrappers import ConcatDataset, MultiImageMixDataset +from .deepfashion import DeepFashionDataset +from .dod import DODDataset +from .dsdl import DSDLDetDataset +from .flickr30k import Flickr30kDataset +from .isaid import iSAIDDataset +from .lvis import LVISDataset, LVISV1Dataset, LVISV05Dataset +from .mdetr_style_refcoco import MDETRStyleRefCocoDataset +from .mot_challenge_dataset import MOTChallengeDataset +from .objects365 import Objects365V1Dataset, Objects365V2Dataset +from .odvg import ODVGDataset +from .openimages import OpenImagesChallengeDataset, OpenImagesDataset +from .refcoco import RefCocoDataset +from .reid_dataset import ReIDDataset +from .samplers import (AspectRatioBatchSampler, ClassAwareSampler, + CustomSampleSizeSampler, GroupMultiSourceSampler, + MultiSourceSampler, TrackAspectRatioBatchSampler, + TrackImgSampler) +from .utils import get_loading_pipeline +from .v3det import V3DetDataset +from .voc import VOCDataset +from .wider_face import WIDERFaceDataset +from .xml_style import XMLDataset +from .youtube_vis_dataset import YouTubeVISDataset + +__all__ = [ + 'XMLDataset', 'CocoDataset', 'DeepFashionDataset', 'VOCDataset', + 'CityscapesDataset', 'LVISDataset', 'LVISV05Dataset', 'LVISV1Dataset', + 'WIDERFaceDataset', 'get_loading_pipeline', 'CocoPanopticDataset', + 'MultiImageMixDataset', 'OpenImagesDataset', 'OpenImagesChallengeDataset', + 'AspectRatioBatchSampler', 'ClassAwareSampler', 'MultiSourceSampler', + 'GroupMultiSourceSampler', 'BaseDetDataset', 'CrowdHumanDataset', + 'Objects365V1Dataset', 'Objects365V2Dataset', 'DSDLDetDataset', + 'BaseVideoDataset', 'MOTChallengeDataset', 'TrackImgSampler', + 'ReIDDataset', 'YouTubeVISDataset', 'TrackAspectRatioBatchSampler', + 'ADE20KPanopticDataset', 'CocoCaptionDataset', 'RefCocoDataset', + 'BaseSegDataset', 'ADE20KSegDataset', 'CocoSegDataset', + 'ADE20KInstanceDataset', 'iSAIDDataset', 'V3DetDataset', 'ConcatDataset', + 'ODVGDataset', 'MDETRStyleRefCocoDataset', 'DODDataset', + 'CustomSampleSizeSampler', 'Flickr30kDataset' +] diff --git a/mmdet_code/mmdetection/mmdet/datasets/ade20k.py b/mmdet_code/mmdetection/mmdet/datasets/ade20k.py new file mode 100644 index 0000000000000000000000000000000000000000..573271cb5d0cb83571564272895bddde9a5f6ad7 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/ade20k.py @@ -0,0 +1,260 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List + +from mmengine import fileio + +from mmdet.registry import DATASETS +from .base_semseg_dataset import BaseSegDataset +from .coco import CocoDataset +from .coco_panoptic import CocoPanopticDataset + +ADE_PALETTE = [(120, 120, 120), (180, 120, 120), (6, 230, 230), (80, 50, 50), + (4, 200, 3), (120, 120, 80), (140, 140, 140), (204, 5, 255), + (230, 230, 230), (4, 250, 7), (224, 5, 255), (235, 255, 7), + (150, 5, 61), (120, 120, 70), (8, 255, 51), (255, 6, 82), + (143, 255, 140), (204, 255, 4), (255, 51, 7), (204, 70, 3), + (0, 102, 200), (61, 230, 250), (255, 6, 51), (11, 102, 255), + (255, 7, 71), (255, 9, 224), (9, 7, 230), (220, 220, 220), + (255, 9, 92), (112, 9, 255), (8, 255, 214), (7, 255, 224), + (255, 184, 6), (10, 255, 71), (255, 41, 10), (7, 255, 255), + (224, 255, 8), (102, 8, 255), (255, 61, 6), (255, 194, 7), + (255, 122, 8), (0, 255, 20), (255, 8, 41), (255, 5, 153), + (6, 51, 255), (235, 12, 255), (160, 150, 20), (0, 163, 255), + (140, 140, 140), (250, 10, 15), (20, 255, 0), (31, 255, 0), + (255, 31, 0), (255, 224, 0), (153, 255, 0), (0, 0, 255), + (255, 71, 0), (0, 235, 255), (0, 173, 255), (31, 0, 255), + (11, 200, 200), (255, 82, 0), (0, 255, 245), (0, 61, 255), + (0, 255, 112), (0, 255, 133), (255, 0, 0), (255, 163, 0), + (255, 102, 0), (194, 255, 0), (0, 143, 255), (51, 255, 0), + (0, 82, 255), (0, 255, 41), (0, 255, 173), (10, 0, 255), + (173, 255, 0), (0, 255, 153), (255, 92, 0), (255, 0, 255), + (255, 0, 245), (255, 0, 102), (255, 173, 0), (255, 0, 20), + (255, 184, 184), (0, 31, 255), (0, 255, 61), (0, 71, 255), + (255, 0, 204), (0, 255, 194), (0, 255, 82), (0, 10, 255), + (0, 112, 255), (51, 0, 255), (0, 194, 255), (0, 122, 255), + (0, 255, 163), (255, 153, 0), (0, 255, 10), (255, 112, 0), + (143, 255, 0), (82, 0, 255), (163, 255, 0), (255, 235, 0), + (8, 184, 170), (133, 0, 255), (0, 255, 92), (184, 0, 255), + (255, 0, 31), (0, 184, 255), (0, 214, 255), (255, 0, 112), + (92, 255, 0), (0, 224, 255), (112, 224, 255), (70, 184, 160), + (163, 0, 255), (153, 0, 255), (71, 255, 0), (255, 0, 163), + (255, 204, 0), (255, 0, 143), (0, 255, 235), (133, 255, 0), + (255, 0, 235), (245, 0, 255), (255, 0, 122), (255, 245, 0), + (10, 190, 212), (214, 255, 0), (0, 204, 255), (20, 0, 255), + (255, 255, 0), (0, 153, 255), (0, 41, 255), (0, 255, 204), + (41, 0, 255), (41, 255, 0), (173, 0, 255), (0, 245, 255), + (71, 0, 255), (122, 0, 255), (0, 255, 184), (0, 92, 255), + (184, 255, 0), (0, 133, 255), (255, 214, 0), (25, 194, 194), + (102, 255, 0), (92, 0, 255)] + + +@DATASETS.register_module() +class ADE20KPanopticDataset(CocoPanopticDataset): + METAINFO = { + 'classes': + ('bed', 'window', 'cabinet', 'person', 'door', 'table', 'curtain', + 'chair', 'car', 'painting, picture', 'sofa', 'shelf', 'mirror', + 'armchair', 'seat', 'fence', 'desk', 'wardrobe, closet, press', + 'lamp', 'tub', 'rail', 'cushion', 'box', 'column, pillar', + 'signboard, sign', 'chest of drawers, chest, bureau, dresser', + 'counter', 'sink', 'fireplace', 'refrigerator, icebox', 'stairs', + 'case, display case, showcase, vitrine', + 'pool table, billiard table, snooker table', 'pillow', + 'screen door, screen', 'bookcase', 'coffee table', + 'toilet, can, commode, crapper, pot, potty, stool, throne', 'flower', + 'book', 'bench', 'countertop', 'stove', 'palm, palm tree', + 'kitchen island', 'computer', 'swivel chair', 'boat', + 'arcade machine', 'bus', 'towel', 'light', 'truck', 'chandelier', + 'awning, sunshade, sunblind', 'street lamp', 'booth', 'tv', + 'airplane', 'clothes', 'pole', + 'bannister, banister, balustrade, balusters, handrail', + 'ottoman, pouf, pouffe, puff, hassock', 'bottle', 'van', 'ship', + 'fountain', 'washer, automatic washer, washing machine', + 'plaything, toy', 'stool', 'barrel, cask', 'basket, handbasket', + 'bag', 'minibike, motorbike', 'oven', 'ball', 'food, solid food', + 'step, stair', 'trade name', 'microwave', 'pot', 'animal', 'bicycle', + 'dishwasher', 'screen', 'sculpture', 'hood, exhaust hood', 'sconce', + 'vase', 'traffic light', 'tray', 'trash can', 'fan', 'plate', + 'monitor', 'bulletin board', 'radiator', 'glass, drinking glass', + 'clock', 'flag', 'wall', 'building', 'sky', 'floor', 'tree', + 'ceiling', 'road, route', 'grass', 'sidewalk, pavement', + 'earth, ground', 'mountain, mount', 'plant', 'water', 'house', 'sea', + 'rug', 'field', 'rock, stone', 'base, pedestal, stand', 'sand', + 'skyscraper', 'grandstand, covered stand', 'path', 'runway', + 'stairway, staircase', 'river', 'bridge, span', 'blind, screen', + 'hill', 'bar', 'hovel, hut, hutch, shack, shanty', 'tower', + 'dirt track', 'land, ground, soil', + 'escalator, moving staircase, moving stairway', + 'buffet, counter, sideboard', + 'poster, posting, placard, notice, bill, card', 'stage', + 'conveyer belt, conveyor belt, conveyer, conveyor, transporter', + 'canopy', 'pool', 'falls', 'tent', 'cradle', 'tank, storage tank', + 'lake', 'blanket, cover', 'pier', 'crt screen', 'shower'), + 'thing_classes': + ('bed', 'window', 'cabinet', 'person', 'door', 'table', 'curtain', + 'chair', 'car', 'painting, picture', 'sofa', 'shelf', 'mirror', + 'armchair', 'seat', 'fence', 'desk', 'wardrobe, closet, press', + 'lamp', 'tub', 'rail', 'cushion', 'box', 'column, pillar', + 'signboard, sign', 'chest of drawers, chest, bureau, dresser', + 'counter', 'sink', 'fireplace', 'refrigerator, icebox', 'stairs', + 'case, display case, showcase, vitrine', + 'pool table, billiard table, snooker table', 'pillow', + 'screen door, screen', 'bookcase', 'coffee table', + 'toilet, can, commode, crapper, pot, potty, stool, throne', 'flower', + 'book', 'bench', 'countertop', 'stove', 'palm, palm tree', + 'kitchen island', 'computer', 'swivel chair', 'boat', + 'arcade machine', 'bus', 'towel', 'light', 'truck', 'chandelier', + 'awning, sunshade, sunblind', 'street lamp', 'booth', 'tv', + 'airplane', 'clothes', 'pole', + 'bannister, banister, balustrade, balusters, handrail', + 'ottoman, pouf, pouffe, puff, hassock', 'bottle', 'van', 'ship', + 'fountain', 'washer, automatic washer, washing machine', + 'plaything, toy', 'stool', 'barrel, cask', 'basket, handbasket', + 'bag', 'minibike, motorbike', 'oven', 'ball', 'food, solid food', + 'step, stair', 'trade name', 'microwave', 'pot', 'animal', 'bicycle', + 'dishwasher', 'screen', 'sculpture', 'hood, exhaust hood', 'sconce', + 'vase', 'traffic light', 'tray', 'trash can', 'fan', 'plate', + 'monitor', 'bulletin board', 'radiator', 'glass, drinking glass', + 'clock', 'flag'), + 'stuff_classes': + ('wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road, route', + 'grass', 'sidewalk, pavement', 'earth, ground', 'mountain, mount', + 'plant', 'water', 'house', 'sea', 'rug', 'field', 'rock, stone', + 'base, pedestal, stand', 'sand', 'skyscraper', + 'grandstand, covered stand', 'path', 'runway', 'stairway, staircase', + 'river', 'bridge, span', 'blind, screen', 'hill', 'bar', + 'hovel, hut, hutch, shack, shanty', 'tower', 'dirt track', + 'land, ground, soil', 'escalator, moving staircase, moving stairway', + 'buffet, counter, sideboard', + 'poster, posting, placard, notice, bill, card', 'stage', + 'conveyer belt, conveyor belt, conveyer, conveyor, transporter', + 'canopy', 'pool', 'falls', 'tent', 'cradle', 'tank, storage tank', + 'lake', 'blanket, cover', 'pier', 'crt screen', 'shower'), + 'palette': + ADE_PALETTE + } + + +@DATASETS.register_module() +class ADE20KInstanceDataset(CocoDataset): + METAINFO = { + 'classes': + ('bed', 'windowpane', 'cabinet', 'person', 'door', 'table', 'curtain', + 'chair', 'car', 'painting', 'sofa', 'shelf', 'mirror', 'armchair', + 'seat', 'fence', 'desk', 'wardrobe', 'lamp', 'bathtub', 'railing', + 'cushion', 'box', 'column', 'signboard', 'chest of drawers', + 'counter', 'sink', 'fireplace', 'refrigerator', 'stairs', 'case', + 'pool table', 'pillow', 'screen door', 'bookcase', 'coffee table', + 'toilet', 'flower', 'book', 'bench', 'countertop', 'stove', 'palm', + 'kitchen island', 'computer', 'swivel chair', 'boat', + 'arcade machine', 'bus', 'towel', 'light', 'truck', 'chandelier', + 'awning', 'streetlight', 'booth', 'television receiver', 'airplane', + 'apparel', 'pole', 'bannister', 'ottoman', 'bottle', 'van', 'ship', + 'fountain', 'washer', 'plaything', 'stool', 'barrel', 'basket', 'bag', + 'minibike', 'oven', 'ball', 'food', 'step', 'trade name', 'microwave', + 'pot', 'animal', 'bicycle', 'dishwasher', 'screen', 'sculpture', + 'hood', 'sconce', 'vase', 'traffic light', 'tray', 'ashcan', 'fan', + 'plate', 'monitor', 'bulletin board', 'radiator', 'glass', 'clock', + 'flag'), + 'palette': [(204, 5, 255), (230, 230, 230), (224, 5, 255), + (150, 5, 61), (8, 255, 51), (255, 6, 82), (255, 51, 7), + (204, 70, 3), (0, 102, 200), (255, 6, 51), (11, 102, 255), + (255, 7, 71), (220, 220, 220), (8, 255, 214), + (7, 255, 224), (255, 184, 6), (10, 255, 71), (7, 255, 255), + (224, 255, 8), (102, 8, 255), (255, 61, 6), (255, 194, 7), + (0, 255, 20), (255, 8, 41), (255, 5, 153), (6, 51, 255), + (235, 12, 255), (0, 163, 255), (250, 10, 15), (20, 255, 0), + (255, 224, 0), (0, 0, 255), (255, 71, 0), (0, 235, 255), + (0, 173, 255), (0, 255, 245), (0, 255, 112), (0, 255, 133), + (255, 0, 0), (255, 163, 0), (194, 255, 0), (0, 143, 255), + (51, 255, 0), (0, 82, 255), (0, 255, 41), (0, 255, 173), + (10, 0, 255), (173, 255, 0), (255, 92, 0), (255, 0, 245), + (255, 0, 102), (255, 173, 0), (255, 0, 20), (0, 31, 255), + (0, 255, 61), (0, 71, 255), (255, 0, 204), (0, 255, 194), + (0, 255, 82), (0, 112, 255), (51, 0, 255), (0, 122, 255), + (255, 153, 0), (0, 255, 10), (163, 255, 0), (255, 235, 0), + (8, 184, 170), (184, 0, 255), (255, 0, 31), (0, 214, 255), + (255, 0, 112), (92, 255, 0), (70, 184, 160), (163, 0, 255), + (71, 255, 0), (255, 0, 163), (255, 204, 0), (255, 0, 143), + (133, 255, 0), (255, 0, 235), (245, 0, 255), (255, 0, 122), + (255, 245, 0), (214, 255, 0), (0, 204, 255), (255, 255, 0), + (0, 153, 255), (0, 41, 255), (0, 255, 204), (41, 0, 255), + (41, 255, 0), (173, 0, 255), (0, 245, 255), (0, 255, 184), + (0, 92, 255), (184, 255, 0), (255, 214, 0), (25, 194, 194), + (102, 255, 0), (92, 0, 255)], + } + + +@DATASETS.register_module() +class ADE20KSegDataset(BaseSegDataset): + """ADE20K dataset. + + In segmentation map annotation for ADE20K, 0 stands for background, which + is not included in 150 categories. The ``img_suffix`` is fixed to '.jpg', + and ``seg_map_suffix`` is fixed to '.png'. + """ + METAINFO = dict( + classes=('wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', + 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk', + 'person', 'earth', 'door', 'table', 'mountain', 'plant', + 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', + 'shelf', 'house', 'sea', 'mirror', 'rug', 'field', 'armchair', + 'seat', 'fence', 'desk', 'rock', 'wardrobe', 'lamp', + 'bathtub', 'railing', 'cushion', 'base', 'box', 'column', + 'signboard', 'chest of drawers', 'counter', 'sand', 'sink', + 'skyscraper', 'fireplace', 'refrigerator', 'grandstand', + 'path', 'stairs', 'runway', 'case', 'pool table', 'pillow', + 'screen door', 'stairway', 'river', 'bridge', 'bookcase', + 'blind', 'coffee table', 'toilet', 'flower', 'book', 'hill', + 'bench', 'countertop', 'stove', 'palm', 'kitchen island', + 'computer', 'swivel chair', 'boat', 'bar', 'arcade machine', + 'hovel', 'bus', 'towel', 'light', 'truck', 'tower', + 'chandelier', 'awning', 'streetlight', 'booth', + 'television receiver', 'airplane', 'dirt track', 'apparel', + 'pole', 'land', 'bannister', 'escalator', 'ottoman', 'bottle', + 'buffet', 'poster', 'stage', 'van', 'ship', 'fountain', + 'conveyer belt', 'canopy', 'washer', 'plaything', + 'swimming pool', 'stool', 'barrel', 'basket', 'waterfall', + 'tent', 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food', + 'step', 'tank', 'trade name', 'microwave', 'pot', 'animal', + 'bicycle', 'lake', 'dishwasher', 'screen', 'blanket', + 'sculpture', 'hood', 'sconce', 'vase', 'traffic light', + 'tray', 'ashcan', 'fan', 'pier', 'crt screen', 'plate', + 'monitor', 'bulletin board', 'shower', 'radiator', 'glass', + 'clock', 'flag'), + palette=ADE_PALETTE) + + def __init__(self, + img_suffix='.jpg', + seg_map_suffix='.png', + return_classes=False, + **kwargs) -> None: + self.return_classes = return_classes + super().__init__( + img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotation from directory or annotation file. + + Returns: + List[dict]: All data info of dataset. + """ + data_list = [] + img_dir = self.data_prefix.get('img_path', None) + ann_dir = self.data_prefix.get('seg_map_path', None) + for img in fileio.list_dir_or_file( + dir_path=img_dir, + list_dir=False, + suffix=self.img_suffix, + recursive=True, + backend_args=self.backend_args): + data_info = dict(img_path=osp.join(img_dir, img)) + if ann_dir is not None: + seg_map = img.replace(self.img_suffix, self.seg_map_suffix) + data_info['seg_map_path'] = osp.join(ann_dir, seg_map) + data_info['label_map'] = self.label_map + if self.return_classes: + data_info['text'] = list(self._metainfo['classes']) + data_list.append(data_info) + return data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/__init__.py b/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e3c41a2f87b14d10339955208e0502aeeeb7082 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .coco_api import COCO, COCOeval, COCOPanoptic +from .cocoeval_mp import COCOevalMP + +__all__ = ['COCO', 'COCOeval', 'COCOPanoptic', 'COCOevalMP'] diff --git a/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/coco_api.py b/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/coco_api.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d11a122e1860d1b097710ff98adfddc1508c5a --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/coco_api.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# This file add snake case alias for coco api + +import warnings +from collections import defaultdict +from typing import List, Optional, Union + +import pycocotools +from pycocotools.coco import COCO as _COCO +from pycocotools.cocoeval import COCOeval as _COCOeval + + +class COCO(_COCO): + """This class is almost the same as official pycocotools package. + + It implements some snake case function aliases. So that the COCO class has + the same interface as LVIS class. + """ + + def __init__(self, annotation_file=None): + if getattr(pycocotools, '__version__', '0') >= '12.0.2': + warnings.warn( + 'mmpycocotools is deprecated. Please install official pycocotools by "pip install pycocotools"', # noqa: E501 + UserWarning) + super().__init__(annotation_file=annotation_file) + self.img_ann_map = self.imgToAnns + self.cat_img_map = self.catToImgs + + def get_ann_ids(self, img_ids=[], cat_ids=[], area_rng=[], iscrowd=None): + return self.getAnnIds(img_ids, cat_ids, area_rng, iscrowd) + + def get_cat_ids(self, cat_names=[], sup_names=[], cat_ids=[]): + return self.getCatIds(cat_names, sup_names, cat_ids) + + def get_img_ids(self, img_ids=[], cat_ids=[]): + return self.getImgIds(img_ids, cat_ids) + + def load_anns(self, ids): + return self.loadAnns(ids) + + def load_cats(self, ids): + return self.loadCats(ids) + + def load_imgs(self, ids): + return self.loadImgs(ids) + + +# just for the ease of import +COCOeval = _COCOeval + + +class COCOPanoptic(COCO): + """This wrapper is for loading the panoptic style annotation file. + + The format is shown in the CocoPanopticDataset class. + + Args: + annotation_file (str, optional): Path of annotation file. + Defaults to None. + """ + + def __init__(self, annotation_file: Optional[str] = None) -> None: + super(COCOPanoptic, self).__init__(annotation_file) + + def createIndex(self) -> None: + """Create index.""" + # create index + print('creating index...') + # anns stores 'segment_id -> annotation' + anns, cats, imgs = {}, {}, {} + img_to_anns, cat_to_imgs = defaultdict(list), defaultdict(list) + if 'annotations' in self.dataset: + for ann in self.dataset['annotations']: + for seg_ann in ann['segments_info']: + # to match with instance.json + seg_ann['image_id'] = ann['image_id'] + img_to_anns[ann['image_id']].append(seg_ann) + # segment_id is not unique in coco dataset orz... + # annotations from different images but + # may have same segment_id + if seg_ann['id'] in anns.keys(): + anns[seg_ann['id']].append(seg_ann) + else: + anns[seg_ann['id']] = [seg_ann] + + # filter out annotations from other images + img_to_anns_ = defaultdict(list) + for k, v in img_to_anns.items(): + img_to_anns_[k] = [x for x in v if x['image_id'] == k] + img_to_anns = img_to_anns_ + + if 'images' in self.dataset: + for img_info in self.dataset['images']: + img_info['segm_file'] = img_info['file_name'].replace( + '.jpg', '.png') + imgs[img_info['id']] = img_info + + if 'categories' in self.dataset: + for cat in self.dataset['categories']: + cats[cat['id']] = cat + + if 'annotations' in self.dataset and 'categories' in self.dataset: + for ann in self.dataset['annotations']: + for seg_ann in ann['segments_info']: + cat_to_imgs[seg_ann['category_id']].append(ann['image_id']) + + print('index created!') + + self.anns = anns + self.imgToAnns = img_to_anns + self.catToImgs = cat_to_imgs + self.imgs = imgs + self.cats = cats + + def load_anns(self, + ids: Union[List[int], int] = []) -> Optional[List[dict]]: + """Load anns with the specified ids. + + ``self.anns`` is a list of annotation lists instead of a + list of annotations. + + Args: + ids (Union[List[int], int]): Integer ids specifying anns. + + Returns: + anns (List[dict], optional): Loaded ann objects. + """ + anns = [] + + if hasattr(ids, '__iter__') and hasattr(ids, '__len__'): + # self.anns is a list of annotation lists instead of + # a list of annotations + for id in ids: + anns += self.anns[id] + return anns + elif type(ids) == int: + return self.anns[ids] diff --git a/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/cocoeval_mp.py b/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/cocoeval_mp.py new file mode 100644 index 0000000000000000000000000000000000000000..b3673ea7a7edc593cb49fb336f352a20c1b1015b --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/api_wrappers/cocoeval_mp.py @@ -0,0 +1,296 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import itertools +import time +from collections import defaultdict + +import numpy as np +import torch.multiprocessing as mp +from mmengine.logging import MMLogger +from pycocotools.cocoeval import COCOeval +from tqdm import tqdm + + +class COCOevalMP(COCOeval): + + def _prepare(self): + ''' + Prepare ._gts and ._dts for evaluation based on params + :return: None + ''' + + def _toMask(anns, coco): + # modify ann['segmentation'] by reference + for ann in anns: + rle = coco.annToRLE(ann) + ann['segmentation'] = rle + + p = self.params + if p.useCats: + gts = [] + dts = [] + img_ids = set(p.imgIds) + cat_ids = set(p.catIds) + for gt in self.cocoGt.dataset['annotations']: + if (gt['category_id'] in cat_ids) and (gt['image_id'] + in img_ids): + gts.append(gt) + for dt in self.cocoDt.dataset['annotations']: + if (dt['category_id'] in cat_ids) and (dt['image_id'] + in img_ids): + dts.append(dt) + # gts=self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)) # noqa + # dts=self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)) # noqa + # gts=self.cocoGt.dataset['annotations'] + # dts=self.cocoDt.dataset['annotations'] + else: + gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds)) + dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds)) + + # convert ground truth to mask if iouType == 'segm' + if p.iouType == 'segm': + _toMask(gts, self.cocoGt) + _toMask(dts, self.cocoDt) + # set ignore flag + for gt in gts: + gt['ignore'] = gt['ignore'] if 'ignore' in gt else 0 + gt['ignore'] = 'iscrowd' in gt and gt['iscrowd'] + if p.iouType == 'keypoints': + gt['ignore'] = (gt['num_keypoints'] == 0) or gt['ignore'] + self._gts = defaultdict(list) # gt for evaluation + self._dts = defaultdict(list) # dt for evaluation + for gt in gts: + self._gts[gt['image_id'], gt['category_id']].append(gt) + for dt in dts: + self._dts[dt['image_id'], dt['category_id']].append(dt) + self.evalImgs = defaultdict( + list) # per-image per-category evaluation results + self.eval = {} # accumulated evaluation results + + def evaluate(self): + """Run per image evaluation on given images and store results (a list + of dict) in self.evalImgs. + + :return: None + """ + tic = time.time() + print('Running per image evaluation...') + p = self.params + # add backward compatibility if useSegm is specified in params + if p.useSegm is not None: + p.iouType = 'segm' if p.useSegm == 1 else 'bbox' + print('useSegm (deprecated) is not None. Running {} evaluation'. + format(p.iouType)) + print('Evaluate annotation type *{}*'.format(p.iouType)) + p.imgIds = list(np.unique(p.imgIds)) + if p.useCats: + p.catIds = list(np.unique(p.catIds)) + p.maxDets = sorted(p.maxDets) + self.params = p + + # loop through images, area range, max detection number + catIds = p.catIds if p.useCats else [-1] + + nproc = 8 + split_size = len(catIds) // nproc + mp_params = [] + for i in range(nproc): + begin = i * split_size + end = (i + 1) * split_size + if i == nproc - 1: + end = len(catIds) + mp_params.append((catIds[begin:end], )) + + MMLogger.get_current_instance().info( + 'start multi processing evaluation ...') + with mp.Pool(nproc) as pool: + self.evalImgs = pool.starmap(self._evaluateImg, mp_params) + + self.evalImgs = list(itertools.chain(*self.evalImgs)) + + self._paramsEval = copy.deepcopy(self.params) + toc = time.time() + print('DONE (t={:0.2f}s).'.format(toc - tic)) + + def _evaluateImg(self, catids_chunk): + self._prepare() + p = self.params + maxDet = max(p.maxDets) + all_params = [] + for catId in catids_chunk: + for areaRng in p.areaRng: + for imgId in p.imgIds: + all_params.append((catId, areaRng, imgId)) + evalImgs = [ + self.evaluateImg(imgId, catId, areaRng, maxDet) + for catId, areaRng, imgId in tqdm(all_params) + ] + return evalImgs + + def evaluateImg(self, imgId, catId, aRng, maxDet): + p = self.params + if p.useCats: + gt = self._gts[imgId, catId] + dt = self._dts[imgId, catId] + else: + gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]] + dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]] + if len(gt) == 0 and len(dt) == 0: + return None + + for g in gt: + if g['ignore'] or (g['area'] < aRng[0] or g['area'] > aRng[1]): + g['_ignore'] = 1 + else: + g['_ignore'] = 0 + + # sort dt highest score first, sort gt ignore last + gtind = np.argsort([g['_ignore'] for g in gt], kind='mergesort') + gt = [gt[i] for i in gtind] + dtind = np.argsort([-d['score'] for d in dt], kind='mergesort') + dt = [dt[i] for i in dtind[0:maxDet]] + iscrowd = [int(o['iscrowd']) for o in gt] + # load computed ious + # ious = self.ious[imgId, catId][:, gtind] if len(self.ious[imgId, catId]) > 0 else self.ious[imgId, catId] # noqa + ious = self.computeIoU(imgId, catId) + ious = ious[:, gtind] if len(ious) > 0 else ious + + T = len(p.iouThrs) + G = len(gt) + D = len(dt) + gtm = np.zeros((T, G)) + dtm = np.zeros((T, D)) + gtIg = np.array([g['_ignore'] for g in gt]) + dtIg = np.zeros((T, D)) + if not len(ious) == 0: + for tind, t in enumerate(p.iouThrs): + for dind, d in enumerate(dt): + # information about best match so far (m=-1 -> unmatched) + iou = min([t, 1 - 1e-10]) + m = -1 + for gind, g in enumerate(gt): + # if this gt already matched, and not a crowd, continue + if gtm[tind, gind] > 0 and not iscrowd[gind]: + continue + # if dt matched to reg gt, and on ignore gt, stop + if m > -1 and gtIg[m] == 0 and gtIg[gind] == 1: + break + # continue to next gt unless better match made + if ious[dind, gind] < iou: + continue + # if match successful and best so far, + # store appropriately + iou = ious[dind, gind] + m = gind + # if match made store id of match for both dt and gt + if m == -1: + continue + dtIg[tind, dind] = gtIg[m] + dtm[tind, dind] = gt[m]['id'] + gtm[tind, m] = d['id'] + # set unmatched detections outside of area range to ignore + a = np.array([d['area'] < aRng[0] or d['area'] > aRng[1] + for d in dt]).reshape((1, len(dt))) + dtIg = np.logical_or(dtIg, np.logical_and(dtm == 0, np.repeat(a, T, + 0))) + # store results for given image and category + + return { + 'image_id': imgId, + 'category_id': catId, + 'aRng': aRng, + 'maxDet': maxDet, + 'dtIds': [d['id'] for d in dt], + 'gtIds': [g['id'] for g in gt], + 'dtMatches': dtm, + 'gtMatches': gtm, + 'dtScores': [d['score'] for d in dt], + 'gtIgnore': gtIg, + 'dtIgnore': dtIg, + } + + def summarize(self): + """Compute and display summary metrics for evaluation results. + + Note this function can *only* be applied on the default parameter + setting + """ + + def _summarize(ap=1, iouThr=None, areaRng='all', maxDets=100): + p = self.params + iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}' # noqa + titleStr = 'Average Precision' if ap == 1 else 'Average Recall' + typeStr = '(AP)' if ap == 1 else '(AR)' + iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \ + if iouThr is None else '{:0.2f}'.format(iouThr) + + aind = [ + i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng + ] + mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets] + if ap == 1: + # dimension of precision: [TxRxKxAxM] + s = self.eval['precision'] + # IoU + if iouThr is not None: + t = np.where(iouThr == p.iouThrs)[0] + s = s[t] + s = s[:, :, :, aind, mind] + else: + # dimension of recall: [TxKxAxM] + s = self.eval['recall'] + if iouThr is not None: + t = np.where(iouThr == p.iouThrs)[0] + s = s[t] + s = s[:, :, aind, mind] + if len(s[s > -1]) == 0: + mean_s = -1 + else: + mean_s = np.mean(s[s > -1]) + print( + iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, + mean_s)) + return mean_s + + def _summarizeDets(): + stats = [] + stats.append(_summarize(1, maxDets=self.params.maxDets[-1])) + stats.append( + _summarize(1, iouThr=.5, maxDets=self.params.maxDets[-1])) + stats.append( + _summarize(1, iouThr=.75, maxDets=self.params.maxDets[-1])) + for area_rng in ('small', 'medium', 'large'): + stats.append( + _summarize( + 1, areaRng=area_rng, maxDets=self.params.maxDets[-1])) + for max_det in self.params.maxDets: + stats.append(_summarize(0, maxDets=max_det)) + for area_rng in ('small', 'medium', 'large'): + stats.append( + _summarize( + 0, areaRng=area_rng, maxDets=self.params.maxDets[-1])) + stats = np.array(stats) + return stats + + def _summarizeKps(): + stats = np.zeros((10, )) + stats[0] = _summarize(1, maxDets=20) + stats[1] = _summarize(1, maxDets=20, iouThr=.5) + stats[2] = _summarize(1, maxDets=20, iouThr=.75) + stats[3] = _summarize(1, maxDets=20, areaRng='medium') + stats[4] = _summarize(1, maxDets=20, areaRng='large') + stats[5] = _summarize(0, maxDets=20) + stats[6] = _summarize(0, maxDets=20, iouThr=.5) + stats[7] = _summarize(0, maxDets=20, iouThr=.75) + stats[8] = _summarize(0, maxDets=20, areaRng='medium') + stats[9] = _summarize(0, maxDets=20, areaRng='large') + return stats + + if not self.eval: + raise Exception('Please run accumulate() first') + iouType = self.params.iouType + if iouType == 'segm' or iouType == 'bbox': + summarize = _summarizeDets + elif iouType == 'keypoints': + summarize = _summarizeKps + self.stats = summarize() diff --git a/mmdet_code/mmdetection/mmdet/datasets/base_det_dataset.py b/mmdet_code/mmdetection/mmdet/datasets/base_det_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..8b3876d5c06eb7d3741a29fe8b0963a7e425ec1b --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/base_det_dataset.py @@ -0,0 +1,131 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List, Optional + +from mmengine.dataset import BaseDataset +from mmengine.fileio import load +from mmengine.utils import is_abs + +from ..registry import DATASETS + + +@DATASETS.register_module() +class BaseDetDataset(BaseDataset): + """Base dataset for detection. + + Args: + proposal_file (str, optional): Proposals file path. Defaults to None. + file_client_args (dict): Arguments to instantiate the + corresponding backend in mmdet <= 3.0.0rc6. Defaults to None. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + return_classes (bool): Whether to return class information + for open vocabulary-based algorithms. Defaults to False. + caption_prompt (dict, optional): Prompt for captioning. + Defaults to None. + """ + + def __init__(self, + *args, + seg_map_suffix: str = '.png', + proposal_file: Optional[str] = None, + file_client_args: dict = None, + backend_args: dict = None, + return_classes: bool = False, + caption_prompt: Optional[dict] = None, + **kwargs) -> None: + self.seg_map_suffix = seg_map_suffix + self.proposal_file = proposal_file + self.backend_args = backend_args + self.return_classes = return_classes + self.caption_prompt = caption_prompt + if self.caption_prompt is not None: + assert self.return_classes, \ + 'return_classes must be True when using caption_prompt' + if file_client_args is not None: + raise RuntimeError( + 'The `file_client_args` is deprecated, ' + 'please use `backend_args` instead, please refer to' + 'https://github.com/open-mmlab/mmdetection/blob/main/configs/_base_/datasets/coco_detection.py' # noqa: E501 + ) + super().__init__(*args, **kwargs) + + def full_init(self) -> None: + """Load annotation file and set ``BaseDataset._fully_initialized`` to + True. + + If ``lazy_init=False``, ``full_init`` will be called during the + instantiation and ``self._fully_initialized`` will be set to True. If + ``obj._fully_initialized=False``, the class method decorated by + ``force_full_init`` will call ``full_init`` automatically. + + Several steps to initialize annotation: + + - load_data_list: Load annotations from annotation file. + - load_proposals: Load proposals from proposal file, if + `self.proposal_file` is not None. + - filter data information: Filter annotations according to + filter_cfg. + - slice_data: Slice dataset according to ``self._indices`` + - serialize_data: Serialize ``self.data_list`` if + ``self.serialize_data`` is True. + """ + if self._fully_initialized: + return + # load data information + self.data_list = self.load_data_list() + # get proposals from file + if self.proposal_file is not None: + self.load_proposals() + # filter illegal data, such as data that has no annotations. + self.data_list = self.filter_data() + + # Get subset data according to indices. + if self._indices is not None: + self.data_list = self._get_unserialized_subset(self._indices) + + # serialize data_list + if self.serialize_data: + self.data_bytes, self.data_address = self._serialize_data() + + self._fully_initialized = True + + def load_proposals(self) -> None: + """Load proposals from proposals file. + + The `proposals_list` should be a dict[img_path: proposals] + with the same length as `data_list`. And the `proposals` should be + a `dict` or :obj:`InstanceData` usually contains following keys. + + - bboxes (np.ndarry): Has a shape (num_instances, 4), + the last dimension 4 arrange as (x1, y1, x2, y2). + - scores (np.ndarry): Classification scores, has a shape + (num_instance, ). + """ + # TODO: Add Unit Test after fully support Dump-Proposal Metric + if not is_abs(self.proposal_file): + self.proposal_file = osp.join(self.data_root, self.proposal_file) + proposals_list = load( + self.proposal_file, backend_args=self.backend_args) + assert len(self.data_list) == len(proposals_list) + for data_info in self.data_list: + img_path = data_info['img_path'] + # `file_name` is the key to obtain the proposals from the + # `proposals_list`. + file_name = osp.join( + osp.split(osp.split(img_path)[0])[-1], + osp.split(img_path)[-1]) + proposals = proposals_list[file_name] + data_info['proposals'] = proposals + + def get_cat_ids(self, idx: int) -> List[int]: + """Get COCO category ids by index. + + Args: + idx (int): Index of data. + + Returns: + List[int]: All categories in the image of specified index. + """ + instances = self.get_data_info(idx)['instances'] + return [instance['bbox_label'] for instance in instances] diff --git a/mmdet_code/mmdetection/mmdet/datasets/base_semseg_dataset.py b/mmdet_code/mmdetection/mmdet/datasets/base_semseg_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..d10f762a21a897ab8274fbe9eefab054691a7c60 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/base_semseg_dataset.py @@ -0,0 +1,265 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import Callable, Dict, List, Optional, Sequence, Union + +import mmengine +import mmengine.fileio as fileio +import numpy as np +from mmengine.dataset import BaseDataset, Compose + +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class BaseSegDataset(BaseDataset): + """Custom dataset for semantic segmentation. An example of file structure + is as followed. + + .. code-block:: none + + ├── data + │ ├── my_dataset + │ │ ├── img_dir + │ │ │ ├── train + │ │ │ │ ├── xxx{img_suffix} + │ │ │ │ ├── yyy{img_suffix} + │ │ │ │ ├── zzz{img_suffix} + │ │ │ ├── val + │ │ ├── ann_dir + │ │ │ ├── train + │ │ │ │ ├── xxx{seg_map_suffix} + │ │ │ │ ├── yyy{seg_map_suffix} + │ │ │ │ ├── zzz{seg_map_suffix} + │ │ │ ├── val + + The img/gt_semantic_seg pair of BaseSegDataset should be of the same + except suffix. A valid img/gt_semantic_seg filename pair should be like + ``xxx{img_suffix}`` and ``xxx{seg_map_suffix}`` (extension is also included + in the suffix). If split is given, then ``xxx`` is specified in txt file. + Otherwise, all files in ``img_dir/``and ``ann_dir`` will be loaded. + Please refer to ``docs/en/tutorials/new_dataset.md`` for more details. + + + Args: + ann_file (str): Annotation file path. Defaults to ''. + metainfo (dict, optional): Meta information for dataset, such as + specify classes to load. Defaults to None. + data_root (str, optional): The root directory for ``data_prefix`` and + ``ann_file``. Defaults to None. + data_prefix (dict, optional): Prefix for training data. Defaults to + dict(img_path=None, seg_map_path=None). + img_suffix (str): Suffix of images. Default: '.jpg' + seg_map_suffix (str): Suffix of segmentation maps. Default: '.png' + filter_cfg (dict, optional): Config for filter data. Defaults to None. + indices (int or Sequence[int], optional): Support using first few + data in annotation file to facilitate training/testing on a smaller + dataset. Defaults to None which means using all ``data_infos``. + serialize_data (bool, optional): Whether to hold memory using + serialized objects, when enabled, data loader workers can use + shared RAM from master process instead of making a copy. Defaults + to True. + pipeline (list, optional): Processing pipeline. Defaults to []. + test_mode (bool, optional): ``test_mode=True`` means in test phase. + Defaults to False. + lazy_init (bool, optional): Whether to load annotation during + instantiation. In some cases, such as visualization, only the meta + information of the dataset is needed, which is not necessary to + load annotation file. ``Basedataset`` can skip load annotations to + save time by set ``lazy_init=True``. Defaults to False. + use_label_map (bool, optional): Whether to use label map. + Defaults to False. + max_refetch (int, optional): If ``Basedataset.prepare_data`` get a + None img. The maximum extra number of cycles to get a valid + image. Defaults to 1000. + backend_args (dict, Optional): Arguments to instantiate a file backend. + See https://mmengine.readthedocs.io/en/latest/api/fileio.htm + for details. Defaults to None. + Notes: mmcv>=2.0.0rc4 required. + """ + METAINFO: dict = dict() + + def __init__(self, + ann_file: str = '', + img_suffix='.jpg', + seg_map_suffix='.png', + metainfo: Optional[dict] = None, + data_root: Optional[str] = None, + data_prefix: dict = dict(img_path='', seg_map_path=''), + filter_cfg: Optional[dict] = None, + indices: Optional[Union[int, Sequence[int]]] = None, + serialize_data: bool = True, + pipeline: List[Union[dict, Callable]] = [], + test_mode: bool = False, + lazy_init: bool = False, + use_label_map: bool = False, + max_refetch: int = 1000, + backend_args: Optional[dict] = None) -> None: + + self.img_suffix = img_suffix + self.seg_map_suffix = seg_map_suffix + self.backend_args = backend_args.copy() if backend_args else None + + self.data_root = data_root + self.data_prefix = copy.copy(data_prefix) + self.ann_file = ann_file + self.filter_cfg = copy.deepcopy(filter_cfg) + self._indices = indices + self.serialize_data = serialize_data + self.test_mode = test_mode + self.max_refetch = max_refetch + self.data_list: List[dict] = [] + self.data_bytes: np.ndarray + + # Set meta information. + self._metainfo = self._load_metainfo(copy.deepcopy(metainfo)) + + # Get label map for custom classes + new_classes = self._metainfo.get('classes', None) + self.label_map = self.get_label_map( + new_classes) if use_label_map else None + self._metainfo.update(dict(label_map=self.label_map)) + + # Update palette based on label map or generate palette + # if it is not defined + updated_palette = self._update_palette() + self._metainfo.update(dict(palette=updated_palette)) + + # Join paths. + if self.data_root is not None: + self._join_prefix() + + # Build pipeline. + self.pipeline = Compose(pipeline) + # Full initialize the dataset. + if not lazy_init: + self.full_init() + + if test_mode: + assert self._metainfo.get('classes') is not None, \ + 'dataset metainfo `classes` should be specified when testing' + + @classmethod + def get_label_map(cls, + new_classes: Optional[Sequence] = None + ) -> Union[Dict, None]: + """Require label mapping. + + The ``label_map`` is a dictionary, its keys are the old label ids and + its values are the new label ids, and is used for changing pixel + labels in load_annotations. If and only if old classes in cls.METAINFO + is not equal to new classes in self._metainfo and nether of them is not + None, `label_map` is not None. + + Args: + new_classes (list, tuple, optional): The new classes name from + metainfo. Default to None. + + + Returns: + dict, optional: The mapping from old classes in cls.METAINFO to + new classes in self._metainfo + """ + old_classes = cls.METAINFO.get('classes', None) + if (new_classes is not None and old_classes is not None + and list(new_classes) != list(old_classes)): + + label_map = {} + if not set(new_classes).issubset(cls.METAINFO['classes']): + raise ValueError( + f'new classes {new_classes} is not a ' + f'subset of classes {old_classes} in METAINFO.') + for i, c in enumerate(old_classes): + if c not in new_classes: + # 0 is background + label_map[i] = 0 + else: + label_map[i] = new_classes.index(c) + return label_map + else: + return None + + def _update_palette(self) -> list: + """Update palette after loading metainfo. + + If length of palette is equal to classes, just return the palette. + If palette is not defined, it will randomly generate a palette. + If classes is updated by customer, it will return the subset of + palette. + + Returns: + Sequence: Palette for current dataset. + """ + palette = self._metainfo.get('palette', []) + classes = self._metainfo.get('classes', []) + # palette does match classes + if len(palette) == len(classes): + return palette + + if len(palette) == 0: + # Get random state before set seed, and restore + # random state later. + # It will prevent loss of randomness, as the palette + # may be different in each iteration if not specified. + # See: https://github.com/open-mmlab/mmdetection/issues/5844 + state = np.random.get_state() + np.random.seed(42) + # random palette + new_palette = np.random.randint( + 0, 255, size=(len(classes), 3)).tolist() + np.random.set_state(state) + elif len(palette) >= len(classes) and self.label_map is not None: + new_palette = [] + # return subset of palette + for old_id, new_id in sorted( + self.label_map.items(), key=lambda x: x[1]): + # 0 is background + if new_id != 0: + new_palette.append(palette[old_id]) + new_palette = type(palette)(new_palette) + elif len(palette) >= len(classes): + # Allow palette length is greater than classes. + return palette + else: + raise ValueError('palette does not match classes ' + f'as metainfo is {self._metainfo}.') + return new_palette + + def load_data_list(self) -> List[dict]: + """Load annotation from directory or annotation file. + + Returns: + list[dict]: All data info of dataset. + """ + data_list = [] + img_dir = self.data_prefix.get('img_path', None) + ann_dir = self.data_prefix.get('seg_map_path', None) + if not osp.isdir(self.ann_file) and self.ann_file: + assert osp.isfile(self.ann_file), \ + f'Failed to load `ann_file` {self.ann_file}' + lines = mmengine.list_from_file( + self.ann_file, backend_args=self.backend_args) + for line in lines: + img_name = line.strip() + data_info = dict( + img_path=osp.join(img_dir, img_name + self.img_suffix)) + if ann_dir is not None: + seg_map = img_name + self.seg_map_suffix + data_info['seg_map_path'] = osp.join(ann_dir, seg_map) + data_info['label_map'] = self.label_map + data_list.append(data_info) + else: + for img in fileio.list_dir_or_file( + dir_path=img_dir, + list_dir=False, + suffix=self.img_suffix, + recursive=True, + backend_args=self.backend_args): + data_info = dict(img_path=osp.join(img_dir, img)) + if ann_dir is not None: + seg_map = img.replace(self.img_suffix, self.seg_map_suffix) + data_info['seg_map_path'] = osp.join(ann_dir, seg_map) + data_info['label_map'] = self.label_map + data_list.append(data_info) + data_list = sorted(data_list, key=lambda x: x['img_path']) + return data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/base_video_dataset.py b/mmdet_code/mmdetection/mmdet/datasets/base_video_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0a4a7a25f16206f06c7b64a7ce4c3588efd5455e --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/base_video_dataset.py @@ -0,0 +1,304 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from collections import defaultdict +from typing import Any, List, Tuple + +import mmengine.fileio as fileio +from mmengine.dataset import BaseDataset +from mmengine.logging import print_log + +from mmdet.datasets.api_wrappers import COCO +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class BaseVideoDataset(BaseDataset): + """Base video dataset for VID, MOT and VIS tasks.""" + + META = dict(classes=None) + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def __init__(self, *args, backend_args: dict = None, **kwargs): + self.backend_args = backend_args + super().__init__(*args, **kwargs) + + def load_data_list(self) -> Tuple[List[dict], List]: + """Load annotations from an annotation file named as ``self.ann_file``. + + Returns: + tuple(list[dict], list): A list of annotation and a list of + valid data indices. + """ + with fileio.get_local_path(self.ann_file) as local_path: + self.coco = COCO(local_path) + # The order of returned `cat_ids` will not + # change with the order of the classes + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + # used in `filter_data` + self.img_ids_with_ann = set() + + img_ids = self.coco.get_img_ids() + total_ann_ids = [] + # if ``video_id`` is not in the annotation file, we will assign a big + # unique video_id for this video. + single_video_id = 100000 + videos = {} + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + if 'video_id' not in raw_img_info: + single_video_id = single_video_id + 1 + video_id = single_video_id + else: + video_id = raw_img_info['video_id'] + + if video_id not in videos: + videos[video_id] = { + 'video_id': video_id, + 'images': [], + 'video_length': 0 + } + + videos[video_id]['video_length'] += 1 + ann_ids = self.coco.get_ann_ids( + img_ids=[img_id], cat_ids=self.cat_ids) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info( + dict(raw_img_info=raw_img_info, raw_ann_info=raw_ann_info)) + + if len(parsed_data_info['instances']) > 0: + self.img_ids_with_ann.add(parsed_data_info['img_id']) + + videos[video_id]['images'].append(parsed_data_info) + + data_list = [v for v in videos.values()] + + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> dict: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information loaded from + ``ann_file``. + + Returns: + dict: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + data_info = {} + + data_info.update(img_info) + if self.data_prefix.get('img_path', None) is not None: + img_path = osp.join(self.data_prefix['img_path'], + img_info['file_name']) + else: + img_path = img_info['file_name'] + data_info['img_path'] = img_path + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + if ann.get('instance_id', None): + instance['instance_id'] = ann['instance_id'] + else: + # image dataset usually has no `instance_id`. + # Therefore, we set it to `i`. + instance['instance_id'] = i + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[int]: + """Filter image annotations according to filter_cfg. + + Returns: + list[int]: Filtered results. + """ + if self.test_mode: + return self.data_list + + num_imgs_before_filter = sum( + [len(info['images']) for info in self.data_list]) + num_imgs_after_filter = 0 + + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= self.img_ids_with_ann + + new_data_list = [] + for video_data_info in self.data_list: + imgs_data_info = video_data_info['images'] + valid_imgs_data_info = [] + + for data_info in imgs_data_info: + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + # TODO: simplify these conditions + if self.filter_cfg is None: + if img_id not in ids_in_cat: + video_data_info['video_length'] -= 1 + continue + if min(width, height) >= 32: + valid_imgs_data_info.append(data_info) + num_imgs_after_filter += 1 + else: + video_data_info['video_length'] -= 1 + else: + if self.filter_cfg.get('filter_empty_gt', + True) and img_id not in ids_in_cat: + video_data_info['video_length'] -= 1 + continue + if min(width, height) >= self.filter_cfg.get( + 'min_size', 32): + valid_imgs_data_info.append(data_info) + num_imgs_after_filter += 1 + else: + video_data_info['video_length'] -= 1 + video_data_info['images'] = valid_imgs_data_info + new_data_list.append(video_data_info) + + print_log( + 'The number of samples before and after filtering: ' + f'{num_imgs_before_filter} / {num_imgs_after_filter}', 'current') + return new_data_list + + def prepare_data(self, idx) -> Any: + """Get date processed by ``self.pipeline``. Note that ``idx`` is a + video index in default since the base element of video dataset is a + video. However, in some cases, we need to specific both the video index + and frame index. For example, in traing mode, we may want to sample the + specific frames and all the frames must be sampled once in a epoch; in + test mode, we may want to output data of a single image rather than the + whole video for saving memory. + + Args: + idx (int): The index of ``data_info``. + + Returns: + Any: Depends on ``self.pipeline``. + """ + if isinstance(idx, tuple): + assert len(idx) == 2, 'The length of idx must be 2: ' + '(video_index, frame_index)' + video_idx, frame_idx = idx[0], idx[1] + else: + video_idx, frame_idx = idx, None + + data_info = self.get_data_info(video_idx) + if self.test_mode: + # Support two test_mode: frame-level and video-level + final_data_info = defaultdict(list) + if frame_idx is None: + frames_idx_list = list(range(data_info['video_length'])) + else: + frames_idx_list = [frame_idx] + for index in frames_idx_list: + frame_ann = data_info['images'][index] + frame_ann['video_id'] = data_info['video_id'] + # Collate data_list (list of dict to dict of list) + for key, value in frame_ann.items(): + final_data_info[key].append(value) + # copy the info in video-level into img-level + # TODO: the value of this key is the same as that of + # `video_length` in test mode + final_data_info['ori_video_length'].append( + data_info['video_length']) + + final_data_info['video_length'] = [len(frames_idx_list) + ] * len(frames_idx_list) + return self.pipeline(final_data_info) + else: + # Specify `key_frame_id` for the frame sampling in the pipeline + if frame_idx is not None: + data_info['key_frame_id'] = frame_idx + return self.pipeline(data_info) + + def get_cat_ids(self, index) -> List[int]: + """Following image detection, we provide this interface function. Get + category ids by video index and frame index. + + Args: + index: The index of the dataset. It support two kinds of inputs: + Tuple: + video_idx (int): Index of video. + frame_idx (int): Index of frame. + Int: Index of video. + + Returns: + List[int]: All categories in the image of specified video index + and frame index. + """ + if isinstance(index, tuple): + assert len( + index + ) == 2, f'Expect the length of index is 2, but got {len(index)}' + video_idx, frame_idx = index + instances = self.get_data_info( + video_idx)['images'][frame_idx]['instances'] + return [instance['bbox_label'] for instance in instances] + else: + cat_ids = [] + for img in self.get_data_info(index)['images']: + for instance in img['instances']: + cat_ids.append(instance['bbox_label']) + return cat_ids + + @property + def num_all_imgs(self): + """Get the number of all the images in this video dataset.""" + return sum( + [len(self.get_data_info(i)['images']) for i in range(len(self))]) + + def get_len_per_video(self, idx): + """Get length of one video. + + Args: + idx (int): Index of video. + + Returns: + int (int): The length of the video. + """ + return len(self.get_data_info(idx)['images']) diff --git a/mmdet_code/mmdetection/mmdet/datasets/cityscapes.py b/mmdet_code/mmdetection/mmdet/datasets/cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..09755eb1e8b0f0c278085bd2fafbb7247a3fc946 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/cityscapes.py @@ -0,0 +1,61 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Modified from https://github.com/facebookresearch/detectron2/blob/master/detectron2/data/datasets/cityscapes.py # noqa +# and https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalInstanceLevelSemanticLabeling.py # noqa + +from typing import List + +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class CityscapesDataset(CocoDataset): + """Dataset for Cityscapes.""" + + METAINFO = { + 'classes': ('person', 'rider', 'car', 'truck', 'bus', 'train', + 'motorcycle', 'bicycle'), + 'palette': [(220, 20, 60), (255, 0, 0), (0, 0, 142), (0, 0, 70), + (0, 60, 100), (0, 80, 100), (0, 0, 230), (119, 11, 32)] + } + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + all_is_crowd = all([ + instance['ignore_flag'] == 1 + for instance in data_info['instances'] + ]) + if filter_empty_gt and (img_id not in ids_in_cat or all_is_crowd): + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/mmdetection/mmdet/datasets/coco.py b/mmdet_code/mmdetection/mmdet/datasets/coco.py new file mode 100644 index 0000000000000000000000000000000000000000..1cf21c4e667e3b565ea01d1eb95bcdbf171b90d0 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/coco.py @@ -0,0 +1,201 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List, Union + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class CocoDataset(BaseDetDataset): + """Dataset for COCO.""" + + METAINFO = { + 'classes': + ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', + 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', + 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', + 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', + 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', + 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', + 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', + 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', + 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', + 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush'), + # palette is a list of color tuples, which is used for visualization. + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208)] + } + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + + data_info = {} + + # TODO: need to change data_prefix['img'] to data_prefix['img_path'] + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].rsplit('.', 1)[0] + self.seg_map_suffix) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['classes'] + data_info['caption_prompt'] = self.caption_prompt + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + + if ann.get('segmentation', None): + instance['mask'] = ann['segmentation'] + + instances.append(instance) + data_info['instances'] = instances + return data_info + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + # obtain images that contain annotation + ids_with_ann = set(data_info['img_id'] for data_info in self.data_list) + # obtain images that contain annotations of the required categories + ids_in_cat = set() + for i, class_id in enumerate(self.cat_ids): + ids_in_cat |= set(self.cat_img_map[class_id]) + # merge the image id sets of the two conditions and use the merged set + # to filter out images if self.filter_empty_gt=True + ids_in_cat &= ids_with_ann + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_in_cat: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/mmdetection/mmdet/datasets/coco_caption.py b/mmdet_code/mmdetection/mmdet/datasets/coco_caption.py new file mode 100644 index 0000000000000000000000000000000000000000..ee695fe9a768f2be5345c6ad6bafc74177f252c0 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/coco_caption.py @@ -0,0 +1,32 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from pathlib import Path +from typing import List + +import mmengine +from mmengine.dataset import BaseDataset +from mmengine.fileio import get_file_backend + +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class CocoCaptionDataset(BaseDataset): + """COCO2014 Caption dataset.""" + + def load_data_list(self) -> List[dict]: + """Load data list.""" + img_prefix = self.data_prefix['img_path'] + annotations = mmengine.load(self.ann_file) + file_backend = get_file_backend(img_prefix) + + data_list = [] + for ann in annotations: + data_info = { + 'img_id': Path(ann['image']).stem.split('_')[-1], + 'img_path': file_backend.join_path(img_prefix, ann['image']), + 'gt_caption': ann['caption'], + } + + data_list.append(data_info) + + return data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/coco_panoptic.py b/mmdet_code/mmdetection/mmdet/datasets/coco_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a200e01d323e998afa782797e1cc92f75c70cf --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/coco_panoptic.py @@ -0,0 +1,292 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import Callable, List, Optional, Sequence, Union + +from mmdet.registry import DATASETS +from .api_wrappers import COCOPanoptic +from .coco import CocoDataset + + +@DATASETS.register_module() +class CocoPanopticDataset(CocoDataset): + """Coco dataset for Panoptic segmentation. + + The annotation format is shown as follows. The `ann` field is optional + for testing. + + .. code-block:: none + + [ + { + 'filename': f'{image_id:012}.png', + 'image_id':9 + 'segments_info': + [ + { + 'id': 8345037, (segment_id in panoptic png, + convert from rgb) + 'category_id': 51, + 'iscrowd': 0, + 'bbox': (x1, y1, w, h), + 'area': 24315 + }, + ... + ] + }, + ... + ] + + Args: + ann_file (str): Annotation file path. Defaults to ''. + metainfo (dict, optional): Meta information for dataset, such as class + information. Defaults to None. + data_root (str, optional): The root directory for ``data_prefix`` and + ``ann_file``. Defaults to None. + data_prefix (dict, optional): Prefix for training data. Defaults to + ``dict(img=None, ann=None, seg=None)``. The prefix ``seg`` which is + for panoptic segmentation map must be not None. + filter_cfg (dict, optional): Config for filter data. Defaults to None. + indices (int or Sequence[int], optional): Support using first few + data in annotation file to facilitate training/testing on a smaller + dataset. Defaults to None which means using all ``data_infos``. + serialize_data (bool, optional): Whether to hold memory using + serialized objects, when enabled, data loader workers can use + shared RAM from master process instead of making a copy. Defaults + to True. + pipeline (list, optional): Processing pipeline. Defaults to []. + test_mode (bool, optional): ``test_mode=True`` means in test phase. + Defaults to False. + lazy_init (bool, optional): Whether to load annotation during + instantiation. In some cases, such as visualization, only the meta + information of the dataset is needed, which is not necessary to + load annotation file. ``Basedataset`` can skip load annotations to + save time by set ``lazy_init=False``. Defaults to False. + max_refetch (int, optional): If ``Basedataset.prepare_data`` get a + None img. The maximum extra number of cycles to get a valid + image. Defaults to 1000. + """ + + METAINFO = { + 'classes': + ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', + 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', + 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', + 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', + 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', + 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', + 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', + 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', + 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', + 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner', + 'blanket', 'bridge', 'cardboard', 'counter', 'curtain', 'door-stuff', + 'floor-wood', 'flower', 'fruit', 'gravel', 'house', 'light', + 'mirror-stuff', 'net', 'pillow', 'platform', 'playingfield', + 'railroad', 'river', 'road', 'roof', 'sand', 'sea', 'shelf', 'snow', + 'stairs', 'tent', 'towel', 'wall-brick', 'wall-stone', 'wall-tile', + 'wall-wood', 'water-other', 'window-blind', 'window-other', + 'tree-merged', 'fence-merged', 'ceiling-merged', 'sky-other-merged', + 'cabinet-merged', 'table-merged', 'floor-other-merged', + 'pavement-merged', 'mountain-merged', 'grass-merged', 'dirt-merged', + 'paper-merged', 'food-other-merged', 'building-other-merged', + 'rock-merged', 'wall-other-merged', 'rug-merged'), + 'thing_classes': + ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', + 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', + 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', + 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', + 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', + 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', + 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', + 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', + 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', + 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush'), + 'stuff_classes': + ('banner', 'blanket', 'bridge', 'cardboard', 'counter', 'curtain', + 'door-stuff', 'floor-wood', 'flower', 'fruit', 'gravel', 'house', + 'light', 'mirror-stuff', 'net', 'pillow', 'platform', 'playingfield', + 'railroad', 'river', 'road', 'roof', 'sand', 'sea', 'shelf', 'snow', + 'stairs', 'tent', 'towel', 'wall-brick', 'wall-stone', 'wall-tile', + 'wall-wood', 'water-other', 'window-blind', 'window-other', + 'tree-merged', 'fence-merged', 'ceiling-merged', 'sky-other-merged', + 'cabinet-merged', 'table-merged', 'floor-other-merged', + 'pavement-merged', 'mountain-merged', 'grass-merged', 'dirt-merged', + 'paper-merged', 'food-other-merged', 'building-other-merged', + 'rock-merged', 'wall-other-merged', 'rug-merged'), + 'palette': + [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), + (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), + (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), + (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), + (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), + (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), + (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), + (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), + (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), + (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), + (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), + (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), + (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), + (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), + (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), + (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), + (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), + (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), + (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), + (246, 0, 122), (191, 162, 208), (255, 255, 128), (147, 211, 203), + (150, 100, 100), (168, 171, 172), (146, 112, 198), (210, 170, 100), + (92, 136, 89), (218, 88, 184), (241, 129, 0), (217, 17, 255), + (124, 74, 181), (70, 70, 70), (255, 228, 255), (154, 208, 0), + (193, 0, 92), (76, 91, 113), (255, 180, 195), (106, 154, 176), + (230, 150, 140), (60, 143, 255), (128, 64, 128), (92, 82, 55), + (254, 212, 124), (73, 77, 174), (255, 160, 98), (255, 255, 255), + (104, 84, 109), (169, 164, 131), (225, 199, 255), (137, 54, 74), + (135, 158, 223), (7, 246, 231), (107, 255, 200), (58, 41, 149), + (183, 121, 142), (255, 73, 97), (107, 142, 35), (190, 153, 153), + (146, 139, 141), (70, 130, 180), (134, 199, 156), (209, 226, 140), + (96, 36, 108), (96, 96, 96), (64, 170, 64), (152, 251, 152), + (208, 229, 228), (206, 186, 171), (152, 161, 64), (116, 112, 0), + (0, 114, 143), (102, 102, 156), (250, 141, 255)] + } + COCOAPI = COCOPanoptic + # ann_id is not unique in coco panoptic dataset. + ANN_ID_UNIQUE = False + + def __init__(self, + ann_file: str = '', + metainfo: Optional[dict] = None, + data_root: Optional[str] = None, + data_prefix: dict = dict(img=None, ann=None, seg=None), + filter_cfg: Optional[dict] = None, + indices: Optional[Union[int, Sequence[int]]] = None, + serialize_data: bool = True, + pipeline: List[Union[dict, Callable]] = [], + test_mode: bool = False, + lazy_init: bool = False, + max_refetch: int = 1000, + backend_args: dict = None, + **kwargs) -> None: + super().__init__( + ann_file=ann_file, + metainfo=metainfo, + data_root=data_root, + data_prefix=data_prefix, + filter_cfg=filter_cfg, + indices=indices, + serialize_data=serialize_data, + pipeline=pipeline, + test_mode=test_mode, + lazy_init=lazy_init, + max_refetch=max_refetch, + backend_args=backend_args, + **kwargs) + + def parse_data_info(self, raw_data_info: dict) -> dict: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file``. + + Returns: + dict: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + # filter out unmatched annotations which have + # same segment_id but belong to other image + ann_info = [ + ann for ann in ann_info if ann['image_id'] == img_info['img_id'] + ] + data_info = {} + + img_path = osp.join(self.data_prefix['img'], img_info['file_name']) + if self.data_prefix.get('seg', None): + seg_map_path = osp.join( + self.data_prefix['seg'], + img_info['file_name'].replace('.jpg', '.png')) + else: + seg_map_path = None + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['seg_map_path'] = seg_map_path + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + if self.return_classes: + data_info['text'] = self.metainfo['thing_classes'] + data_info['stuff_text'] = self.metainfo['stuff_classes'] + data_info['custom_entities'] = True # no important + + instances = [] + segments_info = [] + for ann in ann_info: + instance = {} + x1, y1, w, h = ann['bbox'] + if ann['area'] <= 0 or w < 1 or h < 1: + continue + bbox = [x1, y1, x1 + w, y1 + h] + category_id = ann['category_id'] + contiguous_cat_id = self.cat2label[category_id] + + is_thing = self.coco.load_cats(ids=category_id)[0]['isthing'] + if is_thing: + is_crowd = ann.get('iscrowd', False) + instance['bbox'] = bbox + instance['bbox_label'] = contiguous_cat_id + if not is_crowd: + instance['ignore_flag'] = 0 + else: + instance['ignore_flag'] = 1 + is_thing = False + + segment_info = { + 'id': ann['id'], + 'category': contiguous_cat_id, + 'is_thing': is_thing + } + segments_info.append(segment_info) + if len(instance) > 0 and is_thing: + instances.append(instance) + data_info['instances'] = instances + data_info['segments_info'] = segments_info + return data_info + + def filter_data(self) -> List[dict]: + """Filter images too small or without ground truth. + + Returns: + List[dict]: ``self.data_list`` after filtering. + """ + if self.test_mode: + return self.data_list + + if self.filter_cfg is None: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) + min_size = self.filter_cfg.get('min_size', 0) + + ids_with_ann = set() + # check whether images have legal thing annotations. + for data_info in self.data_list: + for segment_info in data_info['segments_info']: + if not segment_info['is_thing']: + continue + ids_with_ann.add(data_info['img_id']) + + valid_data_list = [] + for data_info in self.data_list: + img_id = data_info['img_id'] + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and img_id not in ids_with_ann: + continue + if min(width, height) >= min_size: + valid_data_list.append(data_info) + + return valid_data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/coco_semantic.py b/mmdet_code/mmdetection/mmdet/datasets/coco_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..752568454456c1e5edcb2a24c6c2b46f042cb334 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/coco_semantic.py @@ -0,0 +1,90 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .ade20k import ADE20KSegDataset + + +@DATASETS.register_module() +class CocoSegDataset(ADE20KSegDataset): + """COCO dataset. + + In segmentation map annotation for COCO. The ``img_suffix`` is fixed to + '.jpg', and ``seg_map_suffix`` is fixed to '.png'. + """ + + METAINFO = dict( + classes=( + 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', + 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', + 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', + 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', + 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', + 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', + 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', + 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', + 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', + 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', + 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner', + 'blanket', 'branch', 'bridge', 'building-other', 'bush', 'cabinet', + 'cage', 'cardboard', 'carpet', 'ceiling-other', 'ceiling-tile', + 'cloth', 'clothes', 'clouds', 'counter', 'cupboard', 'curtain', + 'desk-stuff', 'dirt', 'door-stuff', 'fence', 'floor-marble', + 'floor-other', 'floor-stone', 'floor-tile', 'floor-wood', 'flower', + 'fog', 'food-other', 'fruit', 'furniture-other', 'grass', 'gravel', + 'ground-other', 'hill', 'house', 'leaves', 'light', 'mat', 'metal', + 'mirror-stuff', 'moss', 'mountain', 'mud', 'napkin', 'net', + 'paper', 'pavement', 'pillow', 'plant-other', 'plastic', + 'platform', 'playingfield', 'railing', 'railroad', 'river', 'road', + 'rock', 'roof', 'rug', 'salad', 'sand', 'sea', 'shelf', + 'sky-other', 'skyscraper', 'snow', 'solid-other', 'stairs', + 'stone', 'straw', 'structural-other', 'table', 'tent', + 'textile-other', 'towel', 'tree', 'vegetable', 'wall-brick', + 'wall-concrete', 'wall-other', 'wall-panel', 'wall-stone', + 'wall-tile', 'wall-wood', 'water-other', 'waterdrops', + 'window-blind', 'window-other', 'wood'), + palette=[(120, 120, 120), (180, 120, 120), (6, 230, 230), (80, 50, 50), + (4, 200, 3), (120, 120, 80), (140, 140, 140), (204, 5, 255), + (230, 230, 230), (4, 250, 7), (224, 5, 255), (235, 255, 7), + (150, 5, 61), (120, 120, 70), (8, 255, 51), (255, 6, 82), + (143, 255, 140), (204, 255, 4), (255, 51, 7), (204, 70, 3), + (0, 102, 200), (61, 230, 250), (255, 6, 51), (11, 102, 255), + (255, 7, 71), (255, 9, 224), (9, 7, 230), (220, 220, 220), + (255, 9, 92), (112, 9, 255), (8, 255, 214), (7, 255, 224), + (255, 184, 6), (10, 255, 71), (255, 41, 10), (7, 255, 255), + (224, 255, 8), (102, 8, 255), (255, 61, 6), (255, 194, 7), + (255, 122, 8), (0, 255, 20), (255, 8, 41), (255, 5, 153), + (6, 51, 255), (235, 12, 255), (160, 150, 20), (0, 163, 255), + (140, 140, 140), (250, 10, 15), (20, 255, 0), (31, 255, 0), + (255, 31, 0), (255, 224, 0), (153, 255, 0), (0, 0, 255), + (255, 71, 0), (0, 235, 255), (0, 173, 255), (31, 0, 255), + (11, 200, 200), (255, 82, 0), (0, 255, 245), (0, 61, 255), + (0, 255, 112), (0, 255, 133), (255, 0, 0), (255, 163, 0), + (255, 102, 0), (194, 255, 0), (0, 143, 255), (51, 255, 0), + (0, 82, 255), (0, 255, 41), (0, 255, 173), (10, 0, 255), + (173, 255, 0), (0, 255, 153), (255, 92, 0), (255, 0, 255), + (255, 0, 245), (255, 0, 102), (255, 173, 0), (255, 0, 20), + (255, 184, 184), (0, 31, 255), (0, 255, 61), (0, 71, 255), + (255, 0, 204), (0, 255, 194), (0, 255, 82), (0, 10, 255), + (0, 112, 255), (51, 0, 255), (0, 194, 255), (0, 122, 255), + (0, 255, 163), (255, 153, 0), (0, 255, 10), (255, 112, 0), + (143, 255, 0), (82, 0, 255), (163, 255, 0), (255, 235, 0), + (8, 184, 170), (133, 0, 255), (0, 255, 92), (184, 0, 255), + (255, 0, 31), (0, 184, 255), (0, 214, 255), (255, 0, 112), + (92, 255, 0), (0, 224, 255), (112, 224, 255), (70, 184, 160), + (163, 0, 255), (153, 0, 255), (71, 255, 0), (255, 0, 163), + (255, 204, 0), (255, 0, 143), (0, 255, 235), (133, 255, 0), + (255, 0, 235), (245, 0, 255), (255, 0, 122), (255, 245, 0), + (10, 190, 212), (214, 255, 0), (0, 204, 255), (20, 0, 255), + (255, 255, 0), (0, 153, 255), (0, 41, 255), (0, 255, 204), + (41, 0, 255), (41, 255, 0), (173, 0, 255), (0, 245, 255), + (71, 0, 255), (122, 0, 255), (0, 255, 184), (0, 92, 255), + (184, 255, 0), (0, 133, 255), (255, 214, 0), (25, 194, 194), + (102, 255, 0), (92, 0, 255), (107, 255, 200), (58, 41, 149), + (183, 121, 142), (255, 73, 97), (107, 142, 35), + (190, 153, 153), (146, 139, 141), (70, 130, 180), + (134, 199, 156), (209, 226, 140), (96, 36, 108), (96, 96, 96), + (64, 170, 64), (152, 251, 152), (208, 229, 228), + (206, 186, 171), (152, 161, 64), (116, 112, 0), (0, 114, 143), + (102, 102, 156), (250, 141, 255)]) diff --git a/mmdet_code/mmdetection/mmdet/datasets/crowdhuman.py b/mmdet_code/mmdetection/mmdet/datasets/crowdhuman.py new file mode 100644 index 0000000000000000000000000000000000000000..650176ee545ba6a10a816517553b3b77718d945b --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/crowdhuman.py @@ -0,0 +1,159 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import json +import logging +import os.path as osp +import warnings +from typing import List, Union + +import mmcv +from mmengine.dist import get_rank +from mmengine.fileio import dump, get, get_text, load +from mmengine.logging import print_log +from mmengine.utils import ProgressBar + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class CrowdHumanDataset(BaseDetDataset): + r"""Dataset for CrowdHuman. + + Args: + data_root (str): The root directory for + ``data_prefix`` and ``ann_file``. + ann_file (str): Annotation file path. + extra_ann_file (str | optional):The path of extra image metas + for CrowdHuman. It can be created by CrowdHumanDataset + automatically or by tools/misc/get_crowdhuman_id_hw.py + manually. Defaults to None. + """ + + METAINFO = { + 'classes': ('person', ), + # palette is a list of color tuples, which is used for visualization. + 'palette': [(220, 20, 60)] + } + + def __init__(self, data_root, ann_file, extra_ann_file=None, **kwargs): + # extra_ann_file record the size of each image. This file is + # automatically created when you first load the CrowdHuman + # dataset by mmdet. + if extra_ann_file is not None: + self.extra_ann_exist = True + self.extra_anns = load(extra_ann_file) + else: + ann_file_name = osp.basename(ann_file) + if 'train' in ann_file_name: + self.extra_ann_file = osp.join(data_root, 'id_hw_train.json') + elif 'val' in ann_file_name: + self.extra_ann_file = osp.join(data_root, 'id_hw_val.json') + self.extra_ann_exist = False + if not osp.isfile(self.extra_ann_file): + print_log( + 'extra_ann_file does not exist, prepare to collect ' + 'image height and width...', + level=logging.INFO) + self.extra_anns = {} + else: + self.extra_ann_exist = True + self.extra_anns = load(self.extra_ann_file) + super().__init__(data_root=data_root, ann_file=ann_file, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + anno_strs = get_text( + self.ann_file, backend_args=self.backend_args).strip().split('\n') + print_log('loading CrowdHuman annotation...', level=logging.INFO) + data_list = [] + prog_bar = ProgressBar(len(anno_strs)) + for i, anno_str in enumerate(anno_strs): + anno_dict = json.loads(anno_str) + parsed_data_info = self.parse_data_info(anno_dict) + data_list.append(parsed_data_info) + prog_bar.update() + if not self.extra_ann_exist and get_rank() == 0: + # TODO: support file client + try: + dump(self.extra_anns, self.extra_ann_file, file_format='json') + except: # noqa + warnings.warn( + 'Cache files can not be saved automatically! To speed up' + 'loading the dataset, please manually generate the cache' + ' file by file tools/misc/get_crowdhuman_id_hw.py') + + print_log( + f'\nsave extra_ann_file in {self.data_root}', + level=logging.INFO) + + del self.extra_anns + print_log('\nDone', level=logging.INFO) + return data_list + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + data_info = {} + img_path = osp.join(self.data_prefix['img'], + f"{raw_data_info['ID']}.jpg") + data_info['img_path'] = img_path + data_info['img_id'] = raw_data_info['ID'] + + if not self.extra_ann_exist: + img_bytes = get(img_path, backend_args=self.backend_args) + img = mmcv.imfrombytes(img_bytes, backend='cv2') + data_info['height'], data_info['width'] = img.shape[:2] + self.extra_anns[raw_data_info['ID']] = img.shape[:2] + del img, img_bytes + else: + data_info['height'], data_info['width'] = self.extra_anns[ + raw_data_info['ID']] + + instances = [] + for i, ann in enumerate(raw_data_info['gtboxes']): + instance = {} + if ann['tag'] not in self.metainfo['classes']: + instance['bbox_label'] = -1 + instance['ignore_flag'] = 1 + else: + instance['bbox_label'] = self.metainfo['classes'].index( + ann['tag']) + instance['ignore_flag'] = 0 + if 'extra' in ann: + if 'ignore' in ann['extra']: + if ann['extra']['ignore'] != 0: + instance['bbox_label'] = -1 + instance['ignore_flag'] = 1 + + x1, y1, w, h = ann['fbox'] + bbox = [x1, y1, x1 + w, y1 + h] + instance['bbox'] = bbox + + # Record the full bbox(fbox), head bbox(hbox) and visible + # bbox(vbox) as additional information. If you need to use + # this information, you just need to design the pipeline + # instead of overriding the CrowdHumanDataset. + instance['fbox'] = bbox + hbox = ann['hbox'] + instance['hbox'] = [ + hbox[0], hbox[1], hbox[0] + hbox[2], hbox[1] + hbox[3] + ] + vbox = ann['vbox'] + instance['vbox'] = [ + vbox[0], vbox[1], vbox[0] + vbox[2], vbox[1] + vbox[3] + ] + + instances.append(instance) + + data_info['instances'] = instances + return data_info diff --git a/mmdet_code/mmdetection/mmdet/datasets/dataset_wrappers.py b/mmdet_code/mmdetection/mmdet/datasets/dataset_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..d4e26e07c0f8a9e9f106bcd351f71e7b24d6ccf9 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/dataset_wrappers.py @@ -0,0 +1,260 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import collections +import copy +from typing import List, Sequence, Union + +from mmengine.dataset import BaseDataset +from mmengine.dataset import ConcatDataset as MMENGINE_ConcatDataset +from mmengine.dataset import force_full_init + +from mmdet.registry import DATASETS, TRANSFORMS + + +@DATASETS.register_module() +class MultiImageMixDataset: + """A wrapper of multiple images mixed dataset. + + Suitable for training on multiple images mixed data augmentation like + mosaic and mixup. For the augmentation pipeline of mixed image data, + the `get_indexes` method needs to be provided to obtain the image + indexes, and you can set `skip_flags` to change the pipeline running + process. At the same time, we provide the `dynamic_scale` parameter + to dynamically change the output image size. + + Args: + dataset (:obj:`CustomDataset`): The dataset to be mixed. + pipeline (Sequence[dict]): Sequence of transform object or + config dict to be composed. + dynamic_scale (tuple[int], optional): The image scale can be changed + dynamically. Default to None. It is deprecated. + skip_type_keys (list[str], optional): Sequence of type string to + be skip pipeline. Default to None. + max_refetch (int): The maximum number of retry iterations for getting + valid results from the pipeline. If the number of iterations is + greater than `max_refetch`, but results is still None, then the + iteration is terminated and raise the error. Default: 15. + """ + + def __init__(self, + dataset: Union[BaseDataset, dict], + pipeline: Sequence[str], + skip_type_keys: Union[Sequence[str], None] = None, + max_refetch: int = 15, + lazy_init: bool = False) -> None: + assert isinstance(pipeline, collections.abc.Sequence) + if skip_type_keys is not None: + assert all([ + isinstance(skip_type_key, str) + for skip_type_key in skip_type_keys + ]) + self._skip_type_keys = skip_type_keys + + self.pipeline = [] + self.pipeline_types = [] + for transform in pipeline: + if isinstance(transform, dict): + self.pipeline_types.append(transform['type']) + transform = TRANSFORMS.build(transform) + self.pipeline.append(transform) + else: + raise TypeError('pipeline must be a dict') + + self.dataset: BaseDataset + if isinstance(dataset, dict): + self.dataset = DATASETS.build(dataset) + elif isinstance(dataset, BaseDataset): + self.dataset = dataset + else: + raise TypeError( + 'elements in datasets sequence should be config or ' + f'`BaseDataset` instance, but got {type(dataset)}') + + self._metainfo = self.dataset.metainfo + if hasattr(self.dataset, 'flag'): + self.flag = self.dataset.flag + self.num_samples = len(self.dataset) + self.max_refetch = max_refetch + + self._fully_initialized = False + if not lazy_init: + self.full_init() + + @property + def metainfo(self) -> dict: + """Get the meta information of the multi-image-mixed dataset. + + Returns: + dict: The meta information of multi-image-mixed dataset. + """ + return copy.deepcopy(self._metainfo) + + def full_init(self): + """Loop to ``full_init`` each dataset.""" + if self._fully_initialized: + return + + self.dataset.full_init() + self._ori_len = len(self.dataset) + self._fully_initialized = True + + @force_full_init + def get_data_info(self, idx: int) -> dict: + """Get annotation by index. + + Args: + idx (int): Global index of ``ConcatDataset``. + + Returns: + dict: The idx-th annotation of the datasets. + """ + return self.dataset.get_data_info(idx) + + @force_full_init + def __len__(self): + return self.num_samples + + def __getitem__(self, idx): + results = copy.deepcopy(self.dataset[idx]) + for (transform, transform_type) in zip(self.pipeline, + self.pipeline_types): + if self._skip_type_keys is not None and \ + transform_type in self._skip_type_keys: + continue + + if hasattr(transform, 'get_indexes'): + for i in range(self.max_refetch): + # Make sure the results passed the loading pipeline + # of the original dataset is not None. + indexes = transform.get_indexes(self.dataset) + if not isinstance(indexes, collections.abc.Sequence): + indexes = [indexes] + mix_results = [ + copy.deepcopy(self.dataset[index]) for index in indexes + ] + if None not in mix_results: + results['mix_results'] = mix_results + break + else: + raise RuntimeError( + 'The loading pipeline of the original dataset' + ' always return None. Please check the correctness ' + 'of the dataset and its pipeline.') + + for i in range(self.max_refetch): + # To confirm the results passed the training pipeline + # of the wrapper is not None. + updated_results = transform(copy.deepcopy(results)) + if updated_results is not None: + results = updated_results + break + else: + raise RuntimeError( + 'The training pipeline of the dataset wrapper' + ' always return None.Please check the correctness ' + 'of the dataset and its pipeline.') + + if 'mix_results' in results: + results.pop('mix_results') + + return results + + def update_skip_type_keys(self, skip_type_keys): + """Update skip_type_keys. It is called by an external hook. + + Args: + skip_type_keys (list[str], optional): Sequence of type + string to be skip pipeline. + """ + assert all([ + isinstance(skip_type_key, str) for skip_type_key in skip_type_keys + ]) + self._skip_type_keys = skip_type_keys + + +@DATASETS.register_module() +class ConcatDataset(MMENGINE_ConcatDataset): + """A wrapper of concatenated dataset. + + Same as ``torch.utils.data.dataset.ConcatDataset``, support + lazy_init and get_dataset_source. + + Note: + ``ConcatDataset`` should not inherit from ``BaseDataset`` since + ``get_subset`` and ``get_subset_`` could produce ambiguous meaning + sub-dataset which conflicts with original dataset. If you want to use + a sub-dataset of ``ConcatDataset``, you should set ``indices`` + arguments for wrapped dataset which inherit from ``BaseDataset``. + + Args: + datasets (Sequence[BaseDataset] or Sequence[dict]): A list of datasets + which will be concatenated. + lazy_init (bool, optional): Whether to load annotation during + instantiation. Defaults to False. + ignore_keys (List[str] or str): Ignore the keys that can be + unequal in `dataset.metainfo`. Defaults to None. + `New in version 0.3.0.` + """ + + def __init__(self, + datasets: Sequence[Union[BaseDataset, dict]], + lazy_init: bool = False, + ignore_keys: Union[str, List[str], None] = None): + self.datasets: List[BaseDataset] = [] + for i, dataset in enumerate(datasets): + if isinstance(dataset, dict): + self.datasets.append(DATASETS.build(dataset)) + elif isinstance(dataset, BaseDataset): + self.datasets.append(dataset) + else: + raise TypeError( + 'elements in datasets sequence should be config or ' + f'`BaseDataset` instance, but got {type(dataset)}') + if ignore_keys is None: + self.ignore_keys = [] + elif isinstance(ignore_keys, str): + self.ignore_keys = [ignore_keys] + elif isinstance(ignore_keys, list): + self.ignore_keys = ignore_keys + else: + raise TypeError('ignore_keys should be a list or str, ' + f'but got {type(ignore_keys)}') + + meta_keys: set = set() + for dataset in self.datasets: + meta_keys |= dataset.metainfo.keys() + # if the metainfo of multiple datasets are the same, use metainfo + # of the first dataset, else the metainfo is a list with metainfo + # of all the datasets + is_all_same = True + self._metainfo_first = self.datasets[0].metainfo + for i, dataset in enumerate(self.datasets, 1): + for key in meta_keys: + if key in self.ignore_keys: + continue + if key not in dataset.metainfo: + is_all_same = False + break + if self._metainfo_first[key] != dataset.metainfo[key]: + is_all_same = False + break + + if is_all_same: + self._metainfo = self.datasets[0].metainfo + else: + self._metainfo = [dataset.metainfo for dataset in self.datasets] + + self._fully_initialized = False + if not lazy_init: + self.full_init() + + if is_all_same: + self._metainfo.update( + dict(cumulative_sizes=self.cumulative_sizes)) + else: + for i, dataset in enumerate(self.datasets): + self._metainfo[i].update( + dict(cumulative_sizes=self.cumulative_sizes)) + + def get_dataset_source(self, idx: int) -> int: + dataset_idx, _ = self._get_ori_dataset_idx(idx) + return dataset_idx diff --git a/mmdet_code/mmdetection/mmdet/datasets/deepfashion.py b/mmdet_code/mmdetection/mmdet/datasets/deepfashion.py new file mode 100644 index 0000000000000000000000000000000000000000..f853fc63398d598b90a88323e660ba6f4d81e2df --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/deepfashion.py @@ -0,0 +1,19 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class DeepFashionDataset(CocoDataset): + """Dataset for DeepFashion.""" + + METAINFO = { + 'classes': ('top', 'skirt', 'leggings', 'dress', 'outer', 'pants', + 'bag', 'neckwear', 'headwear', 'eyeglass', 'belt', + 'footwear', 'hair', 'skin', 'face'), + # palette is a list of color tuples, which is used for visualization. + 'palette': [(0, 192, 64), (0, 64, 96), (128, 192, 192), (0, 64, 64), + (0, 192, 224), (0, 192, 192), (128, 192, 64), (0, 192, 96), + (128, 32, 192), (0, 0, 224), (0, 0, 64), (0, 160, 192), + (128, 0, 96), (128, 0, 192), (0, 32, 192)] + } diff --git a/mmdet_code/mmdetection/mmdet/datasets/dod.py b/mmdet_code/mmdetection/mmdet/datasets/dod.py new file mode 100644 index 0000000000000000000000000000000000000000..152d32aaf70c7fb5e3730d46d26e150fc1204f22 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/dod.py @@ -0,0 +1,78 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List, Optional + +import numpy as np + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + +try: + from d_cube import D3 +except ImportError: + D3 = None +from .api_wrappers import COCO + + +@DATASETS.register_module() +class DODDataset(BaseDetDataset): + + def __init__(self, + *args, + data_root: Optional[str] = '', + data_prefix: dict = dict(img_path=''), + **kwargs) -> None: + if D3 is None: + raise ImportError( + 'Please install d3 by `pip install ddd-dataset`.') + pkl_anno_path = osp.join(data_root, data_prefix['anno']) + self.img_root = osp.join(data_root, data_prefix['img']) + self.d3 = D3(self.img_root, pkl_anno_path) + + sent_infos = self.d3.load_sents() + classes = tuple([sent_info['raw_sent'] for sent_info in sent_infos]) + super().__init__( + *args, + data_root=data_root, + data_prefix=data_prefix, + metainfo={'classes': classes}, + **kwargs) + + def load_data_list(self) -> List[dict]: + coco = COCO(self.ann_file) + data_list = [] + img_ids = self.d3.get_img_ids() + for img_id in img_ids: + data_info = {} + + img_info = self.d3.load_imgs(img_id)[0] + file_name = img_info['file_name'] + img_path = osp.join(self.img_root, file_name) + data_info['img_path'] = img_path + data_info['img_id'] = img_id + data_info['height'] = img_info['height'] + data_info['width'] = img_info['width'] + + group_ids = self.d3.get_group_ids(img_ids=[img_id]) + sent_ids = self.d3.get_sent_ids(group_ids=group_ids) + sent_list = self.d3.load_sents(sent_ids=sent_ids) + text_list = [sent['raw_sent'] for sent in sent_list] + ann_ids = coco.get_ann_ids(img_ids=[img_id]) + anno = coco.load_anns(ann_ids) + + data_info['text'] = text_list + data_info['sent_ids'] = np.array([s for s in sent_ids]) + data_info['custom_entities'] = True + + instances = [] + for i, ann in enumerate(anno): + instance = {} + x1, y1, w, h = ann['bbox'] + bbox = [x1, y1, x1 + w, y1 + h] + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = ann['category_id'] - 1 + instances.append(instance) + data_info['instances'] = instances + data_list.append(data_info) + return data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/dsdl.py b/mmdet_code/mmdetection/mmdet/datasets/dsdl.py new file mode 100644 index 0000000000000000000000000000000000000000..75570a2a6396e0e7a4ce5cac5dbf2a23cd164629 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/dsdl.py @@ -0,0 +1,192 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +from typing import List + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + +try: + from dsdl.dataset import DSDLDataset +except ImportError: + DSDLDataset = None + + +@DATASETS.register_module() +class DSDLDetDataset(BaseDetDataset): + """Dataset for dsdl detection. + + Args: + with_bbox(bool): Load bbox or not, defaults to be True. + with_polygon(bool): Load polygon or not, defaults to be False. + with_mask(bool): Load seg map mask or not, defaults to be False. + with_imagelevel_label(bool): Load image level label or not, + defaults to be False. + with_hierarchy(bool): Load hierarchy information or not, + defaults to be False. + specific_key_path(dict): Path of specific key which can not + be loaded by it's field name. + pre_transform(dict): pre-transform functions before loading. + """ + + METAINFO = {} + + def __init__(self, + with_bbox: bool = True, + with_polygon: bool = False, + with_mask: bool = False, + with_imagelevel_label: bool = False, + with_hierarchy: bool = False, + specific_key_path: dict = {}, + pre_transform: dict = {}, + **kwargs) -> None: + + if DSDLDataset is None: + raise RuntimeError( + 'Package dsdl is not installed. Please run "pip install dsdl".' + ) + + self.with_hierarchy = with_hierarchy + self.specific_key_path = specific_key_path + + loc_config = dict(type='LocalFileReader', working_dir='') + if kwargs.get('data_root'): + kwargs['ann_file'] = os.path.join(kwargs['data_root'], + kwargs['ann_file']) + self.required_fields = ['Image', 'ImageShape', 'Label', 'ignore_flag'] + if with_bbox: + self.required_fields.append('Bbox') + if with_polygon: + self.required_fields.append('Polygon') + if with_mask: + self.required_fields.append('LabelMap') + if with_imagelevel_label: + self.required_fields.append('image_level_labels') + assert 'image_level_labels' in specific_key_path.keys( + ), '`image_level_labels` not specified in `specific_key_path` !' + + self.extra_keys = [ + key for key in self.specific_key_path.keys() + if key not in self.required_fields + ] + + self.dsdldataset = DSDLDataset( + dsdl_yaml=kwargs['ann_file'], + location_config=loc_config, + required_fields=self.required_fields, + specific_key_path=specific_key_path, + transform=pre_transform, + ) + + BaseDetDataset.__init__(self, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load data info from an dsdl yaml file named as ``self.ann_file`` + + Returns: + List[dict]: A list of data info. + """ + if self.with_hierarchy: + # get classes_names and relation_matrix + classes_names, relation_matrix = \ + self.dsdldataset.class_dom.get_hierarchy_info() + self._metainfo['classes'] = tuple(classes_names) + self._metainfo['RELATION_MATRIX'] = relation_matrix + + else: + self._metainfo['classes'] = tuple(self.dsdldataset.class_names) + + data_list = [] + + for i, data in enumerate(self.dsdldataset): + # basic image info, including image id, path and size. + datainfo = dict( + img_id=i, + img_path=os.path.join(self.data_prefix['img_path'], + data['Image'][0].location), + width=data['ImageShape'][0].width, + height=data['ImageShape'][0].height, + ) + + # get image label info + if 'image_level_labels' in data.keys(): + if self.with_hierarchy: + # get leaf node name when using hierarchy classes + datainfo['image_level_labels'] = [ + self._metainfo['classes'].index(i.leaf_node_name) + for i in data['image_level_labels'] + ] + else: + datainfo['image_level_labels'] = [ + self._metainfo['classes'].index(i.name) + for i in data['image_level_labels'] + ] + + # get semantic segmentation info + if 'LabelMap' in data.keys(): + datainfo['seg_map_path'] = data['LabelMap'] + + # load instance info + instances = [] + if 'Bbox' in data.keys(): + for idx in range(len(data['Bbox'])): + bbox = data['Bbox'][idx] + if self.with_hierarchy: + # get leaf node name when using hierarchy classes + label = data['Label'][idx].leaf_node_name + label_index = self._metainfo['classes'].index(label) + else: + label = data['Label'][idx].name + label_index = self._metainfo['classes'].index(label) + + instance = {} + instance['bbox'] = bbox.xyxy + instance['bbox_label'] = label_index + + if 'ignore_flag' in data.keys(): + # get ignore flag + instance['ignore_flag'] = data['ignore_flag'][idx] + else: + instance['ignore_flag'] = 0 + + if 'Polygon' in data.keys(): + # get polygon info + polygon = data['Polygon'][idx] + instance['mask'] = polygon.openmmlabformat + + for key in self.extra_keys: + # load extra instance info + instance[key] = data[key][idx] + + instances.append(instance) + + datainfo['instances'] = instances + # append a standard sample in data list + if len(datainfo['instances']) > 0: + data_list.append(datainfo) + + return data_list + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) \ + if self.filter_cfg is not None else False + min_size = self.filter_cfg.get('min_size', 0) \ + if self.filter_cfg is not None else 0 + + valid_data_list = [] + for i, data_info in enumerate(self.data_list): + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and len(data_info['instances']) == 0: + continue + if min(width, height) >= min_size: + valid_data_list.append(data_info) + + return valid_data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/flickr30k.py b/mmdet_code/mmdetection/mmdet/datasets/flickr30k.py new file mode 100644 index 0000000000000000000000000000000000000000..0c76a41bc965bb0e8348c3d13e77d5c6e8ca08ce --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/flickr30k.py @@ -0,0 +1,81 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List + +from pycocotools.coco import COCO + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + + +def convert_phrase_ids(phrase_ids: list) -> list: + unique_elements = sorted(set(phrase_ids)) + element_to_new_label = { + element: label + for label, element in enumerate(unique_elements) + } + phrase_ids = [element_to_new_label[element] for element in phrase_ids] + return phrase_ids + + +@DATASETS.register_module() +class Flickr30kDataset(BaseDetDataset): + """Flickr30K Dataset.""" + + def load_data_list(self) -> List[dict]: + + self.coco = COCO(self.ann_file) + + self.ids = sorted(list(self.coco.imgs.keys())) + + data_list = [] + for img_id in self.ids: + if isinstance(img_id, str): + ann_ids = self.coco.getAnnIds(imgIds=[img_id], iscrowd=None) + else: + ann_ids = self.coco.getAnnIds(imgIds=img_id, iscrowd=None) + + coco_img = self.coco.loadImgs(img_id)[0] + + caption = coco_img['caption'] + file_name = coco_img['file_name'] + img_path = osp.join(self.data_prefix['img'], file_name) + width = coco_img['width'] + height = coco_img['height'] + tokens_positive = coco_img['tokens_positive_eval'] + phrases = [caption[i[0][0]:i[0][1]] for i in tokens_positive] + phrase_ids = [] + + instances = [] + annos = self.coco.loadAnns(ann_ids) + for anno in annos: + instance = { + 'bbox': [ + anno['bbox'][0], anno['bbox'][1], + anno['bbox'][0] + anno['bbox'][2], + anno['bbox'][1] + anno['bbox'][3] + ], + 'bbox_label': + anno['category_id'], + 'ignore_flag': + anno['iscrowd'] + } + phrase_ids.append(anno['phrase_ids']) + instances.append(instance) + + phrase_ids = convert_phrase_ids(phrase_ids) + + data_list.append( + dict( + img_path=img_path, + img_id=img_id, + height=height, + width=width, + instances=instances, + text=caption, + phrase_ids=phrase_ids, + tokens_positive=tokens_positive, + phrases=phrases, + )) + + return data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/isaid.py b/mmdet_code/mmdetection/mmdet/datasets/isaid.py new file mode 100644 index 0000000000000000000000000000000000000000..87067d8459c4dd6e80e5f808f613e0bd600b5f2f --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/isaid.py @@ -0,0 +1,25 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class iSAIDDataset(CocoDataset): + """Dataset for iSAID instance segmentation. + + iSAID: A Large-scale Dataset for Instance Segmentation + in Aerial Images. + + For more detail, please refer to "projects/iSAID/README.md" + """ + + METAINFO = dict( + classes=('background', 'ship', 'store_tank', 'baseball_diamond', + 'tennis_court', 'basketball_court', 'Ground_Track_Field', + 'Bridge', 'Large_Vehicle', 'Small_Vehicle', 'Helicopter', + 'Swimming_pool', 'Roundabout', 'Soccer_ball_field', 'plane', + 'Harbor'), + palette=[(0, 0, 0), (0, 0, 63), (0, 63, 63), (0, 63, 0), (0, 63, 127), + (0, 63, 191), (0, 63, 255), (0, 127, 63), (0, 127, 127), + (0, 0, 127), (0, 0, 191), (0, 0, 255), (0, 191, 127), + (0, 127, 191), (0, 127, 255), (0, 100, 155)]) diff --git a/mmdet_code/mmdetection/mmdet/datasets/lvis.py b/mmdet_code/mmdetection/mmdet/datasets/lvis.py new file mode 100644 index 0000000000000000000000000000000000000000..b9629f5d463da183f0b4ab4c5d0f7ff7b07e4348 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/lvis.py @@ -0,0 +1,638 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import warnings +from typing import List + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class LVISV05Dataset(CocoDataset): + """LVIS v0.5 dataset for detection.""" + + METAINFO = { + 'classes': + ('acorn', 'aerosol_can', 'air_conditioner', 'airplane', 'alarm_clock', + 'alcohol', 'alligator', 'almond', 'ambulance', 'amplifier', 'anklet', + 'antenna', 'apple', 'apple_juice', 'applesauce', 'apricot', 'apron', + 'aquarium', 'armband', 'armchair', 'armoire', 'armor', 'artichoke', + 'trash_can', 'ashtray', 'asparagus', 'atomizer', 'avocado', 'award', + 'awning', 'ax', 'baby_buggy', 'basketball_backboard', 'backpack', + 'handbag', 'suitcase', 'bagel', 'bagpipe', 'baguet', 'bait', 'ball', + 'ballet_skirt', 'balloon', 'bamboo', 'banana', 'Band_Aid', 'bandage', + 'bandanna', 'banjo', 'banner', 'barbell', 'barge', 'barrel', + 'barrette', 'barrow', 'baseball_base', 'baseball', 'baseball_bat', + 'baseball_cap', 'baseball_glove', 'basket', 'basketball_hoop', + 'basketball', 'bass_horn', 'bat_(animal)', 'bath_mat', 'bath_towel', + 'bathrobe', 'bathtub', 'batter_(food)', 'battery', 'beachball', + 'bead', 'beaker', 'bean_curd', 'beanbag', 'beanie', 'bear', 'bed', + 'bedspread', 'cow', 'beef_(food)', 'beeper', 'beer_bottle', + 'beer_can', 'beetle', 'bell', 'bell_pepper', 'belt', 'belt_buckle', + 'bench', 'beret', 'bib', 'Bible', 'bicycle', 'visor', 'binder', + 'binoculars', 'bird', 'birdfeeder', 'birdbath', 'birdcage', + 'birdhouse', 'birthday_cake', 'birthday_card', 'biscuit_(bread)', + 'pirate_flag', 'black_sheep', 'blackboard', 'blanket', 'blazer', + 'blender', 'blimp', 'blinker', 'blueberry', 'boar', 'gameboard', + 'boat', 'bobbin', 'bobby_pin', 'boiled_egg', 'bolo_tie', 'deadbolt', + 'bolt', 'bonnet', 'book', 'book_bag', 'bookcase', 'booklet', + 'bookmark', 'boom_microphone', 'boot', 'bottle', 'bottle_opener', + 'bouquet', 'bow_(weapon)', 'bow_(decorative_ribbons)', 'bow-tie', + 'bowl', 'pipe_bowl', 'bowler_hat', 'bowling_ball', 'bowling_pin', + 'boxing_glove', 'suspenders', 'bracelet', 'brass_plaque', 'brassiere', + 'bread-bin', 'breechcloth', 'bridal_gown', 'briefcase', + 'bristle_brush', 'broccoli', 'broach', 'broom', 'brownie', + 'brussels_sprouts', 'bubble_gum', 'bucket', 'horse_buggy', 'bull', + 'bulldog', 'bulldozer', 'bullet_train', 'bulletin_board', + 'bulletproof_vest', 'bullhorn', 'corned_beef', 'bun', 'bunk_bed', + 'buoy', 'burrito', 'bus_(vehicle)', 'business_card', 'butcher_knife', + 'butter', 'butterfly', 'button', 'cab_(taxi)', 'cabana', 'cabin_car', + 'cabinet', 'locker', 'cake', 'calculator', 'calendar', 'calf', + 'camcorder', 'camel', 'camera', 'camera_lens', 'camper_(vehicle)', + 'can', 'can_opener', 'candelabrum', 'candle', 'candle_holder', + 'candy_bar', 'candy_cane', 'walking_cane', 'canister', 'cannon', + 'canoe', 'cantaloup', 'canteen', 'cap_(headwear)', 'bottle_cap', + 'cape', 'cappuccino', 'car_(automobile)', 'railcar_(part_of_a_train)', + 'elevator_car', 'car_battery', 'identity_card', 'card', 'cardigan', + 'cargo_ship', 'carnation', 'horse_carriage', 'carrot', 'tote_bag', + 'cart', 'carton', 'cash_register', 'casserole', 'cassette', 'cast', + 'cat', 'cauliflower', 'caviar', 'cayenne_(spice)', 'CD_player', + 'celery', 'cellular_telephone', 'chain_mail', 'chair', + 'chaise_longue', 'champagne', 'chandelier', 'chap', 'checkbook', + 'checkerboard', 'cherry', 'chessboard', + 'chest_of_drawers_(furniture)', 'chicken_(animal)', 'chicken_wire', + 'chickpea', 'Chihuahua', 'chili_(vegetable)', 'chime', 'chinaware', + 'crisp_(potato_chip)', 'poker_chip', 'chocolate_bar', + 'chocolate_cake', 'chocolate_milk', 'chocolate_mousse', 'choker', + 'chopping_board', 'chopstick', 'Christmas_tree', 'slide', 'cider', + 'cigar_box', 'cigarette', 'cigarette_case', 'cistern', 'clarinet', + 'clasp', 'cleansing_agent', 'clementine', 'clip', 'clipboard', + 'clock', 'clock_tower', 'clothes_hamper', 'clothespin', 'clutch_bag', + 'coaster', 'coat', 'coat_hanger', 'coatrack', 'cock', 'coconut', + 'coffee_filter', 'coffee_maker', 'coffee_table', 'coffeepot', 'coil', + 'coin', 'colander', 'coleslaw', 'coloring_material', + 'combination_lock', 'pacifier', 'comic_book', 'computer_keyboard', + 'concrete_mixer', 'cone', 'control', 'convertible_(automobile)', + 'sofa_bed', 'cookie', 'cookie_jar', 'cooking_utensil', + 'cooler_(for_food)', 'cork_(bottle_plug)', 'corkboard', 'corkscrew', + 'edible_corn', 'cornbread', 'cornet', 'cornice', 'cornmeal', 'corset', + 'romaine_lettuce', 'costume', 'cougar', 'coverall', 'cowbell', + 'cowboy_hat', 'crab_(animal)', 'cracker', 'crape', 'crate', 'crayon', + 'cream_pitcher', 'credit_card', 'crescent_roll', 'crib', 'crock_pot', + 'crossbar', 'crouton', 'crow', 'crown', 'crucifix', 'cruise_ship', + 'police_cruiser', 'crumb', 'crutch', 'cub_(animal)', 'cube', + 'cucumber', 'cufflink', 'cup', 'trophy_cup', 'cupcake', 'hair_curler', + 'curling_iron', 'curtain', 'cushion', 'custard', 'cutting_tool', + 'cylinder', 'cymbal', 'dachshund', 'dagger', 'dartboard', + 'date_(fruit)', 'deck_chair', 'deer', 'dental_floss', 'desk', + 'detergent', 'diaper', 'diary', 'die', 'dinghy', 'dining_table', + 'tux', 'dish', 'dish_antenna', 'dishrag', 'dishtowel', 'dishwasher', + 'dishwasher_detergent', 'diskette', 'dispenser', 'Dixie_cup', 'dog', + 'dog_collar', 'doll', 'dollar', 'dolphin', 'domestic_ass', 'eye_mask', + 'doorbell', 'doorknob', 'doormat', 'doughnut', 'dove', 'dragonfly', + 'drawer', 'underdrawers', 'dress', 'dress_hat', 'dress_suit', + 'dresser', 'drill', 'drinking_fountain', 'drone', 'dropper', + 'drum_(musical_instrument)', 'drumstick', 'duck', 'duckling', + 'duct_tape', 'duffel_bag', 'dumbbell', 'dumpster', 'dustpan', + 'Dutch_oven', 'eagle', 'earphone', 'earplug', 'earring', 'easel', + 'eclair', 'eel', 'egg', 'egg_roll', 'egg_yolk', 'eggbeater', + 'eggplant', 'electric_chair', 'refrigerator', 'elephant', 'elk', + 'envelope', 'eraser', 'escargot', 'eyepatch', 'falcon', 'fan', + 'faucet', 'fedora', 'ferret', 'Ferris_wheel', 'ferry', 'fig_(fruit)', + 'fighter_jet', 'figurine', 'file_cabinet', 'file_(tool)', + 'fire_alarm', 'fire_engine', 'fire_extinguisher', 'fire_hose', + 'fireplace', 'fireplug', 'fish', 'fish_(food)', 'fishbowl', + 'fishing_boat', 'fishing_rod', 'flag', 'flagpole', 'flamingo', + 'flannel', 'flash', 'flashlight', 'fleece', 'flip-flop_(sandal)', + 'flipper_(footwear)', 'flower_arrangement', 'flute_glass', 'foal', + 'folding_chair', 'food_processor', 'football_(American)', + 'football_helmet', 'footstool', 'fork', 'forklift', 'freight_car', + 'French_toast', 'freshener', 'frisbee', 'frog', 'fruit_juice', + 'fruit_salad', 'frying_pan', 'fudge', 'funnel', 'futon', 'gag', + 'garbage', 'garbage_truck', 'garden_hose', 'gargle', 'gargoyle', + 'garlic', 'gasmask', 'gazelle', 'gelatin', 'gemstone', 'giant_panda', + 'gift_wrap', 'ginger', 'giraffe', 'cincture', + 'glass_(drink_container)', 'globe', 'glove', 'goat', 'goggles', + 'goldfish', 'golf_club', 'golfcart', 'gondola_(boat)', 'goose', + 'gorilla', 'gourd', 'surgical_gown', 'grape', 'grasshopper', 'grater', + 'gravestone', 'gravy_boat', 'green_bean', 'green_onion', 'griddle', + 'grillroom', 'grinder_(tool)', 'grits', 'grizzly', 'grocery_bag', + 'guacamole', 'guitar', 'gull', 'gun', 'hair_spray', 'hairbrush', + 'hairnet', 'hairpin', 'ham', 'hamburger', 'hammer', 'hammock', + 'hamper', 'hamster', 'hair_dryer', 'hand_glass', 'hand_towel', + 'handcart', 'handcuff', 'handkerchief', 'handle', 'handsaw', + 'hardback_book', 'harmonium', 'hat', 'hatbox', 'hatch', 'veil', + 'headband', 'headboard', 'headlight', 'headscarf', 'headset', + 'headstall_(for_horses)', 'hearing_aid', 'heart', 'heater', + 'helicopter', 'helmet', 'heron', 'highchair', 'hinge', 'hippopotamus', + 'hockey_stick', 'hog', 'home_plate_(baseball)', 'honey', 'fume_hood', + 'hook', 'horse', 'hose', 'hot-air_balloon', 'hotplate', 'hot_sauce', + 'hourglass', 'houseboat', 'hummingbird', 'hummus', 'polar_bear', + 'icecream', 'popsicle', 'ice_maker', 'ice_pack', 'ice_skate', + 'ice_tea', 'igniter', 'incense', 'inhaler', 'iPod', + 'iron_(for_clothing)', 'ironing_board', 'jacket', 'jam', 'jean', + 'jeep', 'jelly_bean', 'jersey', 'jet_plane', 'jewelry', 'joystick', + 'jumpsuit', 'kayak', 'keg', 'kennel', 'kettle', 'key', 'keycard', + 'kilt', 'kimono', 'kitchen_sink', 'kitchen_table', 'kite', 'kitten', + 'kiwi_fruit', 'knee_pad', 'knife', 'knight_(chess_piece)', + 'knitting_needle', 'knob', 'knocker_(on_a_door)', 'koala', 'lab_coat', + 'ladder', 'ladle', 'ladybug', 'lamb_(animal)', 'lamb-chop', 'lamp', + 'lamppost', 'lampshade', 'lantern', 'lanyard', 'laptop_computer', + 'lasagna', 'latch', 'lawn_mower', 'leather', 'legging_(clothing)', + 'Lego', 'lemon', 'lemonade', 'lettuce', 'license_plate', 'life_buoy', + 'life_jacket', 'lightbulb', 'lightning_rod', 'lime', 'limousine', + 'linen_paper', 'lion', 'lip_balm', 'lipstick', 'liquor', 'lizard', + 'Loafer_(type_of_shoe)', 'log', 'lollipop', 'lotion', + 'speaker_(stereo_equipment)', 'loveseat', 'machine_gun', 'magazine', + 'magnet', 'mail_slot', 'mailbox_(at_home)', 'mallet', 'mammoth', + 'mandarin_orange', 'manger', 'manhole', 'map', 'marker', 'martini', + 'mascot', 'mashed_potato', 'masher', 'mask', 'mast', + 'mat_(gym_equipment)', 'matchbox', 'mattress', 'measuring_cup', + 'measuring_stick', 'meatball', 'medicine', 'melon', 'microphone', + 'microscope', 'microwave_oven', 'milestone', 'milk', 'minivan', + 'mint_candy', 'mirror', 'mitten', 'mixer_(kitchen_tool)', 'money', + 'monitor_(computer_equipment) computer_monitor', 'monkey', 'motor', + 'motor_scooter', 'motor_vehicle', 'motorboat', 'motorcycle', + 'mound_(baseball)', 'mouse_(animal_rodent)', + 'mouse_(computer_equipment)', 'mousepad', 'muffin', 'mug', 'mushroom', + 'music_stool', 'musical_instrument', 'nailfile', 'nameplate', + 'napkin', 'neckerchief', 'necklace', 'necktie', 'needle', 'nest', + 'newsstand', 'nightshirt', 'nosebag_(for_animals)', + 'noseband_(for_animals)', 'notebook', 'notepad', 'nut', 'nutcracker', + 'oar', 'octopus_(food)', 'octopus_(animal)', 'oil_lamp', 'olive_oil', + 'omelet', 'onion', 'orange_(fruit)', 'orange_juice', 'oregano', + 'ostrich', 'ottoman', 'overalls_(clothing)', 'owl', 'packet', + 'inkpad', 'pad', 'paddle', 'padlock', 'paintbox', 'paintbrush', + 'painting', 'pajamas', 'palette', 'pan_(for_cooking)', + 'pan_(metal_container)', 'pancake', 'pantyhose', 'papaya', + 'paperclip', 'paper_plate', 'paper_towel', 'paperback_book', + 'paperweight', 'parachute', 'parakeet', 'parasail_(sports)', + 'parchment', 'parka', 'parking_meter', 'parrot', + 'passenger_car_(part_of_a_train)', 'passenger_ship', 'passport', + 'pastry', 'patty_(food)', 'pea_(food)', 'peach', 'peanut_butter', + 'pear', 'peeler_(tool_for_fruit_and_vegetables)', 'pegboard', + 'pelican', 'pen', 'pencil', 'pencil_box', 'pencil_sharpener', + 'pendulum', 'penguin', 'pennant', 'penny_(coin)', 'pepper', + 'pepper_mill', 'perfume', 'persimmon', 'baby', 'pet', 'petfood', + 'pew_(church_bench)', 'phonebook', 'phonograph_record', 'piano', + 'pickle', 'pickup_truck', 'pie', 'pigeon', 'piggy_bank', 'pillow', + 'pin_(non_jewelry)', 'pineapple', 'pinecone', 'ping-pong_ball', + 'pinwheel', 'tobacco_pipe', 'pipe', 'pistol', 'pita_(bread)', + 'pitcher_(vessel_for_liquid)', 'pitchfork', 'pizza', 'place_mat', + 'plate', 'platter', 'playing_card', 'playpen', 'pliers', + 'plow_(farm_equipment)', 'pocket_watch', 'pocketknife', + 'poker_(fire_stirring_tool)', 'pole', 'police_van', 'polo_shirt', + 'poncho', 'pony', 'pool_table', 'pop_(soda)', 'portrait', + 'postbox_(public)', 'postcard', 'poster', 'pot', 'flowerpot', + 'potato', 'potholder', 'pottery', 'pouch', 'power_shovel', 'prawn', + 'printer', 'projectile_(weapon)', 'projector', 'propeller', 'prune', + 'pudding', 'puffer_(fish)', 'puffin', 'pug-dog', 'pumpkin', 'puncher', + 'puppet', 'puppy', 'quesadilla', 'quiche', 'quilt', 'rabbit', + 'race_car', 'racket', 'radar', 'radiator', 'radio_receiver', 'radish', + 'raft', 'rag_doll', 'raincoat', 'ram_(animal)', 'raspberry', 'rat', + 'razorblade', 'reamer_(juicer)', 'rearview_mirror', 'receipt', + 'recliner', 'record_player', 'red_cabbage', 'reflector', + 'remote_control', 'rhinoceros', 'rib_(food)', 'rifle', 'ring', + 'river_boat', 'road_map', 'robe', 'rocking_chair', 'roller_skate', + 'Rollerblade', 'rolling_pin', 'root_beer', + 'router_(computer_equipment)', 'rubber_band', 'runner_(carpet)', + 'plastic_bag', 'saddle_(on_an_animal)', 'saddle_blanket', 'saddlebag', + 'safety_pin', 'sail', 'salad', 'salad_plate', 'salami', + 'salmon_(fish)', 'salmon_(food)', 'salsa', 'saltshaker', + 'sandal_(type_of_shoe)', 'sandwich', 'satchel', 'saucepan', 'saucer', + 'sausage', 'sawhorse', 'saxophone', 'scale_(measuring_instrument)', + 'scarecrow', 'scarf', 'school_bus', 'scissors', 'scoreboard', + 'scrambled_eggs', 'scraper', 'scratcher', 'screwdriver', + 'scrubbing_brush', 'sculpture', 'seabird', 'seahorse', 'seaplane', + 'seashell', 'seedling', 'serving_dish', 'sewing_machine', 'shaker', + 'shampoo', 'shark', 'sharpener', 'Sharpie', 'shaver_(electric)', + 'shaving_cream', 'shawl', 'shears', 'sheep', 'shepherd_dog', + 'sherbert', 'shield', 'shirt', 'shoe', 'shopping_bag', + 'shopping_cart', 'short_pants', 'shot_glass', 'shoulder_bag', + 'shovel', 'shower_head', 'shower_curtain', 'shredder_(for_paper)', + 'sieve', 'signboard', 'silo', 'sink', 'skateboard', 'skewer', 'ski', + 'ski_boot', 'ski_parka', 'ski_pole', 'skirt', 'sled', 'sleeping_bag', + 'sling_(bandage)', 'slipper_(footwear)', 'smoothie', 'snake', + 'snowboard', 'snowman', 'snowmobile', 'soap', 'soccer_ball', 'sock', + 'soda_fountain', 'carbonated_water', 'sofa', 'softball', + 'solar_array', 'sombrero', 'soup', 'soup_bowl', 'soupspoon', + 'sour_cream', 'soya_milk', 'space_shuttle', 'sparkler_(fireworks)', + 'spatula', 'spear', 'spectacles', 'spice_rack', 'spider', 'sponge', + 'spoon', 'sportswear', 'spotlight', 'squirrel', + 'stapler_(stapling_machine)', 'starfish', 'statue_(sculpture)', + 'steak_(food)', 'steak_knife', 'steamer_(kitchen_appliance)', + 'steering_wheel', 'stencil', 'stepladder', 'step_stool', + 'stereo_(sound_system)', 'stew', 'stirrer', 'stirrup', + 'stockings_(leg_wear)', 'stool', 'stop_sign', 'brake_light', 'stove', + 'strainer', 'strap', 'straw_(for_drinking)', 'strawberry', + 'street_sign', 'streetlight', 'string_cheese', 'stylus', 'subwoofer', + 'sugar_bowl', 'sugarcane_(plant)', 'suit_(clothing)', 'sunflower', + 'sunglasses', 'sunhat', 'sunscreen', 'surfboard', 'sushi', 'mop', + 'sweat_pants', 'sweatband', 'sweater', 'sweatshirt', 'sweet_potato', + 'swimsuit', 'sword', 'syringe', 'Tabasco_sauce', 'table-tennis_table', + 'table', 'table_lamp', 'tablecloth', 'tachometer', 'taco', 'tag', + 'taillight', 'tambourine', 'army_tank', 'tank_(storage_vessel)', + 'tank_top_(clothing)', 'tape_(sticky_cloth_or_paper)', 'tape_measure', + 'tapestry', 'tarp', 'tartan', 'tassel', 'tea_bag', 'teacup', + 'teakettle', 'teapot', 'teddy_bear', 'telephone', 'telephone_booth', + 'telephone_pole', 'telephoto_lens', 'television_camera', + 'television_set', 'tennis_ball', 'tennis_racket', 'tequila', + 'thermometer', 'thermos_bottle', 'thermostat', 'thimble', 'thread', + 'thumbtack', 'tiara', 'tiger', 'tights_(clothing)', 'timer', + 'tinfoil', 'tinsel', 'tissue_paper', 'toast_(food)', 'toaster', + 'toaster_oven', 'toilet', 'toilet_tissue', 'tomato', 'tongs', + 'toolbox', 'toothbrush', 'toothpaste', 'toothpick', 'cover', + 'tortilla', 'tow_truck', 'towel', 'towel_rack', 'toy', + 'tractor_(farm_equipment)', 'traffic_light', 'dirt_bike', + 'trailer_truck', 'train_(railroad_vehicle)', 'trampoline', 'tray', + 'tree_house', 'trench_coat', 'triangle_(musical_instrument)', + 'tricycle', 'tripod', 'trousers', 'truck', 'truffle_(chocolate)', + 'trunk', 'vat', 'turban', 'turkey_(bird)', 'turkey_(food)', 'turnip', + 'turtle', 'turtleneck_(clothing)', 'typewriter', 'umbrella', + 'underwear', 'unicycle', 'urinal', 'urn', 'vacuum_cleaner', 'valve', + 'vase', 'vending_machine', 'vent', 'videotape', 'vinegar', 'violin', + 'vodka', 'volleyball', 'vulture', 'waffle', 'waffle_iron', 'wagon', + 'wagon_wheel', 'walking_stick', 'wall_clock', 'wall_socket', 'wallet', + 'walrus', 'wardrobe', 'wasabi', 'automatic_washer', 'watch', + 'water_bottle', 'water_cooler', 'water_faucet', 'water_filter', + 'water_heater', 'water_jug', 'water_gun', 'water_scooter', + 'water_ski', 'water_tower', 'watering_can', 'watermelon', + 'weathervane', 'webcam', 'wedding_cake', 'wedding_ring', 'wet_suit', + 'wheel', 'wheelchair', 'whipped_cream', 'whiskey', 'whistle', 'wick', + 'wig', 'wind_chime', 'windmill', 'window_box_(for_plants)', + 'windshield_wiper', 'windsock', 'wine_bottle', 'wine_bucket', + 'wineglass', 'wing_chair', 'blinder_(for_horses)', 'wok', 'wolf', + 'wooden_spoon', 'wreath', 'wrench', 'wristband', 'wristlet', 'yacht', + 'yak', 'yogurt', 'yoke_(animal_equipment)', 'zebra', 'zucchini'), + 'palette': + None + } + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + try: + import lvis + if getattr(lvis, '__version__', '0') >= '10.5.3': + warnings.warn( + 'mmlvis is deprecated, please install official lvis-api by "pip install git+https://github.com/lvis-dataset/lvis-api.git"', # noqa: E501 + UserWarning) + from lvis import LVIS + except ImportError: + raise ImportError( + 'Package lvis is not installed. Please run "pip install git+https://github.com/lvis-dataset/lvis-api.git".' # noqa: E501 + ) + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.lvis = LVIS(local_path) + self.cat_ids = self.lvis.get_cat_ids() + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.lvis.cat_img_map) + + img_ids = self.lvis.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.lvis.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + if raw_img_info['file_name'].startswith('COCO'): + # Convert form the COCO 2014 file naming convention of + # COCO_[train/val/test]2014_000000000000.jpg to the 2017 + # naming convention of 000000000000.jpg + # (LVIS v1 will fix this naming issue) + raw_img_info['file_name'] = raw_img_info['file_name'][-16:] + ann_ids = self.lvis.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.lvis.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.lvis + + return data_list + + +LVISDataset = LVISV05Dataset +DATASETS.register_module(name='LVISDataset', module=LVISDataset) + + +@DATASETS.register_module() +class LVISV1Dataset(LVISDataset): + """LVIS v1 dataset for detection.""" + + METAINFO = { + 'classes': + ('aerosol_can', 'air_conditioner', 'airplane', 'alarm_clock', + 'alcohol', 'alligator', 'almond', 'ambulance', 'amplifier', 'anklet', + 'antenna', 'apple', 'applesauce', 'apricot', 'apron', 'aquarium', + 'arctic_(type_of_shoe)', 'armband', 'armchair', 'armoire', 'armor', + 'artichoke', 'trash_can', 'ashtray', 'asparagus', 'atomizer', + 'avocado', 'award', 'awning', 'ax', 'baboon', 'baby_buggy', + 'basketball_backboard', 'backpack', 'handbag', 'suitcase', 'bagel', + 'bagpipe', 'baguet', 'bait', 'ball', 'ballet_skirt', 'balloon', + 'bamboo', 'banana', 'Band_Aid', 'bandage', 'bandanna', 'banjo', + 'banner', 'barbell', 'barge', 'barrel', 'barrette', 'barrow', + 'baseball_base', 'baseball', 'baseball_bat', 'baseball_cap', + 'baseball_glove', 'basket', 'basketball', 'bass_horn', 'bat_(animal)', + 'bath_mat', 'bath_towel', 'bathrobe', 'bathtub', 'batter_(food)', + 'battery', 'beachball', 'bead', 'bean_curd', 'beanbag', 'beanie', + 'bear', 'bed', 'bedpan', 'bedspread', 'cow', 'beef_(food)', 'beeper', + 'beer_bottle', 'beer_can', 'beetle', 'bell', 'bell_pepper', 'belt', + 'belt_buckle', 'bench', 'beret', 'bib', 'Bible', 'bicycle', 'visor', + 'billboard', 'binder', 'binoculars', 'bird', 'birdfeeder', 'birdbath', + 'birdcage', 'birdhouse', 'birthday_cake', 'birthday_card', + 'pirate_flag', 'black_sheep', 'blackberry', 'blackboard', 'blanket', + 'blazer', 'blender', 'blimp', 'blinker', 'blouse', 'blueberry', + 'gameboard', 'boat', 'bob', 'bobbin', 'bobby_pin', 'boiled_egg', + 'bolo_tie', 'deadbolt', 'bolt', 'bonnet', 'book', 'bookcase', + 'booklet', 'bookmark', 'boom_microphone', 'boot', 'bottle', + 'bottle_opener', 'bouquet', 'bow_(weapon)', + 'bow_(decorative_ribbons)', 'bow-tie', 'bowl', 'pipe_bowl', + 'bowler_hat', 'bowling_ball', 'box', 'boxing_glove', 'suspenders', + 'bracelet', 'brass_plaque', 'brassiere', 'bread-bin', 'bread', + 'breechcloth', 'bridal_gown', 'briefcase', 'broccoli', 'broach', + 'broom', 'brownie', 'brussels_sprouts', 'bubble_gum', 'bucket', + 'horse_buggy', 'bull', 'bulldog', 'bulldozer', 'bullet_train', + 'bulletin_board', 'bulletproof_vest', 'bullhorn', 'bun', 'bunk_bed', + 'buoy', 'burrito', 'bus_(vehicle)', 'business_card', 'butter', + 'butterfly', 'button', 'cab_(taxi)', 'cabana', 'cabin_car', 'cabinet', + 'locker', 'cake', 'calculator', 'calendar', 'calf', 'camcorder', + 'camel', 'camera', 'camera_lens', 'camper_(vehicle)', 'can', + 'can_opener', 'candle', 'candle_holder', 'candy_bar', 'candy_cane', + 'walking_cane', 'canister', 'canoe', 'cantaloup', 'canteen', + 'cap_(headwear)', 'bottle_cap', 'cape', 'cappuccino', + 'car_(automobile)', 'railcar_(part_of_a_train)', 'elevator_car', + 'car_battery', 'identity_card', 'card', 'cardigan', 'cargo_ship', + 'carnation', 'horse_carriage', 'carrot', 'tote_bag', 'cart', 'carton', + 'cash_register', 'casserole', 'cassette', 'cast', 'cat', + 'cauliflower', 'cayenne_(spice)', 'CD_player', 'celery', + 'cellular_telephone', 'chain_mail', 'chair', 'chaise_longue', + 'chalice', 'chandelier', 'chap', 'checkbook', 'checkerboard', + 'cherry', 'chessboard', 'chicken_(animal)', 'chickpea', + 'chili_(vegetable)', 'chime', 'chinaware', 'crisp_(potato_chip)', + 'poker_chip', 'chocolate_bar', 'chocolate_cake', 'chocolate_milk', + 'chocolate_mousse', 'choker', 'chopping_board', 'chopstick', + 'Christmas_tree', 'slide', 'cider', 'cigar_box', 'cigarette', + 'cigarette_case', 'cistern', 'clarinet', 'clasp', 'cleansing_agent', + 'cleat_(for_securing_rope)', 'clementine', 'clip', 'clipboard', + 'clippers_(for_plants)', 'cloak', 'clock', 'clock_tower', + 'clothes_hamper', 'clothespin', 'clutch_bag', 'coaster', 'coat', + 'coat_hanger', 'coatrack', 'cock', 'cockroach', 'cocoa_(beverage)', + 'coconut', 'coffee_maker', 'coffee_table', 'coffeepot', 'coil', + 'coin', 'colander', 'coleslaw', 'coloring_material', + 'combination_lock', 'pacifier', 'comic_book', 'compass', + 'computer_keyboard', 'condiment', 'cone', 'control', + 'convertible_(automobile)', 'sofa_bed', 'cooker', 'cookie', + 'cooking_utensil', 'cooler_(for_food)', 'cork_(bottle_plug)', + 'corkboard', 'corkscrew', 'edible_corn', 'cornbread', 'cornet', + 'cornice', 'cornmeal', 'corset', 'costume', 'cougar', 'coverall', + 'cowbell', 'cowboy_hat', 'crab_(animal)', 'crabmeat', 'cracker', + 'crape', 'crate', 'crayon', 'cream_pitcher', 'crescent_roll', 'crib', + 'crock_pot', 'crossbar', 'crouton', 'crow', 'crowbar', 'crown', + 'crucifix', 'cruise_ship', 'police_cruiser', 'crumb', 'crutch', + 'cub_(animal)', 'cube', 'cucumber', 'cufflink', 'cup', 'trophy_cup', + 'cupboard', 'cupcake', 'hair_curler', 'curling_iron', 'curtain', + 'cushion', 'cylinder', 'cymbal', 'dagger', 'dalmatian', 'dartboard', + 'date_(fruit)', 'deck_chair', 'deer', 'dental_floss', 'desk', + 'detergent', 'diaper', 'diary', 'die', 'dinghy', 'dining_table', + 'tux', 'dish', 'dish_antenna', 'dishrag', 'dishtowel', 'dishwasher', + 'dishwasher_detergent', 'dispenser', 'diving_board', 'Dixie_cup', + 'dog', 'dog_collar', 'doll', 'dollar', 'dollhouse', 'dolphin', + 'domestic_ass', 'doorknob', 'doormat', 'doughnut', 'dove', + 'dragonfly', 'drawer', 'underdrawers', 'dress', 'dress_hat', + 'dress_suit', 'dresser', 'drill', 'drone', 'dropper', + 'drum_(musical_instrument)', 'drumstick', 'duck', 'duckling', + 'duct_tape', 'duffel_bag', 'dumbbell', 'dumpster', 'dustpan', 'eagle', + 'earphone', 'earplug', 'earring', 'easel', 'eclair', 'eel', 'egg', + 'egg_roll', 'egg_yolk', 'eggbeater', 'eggplant', 'electric_chair', + 'refrigerator', 'elephant', 'elk', 'envelope', 'eraser', 'escargot', + 'eyepatch', 'falcon', 'fan', 'faucet', 'fedora', 'ferret', + 'Ferris_wheel', 'ferry', 'fig_(fruit)', 'fighter_jet', 'figurine', + 'file_cabinet', 'file_(tool)', 'fire_alarm', 'fire_engine', + 'fire_extinguisher', 'fire_hose', 'fireplace', 'fireplug', + 'first-aid_kit', 'fish', 'fish_(food)', 'fishbowl', 'fishing_rod', + 'flag', 'flagpole', 'flamingo', 'flannel', 'flap', 'flash', + 'flashlight', 'fleece', 'flip-flop_(sandal)', 'flipper_(footwear)', + 'flower_arrangement', 'flute_glass', 'foal', 'folding_chair', + 'food_processor', 'football_(American)', 'football_helmet', + 'footstool', 'fork', 'forklift', 'freight_car', 'French_toast', + 'freshener', 'frisbee', 'frog', 'fruit_juice', 'frying_pan', 'fudge', + 'funnel', 'futon', 'gag', 'garbage', 'garbage_truck', 'garden_hose', + 'gargle', 'gargoyle', 'garlic', 'gasmask', 'gazelle', 'gelatin', + 'gemstone', 'generator', 'giant_panda', 'gift_wrap', 'ginger', + 'giraffe', 'cincture', 'glass_(drink_container)', 'globe', 'glove', + 'goat', 'goggles', 'goldfish', 'golf_club', 'golfcart', + 'gondola_(boat)', 'goose', 'gorilla', 'gourd', 'grape', 'grater', + 'gravestone', 'gravy_boat', 'green_bean', 'green_onion', 'griddle', + 'grill', 'grits', 'grizzly', 'grocery_bag', 'guitar', 'gull', 'gun', + 'hairbrush', 'hairnet', 'hairpin', 'halter_top', 'ham', 'hamburger', + 'hammer', 'hammock', 'hamper', 'hamster', 'hair_dryer', 'hand_glass', + 'hand_towel', 'handcart', 'handcuff', 'handkerchief', 'handle', + 'handsaw', 'hardback_book', 'harmonium', 'hat', 'hatbox', 'veil', + 'headband', 'headboard', 'headlight', 'headscarf', 'headset', + 'headstall_(for_horses)', 'heart', 'heater', 'helicopter', 'helmet', + 'heron', 'highchair', 'hinge', 'hippopotamus', 'hockey_stick', 'hog', + 'home_plate_(baseball)', 'honey', 'fume_hood', 'hook', 'hookah', + 'hornet', 'horse', 'hose', 'hot-air_balloon', 'hotplate', 'hot_sauce', + 'hourglass', 'houseboat', 'hummingbird', 'hummus', 'polar_bear', + 'icecream', 'popsicle', 'ice_maker', 'ice_pack', 'ice_skate', + 'igniter', 'inhaler', 'iPod', 'iron_(for_clothing)', 'ironing_board', + 'jacket', 'jam', 'jar', 'jean', 'jeep', 'jelly_bean', 'jersey', + 'jet_plane', 'jewel', 'jewelry', 'joystick', 'jumpsuit', 'kayak', + 'keg', 'kennel', 'kettle', 'key', 'keycard', 'kilt', 'kimono', + 'kitchen_sink', 'kitchen_table', 'kite', 'kitten', 'kiwi_fruit', + 'knee_pad', 'knife', 'knitting_needle', 'knob', 'knocker_(on_a_door)', + 'koala', 'lab_coat', 'ladder', 'ladle', 'ladybug', 'lamb_(animal)', + 'lamb-chop', 'lamp', 'lamppost', 'lampshade', 'lantern', 'lanyard', + 'laptop_computer', 'lasagna', 'latch', 'lawn_mower', 'leather', + 'legging_(clothing)', 'Lego', 'legume', 'lemon', 'lemonade', + 'lettuce', 'license_plate', 'life_buoy', 'life_jacket', 'lightbulb', + 'lightning_rod', 'lime', 'limousine', 'lion', 'lip_balm', 'liquor', + 'lizard', 'log', 'lollipop', 'speaker_(stereo_equipment)', 'loveseat', + 'machine_gun', 'magazine', 'magnet', 'mail_slot', 'mailbox_(at_home)', + 'mallard', 'mallet', 'mammoth', 'manatee', 'mandarin_orange', + 'manger', 'manhole', 'map', 'marker', 'martini', 'mascot', + 'mashed_potato', 'masher', 'mask', 'mast', 'mat_(gym_equipment)', + 'matchbox', 'mattress', 'measuring_cup', 'measuring_stick', + 'meatball', 'medicine', 'melon', 'microphone', 'microscope', + 'microwave_oven', 'milestone', 'milk', 'milk_can', 'milkshake', + 'minivan', 'mint_candy', 'mirror', 'mitten', 'mixer_(kitchen_tool)', + 'money', 'monitor_(computer_equipment) computer_monitor', 'monkey', + 'motor', 'motor_scooter', 'motor_vehicle', 'motorcycle', + 'mound_(baseball)', 'mouse_(computer_equipment)', 'mousepad', + 'muffin', 'mug', 'mushroom', 'music_stool', 'musical_instrument', + 'nailfile', 'napkin', 'neckerchief', 'necklace', 'necktie', 'needle', + 'nest', 'newspaper', 'newsstand', 'nightshirt', + 'nosebag_(for_animals)', 'noseband_(for_animals)', 'notebook', + 'notepad', 'nut', 'nutcracker', 'oar', 'octopus_(food)', + 'octopus_(animal)', 'oil_lamp', 'olive_oil', 'omelet', 'onion', + 'orange_(fruit)', 'orange_juice', 'ostrich', 'ottoman', 'oven', + 'overalls_(clothing)', 'owl', 'packet', 'inkpad', 'pad', 'paddle', + 'padlock', 'paintbrush', 'painting', 'pajamas', 'palette', + 'pan_(for_cooking)', 'pan_(metal_container)', 'pancake', 'pantyhose', + 'papaya', 'paper_plate', 'paper_towel', 'paperback_book', + 'paperweight', 'parachute', 'parakeet', 'parasail_(sports)', + 'parasol', 'parchment', 'parka', 'parking_meter', 'parrot', + 'passenger_car_(part_of_a_train)', 'passenger_ship', 'passport', + 'pastry', 'patty_(food)', 'pea_(food)', 'peach', 'peanut_butter', + 'pear', 'peeler_(tool_for_fruit_and_vegetables)', 'wooden_leg', + 'pegboard', 'pelican', 'pen', 'pencil', 'pencil_box', + 'pencil_sharpener', 'pendulum', 'penguin', 'pennant', 'penny_(coin)', + 'pepper', 'pepper_mill', 'perfume', 'persimmon', 'person', 'pet', + 'pew_(church_bench)', 'phonebook', 'phonograph_record', 'piano', + 'pickle', 'pickup_truck', 'pie', 'pigeon', 'piggy_bank', 'pillow', + 'pin_(non_jewelry)', 'pineapple', 'pinecone', 'ping-pong_ball', + 'pinwheel', 'tobacco_pipe', 'pipe', 'pistol', 'pita_(bread)', + 'pitcher_(vessel_for_liquid)', 'pitchfork', 'pizza', 'place_mat', + 'plate', 'platter', 'playpen', 'pliers', 'plow_(farm_equipment)', + 'plume', 'pocket_watch', 'pocketknife', 'poker_(fire_stirring_tool)', + 'pole', 'polo_shirt', 'poncho', 'pony', 'pool_table', 'pop_(soda)', + 'postbox_(public)', 'postcard', 'poster', 'pot', 'flowerpot', + 'potato', 'potholder', 'pottery', 'pouch', 'power_shovel', 'prawn', + 'pretzel', 'printer', 'projectile_(weapon)', 'projector', 'propeller', + 'prune', 'pudding', 'puffer_(fish)', 'puffin', 'pug-dog', 'pumpkin', + 'puncher', 'puppet', 'puppy', 'quesadilla', 'quiche', 'quilt', + 'rabbit', 'race_car', 'racket', 'radar', 'radiator', 'radio_receiver', + 'radish', 'raft', 'rag_doll', 'raincoat', 'ram_(animal)', 'raspberry', + 'rat', 'razorblade', 'reamer_(juicer)', 'rearview_mirror', 'receipt', + 'recliner', 'record_player', 'reflector', 'remote_control', + 'rhinoceros', 'rib_(food)', 'rifle', 'ring', 'river_boat', 'road_map', + 'robe', 'rocking_chair', 'rodent', 'roller_skate', 'Rollerblade', + 'rolling_pin', 'root_beer', 'router_(computer_equipment)', + 'rubber_band', 'runner_(carpet)', 'plastic_bag', + 'saddle_(on_an_animal)', 'saddle_blanket', 'saddlebag', 'safety_pin', + 'sail', 'salad', 'salad_plate', 'salami', 'salmon_(fish)', + 'salmon_(food)', 'salsa', 'saltshaker', 'sandal_(type_of_shoe)', + 'sandwich', 'satchel', 'saucepan', 'saucer', 'sausage', 'sawhorse', + 'saxophone', 'scale_(measuring_instrument)', 'scarecrow', 'scarf', + 'school_bus', 'scissors', 'scoreboard', 'scraper', 'screwdriver', + 'scrubbing_brush', 'sculpture', 'seabird', 'seahorse', 'seaplane', + 'seashell', 'sewing_machine', 'shaker', 'shampoo', 'shark', + 'sharpener', 'Sharpie', 'shaver_(electric)', 'shaving_cream', 'shawl', + 'shears', 'sheep', 'shepherd_dog', 'sherbert', 'shield', 'shirt', + 'shoe', 'shopping_bag', 'shopping_cart', 'short_pants', 'shot_glass', + 'shoulder_bag', 'shovel', 'shower_head', 'shower_cap', + 'shower_curtain', 'shredder_(for_paper)', 'signboard', 'silo', 'sink', + 'skateboard', 'skewer', 'ski', 'ski_boot', 'ski_parka', 'ski_pole', + 'skirt', 'skullcap', 'sled', 'sleeping_bag', 'sling_(bandage)', + 'slipper_(footwear)', 'smoothie', 'snake', 'snowboard', 'snowman', + 'snowmobile', 'soap', 'soccer_ball', 'sock', 'sofa', 'softball', + 'solar_array', 'sombrero', 'soup', 'soup_bowl', 'soupspoon', + 'sour_cream', 'soya_milk', 'space_shuttle', 'sparkler_(fireworks)', + 'spatula', 'spear', 'spectacles', 'spice_rack', 'spider', 'crawfish', + 'sponge', 'spoon', 'sportswear', 'spotlight', 'squid_(food)', + 'squirrel', 'stagecoach', 'stapler_(stapling_machine)', 'starfish', + 'statue_(sculpture)', 'steak_(food)', 'steak_knife', 'steering_wheel', + 'stepladder', 'step_stool', 'stereo_(sound_system)', 'stew', + 'stirrer', 'stirrup', 'stool', 'stop_sign', 'brake_light', 'stove', + 'strainer', 'strap', 'straw_(for_drinking)', 'strawberry', + 'street_sign', 'streetlight', 'string_cheese', 'stylus', 'subwoofer', + 'sugar_bowl', 'sugarcane_(plant)', 'suit_(clothing)', 'sunflower', + 'sunglasses', 'sunhat', 'surfboard', 'sushi', 'mop', 'sweat_pants', + 'sweatband', 'sweater', 'sweatshirt', 'sweet_potato', 'swimsuit', + 'sword', 'syringe', 'Tabasco_sauce', 'table-tennis_table', 'table', + 'table_lamp', 'tablecloth', 'tachometer', 'taco', 'tag', 'taillight', + 'tambourine', 'army_tank', 'tank_(storage_vessel)', + 'tank_top_(clothing)', 'tape_(sticky_cloth_or_paper)', 'tape_measure', + 'tapestry', 'tarp', 'tartan', 'tassel', 'tea_bag', 'teacup', + 'teakettle', 'teapot', 'teddy_bear', 'telephone', 'telephone_booth', + 'telephone_pole', 'telephoto_lens', 'television_camera', + 'television_set', 'tennis_ball', 'tennis_racket', 'tequila', + 'thermometer', 'thermos_bottle', 'thermostat', 'thimble', 'thread', + 'thumbtack', 'tiara', 'tiger', 'tights_(clothing)', 'timer', + 'tinfoil', 'tinsel', 'tissue_paper', 'toast_(food)', 'toaster', + 'toaster_oven', 'toilet', 'toilet_tissue', 'tomato', 'tongs', + 'toolbox', 'toothbrush', 'toothpaste', 'toothpick', 'cover', + 'tortilla', 'tow_truck', 'towel', 'towel_rack', 'toy', + 'tractor_(farm_equipment)', 'traffic_light', 'dirt_bike', + 'trailer_truck', 'train_(railroad_vehicle)', 'trampoline', 'tray', + 'trench_coat', 'triangle_(musical_instrument)', 'tricycle', 'tripod', + 'trousers', 'truck', 'truffle_(chocolate)', 'trunk', 'vat', 'turban', + 'turkey_(food)', 'turnip', 'turtle', 'turtleneck_(clothing)', + 'typewriter', 'umbrella', 'underwear', 'unicycle', 'urinal', 'urn', + 'vacuum_cleaner', 'vase', 'vending_machine', 'vent', 'vest', + 'videotape', 'vinegar', 'violin', 'vodka', 'volleyball', 'vulture', + 'waffle', 'waffle_iron', 'wagon', 'wagon_wheel', 'walking_stick', + 'wall_clock', 'wall_socket', 'wallet', 'walrus', 'wardrobe', + 'washbasin', 'automatic_washer', 'watch', 'water_bottle', + 'water_cooler', 'water_faucet', 'water_heater', 'water_jug', + 'water_gun', 'water_scooter', 'water_ski', 'water_tower', + 'watering_can', 'watermelon', 'weathervane', 'webcam', 'wedding_cake', + 'wedding_ring', 'wet_suit', 'wheel', 'wheelchair', 'whipped_cream', + 'whistle', 'wig', 'wind_chime', 'windmill', 'window_box_(for_plants)', + 'windshield_wiper', 'windsock', 'wine_bottle', 'wine_bucket', + 'wineglass', 'blinder_(for_horses)', 'wok', 'wolf', 'wooden_spoon', + 'wreath', 'wrench', 'wristband', 'wristlet', 'yacht', 'yogurt', + 'yoke_(animal_equipment)', 'zebra', 'zucchini'), + 'palette': + None + } + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + try: + import lvis + if getattr(lvis, '__version__', '0') >= '10.5.3': + warnings.warn( + 'mmlvis is deprecated, please install official lvis-api by "pip install git+https://github.com/lvis-dataset/lvis-api.git"', # noqa: E501 + UserWarning) + from lvis import LVIS + except ImportError: + raise ImportError( + 'Package lvis is not installed. Please run "pip install git+https://github.com/lvis-dataset/lvis-api.git".' # noqa: E501 + ) + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.lvis = LVIS(local_path) + self.cat_ids = self.lvis.get_cat_ids() + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.lvis.cat_img_map) + + img_ids = self.lvis.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.lvis.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + # coco_url is used in LVISv1 instead of file_name + # e.g. http://images.cocodataset.org/train2017/000000391895.jpg + # train/val split in specified in url + raw_img_info['file_name'] = raw_img_info['coco_url'].replace( + 'http://images.cocodataset.org/', '') + ann_ids = self.lvis.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.lvis.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.lvis + + return data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/mdetr_style_refcoco.py b/mmdet_code/mmdetection/mmdet/datasets/mdetr_style_refcoco.py new file mode 100644 index 0000000000000000000000000000000000000000..cc56dec49db72daddf929bcc65471ffc2ca6fb4d --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/mdetr_style_refcoco.py @@ -0,0 +1,57 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List + +from mmengine.fileio import get_local_path + +from mmdet.datasets import BaseDetDataset +from mmdet.registry import DATASETS +from .api_wrappers import COCO + + +@DATASETS.register_module() +class MDETRStyleRefCocoDataset(BaseDetDataset): + """RefCOCO dataset. + + Only support evaluation now. + """ + + def load_data_list(self) -> List[dict]: + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + coco = COCO(local_path) + + img_ids = coco.get_img_ids() + + data_infos = [] + for img_id in img_ids: + raw_img_info = coco.load_imgs([img_id])[0] + ann_ids = coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = coco.load_anns(ann_ids) + + data_info = {} + img_path = osp.join(self.data_prefix['img'], + raw_img_info['file_name']) + data_info['img_path'] = img_path + data_info['img_id'] = img_id + data_info['height'] = raw_img_info['height'] + data_info['width'] = raw_img_info['width'] + data_info['dataset_mode'] = raw_img_info['dataset_name'] + + data_info['text'] = raw_img_info['caption'] + data_info['custom_entities'] = False + data_info['tokens_positive'] = -1 + + instances = [] + for i, ann in enumerate(raw_ann_info): + instance = {} + x1, y1, w, h = ann['bbox'] + bbox = [x1, y1, x1 + w, y1 + h] + instance['bbox'] = bbox + instance['bbox_label'] = ann['category_id'] + instance['ignore_flag'] = 0 + instances.append(instance) + + data_info['instances'] = instances + data_infos.append(data_info) + return data_infos diff --git a/mmdet_code/mmdetection/mmdet/datasets/mot_challenge_dataset.py b/mmdet_code/mmdetection/mmdet/datasets/mot_challenge_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbdc48ebf8d4a4ba11a605c8bc2a479cf2a0c96 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/mot_challenge_dataset.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from typing import List, Union + +from mmdet.registry import DATASETS +from .base_video_dataset import BaseVideoDataset + + +@DATASETS.register_module() +class MOTChallengeDataset(BaseVideoDataset): + """Dataset for MOTChallenge. + + Args: + visibility_thr (float, optional): The minimum visibility + for the objects during training. Default to -1. + """ + + METAINFO = { + 'classes': + ('pedestrian', 'person_on_vehicle', 'car', 'bicycle', 'motorbike', + 'non_mot_vehicle', 'static_person', 'distractor', 'occluder', + 'occluder_on_ground', 'occluder_full', 'reflection', 'crowd') + } + + def __init__(self, visibility_thr: float = -1, *args, **kwargs): + self.visibility_thr = visibility_thr + super().__init__(*args, **kwargs) + + def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. The difference between this + function and the one in ``BaseVideoDataset`` is that the parsing here + adds ``visibility`` and ``mot_conf``. + + Args: + raw_data_info (dict): Raw data information load from ``ann_file`` + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + img_info = raw_data_info['raw_img_info'] + ann_info = raw_data_info['raw_ann_info'] + data_info = {} + + data_info.update(img_info) + if self.data_prefix.get('img_path', None) is not None: + img_path = osp.join(self.data_prefix['img_path'], + img_info['file_name']) + else: + img_path = img_info['file_name'] + data_info['img_path'] = img_path + + instances = [] + for i, ann in enumerate(ann_info): + instance = {} + + if (not self.test_mode) and (ann['visibility'] < + self.visibility_thr): + continue + if ann.get('ignore', False): + continue + x1, y1, w, h = ann['bbox'] + inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) + inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if ann['area'] <= 0 or w < 1 or h < 1: + continue + if ann['category_id'] not in self.cat_ids: + continue + bbox = [x1, y1, x1 + w, y1 + h] + + if ann.get('iscrowd', False): + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[ann['category_id']] + instance['instance_id'] = ann['instance_id'] + instance['category_id'] = ann['category_id'] + instance['mot_conf'] = ann['mot_conf'] + instance['visibility'] = ann['visibility'] + if len(instance) > 0: + instances.append(instance) + if not self.test_mode: + assert len(instances) > 0, f'No valid instances found in ' \ + f'image {data_info["img_path"]}!' + data_info['instances'] = instances + return data_info diff --git a/mmdet_code/mmdetection/mmdet/datasets/objects365.py b/mmdet_code/mmdetection/mmdet/datasets/objects365.py new file mode 100644 index 0000000000000000000000000000000000000000..e99869bfa309635af3c03cbfa77f732db3f50637 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/objects365.py @@ -0,0 +1,284 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from typing import List + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .api_wrappers import COCO +from .coco import CocoDataset + +# images exist in annotations but not in image folder. +objv2_ignore_list = [ + osp.join('patch16', 'objects365_v2_00908726.jpg'), + osp.join('patch6', 'objects365_v1_00320532.jpg'), + osp.join('patch6', 'objects365_v1_00320534.jpg'), +] + + +@DATASETS.register_module() +class Objects365V1Dataset(CocoDataset): + """Objects365 v1 dataset for detection.""" + + METAINFO = { + 'classes': + ('person', 'sneakers', 'chair', 'hat', 'lamp', 'bottle', + 'cabinet/shelf', 'cup', 'car', 'glasses', 'picture/frame', 'desk', + 'handbag', 'street lights', 'book', 'plate', 'helmet', + 'leather shoes', 'pillow', 'glove', 'potted plant', 'bracelet', + 'flower', 'tv', 'storage box', 'vase', 'bench', 'wine glass', 'boots', + 'bowl', 'dining table', 'umbrella', 'boat', 'flag', 'speaker', + 'trash bin/can', 'stool', 'backpack', 'couch', 'belt', 'carpet', + 'basket', 'towel/napkin', 'slippers', 'barrel/bucket', 'coffee table', + 'suv', 'toy', 'tie', 'bed', 'traffic light', 'pen/pencil', + 'microphone', 'sandals', 'canned', 'necklace', 'mirror', 'faucet', + 'bicycle', 'bread', 'high heels', 'ring', 'van', 'watch', 'sink', + 'horse', 'fish', 'apple', 'camera', 'candle', 'teddy bear', 'cake', + 'motorcycle', 'wild bird', 'laptop', 'knife', 'traffic sign', + 'cell phone', 'paddle', 'truck', 'cow', 'power outlet', 'clock', + 'drum', 'fork', 'bus', 'hanger', 'nightstand', 'pot/pan', 'sheep', + 'guitar', 'traffic cone', 'tea pot', 'keyboard', 'tripod', 'hockey', + 'fan', 'dog', 'spoon', 'blackboard/whiteboard', 'balloon', + 'air conditioner', 'cymbal', 'mouse', 'telephone', 'pickup truck', + 'orange', 'banana', 'airplane', 'luggage', 'skis', 'soccer', + 'trolley', 'oven', 'remote', 'baseball glove', 'paper towel', + 'refrigerator', 'train', 'tomato', 'machinery vehicle', 'tent', + 'shampoo/shower gel', 'head phone', 'lantern', 'donut', + 'cleaning products', 'sailboat', 'tangerine', 'pizza', 'kite', + 'computer box', 'elephant', 'toiletries', 'gas stove', 'broccoli', + 'toilet', 'stroller', 'shovel', 'baseball bat', 'microwave', + 'skateboard', 'surfboard', 'surveillance camera', 'gun', 'life saver', + 'cat', 'lemon', 'liquid soap', 'zebra', 'duck', 'sports car', + 'giraffe', 'pumpkin', 'piano', 'stop sign', 'radiator', 'converter', + 'tissue ', 'carrot', 'washing machine', 'vent', 'cookies', + 'cutting/chopping board', 'tennis racket', 'candy', + 'skating and skiing shoes', 'scissors', 'folder', 'baseball', + 'strawberry', 'bow tie', 'pigeon', 'pepper', 'coffee machine', + 'bathtub', 'snowboard', 'suitcase', 'grapes', 'ladder', 'pear', + 'american football', 'basketball', 'potato', 'paint brush', 'printer', + 'billiards', 'fire hydrant', 'goose', 'projector', 'sausage', + 'fire extinguisher', 'extension cord', 'facial mask', 'tennis ball', + 'chopsticks', 'electronic stove and gas stove', 'pie', 'frisbee', + 'kettle', 'hamburger', 'golf club', 'cucumber', 'clutch', 'blender', + 'tong', 'slide', 'hot dog', 'toothbrush', 'facial cleanser', 'mango', + 'deer', 'egg', 'violin', 'marker', 'ship', 'chicken', 'onion', + 'ice cream', 'tape', 'wheelchair', 'plum', 'bar soap', 'scale', + 'watermelon', 'cabbage', 'router/modem', 'golf ball', 'pine apple', + 'crane', 'fire truck', 'peach', 'cello', 'notepaper', 'tricycle', + 'toaster', 'helicopter', 'green beans', 'brush', 'carriage', 'cigar', + 'earphone', 'penguin', 'hurdle', 'swing', 'radio', 'CD', + 'parking meter', 'swan', 'garlic', 'french fries', 'horn', 'avocado', + 'saxophone', 'trumpet', 'sandwich', 'cue', 'kiwi fruit', 'bear', + 'fishing rod', 'cherry', 'tablet', 'green vegetables', 'nuts', 'corn', + 'key', 'screwdriver', 'globe', 'broom', 'pliers', 'volleyball', + 'hammer', 'eggplant', 'trophy', 'dates', 'board eraser', 'rice', + 'tape measure/ruler', 'dumbbell', 'hamimelon', 'stapler', 'camel', + 'lettuce', 'goldfish', 'meat balls', 'medal', 'toothpaste', + 'antelope', 'shrimp', 'rickshaw', 'trombone', 'pomegranate', + 'coconut', 'jellyfish', 'mushroom', 'calculator', 'treadmill', + 'butterfly', 'egg tart', 'cheese', 'pig', 'pomelo', 'race car', + 'rice cooker', 'tuba', 'crosswalk sign', 'papaya', 'hair drier', + 'green onion', 'chips', 'dolphin', 'sushi', 'urinal', 'donkey', + 'electric drill', 'spring rolls', 'tortoise/turtle', 'parrot', + 'flute', 'measuring cup', 'shark', 'steak', 'poker card', + 'binoculars', 'llama', 'radish', 'noodles', 'yak', 'mop', 'crab', + 'microscope', 'barbell', 'bread/bun', 'baozi', 'lion', 'red cabbage', + 'polar bear', 'lighter', 'seal', 'mangosteen', 'comb', 'eraser', + 'pitaya', 'scallop', 'pencil case', 'saw', 'table tennis paddle', + 'okra', 'starfish', 'eagle', 'monkey', 'durian', 'game board', + 'rabbit', 'french horn', 'ambulance', 'asparagus', 'hoverboard', + 'pasta', 'target', 'hotair balloon', 'chainsaw', 'lobster', 'iron', + 'flashlight'), + 'palette': + None + } + + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + + # 'categories' list in objects365_train.json and objects365_val.json + # is inconsistent, need sort list(or dict) before get cat_ids. + cats = self.coco.cats + sorted_cats = {i: cats[i] for i in sorted(cats)} + self.coco.cats = sorted_cats + categories = self.coco.dataset['categories'] + sorted_categories = sorted(categories, key=lambda i: i['id']) + self.coco.dataset['categories'] = sorted_categories + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list + + +@DATASETS.register_module() +class Objects365V2Dataset(CocoDataset): + """Objects365 v2 dataset for detection.""" + METAINFO = { + 'classes': + ('Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', + 'Glasses', 'Bottle', 'Desk', 'Cup', 'Street Lights', 'Cabinet/shelf', + 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', + 'Book', 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', + 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag', 'Pillow', 'Boots', + 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', + 'Moniter/TV', 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', + 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle', 'Stool', + 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Bakset', 'Drum', + 'Pen/Pencil', 'Bus', 'Wild Bird', 'High Heels', 'Motorcycle', + 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', + 'Truck', 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', + 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning', 'Bed', + 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', + 'Air Conditioner', 'Knife', 'Hockey Stick', 'Paddle', 'Pickup Truck', + 'Fork', 'Traffic Sign', 'Ballon', 'Tripod', 'Dog', 'Spoon', 'Clock', + 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', + 'Blackboard/Whiteboard', 'Napkin', 'Other Fish', 'Orange/Tangerine', + 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', + 'Fan', 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', + 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard', 'Luggage', + 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', + 'Sports Car', 'Stop Sign', 'Dessert', 'Scooter', 'Stroller', 'Crane', + 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat', + 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', + 'Elephant', 'Skateboard', 'Surfboard', 'Gun', + 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', + 'Toilet', 'Kite', 'Strawberry', 'Other Balls', 'Shovel', 'Pepper', + 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks', + 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', + 'Coffee Table', 'Side Table', 'Scissors', 'Marker', 'Pie', 'Ladder', + 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', + 'Zebra', 'Grape', 'Giraffe', 'Potato', 'Sausage', 'Tricycle', + 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck', + 'Billards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', + 'Briefcase', 'Cucumber', 'Cigar/Cigarette ', 'Paint Brush', 'Pear', + 'Heavy Truck', 'Hamburger', 'Extractor', 'Extention Cord', 'Tong', + 'Tennis Racket', 'Folder', 'American Football', 'earphone', 'Mask', + 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine', 'Slide', + 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', + 'Washing Machine/Drying Machine', 'Chicken', 'Printer', 'Watermelon', + 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hotair ballon', + 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', + 'Blender', 'Peach', 'Rice', 'Wallet/Purse', 'Volleyball', 'Deer', + 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', + 'Golf Ball', 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', + 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin', 'Megaphone', + 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', + 'Sandwich', 'Nuts', 'Speed Limit Sign', 'Induction Cooker', 'Broom', + 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit', + 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', + 'Notepaper', 'Cherry', 'Pliers', 'CD', 'Pasta', 'Hammer', 'Cue', + 'Avocado', 'Hamimelon', 'Flask', 'Mushroon', 'Screwdriver', 'Soap', + 'Recorder', 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', + 'Tape Measur/ Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips', 'Steak', + 'Crosswalk Sign', 'Stapler', 'Campel', 'Formula 1 ', 'Pomegranate', + 'Dishwasher', 'Crab', 'Hoverboard', 'Meat ball', 'Rice Cooker', + 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal', + 'Buttefly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', + 'Electric Drill', 'Hair Dryer', 'Egg tart', 'Jellyfish', 'Treadmill', + 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', + 'Target', 'French', 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', + 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell', 'Scallop', + 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Teniis paddle', + 'Cosmetics Brush/Eyeliner Pencil', 'Chainsaw', 'Eraser', 'Lobster', + 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', + 'Table Tennis '), + 'palette': + None + } + + COCOAPI = COCO + # ann_id is unique in coco dataset. + ANN_ID_UNIQUE = True + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ # noqa: E501 + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + self.coco = self.COCOAPI(local_path) + # The order of returned `cat_ids` will not + # change with the order of the `classes` + self.cat_ids = self.coco.get_cat_ids( + cat_names=self.metainfo['classes']) + self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} + self.cat_img_map = copy.deepcopy(self.coco.cat_img_map) + + img_ids = self.coco.get_img_ids() + data_list = [] + total_ann_ids = [] + for img_id in img_ids: + raw_img_info = self.coco.load_imgs([img_id])[0] + raw_img_info['img_id'] = img_id + + ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) + raw_ann_info = self.coco.load_anns(ann_ids) + total_ann_ids.extend(ann_ids) + + # file_name should be `patchX/xxx.jpg` + file_name = osp.join( + osp.split(osp.split(raw_img_info['file_name'])[0])[-1], + osp.split(raw_img_info['file_name'])[-1]) + + if file_name in objv2_ignore_list: + continue + + raw_img_info['file_name'] = file_name + parsed_data_info = self.parse_data_info({ + 'raw_ann_info': + raw_ann_info, + 'raw_img_info': + raw_img_info + }) + data_list.append(parsed_data_info) + if self.ANN_ID_UNIQUE: + assert len(set(total_ann_ids)) == len( + total_ann_ids + ), f"Annotation ids in '{self.ann_file}' are not unique!" + + del self.coco + + return data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/odvg.py b/mmdet_code/mmdetection/mmdet/datasets/odvg.py new file mode 100644 index 0000000000000000000000000000000000000000..c73865f2ea724205640bea2c701c355bbd9135e3 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/odvg.py @@ -0,0 +1,106 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import json +import os.path as osp +from typing import List, Optional + +from mmengine.fileio import get_local_path + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class ODVGDataset(BaseDetDataset): + """object detection and visual grounding dataset.""" + + def __init__(self, + *args, + data_root: str = '', + label_map_file: Optional[str] = None, + need_text: bool = True, + **kwargs) -> None: + self.dataset_mode = 'VG' + self.need_text = need_text + if label_map_file: + label_map_file = osp.join(data_root, label_map_file) + with open(label_map_file, 'r') as file: + self.label_map = json.load(file) + self.dataset_mode = 'OD' + super().__init__(*args, data_root=data_root, **kwargs) + assert self.return_classes is True + + def load_data_list(self) -> List[dict]: + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + data_list = [json.loads(line) for line in f] + + out_data_list = [] + for data in data_list: + data_info = {} + img_path = osp.join(self.data_prefix['img'], data['filename']) + data_info['img_path'] = img_path + data_info['height'] = data['height'] + data_info['width'] = data['width'] + if self.dataset_mode == 'OD': + if self.need_text: + data_info['text'] = self.label_map + anno = data.get('detection', {}) + instances = [obj for obj in anno.get('instances', [])] + bboxes = [obj['bbox'] for obj in instances] + bbox_labels = [str(obj['label']) for obj in instances] + + instances = [] + for bbox, label in zip(bboxes, bbox_labels): + instance = {} + x1, y1, x2, y2 = bbox + inter_w = max(0, min(x2, data['width']) - max(x1, 0)) + inter_h = max(0, min(y2, data['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if (x2 - x1) < 1 or (y2 - y1) < 1: + continue + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = int(label) + instances.append(instance) + data_info['instances'] = instances + data_info['dataset_mode'] = self.dataset_mode + out_data_list.append(data_info) + else: + anno = data['grounding'] + data_info['text'] = anno['caption'] + regions = anno['regions'] + + instances = [] + phrases = {} + for i, region in enumerate(regions): + bbox = region['bbox'] + phrase = region['phrase'] + tokens_positive = region['tokens_positive'] + if not isinstance(bbox[0], list): + bbox = [bbox] + for box in bbox: + instance = {} + x1, y1, x2, y2 = box + inter_w = max(0, min(x2, data['width']) - max(x1, 0)) + inter_h = max(0, min(y2, data['height']) - max(y1, 0)) + if inter_w * inter_h == 0: + continue + if (x2 - x1) < 1 or (y2 - y1) < 1: + continue + instance['ignore_flag'] = 0 + instance['bbox'] = box + instance['bbox_label'] = i + phrases[i] = { + 'phrase': phrase, + 'tokens_positive': tokens_positive + } + instances.append(instance) + data_info['instances'] = instances + data_info['phrases'] = phrases + data_info['dataset_mode'] = self.dataset_mode + out_data_list.append(data_info) + + del data_list + return out_data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/openimages.py b/mmdet_code/mmdetection/mmdet/datasets/openimages.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c6c8ec44fdfe86a653fc6a716009836f7d471c --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/openimages.py @@ -0,0 +1,484 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import csv +import os.path as osp +from collections import defaultdict +from typing import Dict, List, Optional + +import numpy as np +from mmengine.fileio import get_local_path, load +from mmengine.utils import is_abs + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class OpenImagesDataset(BaseDetDataset): + """Open Images dataset for detection. + + Args: + ann_file (str): Annotation file path. + label_file (str): File path of the label description file that + maps the classes names in MID format to their short + descriptions. + meta_file (str): File path to get image metas. + hierarchy_file (str): The file path of the class hierarchy. + image_level_ann_file (str): Human-verified image level annotation, + which is used in evaluation. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + """ + + METAINFO: dict = dict(dataset_type='oid_v6') + + def __init__(self, + label_file: str, + meta_file: str, + hierarchy_file: str, + image_level_ann_file: Optional[str] = None, + **kwargs) -> None: + self.label_file = label_file + self.meta_file = meta_file + self.hierarchy_file = hierarchy_file + self.image_level_ann_file = image_level_ann_file + super().__init__(**kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ + classes_names, label_id_mapping = self._parse_label_file( + self.label_file) + self._metainfo['classes'] = classes_names + self.label_id_mapping = label_id_mapping + + if self.image_level_ann_file is not None: + img_level_anns = self._parse_img_level_ann( + self.image_level_ann_file) + else: + img_level_anns = None + + # OpenImagesMetric can get the relation matrix from the dataset meta + relation_matrix = self._get_relation_matrix(self.hierarchy_file) + self._metainfo['RELATION_MATRIX'] = relation_matrix + + data_list = [] + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + last_img_id = None + instances = [] + for i, line in enumerate(reader): + if i == 0: + continue + img_id = line[0] + if last_img_id is None: + last_img_id = img_id + label_id = line[2] + assert label_id in self.label_id_mapping + label = int(self.label_id_mapping[label_id]) + bbox = [ + float(line[4]), # xmin + float(line[6]), # ymin + float(line[5]), # xmax + float(line[7]) # ymax + ] + is_occluded = True if int(line[8]) == 1 else False + is_truncated = True if int(line[9]) == 1 else False + is_group_of = True if int(line[10]) == 1 else False + is_depiction = True if int(line[11]) == 1 else False + is_inside = True if int(line[12]) == 1 else False + + instance = dict( + bbox=bbox, + bbox_label=label, + ignore_flag=0, + is_occluded=is_occluded, + is_truncated=is_truncated, + is_group_of=is_group_of, + is_depiction=is_depiction, + is_inside=is_inside) + last_img_path = osp.join(self.data_prefix['img'], + f'{last_img_id}.jpg') + if img_id != last_img_id: + # switch to a new image, record previous image's data. + data_info = dict( + img_path=last_img_path, + img_id=last_img_id, + instances=instances, + ) + data_list.append(data_info) + instances = [] + instances.append(instance) + last_img_id = img_id + data_list.append( + dict( + img_path=last_img_path, + img_id=last_img_id, + instances=instances, + )) + + # add image metas to data list + img_metas = load( + self.meta_file, file_format='pkl', backend_args=self.backend_args) + assert len(img_metas) == len(data_list) + for i, meta in enumerate(img_metas): + img_id = data_list[i]['img_id'] + assert f'{img_id}.jpg' == osp.split(meta['filename'])[-1] + h, w = meta['ori_shape'][:2] + data_list[i]['height'] = h + data_list[i]['width'] = w + # denormalize bboxes + for j in range(len(data_list[i]['instances'])): + data_list[i]['instances'][j]['bbox'][0] *= w + data_list[i]['instances'][j]['bbox'][2] *= w + data_list[i]['instances'][j]['bbox'][1] *= h + data_list[i]['instances'][j]['bbox'][3] *= h + # add image-level annotation + if img_level_anns is not None: + img_labels = [] + confidences = [] + img_ann_list = img_level_anns.get(img_id, []) + for ann in img_ann_list: + img_labels.append(int(ann['image_level_label'])) + confidences.append(float(ann['confidence'])) + data_list[i]['image_level_labels'] = np.array( + img_labels, dtype=np.int64) + data_list[i]['confidences'] = np.array( + confidences, dtype=np.float32) + return data_list + + def _parse_label_file(self, label_file: str) -> tuple: + """Get classes name and index mapping from cls-label-description file. + + Args: + label_file (str): File path of the label description file that + maps the classes names in MID format to their short + descriptions. + + Returns: + tuple: Class name of OpenImages. + """ + + index_list = [] + classes_names = [] + with get_local_path( + label_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + for line in reader: + # self.cat2label[line[0]] = line[1] + classes_names.append(line[1]) + index_list.append(line[0]) + index_mapping = {index: i for i, index in enumerate(index_list)} + return classes_names, index_mapping + + def _parse_img_level_ann(self, + img_level_ann_file: str) -> Dict[str, List[dict]]: + """Parse image level annotations from csv style ann_file. + + Args: + img_level_ann_file (str): CSV style image level annotation + file path. + + Returns: + Dict[str, List[dict]]: Annotations where item of the defaultdict + indicates an image, each of which has (n) dicts. + Keys of dicts are: + + - `image_level_label` (int): Label id. + - `confidence` (float): Labels that are human-verified to be + present in an image have confidence = 1 (positive labels). + Labels that are human-verified to be absent from an image + have confidence = 0 (negative labels). Machine-generated + labels have fractional confidences, generally >= 0.5. + The higher the confidence, the smaller the chance for + the label to be a false positive. + """ + + item_lists = defaultdict(list) + with get_local_path( + img_level_ann_file, + backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + for i, line in enumerate(reader): + if i == 0: + continue + img_id = line[0] + item_lists[img_id].append( + dict( + image_level_label=int( + self.label_id_mapping[line[2]]), + confidence=float(line[3]))) + return item_lists + + def _get_relation_matrix(self, hierarchy_file: str) -> np.ndarray: + """Get the matrix of class hierarchy from the hierarchy file. Hierarchy + for 600 classes can be found at https://storage.googleapis.com/openimag + es/2018_04/bbox_labels_600_hierarchy_visualizer/circle.html. + + Args: + hierarchy_file (str): File path to the hierarchy for classes. + + Returns: + np.ndarray: The matrix of the corresponding relationship between + the parent class and the child class, of shape + (class_num, class_num). + """ # noqa + + hierarchy = load( + hierarchy_file, file_format='json', backend_args=self.backend_args) + class_num = len(self._metainfo['classes']) + relation_matrix = np.eye(class_num, class_num) + relation_matrix = self._convert_hierarchy_tree(hierarchy, + relation_matrix) + return relation_matrix + + def _convert_hierarchy_tree(self, + hierarchy_map: dict, + relation_matrix: np.ndarray, + parents: list = [], + get_all_parents: bool = True) -> np.ndarray: + """Get matrix of the corresponding relationship between the parent + class and the child class. + + Args: + hierarchy_map (dict): Including label name and corresponding + subcategory. Keys of dicts are: + + - `LabeName` (str): Name of the label. + - `Subcategory` (dict | list): Corresponding subcategory(ies). + relation_matrix (ndarray): The matrix of the corresponding + relationship between the parent class and the child class, + of shape (class_num, class_num). + parents (list): Corresponding parent class. + get_all_parents (bool): Whether get all parent names. + Default: True + + Returns: + ndarray: The matrix of the corresponding relationship between + the parent class and the child class, of shape + (class_num, class_num). + """ + + if 'Subcategory' in hierarchy_map: + for node in hierarchy_map['Subcategory']: + if 'LabelName' in node: + children_name = node['LabelName'] + children_index = self.label_id_mapping[children_name] + children = [children_index] + else: + continue + if len(parents) > 0: + for parent_index in parents: + if get_all_parents: + children.append(parent_index) + relation_matrix[children_index, parent_index] = 1 + relation_matrix = self._convert_hierarchy_tree( + node, relation_matrix, parents=children) + return relation_matrix + + def _join_prefix(self): + """Join ``self.data_root`` with annotation path.""" + super()._join_prefix() + if not is_abs(self.label_file) and self.label_file: + self.label_file = osp.join(self.data_root, self.label_file) + if not is_abs(self.meta_file) and self.meta_file: + self.meta_file = osp.join(self.data_root, self.meta_file) + if not is_abs(self.hierarchy_file) and self.hierarchy_file: + self.hierarchy_file = osp.join(self.data_root, self.hierarchy_file) + if self.image_level_ann_file and not is_abs(self.image_level_ann_file): + self.image_level_ann_file = osp.join(self.data_root, + self.image_level_ann_file) + + +@DATASETS.register_module() +class OpenImagesChallengeDataset(OpenImagesDataset): + """Open Images Challenge dataset for detection. + + Args: + ann_file (str): Open Images Challenge box annotation in txt format. + """ + + METAINFO: dict = dict(dataset_type='oid_challenge') + + def __init__(self, ann_file: str, **kwargs) -> None: + if not ann_file.endswith('txt'): + raise TypeError('The annotation file of Open Images Challenge ' + 'should be a txt file.') + + super().__init__(ann_file=ann_file, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ``self.ann_file`` + + Returns: + List[dict]: A list of annotation. + """ + classes_names, label_id_mapping = self._parse_label_file( + self.label_file) + self._metainfo['classes'] = classes_names + self.label_id_mapping = label_id_mapping + + if self.image_level_ann_file is not None: + img_level_anns = self._parse_img_level_ann( + self.image_level_ann_file) + else: + img_level_anns = None + + # OpenImagesMetric can get the relation matrix from the dataset meta + relation_matrix = self._get_relation_matrix(self.hierarchy_file) + self._metainfo['RELATION_MATRIX'] = relation_matrix + + data_list = [] + with get_local_path( + self.ann_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + lines = f.readlines() + i = 0 + while i < len(lines): + instances = [] + filename = lines[i].rstrip() + i += 2 + img_gt_size = int(lines[i]) + i += 1 + for j in range(img_gt_size): + sp = lines[i + j].split() + instances.append( + dict( + bbox=[ + float(sp[1]), + float(sp[2]), + float(sp[3]), + float(sp[4]) + ], + bbox_label=int(sp[0]) - 1, # labels begin from 1 + ignore_flag=0, + is_group_ofs=True if int(sp[5]) == 1 else False)) + i += img_gt_size + data_list.append( + dict( + img_path=osp.join(self.data_prefix['img'], filename), + instances=instances, + )) + + # add image metas to data list + img_metas = load( + self.meta_file, file_format='pkl', backend_args=self.backend_args) + assert len(img_metas) == len(data_list) + for i, meta in enumerate(img_metas): + img_id = osp.split(data_list[i]['img_path'])[-1][:-4] + assert img_id == osp.split(meta['filename'])[-1][:-4] + h, w = meta['ori_shape'][:2] + data_list[i]['height'] = h + data_list[i]['width'] = w + data_list[i]['img_id'] = img_id + # denormalize bboxes + for j in range(len(data_list[i]['instances'])): + data_list[i]['instances'][j]['bbox'][0] *= w + data_list[i]['instances'][j]['bbox'][2] *= w + data_list[i]['instances'][j]['bbox'][1] *= h + data_list[i]['instances'][j]['bbox'][3] *= h + # add image-level annotation + if img_level_anns is not None: + img_labels = [] + confidences = [] + img_ann_list = img_level_anns.get(img_id, []) + for ann in img_ann_list: + img_labels.append(int(ann['image_level_label'])) + confidences.append(float(ann['confidence'])) + data_list[i]['image_level_labels'] = np.array( + img_labels, dtype=np.int64) + data_list[i]['confidences'] = np.array( + confidences, dtype=np.float32) + return data_list + + def _parse_label_file(self, label_file: str) -> tuple: + """Get classes name and index mapping from cls-label-description file. + + Args: + label_file (str): File path of the label description file that + maps the classes names in MID format to their short + descriptions. + + Returns: + tuple: Class name of OpenImages. + """ + label_list = [] + id_list = [] + index_mapping = {} + with get_local_path( + label_file, backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + for line in reader: + label_name = line[0] + label_id = int(line[2]) + label_list.append(line[1]) + id_list.append(label_id) + index_mapping[label_name] = label_id - 1 + indexes = np.argsort(id_list) + classes_names = [] + for index in indexes: + classes_names.append(label_list[index]) + return classes_names, index_mapping + + def _parse_img_level_ann(self, image_level_ann_file): + """Parse image level annotations from csv style ann_file. + + Args: + image_level_ann_file (str): CSV style image level annotation + file path. + + Returns: + defaultdict[list[dict]]: Annotations where item of the defaultdict + indicates an image, each of which has (n) dicts. + Keys of dicts are: + + - `image_level_label` (int): of shape 1. + - `confidence` (float): of shape 1. + """ + + item_lists = defaultdict(list) + with get_local_path( + image_level_ann_file, + backend_args=self.backend_args) as local_path: + with open(local_path, 'r') as f: + reader = csv.reader(f) + i = -1 + for line in reader: + i += 1 + if i == 0: + continue + else: + img_id = line[0] + label_id = line[1] + assert label_id in self.label_id_mapping + image_level_label = int( + self.label_id_mapping[label_id]) + confidence = float(line[2]) + item_lists[img_id].append( + dict( + image_level_label=image_level_label, + confidence=confidence)) + return item_lists + + def _get_relation_matrix(self, hierarchy_file: str) -> np.ndarray: + """Get the matrix of class hierarchy from the hierarchy file. + + Args: + hierarchy_file (str): File path to the hierarchy for classes. + + Returns: + np.ndarray: The matrix of the corresponding + relationship between the parent class and the child class, + of shape (class_num, class_num). + """ + with get_local_path( + hierarchy_file, backend_args=self.backend_args) as local_path: + class_label_tree = np.load(local_path, allow_pickle=True) + return class_label_tree[1:, 1:] diff --git a/mmdet_code/mmdetection/mmdet/datasets/refcoco.py b/mmdet_code/mmdetection/mmdet/datasets/refcoco.py new file mode 100644 index 0000000000000000000000000000000000000000..0dae75fd547216a5b69033cc821b93a1d9ac6abc --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/refcoco.py @@ -0,0 +1,163 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import collections +import os.path as osp +import random +from typing import Dict, List + +import mmengine +from mmengine.dataset import BaseDataset + +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class RefCocoDataset(BaseDataset): + """RefCOCO dataset. + + The `Refcoco` and `Refcoco+` dataset is based on + `ReferItGame: Referring to Objects in Photographs of Natural Scenes + `_. + + The `Refcocog` dataset is based on + `Generation and Comprehension of Unambiguous Object Descriptions + `_. + + Args: + ann_file (str): Annotation file path. + data_root (str): The root directory for ``data_prefix`` and + ``ann_file``. Defaults to ''. + data_prefix (str): Prefix for training data. + split_file (str): Split file path. + split (str): Split name. Defaults to 'train'. + text_mode (str): Text mode. Defaults to 'random'. + **kwargs: Other keyword arguments in :class:`BaseDataset`. + """ + + def __init__(self, + data_root: str, + ann_file: str, + split_file: str, + data_prefix: Dict, + split: str = 'train', + text_mode: str = 'random', + **kwargs): + self.split_file = split_file + self.split = split + + assert text_mode in ['original', 'random', 'concat', 'select_first'] + self.text_mode = text_mode + super().__init__( + data_root=data_root, + data_prefix=data_prefix, + ann_file=ann_file, + **kwargs, + ) + + def _join_prefix(self): + if not mmengine.is_abs(self.split_file) and self.split_file: + self.split_file = osp.join(self.data_root, self.split_file) + + return super()._join_prefix() + + def _init_refs(self): + """Initialize the refs for RefCOCO.""" + anns, imgs = {}, {} + for ann in self.instances['annotations']: + anns[ann['id']] = ann + for img in self.instances['images']: + imgs[img['id']] = img + + refs, ref_to_ann = {}, {} + for ref in self.splits: + # ids + ref_id = ref['ref_id'] + ann_id = ref['ann_id'] + # add mapping related to ref + refs[ref_id] = ref + ref_to_ann[ref_id] = anns[ann_id] + + self.refs = refs + self.ref_to_ann = ref_to_ann + + def load_data_list(self) -> List[dict]: + """Load data list.""" + self.splits = mmengine.load(self.split_file, file_format='pkl') + self.instances = mmengine.load(self.ann_file, file_format='json') + self._init_refs() + img_prefix = self.data_prefix['img_path'] + + ref_ids = [ + ref['ref_id'] for ref in self.splits if ref['split'] == self.split + ] + full_anno = [] + for ref_id in ref_ids: + ref = self.refs[ref_id] + ann = self.ref_to_ann[ref_id] + ann.update(ref) + full_anno.append(ann) + + image_id_list = [] + final_anno = {} + for anno in full_anno: + image_id_list.append(anno['image_id']) + final_anno[anno['ann_id']] = anno + annotations = [value for key, value in final_anno.items()] + + coco_train_id = [] + image_annot = {} + for i in range(len(self.instances['images'])): + coco_train_id.append(self.instances['images'][i]['id']) + image_annot[self.instances['images'][i] + ['id']] = self.instances['images'][i] + + images = [] + for image_id in list(set(image_id_list)): + images += [image_annot[image_id]] + + data_list = [] + + grounding_dict = collections.defaultdict(list) + for anno in annotations: + image_id = int(anno['image_id']) + grounding_dict[image_id].append(anno) + + join_path = mmengine.fileio.get_file_backend(img_prefix).join_path + for image in images: + img_id = image['id'] + instances = [] + sentences = [] + for grounding_anno in grounding_dict[img_id]: + texts = [x['raw'].lower() for x in grounding_anno['sentences']] + # random select one text + if self.text_mode == 'random': + idx = random.randint(0, len(texts) - 1) + text = [texts[idx]] + # concat all texts + elif self.text_mode == 'concat': + text = [''.join(texts)] + # select the first text + elif self.text_mode == 'select_first': + text = [texts[0]] + # use all texts + elif self.text_mode == 'original': + text = texts + else: + raise ValueError(f'Invalid text mode "{self.text_mode}".') + ins = [{ + 'mask': grounding_anno['segmentation'], + 'ignore_flag': 0 + }] * len(text) + instances.extend(ins) + sentences.extend(text) + data_info = { + 'img_path': join_path(img_prefix, image['file_name']), + 'img_id': img_id, + 'instances': instances, + 'text': sentences + } + data_list.append(data_info) + + if len(data_list) == 0: + raise ValueError(f'No sample in split "{self.split}".') + + return data_list diff --git a/mmdet_code/mmdetection/mmdet/datasets/reid_dataset.py b/mmdet_code/mmdetection/mmdet/datasets/reid_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..1eed3ee4f0358edf59d19695c2b28394336dffd3 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/reid_dataset.py @@ -0,0 +1,127 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +from collections import defaultdict +from typing import Any, Dict, List + +import numpy as np +from mmengine.dataset import BaseDataset +from mmengine.utils import check_file_exist + +from mmdet.registry import DATASETS + + +@DATASETS.register_module() +class ReIDDataset(BaseDataset): + """Dataset for ReID. + + Args: + triplet_sampler (dict, optional): The sampler for hard mining + triplet loss. Defaults to None. + keys: num_ids (int): The number of person ids. + ins_per_id (int): The number of image for each person. + """ + + def __init__(self, triplet_sampler: dict = None, *args, **kwargs): + self.triplet_sampler = triplet_sampler + super().__init__(*args, **kwargs) + + def load_data_list(self) -> List[dict]: + """Load annotations from an annotation file named as ''self.ann_file''. + + Returns: + list[dict]: A list of annotation. + """ + assert isinstance(self.ann_file, str) + check_file_exist(self.ann_file) + data_list = [] + with open(self.ann_file) as f: + samples = [x.strip().split(' ') for x in f.readlines()] + for filename, gt_label in samples: + info = dict(img_prefix=self.data_prefix) + if self.data_prefix['img_path'] is not None: + info['img_path'] = osp.join(self.data_prefix['img_path'], + filename) + else: + info['img_path'] = filename + info['gt_label'] = np.array(gt_label, dtype=np.int64) + data_list.append(info) + self._parse_ann_info(data_list) + return data_list + + def _parse_ann_info(self, data_list: List[dict]): + """Parse person id annotations.""" + index_tmp_dic = defaultdict(list) # pid->[idx1,...,idxN] + self.index_dic = dict() # pid->array([idx1,...,idxN]) + for idx, info in enumerate(data_list): + pid = info['gt_label'] + index_tmp_dic[int(pid)].append(idx) + for pid, idxs in index_tmp_dic.items(): + self.index_dic[pid] = np.asarray(idxs, dtype=np.int64) + self.pids = np.asarray(list(self.index_dic.keys()), dtype=np.int64) + + def prepare_data(self, idx: int) -> Any: + """Get data processed by ''self.pipeline''. + + Args: + idx (int): The index of ''data_info'' + + Returns: + Any: Depends on ''self.pipeline'' + """ + data_info = self.get_data_info(idx) + if self.triplet_sampler is not None: + img_info = self.triplet_sampling(data_info['gt_label'], + **self.triplet_sampler) + data_info = copy.deepcopy(img_info) # triplet -> list + else: + data_info = copy.deepcopy(data_info) # no triplet -> dict + return self.pipeline(data_info) + + def triplet_sampling(self, + pos_pid, + num_ids: int = 8, + ins_per_id: int = 4) -> Dict: + """Triplet sampler for hard mining triplet loss. First, for one + pos_pid, random sample ins_per_id images with same person id. + + Then, random sample num_ids - 1 images for each negative id. + Finally, random sample ins_per_id images for each negative id. + + Args: + pos_pid (ndarray): The person id of the anchor. + num_ids (int): The number of person ids. + ins_per_id (int): The number of images for each person. + + Returns: + Dict: Annotation information of num_ids X ins_per_id images. + """ + assert len(self.pids) >= num_ids, \ + 'The number of person ids in the training set must ' \ + 'be greater than the number of person ids in the sample.' + + pos_idxs = self.index_dic[int( + pos_pid)] # all positive idxs for pos_pid + idxs_list = [] + # select positive samplers + idxs_list.extend(pos_idxs[np.random.choice( + pos_idxs.shape[0], ins_per_id, replace=True)]) + # select negative ids + neg_pids = np.random.choice( + [i for i, _ in enumerate(self.pids) if i != pos_pid], + num_ids - 1, + replace=False) + # select negative samplers for each negative id + for neg_pid in neg_pids: + neg_idxs = self.index_dic[neg_pid] + idxs_list.extend(neg_idxs[np.random.choice( + neg_idxs.shape[0], ins_per_id, replace=True)]) + # return the final triplet batch + triplet_img_infos = [] + for idx in idxs_list: + triplet_img_infos.append(copy.deepcopy(self.get_data_info(idx))) + # Collect data_list scatters (list of dict -> dict of list) + out = dict() + for key in triplet_img_infos[0].keys(): + out[key] = [_info[key] for _info in triplet_img_infos] + return out diff --git a/mmdet_code/mmdetection/mmdet/datasets/samplers/__init__.py b/mmdet_code/mmdetection/mmdet/datasets/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea0e4cb0628fc23bc034c51e503d8ceca5ee90c --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/samplers/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .batch_sampler import (AspectRatioBatchSampler, + MultiDataAspectRatioBatchSampler, + TrackAspectRatioBatchSampler) +from .class_aware_sampler import ClassAwareSampler +from .custom_sample_size_sampler import CustomSampleSizeSampler +from .multi_data_sampler import MultiDataSampler +from .multi_source_sampler import GroupMultiSourceSampler, MultiSourceSampler +from .track_img_sampler import TrackImgSampler + +__all__ = [ + 'ClassAwareSampler', 'AspectRatioBatchSampler', 'MultiSourceSampler', + 'GroupMultiSourceSampler', 'TrackImgSampler', + 'TrackAspectRatioBatchSampler', 'MultiDataSampler', + 'MultiDataAspectRatioBatchSampler', 'CustomSampleSizeSampler' +] diff --git a/mmdet_code/mmdetection/mmdet/datasets/samplers/batch_sampler.py b/mmdet_code/mmdetection/mmdet/datasets/samplers/batch_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..c17789c4e3ea51f1fa140d039a679f797a7660f6 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/samplers/batch_sampler.py @@ -0,0 +1,193 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Sequence + +from torch.utils.data import BatchSampler, Sampler + +from mmdet.datasets.samplers.track_img_sampler import TrackImgSampler +from mmdet.registry import DATA_SAMPLERS + + +# TODO: maybe replace with a data_loader wrapper +@DATA_SAMPLERS.register_module() +class AspectRatioBatchSampler(BatchSampler): + """A sampler wrapper for grouping images with similar aspect ratio (< 1 or. + + >= 1) into a same batch. + + Args: + sampler (Sampler): Base sampler. + batch_size (int): Size of mini-batch. + drop_last (bool): If ``True``, the sampler will drop the last batch if + its size would be less than ``batch_size``. + """ + + def __init__(self, + sampler: Sampler, + batch_size: int, + drop_last: bool = False) -> None: + if not isinstance(sampler, Sampler): + raise TypeError('sampler should be an instance of ``Sampler``, ' + f'but got {sampler}') + if not isinstance(batch_size, int) or batch_size <= 0: + raise ValueError('batch_size should be a positive integer value, ' + f'but got batch_size={batch_size}') + self.sampler = sampler + self.batch_size = batch_size + self.drop_last = drop_last + # two groups for w < h and w >= h + self._aspect_ratio_buckets = [[] for _ in range(2)] + + def __iter__(self) -> Sequence[int]: + for idx in self.sampler: + data_info = self.sampler.dataset.get_data_info(idx) + width, height = data_info['width'], data_info['height'] + bucket_id = 0 if width < height else 1 + bucket = self._aspect_ratio_buckets[bucket_id] + bucket.append(idx) + # yield a batch of indices in the same aspect ratio group + if len(bucket) == self.batch_size: + yield bucket[:] + del bucket[:] + + # yield the rest data and reset the bucket + left_data = self._aspect_ratio_buckets[0] + self._aspect_ratio_buckets[ + 1] + self._aspect_ratio_buckets = [[] for _ in range(2)] + while len(left_data) > 0: + if len(left_data) <= self.batch_size: + if not self.drop_last: + yield left_data[:] + left_data = [] + else: + yield left_data[:self.batch_size] + left_data = left_data[self.batch_size:] + + def __len__(self) -> int: + if self.drop_last: + return len(self.sampler) // self.batch_size + else: + return (len(self.sampler) + self.batch_size - 1) // self.batch_size + + +@DATA_SAMPLERS.register_module() +class TrackAspectRatioBatchSampler(AspectRatioBatchSampler): + """A sampler wrapper for grouping images with similar aspect ratio (< 1 or. + + >= 1) into a same batch. + + Args: + sampler (Sampler): Base sampler. + batch_size (int): Size of mini-batch. + drop_last (bool): If ``True``, the sampler will drop the last batch if + its size would be less than ``batch_size``. + """ + + def __iter__(self) -> Sequence[int]: + for idx in self.sampler: + # hard code to solve TrackImgSampler + if isinstance(self.sampler, TrackImgSampler): + video_idx, _ = idx + else: + video_idx = idx + # video_idx + data_info = self.sampler.dataset.get_data_info(video_idx) + # data_info {video_id, images, video_length} + img_data_info = data_info['images'][0] + width, height = img_data_info['width'], img_data_info['height'] + bucket_id = 0 if width < height else 1 + bucket = self._aspect_ratio_buckets[bucket_id] + bucket.append(idx) + # yield a batch of indices in the same aspect ratio group + if len(bucket) == self.batch_size: + yield bucket[:] + del bucket[:] + + # yield the rest data and reset the bucket + left_data = self._aspect_ratio_buckets[0] + self._aspect_ratio_buckets[ + 1] + self._aspect_ratio_buckets = [[] for _ in range(2)] + while len(left_data) > 0: + if len(left_data) <= self.batch_size: + if not self.drop_last: + yield left_data[:] + left_data = [] + else: + yield left_data[:self.batch_size] + left_data = left_data[self.batch_size:] + + +@DATA_SAMPLERS.register_module() +class MultiDataAspectRatioBatchSampler(BatchSampler): + """A sampler wrapper for grouping images with similar aspect ratio (< 1 or. + + >= 1) into a same batch for multi-source datasets. + + Args: + sampler (Sampler): Base sampler. + batch_size (Sequence(int)): Size of mini-batch for multi-source + datasets. + num_datasets(int): Number of multi-source datasets. + drop_last (bool): If ``True``, the sampler will drop the last batch if + its size would be less than ``batch_size``. + """ + + def __init__(self, + sampler: Sampler, + batch_size: Sequence[int], + num_datasets: int, + drop_last: bool = True) -> None: + if not isinstance(sampler, Sampler): + raise TypeError('sampler should be an instance of ``Sampler``, ' + f'but got {sampler}') + self.sampler = sampler + self.batch_size = batch_size + self.num_datasets = num_datasets + self.drop_last = drop_last + # two groups for w < h and w >= h for each dataset --> 2 * num_datasets + self._buckets = [[] for _ in range(2 * self.num_datasets)] + + def __iter__(self) -> Sequence[int]: + for idx in self.sampler: + data_info = self.sampler.dataset.get_data_info(idx) + width, height = data_info['width'], data_info['height'] + dataset_source_idx = self.sampler.dataset.get_dataset_source(idx) + aspect_ratio_bucket_id = 0 if width < height else 1 + bucket_id = dataset_source_idx * 2 + aspect_ratio_bucket_id + bucket = self._buckets[bucket_id] + bucket.append(idx) + # yield a batch of indices in the same aspect ratio group + if len(bucket) == self.batch_size[dataset_source_idx]: + yield bucket[:] + del bucket[:] + + # yield the rest data and reset the bucket + for i in range(self.num_datasets): + left_data = self._buckets[i * 2 + 0] + self._buckets[i * 2 + 1] + while len(left_data) > 0: + if len(left_data) <= self.batch_size[i]: + if not self.drop_last: + yield left_data[:] + left_data = [] + else: + yield left_data[:self.batch_size[i]] + left_data = left_data[self.batch_size[i]:] + + self._buckets = [[] for _ in range(2 * self.num_datasets)] + + def __len__(self) -> int: + sizes = [0 for _ in range(self.num_datasets)] + for idx in self.sampler: + dataset_source_idx = self.sampler.dataset.get_dataset_source(idx) + sizes[dataset_source_idx] += 1 + + if self.drop_last: + lens = 0 + for i in range(self.num_datasets): + lens += sizes[i] // self.batch_size[i] + return lens + else: + lens = 0 + for i in range(self.num_datasets): + lens += (sizes[i] + self.batch_size[i] - + 1) // self.batch_size[i] + return lens diff --git a/mmdet_code/mmdetection/mmdet/datasets/samplers/class_aware_sampler.py b/mmdet_code/mmdetection/mmdet/datasets/samplers/class_aware_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..6ca2f9b3ffb7c780ab25cc3704b67589763259e0 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/samplers/class_aware_sampler.py @@ -0,0 +1,192 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +from typing import Dict, Iterator, Optional, Union + +import numpy as np +import torch +from mmengine.dataset import BaseDataset +from mmengine.dist import get_dist_info, sync_random_seed +from torch.utils.data import Sampler + +from mmdet.registry import DATA_SAMPLERS + + +@DATA_SAMPLERS.register_module() +class ClassAwareSampler(Sampler): + r"""Sampler that restricts data loading to the label of the dataset. + + A class-aware sampling strategy to effectively tackle the + non-uniform class distribution. The length of the training data is + consistent with source data. Simple improvements based on `Relay + Backpropagation for Effective Learning of Deep Convolutional + Neural Networks `_ + + The implementation logic is referred to + https://github.com/Sense-X/TSD/blob/master/mmdet/datasets/samplers/distributed_classaware_sampler.py + + Args: + dataset: Dataset used for sampling. + seed (int, optional): random seed used to shuffle the sampler. + This number should be identical across all + processes in the distributed group. Defaults to None. + num_sample_class (int): The number of samples taken from each + per-label list. Defaults to 1. + """ + + def __init__(self, + dataset: BaseDataset, + seed: Optional[int] = None, + num_sample_class: int = 1) -> None: + rank, world_size = get_dist_info() + self.rank = rank + self.world_size = world_size + + self.dataset = dataset + self.epoch = 0 + # Must be the same across all workers. If None, will use a + # random seed shared among workers + # (require synchronization among all workers) + if seed is None: + seed = sync_random_seed() + self.seed = seed + + # The number of samples taken from each per-label list + assert num_sample_class > 0 and isinstance(num_sample_class, int) + self.num_sample_class = num_sample_class + # Get per-label image list from dataset + self.cat_dict = self.get_cat2imgs() + + self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / world_size)) + self.total_size = self.num_samples * self.world_size + + # get number of images containing each category + self.num_cat_imgs = [len(x) for x in self.cat_dict.values()] + # filter labels without images + self.valid_cat_inds = [ + i for i, length in enumerate(self.num_cat_imgs) if length != 0 + ] + self.num_classes = len(self.valid_cat_inds) + + def get_cat2imgs(self) -> Dict[int, list]: + """Get a dict with class as key and img_ids as values. + + Returns: + dict[int, list]: A dict of per-label image list, + the item of the dict indicates a label index, + corresponds to the image index that contains the label. + """ + classes = self.dataset.metainfo.get('classes', None) + if classes is None: + raise ValueError('dataset metainfo must contain `classes`') + # sort the label index + cat2imgs = {i: [] for i in range(len(classes))} + for i in range(len(self.dataset)): + cat_ids = set(self.dataset.get_cat_ids(i)) + for cat in cat_ids: + cat2imgs[cat].append(i) + return cat2imgs + + def __iter__(self) -> Iterator[int]: + # deterministically shuffle based on epoch + g = torch.Generator() + g.manual_seed(self.epoch + self.seed) + + # initialize label list + label_iter_list = RandomCycleIter(self.valid_cat_inds, generator=g) + # initialize each per-label image list + data_iter_dict = dict() + for i in self.valid_cat_inds: + data_iter_dict[i] = RandomCycleIter(self.cat_dict[i], generator=g) + + def gen_cat_img_inds(cls_list, data_dict, num_sample_cls): + """Traverse the categories and extract `num_sample_cls` image + indexes of the corresponding categories one by one.""" + id_indices = [] + for _ in range(len(cls_list)): + cls_idx = next(cls_list) + for _ in range(num_sample_cls): + id = next(data_dict[cls_idx]) + id_indices.append(id) + return id_indices + + # deterministically shuffle based on epoch + num_bins = int( + math.ceil(self.total_size * 1.0 / self.num_classes / + self.num_sample_class)) + indices = [] + for i in range(num_bins): + indices += gen_cat_img_inds(label_iter_list, data_iter_dict, + self.num_sample_class) + + # fix extra samples to make it evenly divisible + if len(indices) >= self.total_size: + indices = indices[:self.total_size] + else: + indices += indices[:(self.total_size - len(indices))] + assert len(indices) == self.total_size + + # subsample + offset = self.num_samples * self.rank + indices = indices[offset:offset + self.num_samples] + assert len(indices) == self.num_samples + + return iter(indices) + + def __len__(self) -> int: + """The number of samples in this rank.""" + return self.num_samples + + def set_epoch(self, epoch: int) -> None: + """Sets the epoch for this sampler. + + When :attr:`shuffle=True`, this ensures all replicas use a different + random ordering for each epoch. Otherwise, the next iteration of this + sampler will yield the same ordering. + + Args: + epoch (int): Epoch number. + """ + self.epoch = epoch + + +class RandomCycleIter: + """Shuffle the list and do it again after the list have traversed. + + The implementation logic is referred to + https://github.com/wutong16/DistributionBalancedLoss/blob/master/mllt/datasets/loader/sampler.py + + Example: + >>> label_list = [0, 1, 2, 4, 5] + >>> g = torch.Generator() + >>> g.manual_seed(0) + >>> label_iter_list = RandomCycleIter(label_list, generator=g) + >>> index = next(label_iter_list) + Args: + data (list or ndarray): The data that needs to be shuffled. + generator: An torch.Generator object, which is used in setting the seed + for generating random numbers. + """ # noqa: W605 + + def __init__(self, + data: Union[list, np.ndarray], + generator: torch.Generator = None) -> None: + self.data = data + self.length = len(data) + self.index = torch.randperm(self.length, generator=generator).numpy() + self.i = 0 + self.generator = generator + + def __iter__(self) -> Iterator: + return self + + def __len__(self) -> int: + return len(self.data) + + def __next__(self): + if self.i == self.length: + self.index = torch.randperm( + self.length, generator=self.generator).numpy() + self.i = 0 + idx = self.data[self.index[self.i]] + self.i += 1 + return idx diff --git a/mmdet_code/mmdetection/mmdet/datasets/samplers/custom_sample_size_sampler.py b/mmdet_code/mmdetection/mmdet/datasets/samplers/custom_sample_size_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..6bedf6c66be81b091a6424bae6788953ba7763a3 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/samplers/custom_sample_size_sampler.py @@ -0,0 +1,111 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +from typing import Iterator, Optional, Sequence, Sized + +import torch +from mmengine.dist import get_dist_info, sync_random_seed +from torch.utils.data import Sampler + +from mmdet.registry import DATA_SAMPLERS +from .class_aware_sampler import RandomCycleIter + + +@DATA_SAMPLERS.register_module() +class CustomSampleSizeSampler(Sampler): + + def __init__(self, + dataset: Sized, + dataset_size: Sequence[int], + ratio_mode: bool = False, + seed: Optional[int] = None, + round_up: bool = True) -> None: + assert len(dataset.datasets) == len(dataset_size) + rank, world_size = get_dist_info() + self.rank = rank + self.world_size = world_size + + self.dataset = dataset + if seed is None: + seed = sync_random_seed() + self.seed = seed + self.epoch = 0 + self.round_up = round_up + + total_size = 0 + total_size_fake = 0 + self.dataset_index = [] + self.dataset_cycle_iter = [] + new_dataset_size = [] + for dataset, size in zip(dataset.datasets, dataset_size): + self.dataset_index.append( + list(range(total_size_fake, + len(dataset) + total_size_fake))) + total_size_fake += len(dataset) + if size == -1: + total_size += len(dataset) + self.dataset_cycle_iter.append(None) + new_dataset_size.append(-1) + else: + if ratio_mode: + size = int(size * len(dataset)) + assert size <= len( + dataset + ), f'dataset size {size} is larger than ' \ + f'dataset length {len(dataset)}' + total_size += size + new_dataset_size.append(size) + + g = torch.Generator() + g.manual_seed(self.seed) + self.dataset_cycle_iter.append( + RandomCycleIter(self.dataset_index[-1], generator=g)) + self.dataset_size = new_dataset_size + + if self.round_up: + self.num_samples = math.ceil(total_size / world_size) + self.total_size = self.num_samples * self.world_size + else: + self.num_samples = math.ceil((total_size - rank) / world_size) + self.total_size = total_size + + def __iter__(self) -> Iterator[int]: + """Iterate the indices.""" + # deterministically shuffle based on epoch and seed + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + + out_index = [] + for data_size, data_index, cycle_iter in zip(self.dataset_size, + self.dataset_index, + self.dataset_cycle_iter): + if data_size == -1: + out_index += data_index + else: + index = [next(cycle_iter) for _ in range(data_size)] + out_index += index + + index = torch.randperm(len(out_index), generator=g).numpy().tolist() + indices = [out_index[i] for i in index] + + if self.round_up: + indices = ( + indices * + int(self.total_size / len(indices) + 1))[:self.total_size] + indices = indices[self.rank:self.total_size:self.world_size] + return iter(indices) + + def __len__(self) -> int: + """The number of samples in this rank.""" + return self.num_samples + + def set_epoch(self, epoch: int) -> None: + """Sets the epoch for this sampler. + + When :attr:`shuffle=True`, this ensures all replicas use a different + random ordering for each epoch. Otherwise, the next iteration of this + sampler will yield the same ordering. + + Args: + epoch (int): Epoch number. + """ + self.epoch = epoch diff --git a/mmdet_code/mmdetection/mmdet/datasets/samplers/multi_data_sampler.py b/mmdet_code/mmdetection/mmdet/datasets/samplers/multi_data_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a4b60d84122ce9eb2090095e9744c2bd73cc3d --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/samplers/multi_data_sampler.py @@ -0,0 +1,110 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +from typing import Iterator, Optional, Sequence, Sized + +import torch +from mmengine.dist import get_dist_info, sync_random_seed +from mmengine.registry import DATA_SAMPLERS +from torch.utils.data import Sampler + + +@DATA_SAMPLERS.register_module() +class MultiDataSampler(Sampler): + """The default data sampler for both distributed and non-distributed + environment. + + It has several differences from the PyTorch ``DistributedSampler`` as + below: + + 1. This sampler supports non-distributed environment. + + 2. The round up behaviors are a little different. + + - If ``round_up=True``, this sampler will add extra samples to make the + number of samples is evenly divisible by the world size. And + this behavior is the same as the ``DistributedSampler`` with + ``drop_last=False``. + - If ``round_up=False``, this sampler won't remove or add any samples + while the ``DistributedSampler`` with ``drop_last=True`` will remove + tail samples. + + Args: + dataset (Sized): The dataset. + dataset_ratio (Sequence(int)) The ratios of different datasets. + seed (int, optional): Random seed used to shuffle the sampler if + :attr:`shuffle=True`. This number should be identical across all + processes in the distributed group. Defaults to None. + round_up (bool): Whether to add extra samples to make the number of + samples evenly divisible by the world size. Defaults to True. + """ + + def __init__(self, + dataset: Sized, + dataset_ratio: Sequence[int], + seed: Optional[int] = None, + round_up: bool = True) -> None: + rank, world_size = get_dist_info() + self.rank = rank + self.world_size = world_size + + self.dataset = dataset + self.dataset_ratio = dataset_ratio + + if seed is None: + seed = sync_random_seed() + self.seed = seed + self.epoch = 0 + self.round_up = round_up + + if self.round_up: + self.num_samples = math.ceil(len(self.dataset) / world_size) + self.total_size = self.num_samples * self.world_size + else: + self.num_samples = math.ceil( + (len(self.dataset) - rank) / world_size) + self.total_size = len(self.dataset) + + self.sizes = [len(dataset) for dataset in self.dataset.datasets] + + dataset_weight = [ + torch.ones(s) * max(self.sizes) / s * r / sum(self.dataset_ratio) + for i, (r, s) in enumerate(zip(self.dataset_ratio, self.sizes)) + ] + self.weights = torch.cat(dataset_weight) + + def __iter__(self) -> Iterator[int]: + """Iterate the indices.""" + # deterministically shuffle based on epoch and seed + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + + indices = torch.multinomial( + self.weights, len(self.weights), generator=g, + replacement=True).tolist() + + # add extra samples to make it evenly divisible + if self.round_up: + indices = ( + indices * + int(self.total_size / len(indices) + 1))[:self.total_size] + + # subsample + indices = indices[self.rank:self.total_size:self.world_size] + + return iter(indices) + + def __len__(self) -> int: + """The number of samples in this rank.""" + return self.num_samples + + def set_epoch(self, epoch: int) -> None: + """Sets the epoch for this sampler. + + When :attr:`shuffle=True`, this ensures all replicas use a different + random ordering for each epoch. Otherwise, the next iteration of this + sampler will yield the same ordering. + + Args: + epoch (int): Epoch number. + """ + self.epoch = epoch diff --git a/mmdet_code/mmdetection/mmdet/datasets/samplers/multi_source_sampler.py b/mmdet_code/mmdetection/mmdet/datasets/samplers/multi_source_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..6efcde35e1375547239825a8f78a9e74f7825290 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/samplers/multi_source_sampler.py @@ -0,0 +1,214 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import itertools +from typing import Iterator, List, Optional, Sized, Union + +import numpy as np +import torch +from mmengine.dataset import BaseDataset +from mmengine.dist import get_dist_info, sync_random_seed +from torch.utils.data import Sampler + +from mmdet.registry import DATA_SAMPLERS + + +@DATA_SAMPLERS.register_module() +class MultiSourceSampler(Sampler): + r"""Multi-Source Infinite Sampler. + + According to the sampling ratio, sample data from different + datasets to form batches. + + Args: + dataset (Sized): The dataset. + batch_size (int): Size of mini-batch. + source_ratio (list[int | float]): The sampling ratio of different + source datasets in a mini-batch. + shuffle (bool): Whether shuffle the dataset or not. Defaults to True. + seed (int, optional): Random seed. If None, set a random seed. + Defaults to None. + + Examples: + >>> dataset_type = 'ConcatDataset' + >>> sub_dataset_type = 'CocoDataset' + >>> data_root = 'data/coco/' + >>> sup_ann = '../coco_semi_annos/instances_train2017.1@10.json' + >>> unsup_ann = '../coco_semi_annos/' \ + >>> 'instances_train2017.1@10-unlabeled.json' + >>> dataset = dict(type=dataset_type, + >>> datasets=[ + >>> dict( + >>> type=sub_dataset_type, + >>> data_root=data_root, + >>> ann_file=sup_ann, + >>> data_prefix=dict(img='train2017/'), + >>> filter_cfg=dict(filter_empty_gt=True, min_size=32), + >>> pipeline=sup_pipeline), + >>> dict( + >>> type=sub_dataset_type, + >>> data_root=data_root, + >>> ann_file=unsup_ann, + >>> data_prefix=dict(img='train2017/'), + >>> filter_cfg=dict(filter_empty_gt=True, min_size=32), + >>> pipeline=unsup_pipeline), + >>> ]) + >>> train_dataloader = dict( + >>> batch_size=5, + >>> num_workers=5, + >>> persistent_workers=True, + >>> sampler=dict(type='MultiSourceSampler', + >>> batch_size=5, source_ratio=[1, 4]), + >>> batch_sampler=None, + >>> dataset=dataset) + """ + + def __init__(self, + dataset: Sized, + batch_size: int, + source_ratio: List[Union[int, float]], + shuffle: bool = True, + seed: Optional[int] = None) -> None: + + assert hasattr(dataset, 'cumulative_sizes'),\ + f'The dataset must be ConcatDataset, but get {dataset}' + assert isinstance(batch_size, int) and batch_size > 0, \ + 'batch_size must be a positive integer value, ' \ + f'but got batch_size={batch_size}' + assert isinstance(source_ratio, list), \ + f'source_ratio must be a list, but got source_ratio={source_ratio}' + assert len(source_ratio) == len(dataset.cumulative_sizes), \ + 'The length of source_ratio must be equal to ' \ + f'the number of datasets, but got source_ratio={source_ratio}' + + rank, world_size = get_dist_info() + self.rank = rank + self.world_size = world_size + + self.dataset = dataset + self.cumulative_sizes = [0] + dataset.cumulative_sizes + self.batch_size = batch_size + self.source_ratio = source_ratio + + self.num_per_source = [ + int(batch_size * sr / sum(source_ratio)) for sr in source_ratio + ] + self.num_per_source[0] = batch_size - sum(self.num_per_source[1:]) + + assert sum(self.num_per_source) == batch_size, \ + 'The sum of num_per_source must be equal to ' \ + f'batch_size, but get {self.num_per_source}' + + self.seed = sync_random_seed() if seed is None else seed + self.shuffle = shuffle + self.source2inds = { + source: self._indices_of_rank(len(ds)) + for source, ds in enumerate(dataset.datasets) + } + + def _infinite_indices(self, sample_size: int) -> Iterator[int]: + """Infinitely yield a sequence of indices.""" + g = torch.Generator() + g.manual_seed(self.seed) + while True: + if self.shuffle: + yield from torch.randperm(sample_size, generator=g).tolist() + else: + yield from torch.arange(sample_size).tolist() + + def _indices_of_rank(self, sample_size: int) -> Iterator[int]: + """Slice the infinite indices by rank.""" + yield from itertools.islice( + self._infinite_indices(sample_size), self.rank, None, + self.world_size) + + def __iter__(self) -> Iterator[int]: + batch_buffer = [] + while True: + for source, num in enumerate(self.num_per_source): + batch_buffer_per_source = [] + for idx in self.source2inds[source]: + idx += self.cumulative_sizes[source] + batch_buffer_per_source.append(idx) + if len(batch_buffer_per_source) == num: + batch_buffer += batch_buffer_per_source + break + yield from batch_buffer + batch_buffer = [] + + def __len__(self) -> int: + return len(self.dataset) + + def set_epoch(self, epoch: int) -> None: + """Not supported in `epoch-based runner.""" + pass + + +@DATA_SAMPLERS.register_module() +class GroupMultiSourceSampler(MultiSourceSampler): + r"""Group Multi-Source Infinite Sampler. + + According to the sampling ratio, sample data from different + datasets but the same group to form batches. + + Args: + dataset (Sized): The dataset. + batch_size (int): Size of mini-batch. + source_ratio (list[int | float]): The sampling ratio of different + source datasets in a mini-batch. + shuffle (bool): Whether shuffle the dataset or not. Defaults to True. + seed (int, optional): Random seed. If None, set a random seed. + Defaults to None. + """ + + def __init__(self, + dataset: BaseDataset, + batch_size: int, + source_ratio: List[Union[int, float]], + shuffle: bool = True, + seed: Optional[int] = None) -> None: + super().__init__( + dataset=dataset, + batch_size=batch_size, + source_ratio=source_ratio, + shuffle=shuffle, + seed=seed) + + self._get_source_group_info() + self.group_source2inds = [{ + source: + self._indices_of_rank(self.group2size_per_source[source][group]) + for source in range(len(dataset.datasets)) + } for group in range(len(self.group_ratio))] + + def _get_source_group_info(self) -> None: + self.group2size_per_source = [{0: 0, 1: 0}, {0: 0, 1: 0}] + self.group2inds_per_source = [{0: [], 1: []}, {0: [], 1: []}] + for source, dataset in enumerate(self.dataset.datasets): + for idx in range(len(dataset)): + data_info = dataset.get_data_info(idx) + width, height = data_info['width'], data_info['height'] + group = 0 if width < height else 1 + self.group2size_per_source[source][group] += 1 + self.group2inds_per_source[source][group].append(idx) + + self.group_sizes = np.zeros(2, dtype=np.int64) + for group2size in self.group2size_per_source: + for group, size in group2size.items(): + self.group_sizes[group] += size + self.group_ratio = self.group_sizes / sum(self.group_sizes) + + def __iter__(self) -> Iterator[int]: + batch_buffer = [] + while True: + group = np.random.choice( + list(range(len(self.group_ratio))), p=self.group_ratio) + for source, num in enumerate(self.num_per_source): + batch_buffer_per_source = [] + for idx in self.group_source2inds[group][source]: + idx = self.group2inds_per_source[source][group][ + idx] + self.cumulative_sizes[source] + batch_buffer_per_source.append(idx) + if len(batch_buffer_per_source) == num: + batch_buffer += batch_buffer_per_source + break + yield from batch_buffer + batch_buffer = [] diff --git a/mmdet_code/mmdetection/mmdet/datasets/samplers/track_img_sampler.py b/mmdet_code/mmdetection/mmdet/datasets/samplers/track_img_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..d7db629f40f3f24bdf14cd852ccc4472d1d50f1b --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/samplers/track_img_sampler.py @@ -0,0 +1,146 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +import random +from typing import Iterator, Optional, Sized + +import numpy as np +from mmengine.dataset import ClassBalancedDataset, ConcatDataset +from mmengine.dist import get_dist_info, sync_random_seed +from torch.utils.data import Sampler + +from mmdet.registry import DATA_SAMPLERS +from ..base_video_dataset import BaseVideoDataset + + +@DATA_SAMPLERS.register_module() +class TrackImgSampler(Sampler): + """Sampler that providing image-level sampling outputs for video datasets + in tracking tasks. It could be both used in both distributed and + non-distributed environment. + If using the default sampler in pytorch, the subsequent data receiver will + get one video, which is not desired in some cases: + (Take a non-distributed environment as an example) + 1. In test mode, we want only one image is fed into the data pipeline. This + is in consideration of memory usage since feeding the whole video commonly + requires a large amount of memory (>=20G on MOTChallenge17 dataset), which + is not available in some machines. + 2. In training mode, we may want to make sure all the images in one video + are randomly sampled once in one epoch and this can not be guaranteed in + the default sampler in pytorch. + + Args: + dataset (Sized): Dataset used for sampling. + seed (int, optional): random seed used to shuffle the sampler. This + number should be identical across all processes in the distributed + group. Defaults to None. + """ + + def __init__( + self, + dataset: Sized, + seed: Optional[int] = None, + ) -> None: + rank, world_size = get_dist_info() + self.rank = rank + self.world_size = world_size + self.epoch = 0 + if seed is None: + self.seed = sync_random_seed() + else: + self.seed = seed + + self.dataset = dataset + self.indices = [] + # Hard code here to handle different dataset wrapper + if isinstance(self.dataset, ConcatDataset): + cat_datasets = self.dataset.datasets + assert isinstance( + cat_datasets[0], BaseVideoDataset + ), f'expected BaseVideoDataset, but got {type(cat_datasets[0])}' + self.test_mode = cat_datasets[0].test_mode + assert not self.test_mode, "'ConcatDataset' should not exist in " + 'test mode' + for dataset in cat_datasets: + num_videos = len(dataset) + for video_ind in range(num_videos): + self.indices.extend([ + (video_ind, frame_ind) for frame_ind in range( + dataset.get_len_per_video(video_ind)) + ]) + elif isinstance(self.dataset, ClassBalancedDataset): + ori_dataset = self.dataset.dataset + assert isinstance( + ori_dataset, BaseVideoDataset + ), f'expected BaseVideoDataset, but got {type(ori_dataset)}' + self.test_mode = ori_dataset.test_mode + assert not self.test_mode, "'ClassBalancedDataset' should not " + 'exist in test mode' + video_indices = self.dataset.repeat_indices + for index in video_indices: + self.indices.extend([(index, frame_ind) for frame_ind in range( + ori_dataset.get_len_per_video(index))]) + else: + assert isinstance( + self.dataset, BaseVideoDataset + ), 'TrackImgSampler is only supported in BaseVideoDataset or ' + 'dataset wrapper: ClassBalancedDataset and ConcatDataset, but ' + f'got {type(self.dataset)} ' + self.test_mode = self.dataset.test_mode + num_videos = len(self.dataset) + + if self.test_mode: + # in test mode, the images belong to the same video must be put + # on the same device. + if num_videos < self.world_size: + raise ValueError(f'only {num_videos} videos loaded,' + f'but {self.world_size} gpus were given.') + chunks = np.array_split( + list(range(num_videos)), self.world_size) + for videos_inds in chunks: + indices_chunk = [] + for video_ind in videos_inds: + indices_chunk.extend([ + (video_ind, frame_ind) for frame_ind in range( + self.dataset.get_len_per_video(video_ind)) + ]) + self.indices.append(indices_chunk) + else: + for video_ind in range(num_videos): + self.indices.extend([ + (video_ind, frame_ind) for frame_ind in range( + self.dataset.get_len_per_video(video_ind)) + ]) + + if self.test_mode: + self.num_samples = len(self.indices[self.rank]) + self.total_size = sum( + [len(index_list) for index_list in self.indices]) + else: + self.num_samples = int( + math.ceil(len(self.indices) * 1.0 / self.world_size)) + self.total_size = self.num_samples * self.world_size + + def __iter__(self) -> Iterator: + if self.test_mode: + # in test mode, the order of frames can not be shuffled. + indices = self.indices[self.rank] + else: + # deterministically shuffle based on epoch + rng = random.Random(self.epoch + self.seed) + indices = rng.sample(self.indices, len(self.indices)) + + # add extra samples to make it evenly divisible + indices += indices[:(self.total_size - len(indices))] + assert len(indices) == self.total_size + + # subsample + indices = indices[self.rank:self.total_size:self.world_size] + assert len(indices) == self.num_samples + + return iter(indices) + + def __len__(self): + return self.num_samples + + def set_epoch(self, epoch): + self.epoch = epoch diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/__init__.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3478feb008443cb0e56bf5084261370e38327d --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/__init__.py @@ -0,0 +1,45 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .augment_wrappers import AutoAugment, RandAugment +from .colorspace import (AutoContrast, Brightness, Color, ColorTransform, + Contrast, Equalize, Invert, Posterize, Sharpness, + Solarize, SolarizeAdd) +from .formatting import (ImageToTensor, PackDetInputs, PackReIDInputs, + PackTrackInputs, ToTensor, Transpose) +from .frame_sampling import BaseFrameSample, UniformRefFrameSample +from .geometric import (GeomTransform, Rotate, ShearX, ShearY, TranslateX, + TranslateY) +from .instaboost import InstaBoost +from .loading import (FilterAnnotations, InferencerLoader, LoadAnnotations, + LoadEmptyAnnotations, LoadImageFromNDArray, + LoadMultiChannelImageFromFiles, LoadPanopticAnnotations, + LoadProposals, LoadTrackAnnotations) +from .text_transformers import LoadTextAnnotations, RandomSamplingNegPos +from .transformers_glip import GTBoxSubOne_GLIP, RandomFlip_GLIP +from .transforms import (Albu, CachedMixUp, CachedMosaic, CopyPaste, CutOut, + Expand, FixScaleResize, FixShapeResize, + MinIoURandomCrop, MixUp, Mosaic, Pad, + PhotoMetricDistortion, RandomAffine, + RandomCenterCropPad, RandomCrop, RandomErasing, + RandomFlip, RandomShift, Resize, ResizeShortestEdge, + SegRescale, YOLOXHSVRandomAug) +from .wrappers import MultiBranch, ProposalBroadcaster, RandomOrder + +__all__ = [ + 'PackDetInputs', 'ToTensor', 'ImageToTensor', 'Transpose', + 'LoadImageFromNDArray', 'LoadAnnotations', 'LoadPanopticAnnotations', + 'LoadMultiChannelImageFromFiles', 'LoadProposals', 'Resize', 'RandomFlip', + 'RandomCrop', 'SegRescale', 'MinIoURandomCrop', 'Expand', + 'PhotoMetricDistortion', 'Albu', 'InstaBoost', 'RandomCenterCropPad', + 'AutoAugment', 'CutOut', 'ShearX', 'ShearY', 'Rotate', 'Color', 'Equalize', + 'Brightness', 'Contrast', 'TranslateX', 'TranslateY', 'RandomShift', + 'Mosaic', 'MixUp', 'RandomAffine', 'YOLOXHSVRandomAug', 'CopyPaste', + 'FilterAnnotations', 'Pad', 'GeomTransform', 'ColorTransform', + 'RandAugment', 'Sharpness', 'Solarize', 'SolarizeAdd', 'Posterize', + 'AutoContrast', 'Invert', 'MultiBranch', 'RandomErasing', + 'LoadEmptyAnnotations', 'RandomOrder', 'CachedMosaic', 'CachedMixUp', + 'FixShapeResize', 'ProposalBroadcaster', 'InferencerLoader', + 'LoadTrackAnnotations', 'BaseFrameSample', 'UniformRefFrameSample', + 'PackTrackInputs', 'PackReIDInputs', 'FixScaleResize', + 'ResizeShortestEdge', 'GTBoxSubOne_GLIP', 'RandomFlip_GLIP', + 'RandomSamplingNegPos', 'LoadTextAnnotations' +] diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/augment_wrappers.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/augment_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..19fae6efdf66aa4c26bb85a2f2c96a1e079320b8 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/augment_wrappers.py @@ -0,0 +1,264 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional, Union + +import numpy as np +from mmcv.transforms import RandomChoice +from mmcv.transforms.utils import cache_randomness +from mmengine.config import ConfigDict + +from mmdet.registry import TRANSFORMS + +# AutoAugment uses reinforcement learning to search for +# some widely useful data augmentation strategies, +# here we provide AUTOAUG_POLICIES_V0. +# For AUTOAUG_POLICIES_V0, each tuple is an augmentation +# operation of the form (operation, probability, magnitude). +# Each element in policies is a policy that will be applied +# sequentially on the image. + +# RandAugment defines a data augmentation search space, RANDAUG_SPACE, +# sampling 1~3 data augmentations each time, and +# setting the magnitude of each data augmentation randomly, +# which will be applied sequentially on the image. + +_MAX_LEVEL = 10 + +AUTOAUG_POLICIES_V0 = [ + [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], + [('Color', 0.4, 9), ('Equalize', 0.6, 3)], + [('Color', 0.4, 1), ('Rotate', 0.6, 8)], + [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)], + [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)], + [('Color', 0.2, 0), ('Equalize', 0.8, 8)], + [('Equalize', 0.4, 8), ('SolarizeAdd', 0.8, 3)], + [('ShearX', 0.2, 9), ('Rotate', 0.6, 8)], + [('Color', 0.6, 1), ('Equalize', 1.0, 2)], + [('Invert', 0.4, 9), ('Rotate', 0.6, 0)], + [('Equalize', 1.0, 9), ('ShearY', 0.6, 3)], + [('Color', 0.4, 7), ('Equalize', 0.6, 0)], + [('Posterize', 0.4, 6), ('AutoContrast', 0.4, 7)], + [('Solarize', 0.6, 8), ('Color', 0.6, 9)], + [('Solarize', 0.2, 4), ('Rotate', 0.8, 9)], + [('Rotate', 1.0, 7), ('TranslateY', 0.8, 9)], + [('ShearX', 0.0, 0), ('Solarize', 0.8, 4)], + [('ShearY', 0.8, 0), ('Color', 0.6, 4)], + [('Color', 1.0, 0), ('Rotate', 0.6, 2)], + [('Equalize', 0.8, 4), ('Equalize', 0.0, 8)], + [('Equalize', 1.0, 4), ('AutoContrast', 0.6, 2)], + [('ShearY', 0.4, 7), ('SolarizeAdd', 0.6, 7)], + [('Posterize', 0.8, 2), ('Solarize', 0.6, 10)], + [('Solarize', 0.6, 8), ('Equalize', 0.6, 1)], + [('Color', 0.8, 6), ('Rotate', 0.4, 5)], +] + + +def policies_v0(): + """Autoaugment policies that was used in AutoAugment Paper.""" + policies = list() + for policy_args in AUTOAUG_POLICIES_V0: + policy = list() + for args in policy_args: + policy.append(dict(type=args[0], prob=args[1], level=args[2])) + policies.append(policy) + return policies + + +RANDAUG_SPACE = [[dict(type='AutoContrast')], [dict(type='Equalize')], + [dict(type='Invert')], [dict(type='Rotate')], + [dict(type='Posterize')], [dict(type='Solarize')], + [dict(type='SolarizeAdd')], [dict(type='Color')], + [dict(type='Contrast')], [dict(type='Brightness')], + [dict(type='Sharpness')], [dict(type='ShearX')], + [dict(type='ShearY')], [dict(type='TranslateX')], + [dict(type='TranslateY')]] + + +def level_to_mag(level: Optional[int], min_mag: float, + max_mag: float) -> float: + """Map from level to magnitude.""" + if level is None: + return round(np.random.rand() * (max_mag - min_mag) + min_mag, 1) + else: + return round(level / _MAX_LEVEL * (max_mag - min_mag) + min_mag, 1) + + +@TRANSFORMS.register_module() +class AutoAugment(RandomChoice): + """Auto augmentation. + + This data augmentation is proposed in `AutoAugment: Learning + Augmentation Policies from Data `_ + and in `Learning Data Augmentation Strategies for Object Detection + `_. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_bboxes_labels + - gt_masks + - gt_ignore_flags + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + policies (List[List[Union[dict, ConfigDict]]]): + The policies of auto augmentation.Each policy in ``policies`` + is a specific augmentation policy, and is composed by several + augmentations. When AutoAugment is called, a random policy in + ``policies`` will be selected to augment images. + Defaults to policy_v0(). + prob (list[float], optional): The probabilities associated + with each policy. The length should be equal to the policy + number and the sum should be 1. If not given, a uniform + distribution will be assumed. Defaults to None. + + Examples: + >>> policies = [ + >>> [ + >>> dict(type='Sharpness', prob=0.0, level=8), + >>> dict(type='ShearX', prob=0.4, level=0,) + >>> ], + >>> [ + >>> dict(type='Rotate', prob=0.6, level=10), + >>> dict(type='Color', prob=1.0, level=6) + >>> ] + >>> ] + >>> augmentation = AutoAugment(policies) + >>> img = np.ones(100, 100, 3) + >>> gt_bboxes = np.ones(10, 4) + >>> results = dict(img=img, gt_bboxes=gt_bboxes) + >>> results = augmentation(results) + """ + + def __init__(self, + policies: List[List[Union[dict, ConfigDict]]] = policies_v0(), + prob: Optional[List[float]] = None) -> None: + assert isinstance(policies, list) and len(policies) > 0, \ + 'Policies must be a non-empty list.' + for policy in policies: + assert isinstance(policy, list) and len(policy) > 0, \ + 'Each policy in policies must be a non-empty list.' + for augment in policy: + assert isinstance(augment, dict) and 'type' in augment, \ + 'Each specific augmentation must be a dict with key' \ + ' "type".' + super().__init__(transforms=policies, prob=prob) + self.policies = policies + + def __repr__(self) -> str: + return f'{self.__class__.__name__}(policies={self.policies}, ' \ + f'prob={self.prob})' + + +@TRANSFORMS.register_module() +class RandAugment(RandomChoice): + """Rand augmentation. + + This data augmentation is proposed in `RandAugment: + Practical automated data augmentation with a reduced + search space `_. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_bboxes_labels + - gt_masks + - gt_ignore_flags + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + aug_space (List[List[Union[dict, ConfigDict]]]): The augmentation space + of rand augmentation. Each augmentation transform in ``aug_space`` + is a specific transform, and is composed by several augmentations. + When RandAugment is called, a random transform in ``aug_space`` + will be selected to augment images. Defaults to aug_space. + aug_num (int): Number of augmentation to apply equentially. + Defaults to 2. + prob (list[float], optional): The probabilities associated with + each augmentation. The length should be equal to the + augmentation space and the sum should be 1. If not given, + a uniform distribution will be assumed. Defaults to None. + + Examples: + >>> aug_space = [ + >>> dict(type='Sharpness'), + >>> dict(type='ShearX'), + >>> dict(type='Color'), + >>> ], + >>> augmentation = RandAugment(aug_space) + >>> img = np.ones(100, 100, 3) + >>> gt_bboxes = np.ones(10, 4) + >>> results = dict(img=img, gt_bboxes=gt_bboxes) + >>> results = augmentation(results) + """ + + def __init__(self, + aug_space: List[Union[dict, ConfigDict]] = RANDAUG_SPACE, + aug_num: int = 2, + prob: Optional[List[float]] = None) -> None: + assert isinstance(aug_space, list) and len(aug_space) > 0, \ + 'Augmentation space must be a non-empty list.' + for aug in aug_space: + assert isinstance(aug, list) and len(aug) == 1, \ + 'Each augmentation in aug_space must be a list.' + for transform in aug: + assert isinstance(transform, dict) and 'type' in transform, \ + 'Each specific transform must be a dict with key' \ + ' "type".' + super().__init__(transforms=aug_space, prob=prob) + self.aug_space = aug_space + self.aug_num = aug_num + + @cache_randomness + def random_pipeline_index(self): + indices = np.arange(len(self.transforms)) + return np.random.choice( + indices, self.aug_num, p=self.prob, replace=False) + + def transform(self, results: dict) -> dict: + """Transform function to use RandAugment. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with RandAugment. + """ + for idx in self.random_pipeline_index(): + results = self.transforms[idx](results) + return results + + def __repr__(self) -> str: + return f'{self.__class__.__name__}(' \ + f'aug_space={self.aug_space}, '\ + f'aug_num={self.aug_num}, ' \ + f'prob={self.prob})' diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/colorspace.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/colorspace.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ba2e97c7eedf65df5ab8942ee461f48a785f39 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/colorspace.py @@ -0,0 +1,493 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +from typing import Optional + +import mmcv +import numpy as np +from mmcv.transforms import BaseTransform +from mmcv.transforms.utils import cache_randomness + +from mmdet.registry import TRANSFORMS +from .augment_wrappers import _MAX_LEVEL, level_to_mag + + +@TRANSFORMS.register_module() +class ColorTransform(BaseTransform): + """Base class for color transformations. All color transformations need to + inherit from this base class. ``ColorTransform`` unifies the class + attributes and class functions of color transformations (Color, Brightness, + Contrast, Sharpness, Solarize, SolarizeAdd, Equalize, AutoContrast, Invert, + and Posterize), and only distort color channels, without impacting the + locations of the instances. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing the geometric + transformation and should be in range [0, 1]. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for color transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for color transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0 <= prob <= 1.0, f'The probability of the transformation ' \ + f'should be in range [0,1], got {prob}.' + assert level is None or isinstance(level, int), \ + f'The level should be None or type int, got {type(level)}.' + assert level is None or 0 <= level <= _MAX_LEVEL, \ + f'The level should be in range [0,{_MAX_LEVEL}], got {level}.' + assert isinstance(min_mag, float), \ + f'min_mag should be type float, got {type(min_mag)}.' + assert isinstance(max_mag, float), \ + f'max_mag should be type float, got {type(max_mag)}.' + assert min_mag <= max_mag, \ + f'min_mag should smaller than max_mag, ' \ + f'got min_mag={min_mag} and max_mag={max_mag}' + self.prob = prob + self.level = level + self.min_mag = min_mag + self.max_mag = max_mag + + def _transform_img(self, results: dict, mag: float) -> None: + """Transform the image.""" + pass + + @cache_randomness + def _random_disable(self): + """Randomly disable the transform.""" + return np.random.rand() > self.prob + + @cache_randomness + def _get_mag(self): + """Get the magnitude of the transform.""" + return level_to_mag(self.level, self.min_mag, self.max_mag) + + def transform(self, results: dict) -> dict: + """Transform function for images. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Transformed results. + """ + + if self._random_disable(): + return results + mag = self._get_mag() + self._transform_img(results, mag) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'level={self.level}, ' + repr_str += f'min_mag={self.min_mag}, ' + repr_str += f'max_mag={self.max_mag})' + return repr_str + + +@TRANSFORMS.register_module() +class Color(ColorTransform): + """Adjust the color balance of the image, in a manner similar to the + controls on a colour TV set. A magnitude=0 gives a black & white image, + whereas magnitude=1 gives the original image. The bboxes, masks and + segmentations are not modified. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Color transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Color transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for Color transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0. <= min_mag <= 2.0, \ + f'min_mag for Color should be in range [0,2], got {min_mag}.' + assert 0. <= max_mag <= 2.0, \ + f'max_mag for Color should be in range [0,2], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Apply Color transformation to image.""" + # NOTE defaultly the image should be BGR format + img = results['img'] + results['img'] = mmcv.adjust_color(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Brightness(ColorTransform): + """Adjust the brightness of the image. A magnitude=0 gives a black image, + whereas magnitude=1 gives the original image. The bboxes, masks and + segmentations are not modified. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Brightness transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Brightness transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for Brightness transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0. <= min_mag <= 2.0, \ + f'min_mag for Brightness should be in range [0,2], got {min_mag}.' + assert 0. <= max_mag <= 2.0, \ + f'max_mag for Brightness should be in range [0,2], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Adjust the brightness of image.""" + img = results['img'] + results['img'] = mmcv.adjust_brightness(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Contrast(ColorTransform): + """Control the contrast of the image. A magnitude=0 gives a gray image, + whereas magnitude=1 gives the original imageThe bboxes, masks and + segmentations are not modified. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Contrast transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Contrast transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for Contrast transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0. <= min_mag <= 2.0, \ + f'min_mag for Contrast should be in range [0,2], got {min_mag}.' + assert 0. <= max_mag <= 2.0, \ + f'max_mag for Contrast should be in range [0,2], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Adjust the image contrast.""" + img = results['img'] + results['img'] = mmcv.adjust_contrast(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Sharpness(ColorTransform): + """Adjust images sharpness. A positive magnitude would enhance the + sharpness and a negative magnitude would make the image blurry. A + magnitude=0 gives the origin img. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Sharpness transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Sharpness transformation. + Defaults to 0.1. + max_mag (float): The maximum magnitude for Sharpness transformation. + Defaults to 1.9. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.1, + max_mag: float = 1.9) -> None: + assert 0. <= min_mag <= 2.0, \ + f'min_mag for Sharpness should be in range [0,2], got {min_mag}.' + assert 0. <= max_mag <= 2.0, \ + f'max_mag for Sharpness should be in range [0,2], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Adjust the image sharpness.""" + img = results['img'] + results['img'] = mmcv.adjust_sharpness(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Solarize(ColorTransform): + """Solarize images (Invert all pixels above a threshold value of + magnitude.). + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Solarize transformation. + Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Solarize transformation. + Defaults to 0.0. + max_mag (float): The maximum magnitude for Solarize transformation. + Defaults to 256.0. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 256.0) -> None: + assert 0. <= min_mag <= 256.0, f'min_mag for Solarize should be ' \ + f'in range [0, 256], got {min_mag}.' + assert 0. <= max_mag <= 256.0, f'max_mag for Solarize should be ' \ + f'in range [0, 256], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Invert all pixel values above magnitude.""" + img = results['img'] + results['img'] = mmcv.solarize(img, mag).astype(img.dtype) + + +@TRANSFORMS.register_module() +class SolarizeAdd(ColorTransform): + """SolarizeAdd images. For each pixel in the image that is less than 128, + add an additional amount to it decided by the magnitude. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing SolarizeAdd + transformation. Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for SolarizeAdd transformation. + Defaults to 0.0. + max_mag (float): The maximum magnitude for SolarizeAdd transformation. + Defaults to 110.0. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 110.0) -> None: + assert 0. <= min_mag <= 110.0, f'min_mag for SolarizeAdd should be ' \ + f'in range [0, 110], got {min_mag}.' + assert 0. <= max_mag <= 110.0, f'max_mag for SolarizeAdd should be ' \ + f'in range [0, 110], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """SolarizeAdd the image.""" + img = results['img'] + img_solarized = np.where(img < 128, np.minimum(img + mag, 255), img) + results['img'] = img_solarized.astype(img.dtype) + + +@TRANSFORMS.register_module() +class Posterize(ColorTransform): + """Posterize images (reduce the number of bits for each color channel). + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Posterize + transformation. Defaults to 1.0. + level (int, optional): Should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for Posterize transformation. + Defaults to 0.0. + max_mag (float): The maximum magnitude for Posterize transformation. + Defaults to 4.0. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 4.0) -> None: + assert 0. <= min_mag <= 8.0, f'min_mag for Posterize should be ' \ + f'in range [0, 8], got {min_mag}.' + assert 0. <= max_mag <= 8.0, f'max_mag for Posterize should be ' \ + f'in range [0, 8], got {max_mag}.' + super().__init__( + prob=prob, level=level, min_mag=min_mag, max_mag=max_mag) + + def _transform_img(self, results: dict, mag: float) -> None: + """Posterize the image.""" + img = results['img'] + results['img'] = mmcv.posterize(img, math.ceil(mag)).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Equalize(ColorTransform): + """Equalize the image histogram. The bboxes, masks and segmentations are + not modified. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing Equalize transformation. + Defaults to 1.0. + level (int, optional): No use for Equalize transformation. + Defaults to None. + min_mag (float): No use for Equalize transformation. Defaults to 0.1. + max_mag (float): No use for Equalize transformation. Defaults to 1.9. + """ + + def _transform_img(self, results: dict, mag: float) -> None: + """Equalizes the histogram of one image.""" + img = results['img'] + results['img'] = mmcv.imequalize(img).astype(img.dtype) + + +@TRANSFORMS.register_module() +class AutoContrast(ColorTransform): + """Auto adjust image contrast. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing AutoContrast should + be in range [0, 1]. Defaults to 1.0. + level (int, optional): No use for AutoContrast transformation. + Defaults to None. + min_mag (float): No use for AutoContrast transformation. + Defaults to 0.1. + max_mag (float): No use for AutoContrast transformation. + Defaults to 1.9. + """ + + def _transform_img(self, results: dict, mag: float) -> None: + """Auto adjust image contrast.""" + img = results['img'] + results['img'] = mmcv.auto_contrast(img).astype(img.dtype) + + +@TRANSFORMS.register_module() +class Invert(ColorTransform): + """Invert images. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + prob (float): The probability for performing invert therefore should + be in range [0, 1]. Defaults to 1.0. + level (int, optional): No use for Invert transformation. + Defaults to None. + min_mag (float): No use for Invert transformation. Defaults to 0.1. + max_mag (float): No use for Invert transformation. Defaults to 1.9. + """ + + def _transform_img(self, results: dict, mag: float) -> None: + """Invert the image.""" + img = results['img'] + results['img'] = mmcv.iminvert(img).astype(img.dtype) diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/formatting.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..05263807c0eab470b0c73f435d327ad8cadb60b3 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/formatting.py @@ -0,0 +1,512 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional, Sequence + +import numpy as np +from mmcv.transforms import to_tensor +from mmcv.transforms.base import BaseTransform +from mmengine.structures import InstanceData, PixelData + +from mmdet.registry import TRANSFORMS +from mmdet.structures import DetDataSample, ReIDDataSample, TrackDataSample +from mmdet.structures.bbox import BaseBoxes + + +@TRANSFORMS.register_module() +class PackDetInputs(BaseTransform): + """Pack the inputs data for the detection / semantic segmentation / + panoptic segmentation. + + The ``img_meta`` item is always populated. The contents of the + ``img_meta`` dictionary depends on ``meta_keys``. By default this includes: + + - ``img_id``: id of the image + + - ``img_path``: path to the image file + + - ``ori_shape``: original shape of the image as a tuple (h, w) + + - ``img_shape``: shape of the image input to the network as a tuple \ + (h, w). Note that images may be zero padded on the \ + bottom/right if the batch tensor is larger than this shape. + + - ``scale_factor``: a float indicating the preprocessing scale + + - ``flip``: a boolean indicating if image flip transform was used + + - ``flip_direction``: the flipping direction + + Args: + meta_keys (Sequence[str], optional): Meta keys to be converted to + ``mmcv.DataContainer`` and collected in ``data[img_metas]``. + Default: ``('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction')`` + """ + mapping_table = { + 'gt_bboxes': 'bboxes', + 'gt_bboxes_labels': 'labels', + 'gt_masks': 'masks' + } + + def __init__(self, + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction')): + self.meta_keys = meta_keys + + def transform(self, results: dict) -> dict: + """Method to pack the input data. + + Args: + results (dict): Result dict from the data pipeline. + + Returns: + dict: + + - 'inputs' (obj:`torch.Tensor`): The forward data of models. + - 'data_sample' (obj:`DetDataSample`): The annotation info of the + sample. + """ + packed_results = dict() + if 'img' in results: + img = results['img'] + if len(img.shape) < 3: + img = np.expand_dims(img, -1) + # To improve the computational speed by by 3-5 times, apply: + # If image is not contiguous, use + # `numpy.transpose()` followed by `numpy.ascontiguousarray()` + # If image is already contiguous, use + # `torch.permute()` followed by `torch.contiguous()` + # Refer to https://github.com/open-mmlab/mmdetection/pull/9533 + # for more details + if not img.flags.c_contiguous: + img = np.ascontiguousarray(img.transpose(2, 0, 1)) + img = to_tensor(img) + else: + img = to_tensor(img).permute(2, 0, 1).contiguous() + + packed_results['inputs'] = img + + if 'gt_ignore_flags' in results: + valid_idx = np.where(results['gt_ignore_flags'] == 0)[0] + ignore_idx = np.where(results['gt_ignore_flags'] == 1)[0] + + data_sample = DetDataSample() + instance_data = InstanceData() + ignore_instance_data = InstanceData() + + for key in self.mapping_table.keys(): + if key not in results: + continue + if key == 'gt_masks' or isinstance(results[key], BaseBoxes): + if 'gt_ignore_flags' in results: + instance_data[ + self.mapping_table[key]] = results[key][valid_idx] + ignore_instance_data[ + self.mapping_table[key]] = results[key][ignore_idx] + else: + instance_data[self.mapping_table[key]] = results[key] + else: + if 'gt_ignore_flags' in results: + instance_data[self.mapping_table[key]] = to_tensor( + results[key][valid_idx]) + ignore_instance_data[self.mapping_table[key]] = to_tensor( + results[key][ignore_idx]) + else: + instance_data[self.mapping_table[key]] = to_tensor( + results[key]) + data_sample.gt_instances = instance_data + data_sample.ignored_instances = ignore_instance_data + + if 'proposals' in results: + proposals = InstanceData( + bboxes=to_tensor(results['proposals']), + scores=to_tensor(results['proposals_scores'])) + data_sample.proposals = proposals + + if 'gt_seg_map' in results: + gt_sem_seg_data = dict( + sem_seg=to_tensor(results['gt_seg_map'][None, ...].copy())) + gt_sem_seg_data = PixelData(**gt_sem_seg_data) + if 'ignore_index' in results: + metainfo = dict(ignore_index=results['ignore_index']) + gt_sem_seg_data.set_metainfo(metainfo) + data_sample.gt_sem_seg = gt_sem_seg_data + + img_meta = {} + for key in self.meta_keys: + if key in results: + img_meta[key] = results[key] + data_sample.set_metainfo(img_meta) + packed_results['data_samples'] = data_sample + + return packed_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(meta_keys={self.meta_keys})' + return repr_str + + +@TRANSFORMS.register_module() +class ToTensor: + """Convert some results to :obj:`torch.Tensor` by given keys. + + Args: + keys (Sequence[str]): Keys that need to be converted to Tensor. + """ + + def __init__(self, keys): + self.keys = keys + + def __call__(self, results): + """Call function to convert data in results to :obj:`torch.Tensor`. + + Args: + results (dict): Result dict contains the data to convert. + + Returns: + dict: The result dict contains the data converted + to :obj:`torch.Tensor`. + """ + for key in self.keys: + results[key] = to_tensor(results[key]) + return results + + def __repr__(self): + return self.__class__.__name__ + f'(keys={self.keys})' + + +@TRANSFORMS.register_module() +class ImageToTensor: + """Convert image to :obj:`torch.Tensor` by given keys. + + The dimension order of input image is (H, W, C). The pipeline will convert + it to (C, H, W). If only 2 dimension (H, W) is given, the output would be + (1, H, W). + + Args: + keys (Sequence[str]): Key of images to be converted to Tensor. + """ + + def __init__(self, keys): + self.keys = keys + + def __call__(self, results): + """Call function to convert image in results to :obj:`torch.Tensor` and + transpose the channel order. + + Args: + results (dict): Result dict contains the image data to convert. + + Returns: + dict: The result dict contains the image converted + to :obj:`torch.Tensor` and permuted to (C, H, W) order. + """ + for key in self.keys: + img = results[key] + if len(img.shape) < 3: + img = np.expand_dims(img, -1) + results[key] = to_tensor(img).permute(2, 0, 1).contiguous() + + return results + + def __repr__(self): + return self.__class__.__name__ + f'(keys={self.keys})' + + +@TRANSFORMS.register_module() +class Transpose: + """Transpose some results by given keys. + + Args: + keys (Sequence[str]): Keys of results to be transposed. + order (Sequence[int]): Order of transpose. + """ + + def __init__(self, keys, order): + self.keys = keys + self.order = order + + def __call__(self, results): + """Call function to transpose the channel order of data in results. + + Args: + results (dict): Result dict contains the data to transpose. + + Returns: + dict: The result dict contains the data transposed to \ + ``self.order``. + """ + for key in self.keys: + results[key] = results[key].transpose(self.order) + return results + + def __repr__(self): + return self.__class__.__name__ + \ + f'(keys={self.keys}, order={self.order})' + + +@TRANSFORMS.register_module() +class WrapFieldsToLists: + """Wrap fields of the data dictionary into lists for evaluation. + + This class can be used as a last step of a test or validation + pipeline for single image evaluation or inference. + + Example: + >>> test_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> 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']), + >>> dict(type='WrapFieldsToLists') + >>> ] + """ + + def __call__(self, results): + """Call function to wrap fields into lists. + + Args: + results (dict): Result dict contains the data to wrap. + + Returns: + dict: The result dict where value of ``self.keys`` are wrapped \ + into list. + """ + + # Wrap dict fields into lists + for key, val in results.items(): + results[key] = [val] + return results + + def __repr__(self): + return f'{self.__class__.__name__}()' + + +@TRANSFORMS.register_module() +class PackTrackInputs(BaseTransform): + """Pack the inputs data for the multi object tracking and video instance + segmentation. All the information of images are packed to ``inputs``. All + the information except images are packed to ``data_samples``. In order to + get the original annotaiton and meta info, we add `instances` key into meta + keys. + + Args: + meta_keys (Sequence[str]): Meta keys to be collected in + ``data_sample.metainfo``. Defaults to None. + default_meta_keys (tuple): Default meta keys. Defaults to ('img_id', + 'img_path', 'ori_shape', 'img_shape', 'scale_factor', + 'flip', 'flip_direction', 'frame_id', 'is_video_data', + 'video_id', 'video_length', 'instances'). + """ + mapping_table = { + 'gt_bboxes': 'bboxes', + 'gt_bboxes_labels': 'labels', + 'gt_masks': 'masks', + 'gt_instances_ids': 'instances_ids' + } + + def __init__(self, + meta_keys: Optional[dict] = None, + default_meta_keys: tuple = ('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', + 'flip', 'flip_direction', + 'frame_id', 'video_id', + 'video_length', + 'ori_video_length', 'instances')): + self.meta_keys = default_meta_keys + if meta_keys is not None: + if isinstance(meta_keys, str): + meta_keys = (meta_keys, ) + else: + assert isinstance(meta_keys, tuple), \ + 'meta_keys must be str or tuple' + self.meta_keys += meta_keys + + def transform(self, results: dict) -> dict: + """Method to pack the input data. + Args: + results (dict): Result dict from the data pipeline. + Returns: + dict: + - 'inputs' (dict[Tensor]): The forward data of models. + - 'data_samples' (obj:`TrackDataSample`): The annotation info of + the samples. + """ + packed_results = dict() + packed_results['inputs'] = dict() + + # 1. Pack images + if 'img' in results: + imgs = results['img'] + imgs = np.stack(imgs, axis=0) + imgs = imgs.transpose(0, 3, 1, 2) + packed_results['inputs'] = to_tensor(imgs) + + # 2. Pack InstanceData + if 'gt_ignore_flags' in results: + gt_ignore_flags_list = results['gt_ignore_flags'] + valid_idx_list, ignore_idx_list = [], [] + for gt_ignore_flags in gt_ignore_flags_list: + valid_idx = np.where(gt_ignore_flags == 0)[0] + ignore_idx = np.where(gt_ignore_flags == 1)[0] + valid_idx_list.append(valid_idx) + ignore_idx_list.append(ignore_idx) + + assert 'img_id' in results, "'img_id' must contained in the results " + 'for counting the number of images' + + num_imgs = len(results['img_id']) + instance_data_list = [InstanceData() for _ in range(num_imgs)] + ignore_instance_data_list = [InstanceData() for _ in range(num_imgs)] + + for key in self.mapping_table.keys(): + if key not in results: + continue + if key == 'gt_masks': + mapped_key = self.mapping_table[key] + gt_masks_list = results[key] + if 'gt_ignore_flags' in results: + for i, gt_mask in enumerate(gt_masks_list): + valid_idx, ignore_idx = valid_idx_list[ + i], ignore_idx_list[i] + instance_data_list[i][mapped_key] = gt_mask[valid_idx] + ignore_instance_data_list[i][mapped_key] = gt_mask[ + ignore_idx] + + else: + for i, gt_mask in enumerate(gt_masks_list): + instance_data_list[i][mapped_key] = gt_mask + + else: + anns_list = results[key] + if 'gt_ignore_flags' in results: + for i, ann in enumerate(anns_list): + valid_idx, ignore_idx = valid_idx_list[ + i], ignore_idx_list[i] + instance_data_list[i][ + self.mapping_table[key]] = to_tensor( + ann[valid_idx]) + ignore_instance_data_list[i][ + self.mapping_table[key]] = to_tensor( + ann[ignore_idx]) + else: + for i, ann in enumerate(anns_list): + instance_data_list[i][ + self.mapping_table[key]] = to_tensor(ann) + + det_data_samples_list = [] + for i in range(num_imgs): + det_data_sample = DetDataSample() + det_data_sample.gt_instances = instance_data_list[i] + det_data_sample.ignored_instances = ignore_instance_data_list[i] + det_data_samples_list.append(det_data_sample) + + # 3. Pack metainfo + for key in self.meta_keys: + if key not in results: + continue + img_metas_list = results[key] + for i, img_meta in enumerate(img_metas_list): + det_data_samples_list[i].set_metainfo({f'{key}': img_meta}) + + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = det_data_samples_list + if 'key_frame_flags' in results: + key_frame_flags = np.asarray(results['key_frame_flags']) + key_frames_inds = np.where(key_frame_flags)[0].tolist() + ref_frames_inds = np.where(~key_frame_flags)[0].tolist() + track_data_sample.set_metainfo( + dict(key_frames_inds=key_frames_inds)) + track_data_sample.set_metainfo( + dict(ref_frames_inds=ref_frames_inds)) + + packed_results['data_samples'] = track_data_sample + return packed_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'meta_keys={self.meta_keys}, ' + repr_str += f'default_meta_keys={self.default_meta_keys})' + return repr_str + + +@TRANSFORMS.register_module() +class PackReIDInputs(BaseTransform): + """Pack the inputs data for the ReID. The ``meta_info`` item is always + populated. The contents of the ``meta_info`` dictionary depends on + ``meta_keys``. By default this includes: + + - ``img_path``: path to the image file. + - ``ori_shape``: original shape of the image as a tuple (H, W). + - ``img_shape``: shape of the image input to the network as a tuple + (H, W). Note that images may be zero padded on the bottom/right + if the batch tensor is larger than this shape. + - ``scale``: scale of the image as a tuple (W, H). + - ``scale_factor``: a float indicating the pre-processing scale. + - ``flip``: a boolean indicating if image flip transform was used. + - ``flip_direction``: the flipping direction. + Args: + meta_keys (Sequence[str], optional): The meta keys to saved in the + ``metainfo`` of the packed ``data_sample``. + """ + default_meta_keys = ('img_path', 'ori_shape', 'img_shape', 'scale', + 'scale_factor') + + def __init__(self, meta_keys: Sequence[str] = ()) -> None: + self.meta_keys = self.default_meta_keys + if meta_keys is not None: + if isinstance(meta_keys, str): + meta_keys = (meta_keys, ) + else: + assert isinstance(meta_keys, tuple), \ + 'meta_keys must be str or tuple.' + self.meta_keys += meta_keys + + def transform(self, results: dict) -> dict: + """Method to pack the input data. + Args: + results (dict): Result dict from the data pipeline. + Returns: + dict: + - 'inputs' (dict[Tensor]): The forward data of models. + - 'data_samples' (obj:`ReIDDataSample`): The meta info of the + sample. + """ + packed_results = dict(inputs=dict(), data_samples=None) + assert 'img' in results, 'Missing the key ``img``.' + _type = type(results['img']) + label = results['gt_label'] + + if _type == list: + img = results['img'] + label = np.stack(label, axis=0) # (N,) + assert all([type(v) == _type for v in results.values()]), \ + 'All items in the results must have the same type.' + else: + img = [results['img']] + + img = np.stack(img, axis=3) # (H, W, C, N) + img = img.transpose(3, 2, 0, 1) # (N, C, H, W) + img = np.ascontiguousarray(img) + + packed_results['inputs'] = to_tensor(img) + + data_sample = ReIDDataSample() + data_sample.set_gt_label(label) + + meta_info = dict() + for key in self.meta_keys: + meta_info[key] = results[key] + data_sample.set_metainfo(meta_info) + packed_results['data_samples'] = data_sample + + return packed_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(meta_keys={self.meta_keys})' + return repr_str diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/frame_sampling.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/frame_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..a91f1e7880f8f061f183dc30a01758d97b7d03da --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/frame_sampling.py @@ -0,0 +1,177 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import random +from collections import defaultdict +from typing import Dict, List, Optional, Union + +from mmcv.transforms import BaseTransform + +from mmdet.registry import TRANSFORMS + + +@TRANSFORMS.register_module() +class BaseFrameSample(BaseTransform): + """Directly get the key frame, no reference frames. + + Args: + collect_video_keys (list[str]): The keys of video info to be + collected. + """ + + def __init__(self, + collect_video_keys: List[str] = ['video_id', 'video_length']): + self.collect_video_keys = collect_video_keys + + def prepare_data(self, video_infos: dict, + sampled_inds: List[int]) -> Dict[str, List]: + """Prepare data for the subsequent pipeline. + + Args: + video_infos (dict): The whole video information. + sampled_inds (list[int]): The sampled frame indices. + + Returns: + dict: The processed data information. + """ + frames_anns = video_infos['images'] + final_data_info = defaultdict(list) + # for data in frames_anns: + for index in sampled_inds: + data = frames_anns[index] + # copy the info in video-level into img-level + for key in self.collect_video_keys: + if key == 'video_length': + data['ori_video_length'] = video_infos[key] + data['video_length'] = len(sampled_inds) + else: + data[key] = video_infos[key] + # Collate data_list (list of dict to dict of list) + for key, value in data.items(): + final_data_info[key].append(value) + + return final_data_info + + def transform(self, video_infos: dict) -> Optional[Dict[str, List]]: + """Transform the video information. + + Args: + video_infos (dict): The whole video information. + + Returns: + dict: The data information of the key frames. + """ + if 'key_frame_id' in video_infos: + key_frame_id = video_infos['key_frame_id'] + assert isinstance(video_infos['key_frame_id'], int) + else: + key_frame_id = random.sample( + list(range(video_infos['video_length'])), 1)[0] + results = self.prepare_data(video_infos, [key_frame_id]) + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(collect_video_keys={self.collect_video_keys})' + return repr_str + + +@TRANSFORMS.register_module() +class UniformRefFrameSample(BaseFrameSample): + """Uniformly sample reference frames. + + Args: + num_ref_imgs (int): Number of reference frames to be sampled. + frame_range (int | list[int]): Range of frames to be sampled around + key frame. If int, the range is [-frame_range, frame_range]. + Defaults to 10. + filter_key_img (bool): Whether to filter the key frame when + sampling reference frames. Defaults to True. + collect_video_keys (list[str]): The keys of video info to be + collected. + """ + + def __init__(self, + num_ref_imgs: int = 1, + frame_range: Union[int, List[int]] = 10, + filter_key_img: bool = True, + collect_video_keys: List[str] = ['video_id', 'video_length']): + self.num_ref_imgs = num_ref_imgs + self.filter_key_img = filter_key_img + if isinstance(frame_range, int): + assert frame_range >= 0, 'frame_range can not be a negative value.' + frame_range = [-frame_range, frame_range] + elif isinstance(frame_range, list): + assert len(frame_range) == 2, 'The length must be 2.' + assert frame_range[0] <= 0 and frame_range[1] >= 0 + for i in frame_range: + assert isinstance(i, int), 'Each element must be int.' + else: + raise TypeError('The type of frame_range must be int or list.') + self.frame_range = frame_range + super().__init__(collect_video_keys=collect_video_keys) + + def sampling_frames(self, video_length: int, key_frame_id: int): + """Sampling frames. + + Args: + video_length (int): The length of the video. + key_frame_id (int): The key frame id. + + Returns: + list[int]: The sampled frame indices. + """ + if video_length > 1: + left = max(0, key_frame_id + self.frame_range[0]) + right = min(key_frame_id + self.frame_range[1], video_length - 1) + frame_ids = list(range(0, video_length)) + + valid_ids = frame_ids[left:right + 1] + if self.filter_key_img and key_frame_id in valid_ids: + valid_ids.remove(key_frame_id) + assert len( + valid_ids + ) > 0, 'After filtering key frame, there are no valid frames' + if len(valid_ids) < self.num_ref_imgs: + valid_ids = valid_ids * self.num_ref_imgs + ref_frame_ids = random.sample(valid_ids, self.num_ref_imgs) + else: + ref_frame_ids = [key_frame_id] * self.num_ref_imgs + + sampled_frames_ids = [key_frame_id] + ref_frame_ids + sampled_frames_ids = sorted(sampled_frames_ids) + + key_frames_ind = sampled_frames_ids.index(key_frame_id) + key_frame_flags = [False] * len(sampled_frames_ids) + key_frame_flags[key_frames_ind] = True + return sampled_frames_ids, key_frame_flags + + def transform(self, video_infos: dict) -> Optional[Dict[str, List]]: + """Transform the video information. + + Args: + video_infos (dict): The whole video information. + + Returns: + dict: The data information of the sampled frames. + """ + if 'key_frame_id' in video_infos: + key_frame_id = video_infos['key_frame_id'] + assert isinstance(video_infos['key_frame_id'], int) + else: + key_frame_id = random.sample( + list(range(video_infos['video_length'])), 1)[0] + + (sampled_frames_ids, key_frame_flags) = self.sampling_frames( + video_infos['video_length'], key_frame_id=key_frame_id) + results = self.prepare_data(video_infos, sampled_frames_ids) + results['key_frame_flags'] = key_frame_flags + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(num_ref_imgs={self.num_ref_imgs}, ' + repr_str += f'frame_range={self.frame_range}, ' + repr_str += f'filter_key_img={self.filter_key_img}, ' + repr_str += f'collect_video_keys={self.collect_video_keys})' + return repr_str diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/geometric.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/geometric.py new file mode 100644 index 0000000000000000000000000000000000000000..d2cd6be258f73a69aa2c2b36fef64c6c4e46a2a4 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/geometric.py @@ -0,0 +1,754 @@ +# Copyright (c) OpenMMLab. All rights reserved. + +from typing import Optional, Union + +import cv2 +import mmcv +import numpy as np +from mmcv.transforms import BaseTransform +from mmcv.transforms.utils import cache_randomness + +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import autocast_box_type +from .augment_wrappers import _MAX_LEVEL, level_to_mag + + +@TRANSFORMS.register_module() +class GeomTransform(BaseTransform): + """Base class for geometric transformations. All geometric transformations + need to inherit from this base class. ``GeomTransform`` unifies the class + attributes and class functions of geometric transformations (ShearX, + ShearY, Rotate, TranslateX, and TranslateY), and records the homography + matrix. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for performing the geometric + transformation and should be in range [0, 1]. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum magnitude for geometric transformation. + Defaults to 0.0. + max_mag (float): The maximum magnitude for geometric transformation. + Defaults to 1.0. + reversal_prob (float): The probability that reverses the geometric + transformation magnitude. Should be in range [0,1]. + Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 1.0, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0 <= prob <= 1.0, f'The probability of the transformation ' \ + f'should be in range [0,1], got {prob}.' + assert level is None or isinstance(level, int), \ + f'The level should be None or type int, got {type(level)}.' + assert level is None or 0 <= level <= _MAX_LEVEL, \ + f'The level should be in range [0,{_MAX_LEVEL}], got {level}.' + assert isinstance(min_mag, float), \ + f'min_mag should be type float, got {type(min_mag)}.' + assert isinstance(max_mag, float), \ + f'max_mag should be type float, got {type(max_mag)}.' + assert min_mag <= max_mag, \ + f'min_mag should smaller than max_mag, ' \ + f'got min_mag={min_mag} and max_mag={max_mag}' + assert isinstance(reversal_prob, float), \ + f'reversal_prob should be type float, got {type(max_mag)}.' + assert 0 <= reversal_prob <= 1.0, \ + f'The reversal probability of the transformation magnitude ' \ + f'should be type float, got {type(reversal_prob)}.' + if isinstance(img_border_value, (float, int)): + img_border_value = tuple([float(img_border_value)] * 3) + elif isinstance(img_border_value, tuple): + assert len(img_border_value) == 3, \ + f'img_border_value as tuple must have 3 elements, ' \ + f'got {len(img_border_value)}.' + img_border_value = tuple([float(val) for val in img_border_value]) + else: + raise ValueError( + 'img_border_value must be float or tuple with 3 elements.') + assert np.all([0 <= val <= 255 for val in img_border_value]), 'all ' \ + 'elements of img_border_value should between range [0,255].' \ + f'got {img_border_value}.' + self.prob = prob + self.level = level + self.min_mag = min_mag + self.max_mag = max_mag + self.reversal_prob = reversal_prob + self.img_border_value = img_border_value + self.mask_border_value = mask_border_value + self.seg_ignore_label = seg_ignore_label + self.interpolation = interpolation + + def _transform_img(self, results: dict, mag: float) -> None: + """Transform the image.""" + pass + + def _transform_masks(self, results: dict, mag: float) -> None: + """Transform the masks.""" + pass + + def _transform_seg(self, results: dict, mag: float) -> None: + """Transform the segmentation map.""" + pass + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for the geometric transformation.""" + return np.eye(3, dtype=np.float32) + + def _transform_bboxes(self, results: dict, mag: float) -> None: + """Transform the bboxes.""" + results['gt_bboxes'].project_(self.homography_matrix) + results['gt_bboxes'].clip_(results['img_shape']) + + def _record_homography_matrix(self, results: dict) -> None: + """Record the homography matrix for the geometric transformation.""" + if results.get('homography_matrix', None) is None: + results['homography_matrix'] = self.homography_matrix + else: + results['homography_matrix'] = self.homography_matrix @ results[ + 'homography_matrix'] + + @cache_randomness + def _random_disable(self): + """Randomly disable the transform.""" + return np.random.rand() > self.prob + + @cache_randomness + def _get_mag(self): + """Get the magnitude of the transform.""" + mag = level_to_mag(self.level, self.min_mag, self.max_mag) + return -mag if np.random.rand() > self.reversal_prob else mag + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function for images, bounding boxes, masks and semantic + segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Transformed results. + """ + + if self._random_disable(): + return results + mag = self._get_mag() + self.homography_matrix = self._get_homography_matrix(results, mag) + self._record_homography_matrix(results) + self._transform_img(results, mag) + if results.get('gt_bboxes', None) is not None: + self._transform_bboxes(results, mag) + if results.get('gt_masks', None) is not None: + self._transform_masks(results, mag) + if results.get('gt_seg_map', None) is not None: + self._transform_seg(results, mag) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'level={self.level}, ' + repr_str += f'min_mag={self.min_mag}, ' + repr_str += f'max_mag={self.max_mag}, ' + repr_str += f'reversal_prob={self.reversal_prob}, ' + repr_str += f'img_border_value={self.img_border_value}, ' + repr_str += f'mask_border_value={self.mask_border_value}, ' + repr_str += f'seg_ignore_label={self.seg_ignore_label}, ' + repr_str += f'interpolation={self.interpolation})' + return repr_str + + +@TRANSFORMS.register_module() +class ShearX(GeomTransform): + """Shear the images, bboxes, masks and segmentation map horizontally. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for performing Shear and should be in + range [0, 1]. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum angle for the horizontal shear. + Defaults to 0.0. + max_mag (float): The maximum angle for the horizontal shear. + Defaults to 30.0. + reversal_prob (float): The probability that reverses the horizontal + shear magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 30.0, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 90., \ + f'min_mag angle for ShearX should be ' \ + f'in range [0, 90], got {min_mag}.' + assert 0. <= max_mag <= 90., \ + f'max_mag angle for ShearX should be ' \ + f'in range [0, 90], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + @cache_randomness + def _get_mag(self): + """Get the magnitude of the transform.""" + mag = level_to_mag(self.level, self.min_mag, self.max_mag) + mag = np.tan(mag * np.pi / 180) + return -mag if np.random.rand() > self.reversal_prob else mag + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for ShearX.""" + return np.array([[1, mag, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Shear the image horizontally.""" + results['img'] = mmcv.imshear( + results['img'], + mag, + direction='horizontal', + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Shear the masks horizontally.""" + results['gt_masks'] = results['gt_masks'].shear( + results['img_shape'], + mag, + direction='horizontal', + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Shear the segmentation map horizontally.""" + results['gt_seg_map'] = mmcv.imshear( + results['gt_seg_map'], + mag, + direction='horizontal', + border_value=self.seg_ignore_label, + interpolation='nearest') + + +@TRANSFORMS.register_module() +class ShearY(GeomTransform): + """Shear the images, bboxes, masks and segmentation map vertically. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for performing ShearY and should be in + range [0, 1]. Defaults to 1.0. + level (int, optional): The level should be in range [0,_MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum angle for the vertical shear. + Defaults to 0.0. + max_mag (float): The maximum angle for the vertical shear. + Defaults to 30.0. + reversal_prob (float): The probability that reverses the vertical + shear magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 30., + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 90., \ + f'min_mag angle for ShearY should be ' \ + f'in range [0, 90], got {min_mag}.' + assert 0. <= max_mag <= 90., \ + f'max_mag angle for ShearY should be ' \ + f'in range [0, 90], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + @cache_randomness + def _get_mag(self): + """Get the magnitude of the transform.""" + mag = level_to_mag(self.level, self.min_mag, self.max_mag) + mag = np.tan(mag * np.pi / 180) + return -mag if np.random.rand() > self.reversal_prob else mag + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for ShearY.""" + return np.array([[1, 0, 0], [mag, 1, 0], [0, 0, 1]], dtype=np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Shear the image vertically.""" + results['img'] = mmcv.imshear( + results['img'], + mag, + direction='vertical', + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Shear the masks vertically.""" + results['gt_masks'] = results['gt_masks'].shear( + results['img_shape'], + mag, + direction='vertical', + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Shear the segmentation map vertically.""" + results['gt_seg_map'] = mmcv.imshear( + results['gt_seg_map'], + mag, + direction='vertical', + border_value=self.seg_ignore_label, + interpolation='nearest') + + +@TRANSFORMS.register_module() +class Rotate(GeomTransform): + """Rotate the images, bboxes, masks and segmentation map. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for perform transformation and + should be in range 0 to 1. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The maximum angle for rotation. + Defaults to 0.0. + max_mag (float): The maximum angle for rotation. + Defaults to 30.0. + reversal_prob (float): The probability that reverses the rotation + magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 30.0, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 180., \ + f'min_mag for Rotate should be in range [0,180], got {min_mag}.' + assert 0. <= max_mag <= 180., \ + f'max_mag for Rotate should be in range [0,180], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for Rotate.""" + img_shape = results['img_shape'] + center = ((img_shape[1] - 1) * 0.5, (img_shape[0] - 1) * 0.5) + cv2_rotation_matrix = cv2.getRotationMatrix2D(center, -mag, 1.0) + return np.concatenate( + [cv2_rotation_matrix, + np.array([0, 0, 1]).reshape((1, 3))]).astype(np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Rotate the image.""" + results['img'] = mmcv.imrotate( + results['img'], + mag, + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Rotate the masks.""" + results['gt_masks'] = results['gt_masks'].rotate( + results['img_shape'], + mag, + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Rotate the segmentation map.""" + results['gt_seg_map'] = mmcv.imrotate( + results['gt_seg_map'], + mag, + border_value=self.seg_ignore_label, + interpolation='nearest') + + +@TRANSFORMS.register_module() +class TranslateX(GeomTransform): + """Translate the images, bboxes, masks and segmentation map horizontally. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for perform transformation and + should be in range 0 to 1. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum pixel's offset ratio for horizontal + translation. Defaults to 0.0. + max_mag (float): The maximum pixel's offset ratio for horizontal + translation. Defaults to 0.1. + reversal_prob (float): The probability that reverses the horizontal + translation magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 0.1, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 1., \ + f'min_mag ratio for TranslateX should be ' \ + f'in range [0, 1], got {min_mag}.' + assert 0. <= max_mag <= 1., \ + f'max_mag ratio for TranslateX should be ' \ + f'in range [0, 1], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for TranslateX.""" + mag = int(results['img_shape'][1] * mag) + return np.array([[1, 0, mag], [0, 1, 0], [0, 0, 1]], dtype=np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Translate the image horizontally.""" + mag = int(results['img_shape'][1] * mag) + results['img'] = mmcv.imtranslate( + results['img'], + mag, + direction='horizontal', + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Translate the masks horizontally.""" + mag = int(results['img_shape'][1] * mag) + results['gt_masks'] = results['gt_masks'].translate( + results['img_shape'], + mag, + direction='horizontal', + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Translate the segmentation map horizontally.""" + mag = int(results['img_shape'][1] * mag) + results['gt_seg_map'] = mmcv.imtranslate( + results['gt_seg_map'], + mag, + direction='horizontal', + border_value=self.seg_ignore_label, + interpolation='nearest') + + +@TRANSFORMS.register_module() +class TranslateY(GeomTransform): + """Translate the images, bboxes, masks and segmentation map vertically. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - homography_matrix + + Args: + prob (float): The probability for perform transformation and + should be in range 0 to 1. Defaults to 1.0. + level (int, optional): The level should be in range [0, _MAX_LEVEL]. + If level is None, it will generate from [0, _MAX_LEVEL] randomly. + Defaults to None. + min_mag (float): The minimum pixel's offset ratio for vertical + translation. Defaults to 0.0. + max_mag (float): The maximum pixel's offset ratio for vertical + translation. Defaults to 0.1. + reversal_prob (float): The probability that reverses the vertical + translation magnitude. Should be in range [0,1]. Defaults to 0.5. + img_border_value (int | float | tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + prob: float = 1.0, + level: Optional[int] = None, + min_mag: float = 0.0, + max_mag: float = 0.1, + reversal_prob: float = 0.5, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + interpolation: str = 'bilinear') -> None: + assert 0. <= min_mag <= 1., \ + f'min_mag ratio for TranslateY should be ' \ + f'in range [0,1], got {min_mag}.' + assert 0. <= max_mag <= 1., \ + f'max_mag ratio for TranslateY should be ' \ + f'in range [0,1], got {max_mag}.' + super().__init__( + prob=prob, + level=level, + min_mag=min_mag, + max_mag=max_mag, + reversal_prob=reversal_prob, + img_border_value=img_border_value, + mask_border_value=mask_border_value, + seg_ignore_label=seg_ignore_label, + interpolation=interpolation) + + def _get_homography_matrix(self, results: dict, mag: float) -> np.ndarray: + """Get the homography matrix for TranslateY.""" + mag = int(results['img_shape'][0] * mag) + return np.array([[1, 0, 0], [0, 1, mag], [0, 0, 1]], dtype=np.float32) + + def _transform_img(self, results: dict, mag: float) -> None: + """Translate the image vertically.""" + mag = int(results['img_shape'][0] * mag) + results['img'] = mmcv.imtranslate( + results['img'], + mag, + direction='vertical', + border_value=self.img_border_value, + interpolation=self.interpolation) + + def _transform_masks(self, results: dict, mag: float) -> None: + """Translate masks vertically.""" + mag = int(results['img_shape'][0] * mag) + results['gt_masks'] = results['gt_masks'].translate( + results['img_shape'], + mag, + direction='vertical', + border_value=self.mask_border_value, + interpolation=self.interpolation) + + def _transform_seg(self, results: dict, mag: float) -> None: + """Translate segmentation map vertically.""" + mag = int(results['img_shape'][0] * mag) + results['gt_seg_map'] = mmcv.imtranslate( + results['gt_seg_map'], + mag, + direction='vertical', + border_value=self.seg_ignore_label, + interpolation='nearest') diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/instaboost.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/instaboost.py new file mode 100644 index 0000000000000000000000000000000000000000..30dc1603643ec8d398bfade95f5ec1c9b8f89c8d --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/instaboost.py @@ -0,0 +1,150 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Tuple + +import numpy as np +from mmcv.transforms import BaseTransform + +from mmdet.registry import TRANSFORMS + + +@TRANSFORMS.register_module() +class InstaBoost(BaseTransform): + r"""Data augmentation method in `InstaBoost: Boosting Instance + Segmentation Via Probability Map Guided Copy-Pasting + `_. + + Refer to https://github.com/GothicAi/Instaboost for implementation details. + + + Required Keys: + + - img (np.uint8) + - instances + + Modified Keys: + + - img (np.uint8) + - instances + + Args: + action_candidate (tuple): Action candidates. "normal", "horizontal", \ + "vertical", "skip" are supported. Defaults to ('normal', \ + 'horizontal', 'skip'). + action_prob (tuple): Corresponding action probabilities. Should be \ + the same length as action_candidate. Defaults to (1, 0, 0). + scale (tuple): (min scale, max scale). Defaults to (0.8, 1.2). + dx (int): The maximum x-axis shift will be (instance width) / dx. + Defaults to 15. + dy (int): The maximum y-axis shift will be (instance height) / dy. + Defaults to 15. + theta (tuple): (min rotation degree, max rotation degree). \ + Defaults to (-1, 1). + color_prob (float): Probability of images for color augmentation. + Defaults to 0.5. + hflag (bool): Whether to use heatmap guided. Defaults to False. + aug_ratio (float): Probability of applying this transformation. \ + Defaults to 0.5. + """ + + def __init__(self, + action_candidate: tuple = ('normal', 'horizontal', 'skip'), + action_prob: tuple = (1, 0, 0), + scale: tuple = (0.8, 1.2), + dx: int = 15, + dy: int = 15, + theta: tuple = (-1, 1), + color_prob: float = 0.5, + hflag: bool = False, + aug_ratio: float = 0.5) -> None: + + import matplotlib + import matplotlib.pyplot as plt + default_backend = plt.get_backend() + + try: + import instaboostfast as instaboost + except ImportError: + raise ImportError( + 'Please run "pip install instaboostfast" ' + 'to install instaboostfast first for instaboost augmentation.') + + # instaboost will modify the default backend + # and cause visualization to fail. + matplotlib.use(default_backend) + + self.cfg = instaboost.InstaBoostConfig(action_candidate, action_prob, + scale, dx, dy, theta, + color_prob, hflag) + self.aug_ratio = aug_ratio + + def _load_anns(self, results: dict) -> Tuple[list, list]: + """Convert raw anns to instaboost expected input format.""" + anns = [] + ignore_anns = [] + for instance in results['instances']: + label = instance['bbox_label'] + bbox = instance['bbox'] + mask = instance['mask'] + x1, y1, x2, y2 = bbox + # assert (x2 - x1) >= 1 and (y2 - y1) >= 1 + bbox = [x1, y1, x2 - x1, y2 - y1] + + if instance['ignore_flag'] == 0: + anns.append({ + 'category_id': label, + 'segmentation': mask, + 'bbox': bbox + }) + else: + # Ignore instances without data augmentation + ignore_anns.append(instance) + return anns, ignore_anns + + def _parse_anns(self, results: dict, anns: list, ignore_anns: list, + img: np.ndarray) -> dict: + """Restore the result of instaboost processing to the original anns + format.""" + instances = [] + for ann in anns: + x1, y1, w, h = ann['bbox'] + # TODO: more essential bug need to be fixed in instaboost + if w <= 0 or h <= 0: + continue + bbox = [x1, y1, x1 + w, y1 + h] + instances.append( + dict( + bbox=bbox, + bbox_label=ann['category_id'], + mask=ann['segmentation'], + ignore_flag=0)) + + instances.extend(ignore_anns) + results['img'] = img + results['instances'] = instances + return results + + def transform(self, results) -> dict: + """The transform function.""" + img = results['img'] + ori_type = img.dtype + if 'instances' not in results or len(results['instances']) == 0: + return results + + anns, ignore_anns = self._load_anns(results) + if np.random.choice([0, 1], p=[1 - self.aug_ratio, self.aug_ratio]): + try: + import instaboostfast as instaboost + except ImportError: + raise ImportError('Please run "pip install instaboostfast" ' + 'to install instaboostfast first.') + anns, img = instaboost.get_new_data( + anns, img.astype(np.uint8), self.cfg, background=None) + + results = self._parse_anns(results, anns, ignore_anns, + img.astype(ori_type)) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(aug_ratio={self.aug_ratio})' + return repr_str diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/loading.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/loading.py new file mode 100644 index 0000000000000000000000000000000000000000..722d4b0e7c830dfde2412746db1258b880167a2f --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/loading.py @@ -0,0 +1,1074 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional, Tuple, Union + +import mmcv +import numpy as np +import pycocotools.mask as maskUtils +import torch +from mmcv.transforms import BaseTransform +from mmcv.transforms import LoadAnnotations as MMCV_LoadAnnotations +from mmcv.transforms import LoadImageFromFile +from mmengine.fileio import get +from mmengine.structures import BaseDataElement + +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import get_box_type +from mmdet.structures.bbox.box_type import autocast_box_type +from mmdet.structures.mask import BitmapMasks, PolygonMasks + + +@TRANSFORMS.register_module() +class LoadImageFromNDArray(LoadImageFromFile): + """Load an image from ``results['img']``. + + Similar with :obj:`LoadImageFromFile`, but the image has been loaded as + :obj:`np.ndarray` in ``results['img']``. Can be used when loading image + from webcam. + + Required Keys: + + - img + + Modified Keys: + + - img + - img_path + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + """ + + def transform(self, results: dict) -> dict: + """Transform function to add image meta information. + + Args: + results (dict): Result dict with Webcam read image in + ``results['img']``. + + Returns: + dict: The dict contains loaded image and meta information. + """ + + img = results['img'] + if self.to_float32: + img = img.astype(np.float32) + + results['img_path'] = None + results['img'] = img + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + return results + + +@TRANSFORMS.register_module() +class LoadMultiChannelImageFromFiles(BaseTransform): + """Load multi-channel images from a list of separate channel files. + + Required Keys: + + - img_path + + Modified Keys: + + - img + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + color_type (str): The flag argument for :func:``mmcv.imfrombytes``. + Defaults to 'unchanged'. + imdecode_backend (str): The image decoding backend type. The backend + argument for :func:``mmcv.imfrombytes``. + See :func:``mmcv.imfrombytes`` for details. + Defaults to 'cv2'. + file_client_args (dict): Arguments to instantiate the + corresponding backend in mmdet <= 3.0.0rc6. Defaults to None. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend in mmdet >= 3.0.0rc7. Defaults to None. + """ + + def __init__( + self, + to_float32: bool = False, + color_type: str = 'unchanged', + imdecode_backend: str = 'cv2', + file_client_args: dict = None, + backend_args: dict = None, + ) -> None: + self.to_float32 = to_float32 + self.color_type = color_type + self.imdecode_backend = imdecode_backend + self.backend_args = backend_args + if file_client_args is not None: + raise RuntimeError( + 'The `file_client_args` is deprecated, ' + 'please use `backend_args` instead, please refer to' + 'https://github.com/open-mmlab/mmdetection/blob/main/configs/_base_/datasets/coco_detection.py' # noqa: E501 + ) + + def transform(self, results: dict) -> dict: + """Transform functions to load multiple images and get images meta + information. + + Args: + results (dict): Result dict from :obj:`mmdet.CustomDataset`. + + Returns: + dict: The dict contains loaded images and meta information. + """ + + assert isinstance(results['img_path'], list) + img = [] + for name in results['img_path']: + img_bytes = get(name, backend_args=self.backend_args) + img.append( + mmcv.imfrombytes( + img_bytes, + flag=self.color_type, + backend=self.imdecode_backend)) + img = np.stack(img, axis=-1) + if self.to_float32: + img = img.astype(np.float32) + + results['img'] = img + results['img_shape'] = img.shape[:2] + results['ori_shape'] = img.shape[:2] + return results + + def __repr__(self): + repr_str = (f'{self.__class__.__name__}(' + f'to_float32={self.to_float32}, ' + f"color_type='{self.color_type}', " + f"imdecode_backend='{self.imdecode_backend}', " + f'backend_args={self.backend_args})') + return repr_str + + +@TRANSFORMS.register_module() +class LoadAnnotations(MMCV_LoadAnnotations): + """Load and process the ``instances`` and ``seg_map`` annotation provided + by dataset. + + The annotation format is as the following: + + .. code-block:: python + + { + 'instances': + [ + { + # List of 4 numbers representing the bounding box of the + # instance, in (x1, y1, x2, y2) order. + 'bbox': [x1, y1, x2, y2], + + # Label of image classification. + 'bbox_label': 1, + + # Used in instance/panoptic segmentation. The segmentation mask + # of the instance or the information of segments. + # 1. If list[list[float]], it represents a list of polygons, + # one for each connected component of the object. Each + # list[float] is one simple polygon in the format of + # [x1, y1, ..., xn, yn] (n >= 3). The Xs and Ys are absolute + # coordinates in unit of pixels. + # 2. If dict, it represents the per-pixel segmentation mask in + # COCO's compressed RLE format. The dict should have keys + # “size” and “counts”. Can be loaded by pycocotools + 'mask': list[list[float]] or dict, + + } + ] + # Filename of semantic or panoptic segmentation ground truth file. + 'seg_map_path': 'a/b/c' + } + + After this module, the annotation has been changed to the format below: + + .. code-block:: python + + { + # In (x1, y1, x2, y2) order, float type. N is the number of bboxes + # in an image + 'gt_bboxes': BaseBoxes(N, 4) + # In int type. + 'gt_bboxes_labels': np.ndarray(N, ) + # In built-in class + 'gt_masks': PolygonMasks (H, W) or BitmapMasks (H, W) + # In uint8 type. + 'gt_seg_map': np.ndarray (H, W) + # in (x, y, v) order, float type. + } + + Required Keys: + + - height + - width + - instances + + - bbox (optional) + - bbox_label + - mask (optional) + - ignore_flag + + - seg_map_path (optional) + + Added Keys: + + - gt_bboxes (BaseBoxes[torch.float32]) + - gt_bboxes_labels (np.int64) + - gt_masks (BitmapMasks | PolygonMasks) + - gt_seg_map (np.uint8) + - gt_ignore_flags (bool) + + Args: + with_bbox (bool): Whether to parse and load the bbox annotation. + Defaults to True. + with_label (bool): Whether to parse and load the label annotation. + Defaults to True. + with_mask (bool): Whether to parse and load the mask annotation. + Default: False. + with_seg (bool): Whether to parse and load the semantic segmentation + annotation. Defaults to False. + poly2mask (bool): Whether to convert mask to bitmap. Default: True. + box_type (str): The box type used to wrap the bboxes. If ``box_type`` + is None, gt_bboxes will keep being np.ndarray. Defaults to 'hbox'. + reduce_zero_label (bool): Whether reduce all label value + by 1. Usually used for datasets where 0 is background label. + Defaults to False. + ignore_index (int): The label index to be ignored. + Valid only if reduce_zero_label is true. Defaults is 255. + imdecode_backend (str): The image decoding backend type. The backend + argument for :func:``mmcv.imfrombytes``. + See :fun:``mmcv.imfrombytes`` for details. + Defaults to 'cv2'. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + """ + + def __init__( + self, + with_mask: bool = False, + poly2mask: bool = True, + box_type: str = 'hbox', + # use for semseg + reduce_zero_label: bool = False, + ignore_index: int = 255, + **kwargs) -> None: + super(LoadAnnotations, self).__init__(**kwargs) + self.with_mask = with_mask + self.poly2mask = poly2mask + self.box_type = box_type + self.reduce_zero_label = reduce_zero_label + self.ignore_index = ignore_index + + def _load_bboxes(self, results: dict) -> None: + """Private function to load bounding box annotations. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + Returns: + dict: The dict contains loaded bounding box annotations. + """ + gt_bboxes = [] + gt_ignore_flags = [] + for instance in results.get('instances', []): + gt_bboxes.append(instance['bbox']) + gt_ignore_flags.append(instance['ignore_flag']) + if self.box_type is None: + results['gt_bboxes'] = np.array( + gt_bboxes, dtype=np.float32).reshape((-1, 4)) + else: + _, box_type_cls = get_box_type(self.box_type) + results['gt_bboxes'] = box_type_cls(gt_bboxes, dtype=torch.float32) + results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool) + + def _load_labels(self, results: dict) -> None: + """Private function to load label annotations. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + + Returns: + dict: The dict contains loaded label annotations. + """ + gt_bboxes_labels = [] + for instance in results.get('instances', []): + gt_bboxes_labels.append(instance['bbox_label']) + # TODO: Inconsistent with mmcv, consider how to deal with it later. + results['gt_bboxes_labels'] = np.array( + gt_bboxes_labels, dtype=np.int64) + + def _poly2mask(self, mask_ann: Union[list, dict], img_h: int, + img_w: int) -> np.ndarray: + """Private function to convert masks represented with polygon to + bitmaps. + + Args: + mask_ann (list | dict): Polygon mask annotation input. + img_h (int): The height of output mask. + img_w (int): The width of output mask. + + Returns: + np.ndarray: The decode bitmap mask of shape (img_h, img_w). + """ + + if isinstance(mask_ann, list): + # polygon -- a single object might consist of multiple parts + # we merge all parts into one mask rle code + rles = maskUtils.frPyObjects(mask_ann, img_h, img_w) + rle = maskUtils.merge(rles) + elif isinstance(mask_ann['counts'], list): + # uncompressed RLE + rle = maskUtils.frPyObjects(mask_ann, img_h, img_w) + else: + # rle + rle = mask_ann + mask = maskUtils.decode(rle) + return mask + + def _process_masks(self, results: dict) -> list: + """Process gt_masks and filter invalid polygons. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + + Returns: + list: Processed gt_masks. + """ + gt_masks = [] + gt_ignore_flags = [] + for instance in results.get('instances', []): + gt_mask = instance['mask'] + # If the annotation of segmentation mask is invalid, + # ignore the whole instance. + if isinstance(gt_mask, list): + gt_mask = [ + np.array(polygon) for polygon in gt_mask + if len(polygon) % 2 == 0 and len(polygon) >= 6 + ] + if len(gt_mask) == 0: + # ignore this instance and set gt_mask to a fake mask + instance['ignore_flag'] = 1 + gt_mask = [np.zeros(6)] + elif not self.poly2mask: + # `PolygonMasks` requires a ploygon of format List[np.array], + # other formats are invalid. + instance['ignore_flag'] = 1 + gt_mask = [np.zeros(6)] + elif isinstance(gt_mask, dict) and \ + not (gt_mask.get('counts') is not None and + gt_mask.get('size') is not None and + isinstance(gt_mask['counts'], (list, str))): + # if gt_mask is a dict, it should include `counts` and `size`, + # so that `BitmapMasks` can uncompressed RLE + instance['ignore_flag'] = 1 + gt_mask = [np.zeros(6)] + gt_masks.append(gt_mask) + # re-process gt_ignore_flags + gt_ignore_flags.append(instance['ignore_flag']) + results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool) + return gt_masks + + def _load_masks(self, results: dict) -> None: + """Private function to load mask annotations. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + """ + h, w = results['ori_shape'] + gt_masks = self._process_masks(results) + if self.poly2mask: + gt_masks = BitmapMasks( + [self._poly2mask(mask, h, w) for mask in gt_masks], h, w) + else: + # fake polygon masks will be ignored in `PackDetInputs` + gt_masks = PolygonMasks([mask for mask in gt_masks], h, w) + results['gt_masks'] = gt_masks + + def _load_seg_map(self, results: dict) -> None: + """Private function to load semantic segmentation annotations. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded semantic segmentation annotations. + """ + if results.get('seg_map_path', None) is None: + return + + img_bytes = get( + results['seg_map_path'], backend_args=self.backend_args) + gt_semantic_seg = mmcv.imfrombytes( + img_bytes, flag='unchanged', + backend=self.imdecode_backend).squeeze() + + if self.reduce_zero_label: + # avoid using underflow conversion + gt_semantic_seg[gt_semantic_seg == 0] = self.ignore_index + gt_semantic_seg = gt_semantic_seg - 1 + gt_semantic_seg[gt_semantic_seg == self.ignore_index - + 1] = self.ignore_index + + # modify if custom classes + if results.get('label_map', None) is not None: + # Add deep copy to solve bug of repeatedly + # replace `gt_semantic_seg`, which is reported in + # https://github.com/open-mmlab/mmsegmentation/pull/1445/ + gt_semantic_seg_copy = gt_semantic_seg.copy() + for old_id, new_id in results['label_map'].items(): + gt_semantic_seg[gt_semantic_seg_copy == old_id] = new_id + results['gt_seg_map'] = gt_semantic_seg + results['ignore_index'] = self.ignore_index + + def transform(self, results: dict) -> dict: + """Function to load multiple types annotations. + + Args: + results (dict): Result dict from :obj:``mmengine.BaseDataset``. + + Returns: + dict: The dict contains loaded bounding box, label and + semantic segmentation. + """ + + if self.with_bbox: + self._load_bboxes(results) + if self.with_label: + self._load_labels(results) + if self.with_mask: + self._load_masks(results) + if self.with_seg: + self._load_seg_map(results) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(with_bbox={self.with_bbox}, ' + repr_str += f'with_label={self.with_label}, ' + repr_str += f'with_mask={self.with_mask}, ' + repr_str += f'with_seg={self.with_seg}, ' + repr_str += f'poly2mask={self.poly2mask}, ' + repr_str += f"imdecode_backend='{self.imdecode_backend}', " + repr_str += f'backend_args={self.backend_args})' + return repr_str + + +@TRANSFORMS.register_module() +class LoadPanopticAnnotations(LoadAnnotations): + """Load multiple types of panoptic annotations. + + The annotation format is as the following: + + .. code-block:: python + + { + 'instances': + [ + { + # List of 4 numbers representing the bounding box of the + # instance, in (x1, y1, x2, y2) order. + 'bbox': [x1, y1, x2, y2], + + # Label of image classification. + 'bbox_label': 1, + }, + ... + ] + 'segments_info': + [ + { + # id = cls_id + instance_id * INSTANCE_OFFSET + 'id': int, + + # Contiguous category id defined in dataset. + 'category': int + + # Thing flag. + 'is_thing': bool + }, + ... + ] + + # Filename of semantic or panoptic segmentation ground truth file. + 'seg_map_path': 'a/b/c' + } + + After this module, the annotation has been changed to the format below: + + .. code-block:: python + + { + # In (x1, y1, x2, y2) order, float type. N is the number of bboxes + # in an image + 'gt_bboxes': BaseBoxes(N, 4) + # In int type. + 'gt_bboxes_labels': np.ndarray(N, ) + # In built-in class + 'gt_masks': PolygonMasks (H, W) or BitmapMasks (H, W) + # In uint8 type. + 'gt_seg_map': np.ndarray (H, W) + # in (x, y, v) order, float type. + } + + Required Keys: + + - height + - width + - instances + - bbox + - bbox_label + - ignore_flag + - segments_info + - id + - category + - is_thing + - seg_map_path + + Added Keys: + + - gt_bboxes (BaseBoxes[torch.float32]) + - gt_bboxes_labels (np.int64) + - gt_masks (BitmapMasks | PolygonMasks) + - gt_seg_map (np.uint8) + - gt_ignore_flags (bool) + + Args: + with_bbox (bool): Whether to parse and load the bbox annotation. + Defaults to True. + with_label (bool): Whether to parse and load the label annotation. + Defaults to True. + with_mask (bool): Whether to parse and load the mask annotation. + Defaults to True. + with_seg (bool): Whether to parse and load the semantic segmentation + annotation. Defaults to False. + box_type (str): The box mode used to wrap the bboxes. + imdecode_backend (str): The image decoding backend type. The backend + argument for :func:``mmcv.imfrombytes``. + See :fun:``mmcv.imfrombytes`` for details. + Defaults to 'cv2'. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend in mmdet >= 3.0.0rc7. Defaults to None. + """ + + def __init__(self, + with_bbox: bool = True, + with_label: bool = True, + with_mask: bool = True, + with_seg: bool = True, + box_type: str = 'hbox', + imdecode_backend: str = 'cv2', + backend_args: dict = None) -> None: + try: + from panopticapi import utils + except ImportError: + raise ImportError( + 'panopticapi is not installed, please install it by: ' + 'pip install git+https://github.com/cocodataset/' + 'panopticapi.git.') + self.rgb2id = utils.rgb2id + + super(LoadPanopticAnnotations, self).__init__( + with_bbox=with_bbox, + with_label=with_label, + with_mask=with_mask, + with_seg=with_seg, + with_keypoints=False, + box_type=box_type, + imdecode_backend=imdecode_backend, + backend_args=backend_args) + + def _load_masks_and_semantic_segs(self, results: dict) -> None: + """Private function to load mask and semantic segmentation annotations. + + In gt_semantic_seg, the foreground label is from ``0`` to + ``num_things - 1``, the background label is from ``num_things`` to + ``num_things + num_stuff - 1``, 255 means the ignored label (``VOID``). + + Args: + results (dict): Result dict from :obj:``mmdet.CustomDataset``. + """ + # seg_map_path is None, when inference on the dataset without gts. + if results.get('seg_map_path', None) is None: + return + + img_bytes = get( + results['seg_map_path'], backend_args=self.backend_args) + pan_png = mmcv.imfrombytes( + img_bytes, flag='color', channel_order='rgb').squeeze() + pan_png = self.rgb2id(pan_png) + + gt_masks = [] + gt_seg = np.zeros_like(pan_png) + 255 # 255 as ignore + + for segment_info in results['segments_info']: + mask = (pan_png == segment_info['id']) + gt_seg = np.where(mask, segment_info['category'], gt_seg) + + # The legal thing masks + if segment_info.get('is_thing'): + gt_masks.append(mask.astype(np.uint8)) + + if self.with_mask: + h, w = results['ori_shape'] + gt_masks = BitmapMasks(gt_masks, h, w) + results['gt_masks'] = gt_masks + + if self.with_seg: + results['gt_seg_map'] = gt_seg + + def transform(self, results: dict) -> dict: + """Function to load multiple types panoptic annotations. + + Args: + results (dict): Result dict from :obj:``mmdet.CustomDataset``. + + Returns: + dict: The dict contains loaded bounding box, label, mask and + semantic segmentation annotations. + """ + + if self.with_bbox: + self._load_bboxes(results) + if self.with_label: + self._load_labels(results) + if self.with_mask or self.with_seg: + # The tasks completed by '_load_masks' and '_load_semantic_segs' + # in LoadAnnotations are merged to one function. + self._load_masks_and_semantic_segs(results) + + return results + + +@TRANSFORMS.register_module() +class LoadProposals(BaseTransform): + """Load proposal pipeline. + + Required Keys: + + - proposals + + Modified Keys: + + - proposals + + Args: + num_max_proposals (int, optional): Maximum number of proposals to load. + If not specified, all proposals will be loaded. + """ + + def __init__(self, num_max_proposals: Optional[int] = None) -> None: + self.num_max_proposals = num_max_proposals + + def transform(self, results: dict) -> dict: + """Transform function to load proposals from file. + + Args: + results (dict): Result dict from :obj:`mmdet.CustomDataset`. + + Returns: + dict: The dict contains loaded proposal annotations. + """ + + proposals = results['proposals'] + # the type of proposals should be `dict` or `InstanceData` + assert isinstance(proposals, dict) \ + or isinstance(proposals, BaseDataElement) + bboxes = proposals['bboxes'].astype(np.float32) + assert bboxes.shape[1] == 4, \ + f'Proposals should have shapes (n, 4), but found {bboxes.shape}' + + if 'scores' in proposals: + scores = proposals['scores'].astype(np.float32) + assert bboxes.shape[0] == scores.shape[0] + else: + scores = np.zeros(bboxes.shape[0], dtype=np.float32) + + if self.num_max_proposals is not None: + # proposals should sort by scores during dumping the proposals + bboxes = bboxes[:self.num_max_proposals] + scores = scores[:self.num_max_proposals] + + if len(bboxes) == 0: + bboxes = np.zeros((0, 4), dtype=np.float32) + scores = np.zeros(0, dtype=np.float32) + + results['proposals'] = bboxes + results['proposals_scores'] = scores + return results + + def __repr__(self): + return self.__class__.__name__ + \ + f'(num_max_proposals={self.num_max_proposals})' + + +@TRANSFORMS.register_module() +class FilterAnnotations(BaseTransform): + """Filter invalid annotations. + + Required Keys: + + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_masks (optional) + - gt_ignore_flags (optional) + + Args: + min_gt_bbox_wh (tuple[float]): Minimum width and height of ground truth + boxes. Default: (1., 1.) + min_gt_mask_area (int): Minimum foreground area of ground truth masks. + Default: 1 + by_box (bool): Filter instances with bounding boxes not meeting the + min_gt_bbox_wh threshold. Default: True + by_mask (bool): Filter instances with masks not meeting + min_gt_mask_area threshold. Default: False + keep_empty (bool): Whether to return None when it + becomes an empty bbox after filtering. Defaults to True. + """ + + def __init__(self, + min_gt_bbox_wh: Tuple[int, int] = (1, 1), + min_gt_mask_area: int = 1, + by_box: bool = True, + by_mask: bool = False, + keep_empty: bool = True) -> None: + # TODO: add more filter options + assert by_box or by_mask + self.min_gt_bbox_wh = min_gt_bbox_wh + self.min_gt_mask_area = min_gt_mask_area + self.by_box = by_box + self.by_mask = by_mask + self.keep_empty = keep_empty + + @autocast_box_type() + def transform(self, results: dict) -> Union[dict, None]: + """Transform function to filter annotations. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + assert 'gt_bboxes' in results + gt_bboxes = results['gt_bboxes'] + if gt_bboxes.shape[0] == 0: + return results + + tests = [] + if self.by_box: + tests.append( + ((gt_bboxes.widths > self.min_gt_bbox_wh[0]) & + (gt_bboxes.heights > self.min_gt_bbox_wh[1])).numpy()) + if self.by_mask: + assert 'gt_masks' in results + gt_masks = results['gt_masks'] + tests.append(gt_masks.areas >= self.min_gt_mask_area) + + keep = tests[0] + for t in tests[1:]: + keep = keep & t + + if not keep.any(): + if self.keep_empty: + return None + + keys = ('gt_bboxes', 'gt_bboxes_labels', 'gt_masks', 'gt_ignore_flags') + for key in keys: + if key in results: + results[key] = results[key][keep] + + return results + + def __repr__(self): + return self.__class__.__name__ + \ + f'(min_gt_bbox_wh={self.min_gt_bbox_wh}, ' \ + f'keep_empty={self.keep_empty})' + + +@TRANSFORMS.register_module() +class LoadEmptyAnnotations(BaseTransform): + """Load Empty Annotations for unlabeled images. + + Added Keys: + - gt_bboxes (np.float32) + - gt_bboxes_labels (np.int64) + - gt_masks (BitmapMasks | PolygonMasks) + - gt_seg_map (np.uint8) + - gt_ignore_flags (bool) + + Args: + with_bbox (bool): Whether to load the pseudo bbox annotation. + Defaults to True. + with_label (bool): Whether to load the pseudo label annotation. + Defaults to True. + with_mask (bool): Whether to load the pseudo mask annotation. + Default: False. + with_seg (bool): Whether to load the pseudo semantic segmentation + annotation. Defaults to False. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + """ + + def __init__(self, + with_bbox: bool = True, + with_label: bool = True, + with_mask: bool = False, + with_seg: bool = False, + seg_ignore_label: int = 255) -> None: + self.with_bbox = with_bbox + self.with_label = with_label + self.with_mask = with_mask + self.with_seg = with_seg + self.seg_ignore_label = seg_ignore_label + + def transform(self, results: dict) -> dict: + """Transform function to load empty annotations. + + Args: + results (dict): Result dict. + Returns: + dict: Updated result dict. + """ + if self.with_bbox: + results['gt_bboxes'] = np.zeros((0, 4), dtype=np.float32) + results['gt_ignore_flags'] = np.zeros((0, ), dtype=bool) + if self.with_label: + results['gt_bboxes_labels'] = np.zeros((0, ), dtype=np.int64) + if self.with_mask: + # TODO: support PolygonMasks + h, w = results['img_shape'] + gt_masks = np.zeros((0, h, w), dtype=np.uint8) + results['gt_masks'] = BitmapMasks(gt_masks, h, w) + if self.with_seg: + h, w = results['img_shape'] + results['gt_seg_map'] = self.seg_ignore_label * np.ones( + (h, w), dtype=np.uint8) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(with_bbox={self.with_bbox}, ' + repr_str += f'with_label={self.with_label}, ' + repr_str += f'with_mask={self.with_mask}, ' + repr_str += f'with_seg={self.with_seg}, ' + repr_str += f'seg_ignore_label={self.seg_ignore_label})' + return repr_str + + +@TRANSFORMS.register_module() +class InferencerLoader(BaseTransform): + """Load an image from ``results['img']``. + + Similar with :obj:`LoadImageFromFile`, but the image has been loaded as + :obj:`np.ndarray` in ``results['img']``. Can be used when loading image + from webcam. + + Required Keys: + + - img + + Modified Keys: + + - img + - img_path + - img_shape + - ori_shape + + Args: + to_float32 (bool): Whether to convert the loaded image to a float32 + numpy array. If set to False, the loaded image is an uint8 array. + Defaults to False. + """ + + def __init__(self, **kwargs) -> None: + super().__init__() + self.from_file = TRANSFORMS.build( + dict(type='LoadImageFromFile', **kwargs)) + self.from_ndarray = TRANSFORMS.build( + dict(type='mmdet.LoadImageFromNDArray', **kwargs)) + + def transform(self, results: Union[str, np.ndarray, dict]) -> dict: + """Transform function to add image meta information. + + Args: + results (str, np.ndarray or dict): The result. + + Returns: + dict: The dict contains loaded image and meta information. + """ + if isinstance(results, str): + inputs = dict(img_path=results) + elif isinstance(results, np.ndarray): + inputs = dict(img=results) + elif isinstance(results, dict): + inputs = results + else: + raise NotImplementedError + + if 'img' in inputs: + return self.from_ndarray(inputs) + return self.from_file(inputs) + + +@TRANSFORMS.register_module() +class LoadTrackAnnotations(LoadAnnotations): + """Load and process the ``instances`` and ``seg_map`` annotation provided + by dataset. It must load ``instances_ids`` which is only used in the + tracking tasks. The annotation format is as the following: + + .. code-block:: python + { + 'instances': + [ + { + # List of 4 numbers representing the bounding box of the + # instance, in (x1, y1, x2, y2) order. + 'bbox': [x1, y1, x2, y2], + # Label of image classification. + 'bbox_label': 1, + # Used in tracking. + # Id of instances. + 'instance_id': 100, + # Used in instance/panoptic segmentation. The segmentation mask + # of the instance or the information of segments. + # 1. If list[list[float]], it represents a list of polygons, + # one for each connected component of the object. Each + # list[float] is one simple polygon in the format of + # [x1, y1, ..., xn, yn] (n >= 3). The Xs and Ys are absolute + # coordinates in unit of pixels. + # 2. If dict, it represents the per-pixel segmentation mask in + # COCO's compressed RLE format. The dict should have keys + # “size” and “counts”. Can be loaded by pycocotools + 'mask': list[list[float]] or dict, + } + ] + # Filename of semantic or panoptic segmentation ground truth file. + 'seg_map_path': 'a/b/c' + } + + After this module, the annotation has been changed to the format below: + .. code-block:: python + { + # In (x1, y1, x2, y2) order, float type. N is the number of bboxes + # in an image + 'gt_bboxes': np.ndarray(N, 4) + # In int type. + 'gt_bboxes_labels': np.ndarray(N, ) + # In built-in class + 'gt_masks': PolygonMasks (H, W) or BitmapMasks (H, W) + # In uint8 type. + 'gt_seg_map': np.ndarray (H, W) + # in (x, y, v) order, float type. + } + + Required Keys: + + - height (optional) + - width (optional) + - instances + - bbox (optional) + - bbox_label + - instance_id (optional) + - mask (optional) + - ignore_flag (optional) + - seg_map_path (optional) + + Added Keys: + + - gt_bboxes (np.float32) + - gt_bboxes_labels (np.int32) + - gt_instances_ids (np.int32) + - gt_masks (BitmapMasks | PolygonMasks) + - gt_seg_map (np.uint8) + - gt_ignore_flags (np.bool) + """ + + def __init__(self, **kwargs) -> None: + super().__init__(**kwargs) + + def _load_bboxes(self, results: dict) -> None: + """Private function to load bounding box annotations. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded bounding box annotations. + """ + gt_bboxes = [] + gt_ignore_flags = [] + # TODO: use bbox_type + for instance in results['instances']: + # The datasets which are only format in evaluation don't have + # groundtruth boxes. + if 'bbox' in instance: + gt_bboxes.append(instance['bbox']) + if 'ignore_flag' in instance: + gt_ignore_flags.append(instance['ignore_flag']) + + # TODO: check this case + if len(gt_bboxes) != len(gt_ignore_flags): + # There may be no ``gt_ignore_flags`` in some cases, we treat them + # as all False in order to keep the length of ``gt_bboxes`` and + # ``gt_ignore_flags`` the same + gt_ignore_flags = [False] * len(gt_bboxes) + + results['gt_bboxes'] = np.array( + gt_bboxes, dtype=np.float32).reshape(-1, 4) + results['gt_ignore_flags'] = np.array(gt_ignore_flags, dtype=bool) + + def _load_instances_ids(self, results: dict) -> None: + """Private function to load instances id annotations. + + Args: + results (dict): Result dict from :obj :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict containing instances id annotations. + """ + gt_instances_ids = [] + for instance in results['instances']: + gt_instances_ids.append(instance['instance_id']) + results['gt_instances_ids'] = np.array( + gt_instances_ids, dtype=np.int32) + + def transform(self, results: dict) -> dict: + """Function to load multiple types annotations. + + Args: + results (dict): Result dict from :obj:``mmcv.BaseDataset``. + + Returns: + dict: The dict contains loaded bounding box, label, instances id + and semantic segmentation and keypoints annotations. + """ + results = super().transform(results) + self._load_instances_ids(results) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(with_bbox={self.with_bbox}, ' + repr_str += f'with_label={self.with_label}, ' + repr_str += f'with_mask={self.with_mask}, ' + repr_str += f'with_seg={self.with_seg}, ' + repr_str += f'poly2mask={self.poly2mask}, ' + repr_str += f"imdecode_backend='{self.imdecode_backend}', " + repr_str += f'file_client_args={self.file_client_args})' + return repr_str diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/text_transformers.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/text_transformers.py new file mode 100644 index 0000000000000000000000000000000000000000..25304d5fe451860547dea24b78f645d32536e2ae --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/text_transformers.py @@ -0,0 +1,255 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import json + +from mmcv.transforms import BaseTransform + +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import BaseBoxes + +try: + from transformers import AutoTokenizer + from transformers import BertModel as HFBertModel +except ImportError: + AutoTokenizer = None + HFBertModel = None + +import random +import re + +import numpy as np + + +def clean_name(name): + name = re.sub(r'\(.*\)', '', name) + name = re.sub(r'_', ' ', name) + name = re.sub(r' ', ' ', name) + name = name.lower() + return name + + +def check_for_positive_overflow(gt_bboxes, gt_labels, text, tokenizer, + max_tokens): + # Check if we have too many positive labels + # generate a caption by appending the positive labels + positive_label_list = np.unique(gt_labels).tolist() + # random shuffule so we can sample different annotations + # at different epochs + random.shuffle(positive_label_list) + + kept_lables = [] + length = 0 + + for index, label in enumerate(positive_label_list): + + label_text = clean_name(text[str(label)]) + '. ' + + tokenized = tokenizer.tokenize(label_text) + + length += len(tokenized) + + if length > max_tokens: + break + else: + kept_lables.append(label) + + keep_box_index = [] + keep_gt_labels = [] + for i in range(len(gt_labels)): + if gt_labels[i] in kept_lables: + keep_box_index.append(i) + keep_gt_labels.append(gt_labels[i]) + + return gt_bboxes[keep_box_index], np.array( + keep_gt_labels, dtype=np.long), length + + +def generate_senetence_given_labels(positive_label_list, negative_label_list, + text): + label_to_positions = {} + + label_list = negative_label_list + positive_label_list + + random.shuffle(label_list) + + pheso_caption = '' + + label_remap_dict = {} + for index, label in enumerate(label_list): + + start_index = len(pheso_caption) + + pheso_caption += clean_name(text[str(label)]) + + end_index = len(pheso_caption) + + if label in positive_label_list: + label_to_positions[index] = [[start_index, end_index]] + label_remap_dict[int(label)] = index + + # if index != len(label_list) - 1: + # pheso_caption += '. ' + pheso_caption += '. ' + + return label_to_positions, pheso_caption, label_remap_dict + + +@TRANSFORMS.register_module() +class RandomSamplingNegPos(BaseTransform): + + def __init__(self, + tokenizer_name, + num_sample_negative=85, + max_tokens=256, + full_sampling_prob=0.5, + label_map_file=None): + if AutoTokenizer is None: + raise RuntimeError( + 'transformers is not installed, please install it by: ' + 'pip install transformers.') + + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + self.num_sample_negative = num_sample_negative + self.full_sampling_prob = full_sampling_prob + self.max_tokens = max_tokens + self.label_map = None + if label_map_file: + with open(label_map_file, 'r') as file: + self.label_map = json.load(file) + + def transform(self, results: dict) -> dict: + if 'phrases' in results: + return self.vg_aug(results) + else: + return self.od_aug(results) + + def vg_aug(self, results): + gt_bboxes = results['gt_bboxes'] + if isinstance(gt_bboxes, BaseBoxes): + gt_bboxes = gt_bboxes.tensor + gt_labels = results['gt_bboxes_labels'] + text = results['text'].lower().strip() + if not text.endswith('.'): + text = text + '. ' + + phrases = results['phrases'] + # TODO: add neg + positive_label_list = np.unique(gt_labels).tolist() + label_to_positions = {} + for label in positive_label_list: + label_to_positions[label] = phrases[label]['tokens_positive'] + + results['gt_bboxes'] = gt_bboxes + results['gt_bboxes_labels'] = gt_labels + + results['text'] = text + results['tokens_positive'] = label_to_positions + return results + + def od_aug(self, results): + gt_bboxes = results['gt_bboxes'] + if isinstance(gt_bboxes, BaseBoxes): + gt_bboxes = gt_bboxes.tensor + gt_labels = results['gt_bboxes_labels'] + + if 'text' not in results: + assert self.label_map is not None + text = self.label_map + else: + text = results['text'] + + original_box_num = len(gt_labels) + # If the category name is in the format of 'a/b' (in object365), + # we randomly select one of them. + for key, value in text.items(): + if '/' in value: + text[key] = random.choice(value.split('/')).strip() + + gt_bboxes, gt_labels, positive_caption_length = \ + check_for_positive_overflow(gt_bboxes, gt_labels, + text, self.tokenizer, self.max_tokens) + + if len(gt_bboxes) < original_box_num: + print('WARNING: removed {} boxes due to positive caption overflow'. + format(original_box_num - len(gt_bboxes))) + + valid_negative_indexes = list(text.keys()) + + positive_label_list = np.unique(gt_labels).tolist() + full_negative = self.num_sample_negative + + if full_negative > len(valid_negative_indexes): + full_negative = len(valid_negative_indexes) + + outer_prob = random.random() + + if outer_prob < self.full_sampling_prob: + # c. probability_full: add both all positive and all negatives + num_negatives = full_negative + else: + if random.random() < 1.0: + num_negatives = np.random.choice(max(1, full_negative)) + 1 + else: + num_negatives = full_negative + + # Keep some negatives + negative_label_list = set() + if num_negatives != -1: + if num_negatives > len(valid_negative_indexes): + num_negatives = len(valid_negative_indexes) + + for i in np.random.choice( + valid_negative_indexes, size=num_negatives, replace=False): + if i not in positive_label_list: + negative_label_list.add(i) + + random.shuffle(positive_label_list) + + negative_label_list = list(negative_label_list) + random.shuffle(negative_label_list) + + negative_max_length = self.max_tokens - positive_caption_length + screened_negative_label_list = [] + + for negative_label in negative_label_list: + label_text = clean_name(text[str(negative_label)]) + '. ' + + tokenized = self.tokenizer.tokenize(label_text) + + negative_max_length -= len(tokenized) + + if negative_max_length > 0: + screened_negative_label_list.append(negative_label) + else: + break + negative_label_list = screened_negative_label_list + label_to_positions, pheso_caption, label_remap_dict = \ + generate_senetence_given_labels(positive_label_list, + negative_label_list, text) + + # label remap + if len(gt_labels) > 0: + gt_labels = np.vectorize(lambda x: label_remap_dict[x])(gt_labels) + + results['gt_bboxes'] = gt_bboxes + results['gt_bboxes_labels'] = gt_labels + + results['text'] = pheso_caption + results['tokens_positive'] = label_to_positions + + return results + + +@TRANSFORMS.register_module() +class LoadTextAnnotations(BaseTransform): + + def transform(self, results: dict) -> dict: + if 'phrases' in results: + tokens_positive = [ + phrase['tokens_positive'] + for phrase in results['phrases'].values() + ] + results['tokens_positive'] = tokens_positive + else: + text = results['text'] + results['text'] = list(text.values()) + return results diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/transformers_glip.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/transformers_glip.py new file mode 100644 index 0000000000000000000000000000000000000000..60c4f87d1b86c13f886da27584114b6420b8b8cb --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/transformers_glip.py @@ -0,0 +1,66 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import mmcv +import numpy as np +from mmcv.transforms import BaseTransform + +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import HorizontalBoxes, autocast_box_type +from .transforms import RandomFlip + + +@TRANSFORMS.register_module() +class GTBoxSubOne_GLIP(BaseTransform): + """Subtract 1 from the x2 and y2 coordinates of the gt_bboxes.""" + + def transform(self, results: dict) -> dict: + if 'gt_bboxes' in results: + gt_bboxes = results['gt_bboxes'] + if isinstance(gt_bboxes, np.ndarray): + gt_bboxes[:, 2:] -= 1 + results['gt_bboxes'] = gt_bboxes + elif isinstance(gt_bboxes, HorizontalBoxes): + gt_bboxes = results['gt_bboxes'].tensor + gt_bboxes[:, 2:] -= 1 + results['gt_bboxes'] = HorizontalBoxes(gt_bboxes) + else: + raise NotImplementedError + return results + + +@TRANSFORMS.register_module() +class RandomFlip_GLIP(RandomFlip): + """Flip the image & bboxes & masks & segs horizontally or vertically. + + When using horizontal flipping, the corresponding bbox x-coordinate needs + to be additionally subtracted by one. + """ + + @autocast_box_type() + def _flip(self, results: dict) -> None: + """Flip images, bounding boxes, and semantic segmentation map.""" + # flip image + results['img'] = mmcv.imflip( + results['img'], direction=results['flip_direction']) + + img_shape = results['img'].shape[:2] + + # flip bboxes + if results.get('gt_bboxes', None) is not None: + results['gt_bboxes'].flip_(img_shape, results['flip_direction']) + # Only change this line + if results['flip_direction'] == 'horizontal': + results['gt_bboxes'].translate_([-1, 0]) + + # TODO: check it + # flip masks + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'].flip( + results['flip_direction']) + + # flip segs + if results.get('gt_seg_map', None) is not None: + results['gt_seg_map'] = mmcv.imflip( + results['gt_seg_map'], direction=results['flip_direction']) + + # record homography matrix for flip + self._record_homography_matrix(results) diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/transforms.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..c50b987db33c91f759f6c89580f605631ce4f558 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/transforms.py @@ -0,0 +1,3856 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import inspect +import math +import warnings +from typing import List, Optional, Sequence, Tuple, Union + +import cv2 +import mmcv +import numpy as np +from mmcv.image import imresize +from mmcv.image.geometric import _scale_size +from mmcv.transforms import BaseTransform +from mmcv.transforms import Pad as MMCV_Pad +from mmcv.transforms import RandomFlip as MMCV_RandomFlip +from mmcv.transforms import Resize as MMCV_Resize +from mmcv.transforms.utils import avoid_cache_randomness, cache_randomness +from mmengine.dataset import BaseDataset +from mmengine.utils import is_str +from numpy import random + +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import HorizontalBoxes, autocast_box_type +from mmdet.structures.mask import BitmapMasks, PolygonMasks +from mmdet.utils import log_img_scale + +try: + from imagecorruptions import corrupt +except ImportError: + corrupt = None + +try: + import albumentations + from albumentations import Compose +except ImportError: + albumentations = None + Compose = None + +Number = Union[int, float] + + +def _fixed_scale_size( + size: Tuple[int, int], + scale: Union[float, int, tuple], +) -> Tuple[int, int]: + """Rescale a size by a ratio. + + Args: + size (tuple[int]): (w, h). + scale (float | tuple(float)): Scaling factor. + + Returns: + tuple[int]: scaled size. + """ + if isinstance(scale, (float, int)): + scale = (scale, scale) + w, h = size + # don't need o.5 offset + return int(w * float(scale[0])), int(h * float(scale[1])) + + +def rescale_size(old_size: tuple, + scale: Union[float, int, tuple], + return_scale: bool = False) -> tuple: + """Calculate the new size to be rescaled to. + + Args: + old_size (tuple[int]): The old size (w, h) of image. + scale (float | tuple[int]): The scaling factor or maximum size. + If it is a float number, then the image will be rescaled by this + factor, else if it is a tuple of 2 integers, then the image will + be rescaled as large as possible within the scale. + return_scale (bool): Whether to return the scaling factor besides the + rescaled image size. + + Returns: + tuple[int]: The new rescaled image size. + """ + w, h = old_size + if isinstance(scale, (float, int)): + if scale <= 0: + raise ValueError(f'Invalid scale {scale}, must be positive.') + scale_factor = scale + elif isinstance(scale, tuple): + max_long_edge = max(scale) + max_short_edge = min(scale) + scale_factor = min(max_long_edge / max(h, w), + max_short_edge / min(h, w)) + else: + raise TypeError( + f'Scale must be a number or tuple of int, but got {type(scale)}') + # only change this + new_size = _fixed_scale_size((w, h), scale_factor) + + if return_scale: + return new_size, scale_factor + else: + return new_size + + +def imrescale( + img: np.ndarray, + scale: Union[float, Tuple[int, int]], + return_scale: bool = False, + interpolation: str = 'bilinear', + backend: Optional[str] = None +) -> Union[np.ndarray, Tuple[np.ndarray, float]]: + """Resize image while keeping the aspect ratio. + + Args: + img (ndarray): The input image. + scale (float | tuple[int]): The scaling factor or maximum size. + If it is a float number, then the image will be rescaled by this + factor, else if it is a tuple of 2 integers, then the image will + be rescaled as large as possible within the scale. + return_scale (bool): Whether to return the scaling factor besides the + rescaled image. + interpolation (str): Same as :func:`resize`. + backend (str | None): Same as :func:`resize`. + + Returns: + ndarray: The rescaled image. + """ + h, w = img.shape[:2] + new_size, scale_factor = rescale_size((w, h), scale, return_scale=True) + rescaled_img = imresize( + img, new_size, interpolation=interpolation, backend=backend) + if return_scale: + return rescaled_img, scale_factor + else: + return rescaled_img + + +@TRANSFORMS.register_module() +class Resize(MMCV_Resize): + """Resize images & bbox & seg. + + This transform resizes the input image according to ``scale`` or + ``scale_factor``. Bboxes, masks, and seg map are then resized + with the same scale factor. + if ``scale`` and ``scale_factor`` are both set, it will use ``scale`` to + resize. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_masks + - gt_seg_map + + + Added Keys: + + - scale + - scale_factor + - keep_ratio + - homography_matrix + + Args: + scale (int or tuple): Images scales for resizing. Defaults to None + scale_factor (float or tuple[float]): Scale factors for resizing. + Defaults to None. + keep_ratio (bool): Whether to keep the aspect ratio when resizing the + image. Defaults to False. + clip_object_border (bool): Whether to clip the objects + outside the border of the image. In some dataset like MOT17, the gt + bboxes are allowed to cross the border of images. Therefore, we + don't need to clip the gt bboxes in these cases. Defaults to True. + backend (str): Image resize backend, choices are 'cv2' and 'pillow'. + These two backends generates slightly different results. Defaults + to 'cv2'. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def _resize_masks(self, results: dict) -> None: + """Resize masks with ``results['scale']``""" + if results.get('gt_masks', None) is not None: + if self.keep_ratio: + results['gt_masks'] = results['gt_masks'].rescale( + results['scale']) + else: + results['gt_masks'] = results['gt_masks'].resize( + results['img_shape']) + + def _resize_bboxes(self, results: dict) -> None: + """Resize bounding boxes with ``results['scale_factor']``.""" + if results.get('gt_bboxes', None) is not None: + results['gt_bboxes'].rescale_(results['scale_factor']) + if self.clip_object_border: + results['gt_bboxes'].clip_(results['img_shape']) + + def _record_homography_matrix(self, results: dict) -> None: + """Record the homography matrix for the Resize.""" + w_scale, h_scale = results['scale_factor'] + homography_matrix = np.array( + [[w_scale, 0, 0], [0, h_scale, 0], [0, 0, 1]], dtype=np.float32) + if results.get('homography_matrix', None) is None: + results['homography_matrix'] = homography_matrix + else: + results['homography_matrix'] = homography_matrix @ results[ + 'homography_matrix'] + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to resize images, bounding boxes and semantic + segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + Returns: + dict: Resized results, 'img', 'gt_bboxes', 'gt_seg_map', + 'scale', 'scale_factor', 'height', 'width', and 'keep_ratio' keys + are updated in result dict. + """ + if self.scale: + results['scale'] = self.scale + else: + img_shape = results['img'].shape[:2] + results['scale'] = _scale_size(img_shape[::-1], self.scale_factor) + self._resize_img(results) + self._resize_bboxes(results) + self._resize_masks(results) + self._resize_seg(results) + self._record_homography_matrix(results) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(scale={self.scale}, ' + repr_str += f'scale_factor={self.scale_factor}, ' + repr_str += f'keep_ratio={self.keep_ratio}, ' + repr_str += f'clip_object_border={self.clip_object_border}), ' + repr_str += f'backend={self.backend}), ' + repr_str += f'interpolation={self.interpolation})' + return repr_str + + +@TRANSFORMS.register_module() +class FixScaleResize(Resize): + """Compared to Resize, FixScaleResize fixes the scaling issue when + `keep_ratio=true`.""" + + def _resize_img(self, results): + """Resize images with ``results['scale']``.""" + if results.get('img', None) is not None: + if self.keep_ratio: + img, scale_factor = imrescale( + results['img'], + results['scale'], + interpolation=self.interpolation, + return_scale=True, + backend=self.backend) + new_h, new_w = img.shape[:2] + h, w = results['img'].shape[:2] + w_scale = new_w / w + h_scale = new_h / h + else: + img, w_scale, h_scale = mmcv.imresize( + results['img'], + results['scale'], + interpolation=self.interpolation, + return_scale=True, + backend=self.backend) + results['img'] = img + results['img_shape'] = img.shape[:2] + results['scale_factor'] = (w_scale, h_scale) + results['keep_ratio'] = self.keep_ratio + + +@TRANSFORMS.register_module() +class ResizeShortestEdge(BaseTransform): + """Resize the image and mask while keeping the aspect ratio unchanged. + + Modified from https://github.com/facebookresearch/detectron2/blob/main/detectron2/data/transforms/augmentation_impl.py#L130 # noqa:E501 + + This transform attempts to scale the shorter edge to the given + `scale`, as long as the longer edge does not exceed `max_size`. + If `max_size` is reached, then downscale so that the longer + edge does not exceed `max_size`. + + Required Keys: + - img + - gt_seg_map (optional) + Modified Keys: + - img + - img_shape + - gt_seg_map (optional)) + Added Keys: + - scale + - scale_factor + - keep_ratio + + Args: + scale (Union[int, Tuple[int, int]]): The target short edge length. + If it's tuple, will select the min value as the short edge length. + max_size (int): The maximum allowed longest edge length. + """ + + def __init__(self, + scale: Union[int, Tuple[int, int]], + max_size: Optional[int] = None, + resize_type: str = 'Resize', + **resize_kwargs) -> None: + super().__init__() + self.scale = scale + self.max_size = max_size + + self.resize_cfg = dict(type=resize_type, **resize_kwargs) + self.resize = TRANSFORMS.build({'scale': 0, **self.resize_cfg}) + + def _get_output_shape( + self, img: np.ndarray, + short_edge_length: Union[int, Tuple[int, int]]) -> Tuple[int, int]: + """Compute the target image shape with the given `short_edge_length`. + + Args: + img (np.ndarray): The input image. + short_edge_length (Union[int, Tuple[int, int]]): The target short + edge length. If it's tuple, will select the min value as the + short edge length. + """ + h, w = img.shape[:2] + if isinstance(short_edge_length, int): + size = short_edge_length * 1.0 + elif isinstance(short_edge_length, tuple): + size = min(short_edge_length) * 1.0 + scale = size / min(h, w) + if h < w: + new_h, new_w = size, scale * w + else: + new_h, new_w = scale * h, size + + if self.max_size and max(new_h, new_w) > self.max_size: + scale = self.max_size * 1.0 / max(new_h, new_w) + new_h *= scale + new_w *= scale + + new_h = int(new_h + 0.5) + new_w = int(new_w + 0.5) + return new_w, new_h + + def transform(self, results: dict) -> dict: + self.resize.scale = self._get_output_shape(results['img'], self.scale) + return self.resize(results) + + +@TRANSFORMS.register_module() +class FixShapeResize(Resize): + """Resize images & bbox & seg to the specified size. + + This transform resizes the input image according to ``width`` and + ``height``. Bboxes, masks, and seg map are then resized + with the same parameters. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_masks + - gt_seg_map + + + Added Keys: + + - scale + - scale_factor + - keep_ratio + - homography_matrix + + Args: + width (int): width for resizing. + height (int): height for resizing. + Defaults to None. + pad_val (Number | dict[str, Number], optional): Padding value for if + the pad_mode is "constant". If it is a single number, the value + to pad the image is the number and to pad the semantic + segmentation map is 255. If it is a dict, it should have the + following keys: + + - img: The value to pad the image. + - seg: The value to pad the semantic segmentation map. + Defaults to dict(img=0, seg=255). + keep_ratio (bool): Whether to keep the aspect ratio when resizing the + image. Defaults to False. + clip_object_border (bool): Whether to clip the objects + outside the border of the image. In some dataset like MOT17, the gt + bboxes are allowed to cross the border of images. Therefore, we + don't need to clip the gt bboxes in these cases. Defaults to True. + backend (str): Image resize backend, choices are 'cv2' and 'pillow'. + These two backends generates slightly different results. Defaults + to 'cv2'. + interpolation (str): Interpolation method, accepted values are + "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' + backend, "nearest", "bilinear" for 'pillow' backend. Defaults + to 'bilinear'. + """ + + def __init__(self, + width: int, + height: int, + pad_val: Union[Number, dict] = dict(img=0, seg=255), + keep_ratio: bool = False, + clip_object_border: bool = True, + backend: str = 'cv2', + interpolation: str = 'bilinear') -> None: + assert width is not None and height is not None, ( + '`width` and' + '`height` can not be `None`') + + self.width = width + self.height = height + self.scale = (width, height) + + self.backend = backend + self.interpolation = interpolation + self.keep_ratio = keep_ratio + self.clip_object_border = clip_object_border + + if keep_ratio is True: + # padding to the fixed size when keep_ratio=True + self.pad_transform = Pad(size=self.scale, pad_val=pad_val) + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to resize images, bounding boxes and semantic + segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + Returns: + dict: Resized results, 'img', 'gt_bboxes', 'gt_seg_map', + 'scale', 'scale_factor', 'height', 'width', and 'keep_ratio' keys + are updated in result dict. + """ + img = results['img'] + h, w = img.shape[:2] + if self.keep_ratio: + scale_factor = min(self.width / w, self.height / h) + results['scale_factor'] = (scale_factor, scale_factor) + real_w, real_h = int(w * float(scale_factor) + + 0.5), int(h * float(scale_factor) + 0.5) + img, scale_factor = mmcv.imrescale( + results['img'], (real_w, real_h), + interpolation=self.interpolation, + return_scale=True, + backend=self.backend) + # the w_scale and h_scale has minor difference + # a real fix should be done in the mmcv.imrescale in the future + results['img'] = img + results['img_shape'] = img.shape[:2] + results['keep_ratio'] = self.keep_ratio + results['scale'] = (real_w, real_h) + else: + results['scale'] = (self.width, self.height) + results['scale_factor'] = (self.width / w, self.height / h) + super()._resize_img(results) + + self._resize_bboxes(results) + self._resize_masks(results) + self._resize_seg(results) + self._record_homography_matrix(results) + if self.keep_ratio: + self.pad_transform(results) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(width={self.width}, height={self.height}, ' + repr_str += f'keep_ratio={self.keep_ratio}, ' + repr_str += f'clip_object_border={self.clip_object_border}), ' + repr_str += f'backend={self.backend}), ' + repr_str += f'interpolation={self.interpolation})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomFlip(MMCV_RandomFlip): + """Flip the image & bbox & mask & segmentation map. Added or Updated keys: + flip, flip_direction, img, gt_bboxes, and gt_seg_map. There are 3 flip + modes: + + - ``prob`` is float, ``direction`` is string: the image will be + ``direction``ly flipped with probability of ``prob`` . + E.g., ``prob=0.5``, ``direction='horizontal'``, + then image will be horizontally flipped with probability of 0.5. + - ``prob`` is float, ``direction`` is list of string: the image will + be ``direction[i]``ly flipped with probability of + ``prob/len(direction)``. + E.g., ``prob=0.5``, ``direction=['horizontal', 'vertical']``, + then image will be horizontally flipped with probability of 0.25, + vertically with probability of 0.25. + - ``prob`` is list of float, ``direction`` is list of string: + given ``len(prob) == len(direction)``, the image will + be ``direction[i]``ly flipped with probability of ``prob[i]``. + E.g., ``prob=[0.3, 0.5]``, ``direction=['horizontal', + 'vertical']``, then image will be horizontally flipped with + probability of 0.3, vertically with probability of 0.5. + + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_masks + - gt_seg_map + + Added Keys: + + - flip + - flip_direction + - homography_matrix + + + Args: + prob (float | list[float], optional): The flipping probability. + Defaults to None. + direction(str | list[str]): The flipping direction. Options + If input is a list, the length must equal ``prob``. Each + element in ``prob`` indicates the flip probability of + corresponding direction. Defaults to 'horizontal'. + """ + + def _record_homography_matrix(self, results: dict) -> None: + """Record the homography matrix for the RandomFlip.""" + cur_dir = results['flip_direction'] + h, w = results['img'].shape[:2] + + if cur_dir == 'horizontal': + homography_matrix = np.array([[-1, 0, w], [0, 1, 0], [0, 0, 1]], + dtype=np.float32) + elif cur_dir == 'vertical': + homography_matrix = np.array([[1, 0, 0], [0, -1, h], [0, 0, 1]], + dtype=np.float32) + elif cur_dir == 'diagonal': + homography_matrix = np.array([[-1, 0, w], [0, -1, h], [0, 0, 1]], + dtype=np.float32) + else: + homography_matrix = np.eye(3, dtype=np.float32) + + if results.get('homography_matrix', None) is None: + results['homography_matrix'] = homography_matrix + else: + results['homography_matrix'] = homography_matrix @ results[ + 'homography_matrix'] + + @autocast_box_type() + def _flip(self, results: dict) -> None: + """Flip images, bounding boxes, and semantic segmentation map.""" + # flip image + results['img'] = mmcv.imflip( + results['img'], direction=results['flip_direction']) + + img_shape = results['img'].shape[:2] + + # flip bboxes + if results.get('gt_bboxes', None) is not None: + results['gt_bboxes'].flip_(img_shape, results['flip_direction']) + + # flip masks + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'].flip( + results['flip_direction']) + + # flip segs + if results.get('gt_seg_map', None) is not None: + results['gt_seg_map'] = mmcv.imflip( + results['gt_seg_map'], direction=results['flip_direction']) + + # record homography matrix for flip + self._record_homography_matrix(results) + + +@TRANSFORMS.register_module() +class RandomShift(BaseTransform): + """Shift the image and box given shift pixels and probability. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) + - gt_bboxes_labels (np.int64) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - img + - gt_bboxes + - gt_bboxes_labels + - gt_ignore_flags (bool) (optional) + + Args: + prob (float): Probability of shifts. Defaults to 0.5. + max_shift_px (int): The max pixels for shifting. Defaults to 32. + filter_thr_px (int): The width and height threshold for filtering. + The bbox and the rest of the targets below the width and + height threshold will be filtered. Defaults to 1. + """ + + def __init__(self, + prob: float = 0.5, + max_shift_px: int = 32, + filter_thr_px: int = 1) -> None: + assert 0 <= prob <= 1 + assert max_shift_px >= 0 + self.prob = prob + self.max_shift_px = max_shift_px + self.filter_thr_px = int(filter_thr_px) + + @cache_randomness + def _random_prob(self) -> float: + return random.uniform(0, 1) + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to random shift images, bounding boxes. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Shift results. + """ + if self._random_prob() < self.prob: + img_shape = results['img'].shape[:2] + + random_shift_x = random.randint(-self.max_shift_px, + self.max_shift_px) + random_shift_y = random.randint(-self.max_shift_px, + self.max_shift_px) + new_x = max(0, random_shift_x) + ori_x = max(0, -random_shift_x) + new_y = max(0, random_shift_y) + ori_y = max(0, -random_shift_y) + + # TODO: support mask and semantic segmentation maps. + bboxes = results['gt_bboxes'].clone() + bboxes.translate_([random_shift_x, random_shift_y]) + + # clip border + bboxes.clip_(img_shape) + + # remove invalid bboxes + valid_inds = (bboxes.widths > self.filter_thr_px).numpy() & ( + bboxes.heights > self.filter_thr_px).numpy() + # If the shift does not contain any gt-bbox area, skip this + # image. + if not valid_inds.any(): + return results + bboxes = bboxes[valid_inds] + results['gt_bboxes'] = bboxes + results['gt_bboxes_labels'] = results['gt_bboxes_labels'][ + valid_inds] + + if results.get('gt_ignore_flags', None) is not None: + results['gt_ignore_flags'] = \ + results['gt_ignore_flags'][valid_inds] + + # shift img + img = results['img'] + new_img = np.zeros_like(img) + img_h, img_w = img.shape[:2] + new_h = img_h - np.abs(random_shift_y) + new_w = img_w - np.abs(random_shift_x) + new_img[new_y:new_y + new_h, new_x:new_x + new_w] \ + = img[ori_y:ori_y + new_h, ori_x:ori_x + new_w] + results['img'] = new_img + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(prob={self.prob}, ' + repr_str += f'max_shift_px={self.max_shift_px}, ' + repr_str += f'filter_thr_px={self.filter_thr_px})' + return repr_str + + +@TRANSFORMS.register_module() +class Pad(MMCV_Pad): + """Pad the image & segmentation map. + + There are three padding modes: (1) pad to a fixed size and (2) pad to the + minimum size that is divisible by some number. and (3)pad to square. Also, + pad to square and pad to the minimum size can be used as the same time. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_masks + - gt_seg_map + + Added Keys: + + - pad_shape + - pad_fixed_size + - pad_size_divisor + + Args: + size (tuple, optional): Fixed padding size. + Expected padding shape (width, height). Defaults to None. + size_divisor (int, optional): The divisor of padded size. Defaults to + None. + pad_to_square (bool): Whether to pad the image into a square. + Currently only used for YOLOX. Defaults to False. + pad_val (Number | dict[str, Number], optional) - Padding value for if + the pad_mode is "constant". If it is a single number, the value + to pad the image is the number and to pad the semantic + segmentation map is 255. If it is a dict, it should have the + following keys: + + - img: The value to pad the image. + - seg: The value to pad the semantic segmentation map. + Defaults to dict(img=0, seg=255). + padding_mode (str): Type of padding. Should be: constant, edge, + reflect or symmetric. Defaults to 'constant'. + + - constant: pads with a constant value, this value is specified + with pad_val. + - edge: pads with the last value at the edge of the image. + - reflect: pads with reflection of image without repeating the last + value on the edge. For example, padding [1, 2, 3, 4] with 2 + elements on both sides in reflect mode will result in + [3, 2, 1, 2, 3, 4, 3, 2]. + - symmetric: pads with reflection of image repeating the last value + on the edge. For example, padding [1, 2, 3, 4] with 2 elements on + both sides in symmetric mode will result in + [2, 1, 1, 2, 3, 4, 4, 3] + """ + + def _pad_masks(self, results: dict) -> None: + """Pad masks according to ``results['pad_shape']``.""" + if results.get('gt_masks', None) is not None: + pad_val = self.pad_val.get('masks', 0) + pad_shape = results['pad_shape'][:2] + results['gt_masks'] = results['gt_masks'].pad( + pad_shape, pad_val=pad_val) + + def transform(self, results: dict) -> dict: + """Call function to pad images, masks, semantic segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Updated result dict. + """ + self._pad_img(results) + self._pad_seg(results) + self._pad_masks(results) + return results + + +@TRANSFORMS.register_module() +class RandomCrop(BaseTransform): + """Random crop the image & bboxes & masks. + + The absolute ``crop_size`` is sampled based on ``crop_type`` and + ``image_size``, then the cropped results are generated. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_masks (optional) + - gt_ignore_flags (optional) + - gt_seg_map (optional) + - gt_instances_ids (options, only used in MOT/VIS) + + Added Keys: + + - homography_matrix + + Args: + crop_size (tuple): The relative ratio or absolute pixels of + (width, height). + crop_type (str, optional): One of "relative_range", "relative", + "absolute", "absolute_range". "relative" randomly crops + (h * crop_size[0], w * crop_size[1]) part from an input of size + (h, w). "relative_range" uniformly samples relative crop size from + range [crop_size[0], 1] and [crop_size[1], 1] for height and width + respectively. "absolute" crops from an input with absolute size + (crop_size[0], crop_size[1]). "absolute_range" uniformly samples + crop_h in range [crop_size[0], min(h, crop_size[1])] and crop_w + in range [crop_size[0], min(w, crop_size[1])]. + Defaults to "absolute". + allow_negative_crop (bool, optional): Whether to allow a crop that does + not contain any bbox area. Defaults to False. + recompute_bbox (bool, optional): Whether to re-compute the boxes based + on cropped instance masks. Defaults to False. + bbox_clip_border (bool, optional): Whether clip the objects outside + the border of the image. Defaults to True. + + Note: + - If the image is smaller than the absolute crop size, return the + original image. + - The keys for bboxes, labels and masks must be aligned. That is, + ``gt_bboxes`` corresponds to ``gt_labels`` and ``gt_masks``, and + ``gt_bboxes_ignore`` corresponds to ``gt_labels_ignore`` and + ``gt_masks_ignore``. + - If the crop does not contain any gt-bbox region and + ``allow_negative_crop`` is set to False, skip this image. + """ + + def __init__(self, + crop_size: tuple, + crop_type: str = 'absolute', + allow_negative_crop: bool = False, + recompute_bbox: bool = False, + bbox_clip_border: bool = True) -> None: + if crop_type not in [ + 'relative_range', 'relative', 'absolute', 'absolute_range' + ]: + raise ValueError(f'Invalid crop_type {crop_type}.') + if crop_type in ['absolute', 'absolute_range']: + assert crop_size[0] > 0 and crop_size[1] > 0 + assert isinstance(crop_size[0], int) and isinstance( + crop_size[1], int) + if crop_type == 'absolute_range': + assert crop_size[0] <= crop_size[1] + else: + assert 0 < crop_size[0] <= 1 and 0 < crop_size[1] <= 1 + self.crop_size = crop_size + self.crop_type = crop_type + self.allow_negative_crop = allow_negative_crop + self.bbox_clip_border = bbox_clip_border + self.recompute_bbox = recompute_bbox + + def _crop_data(self, results: dict, crop_size: Tuple[int, int], + allow_negative_crop: bool) -> Union[dict, None]: + """Function to randomly crop images, bounding boxes, masks, semantic + segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + crop_size (Tuple[int, int]): Expected absolute size after + cropping, (h, w). + allow_negative_crop (bool): Whether to allow a crop that does not + contain any bbox area. + + Returns: + results (Union[dict, None]): Randomly cropped results, 'img_shape' + key in result dict is updated according to crop size. None will + be returned when there is no valid bbox after cropping. + """ + assert crop_size[0] > 0 and crop_size[1] > 0 + img = results['img'] + margin_h = max(img.shape[0] - crop_size[0], 0) + margin_w = max(img.shape[1] - crop_size[1], 0) + offset_h, offset_w = self._rand_offset((margin_h, margin_w)) + crop_y1, crop_y2 = offset_h, offset_h + crop_size[0] + crop_x1, crop_x2 = offset_w, offset_w + crop_size[1] + + # Record the homography matrix for the RandomCrop + homography_matrix = np.array( + [[1, 0, -offset_w], [0, 1, -offset_h], [0, 0, 1]], + dtype=np.float32) + if results.get('homography_matrix', None) is None: + results['homography_matrix'] = homography_matrix + else: + results['homography_matrix'] = homography_matrix @ results[ + 'homography_matrix'] + + # crop the image + img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...] + img_shape = img.shape + results['img'] = img + results['img_shape'] = img_shape[:2] + + # crop bboxes accordingly and clip to the image boundary + if results.get('gt_bboxes', None) is not None: + bboxes = results['gt_bboxes'] + bboxes.translate_([-offset_w, -offset_h]) + if self.bbox_clip_border: + bboxes.clip_(img_shape[:2]) + valid_inds = bboxes.is_inside(img_shape[:2]).numpy() + # If the crop does not contain any gt-bbox area and + # allow_negative_crop is False, skip this image. + if (not valid_inds.any() and not allow_negative_crop): + return None + + results['gt_bboxes'] = bboxes[valid_inds] + + if results.get('gt_ignore_flags', None) is not None: + results['gt_ignore_flags'] = \ + results['gt_ignore_flags'][valid_inds] + + if results.get('gt_bboxes_labels', None) is not None: + results['gt_bboxes_labels'] = \ + results['gt_bboxes_labels'][valid_inds] + + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'][ + valid_inds.nonzero()[0]].crop( + np.asarray([crop_x1, crop_y1, crop_x2, crop_y2])) + if self.recompute_bbox: + results['gt_bboxes'] = results['gt_masks'].get_bboxes( + type(results['gt_bboxes'])) + + # We should remove the instance ids corresponding to invalid boxes. + if results.get('gt_instances_ids', None) is not None: + results['gt_instances_ids'] = \ + results['gt_instances_ids'][valid_inds] + + # crop semantic seg + if results.get('gt_seg_map', None) is not None: + results['gt_seg_map'] = results['gt_seg_map'][crop_y1:crop_y2, + crop_x1:crop_x2] + + return results + + @cache_randomness + def _rand_offset(self, margin: Tuple[int, int]) -> Tuple[int, int]: + """Randomly generate crop offset. + + Args: + margin (Tuple[int, int]): The upper bound for the offset generated + randomly. + + Returns: + Tuple[int, int]: The random offset for the crop. + """ + margin_h, margin_w = margin + offset_h = np.random.randint(0, margin_h + 1) + offset_w = np.random.randint(0, margin_w + 1) + + return offset_h, offset_w + + @cache_randomness + def _get_crop_size(self, image_size: Tuple[int, int]) -> Tuple[int, int]: + """Randomly generates the absolute crop size based on `crop_type` and + `image_size`. + + Args: + image_size (Tuple[int, int]): (h, w). + + Returns: + crop_size (Tuple[int, int]): (crop_h, crop_w) in absolute pixels. + """ + h, w = image_size + if self.crop_type == 'absolute': + return min(self.crop_size[1], h), min(self.crop_size[0], w) + elif self.crop_type == 'absolute_range': + crop_h = np.random.randint( + min(h, self.crop_size[0]), + min(h, self.crop_size[1]) + 1) + crop_w = np.random.randint( + min(w, self.crop_size[0]), + min(w, self.crop_size[1]) + 1) + return crop_h, crop_w + elif self.crop_type == 'relative': + crop_w, crop_h = self.crop_size + return int(h * crop_h + 0.5), int(w * crop_w + 0.5) + else: + # 'relative_range' + crop_size = np.asarray(self.crop_size, dtype=np.float32) + crop_h, crop_w = crop_size + np.random.rand(2) * (1 - crop_size) + return int(h * crop_h + 0.5), int(w * crop_w + 0.5) + + @autocast_box_type() + def transform(self, results: dict) -> Union[dict, None]: + """Transform function to randomly crop images, bounding boxes, masks, + semantic segmentation maps. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + results (Union[dict, None]): Randomly cropped results, 'img_shape' + key in result dict is updated according to crop size. None will + be returned when there is no valid bbox after cropping. + """ + image_size = results['img'].shape[:2] + crop_size = self._get_crop_size(image_size) + results = self._crop_data(results, crop_size, self.allow_negative_crop) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(crop_size={self.crop_size}, ' + repr_str += f'crop_type={self.crop_type}, ' + repr_str += f'allow_negative_crop={self.allow_negative_crop}, ' + repr_str += f'recompute_bbox={self.recompute_bbox}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + +@TRANSFORMS.register_module() +class SegRescale(BaseTransform): + """Rescale semantic segmentation maps. + + This transform rescale the ``gt_seg_map`` according to ``scale_factor``. + + Required Keys: + + - gt_seg_map + + Modified Keys: + + - gt_seg_map + + Args: + scale_factor (float): The scale factor of the final output. Defaults + to 1. + backend (str): Image rescale backend, choices are 'cv2' and 'pillow'. + These two backends generates slightly different results. Defaults + to 'cv2'. + """ + + def __init__(self, scale_factor: float = 1, backend: str = 'cv2') -> None: + self.scale_factor = scale_factor + self.backend = backend + + def transform(self, results: dict) -> dict: + """Transform function to scale the semantic segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with semantic segmentation map scaled. + """ + if self.scale_factor != 1: + results['gt_seg_map'] = mmcv.imrescale( + results['gt_seg_map'], + self.scale_factor, + interpolation='nearest', + backend=self.backend) + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(scale_factor={self.scale_factor}, ' + repr_str += f'backend={self.backend})' + return repr_str + + +@TRANSFORMS.register_module() +class PhotoMetricDistortion(BaseTransform): + """Apply photometric distortion to image sequentially, every transformation + is applied with a probability of 0.5. The position of random contrast is in + second or second to last. + + 1. random brightness + 2. random contrast (mode 0) + 3. convert color from BGR to HSV + 4. random saturation + 5. random hue + 6. convert color from HSV to BGR + 7. random contrast (mode 1) + 8. randomly swap channels + + Required Keys: + + - img (np.uint8) + + Modified Keys: + + - img (np.float32) + + Args: + brightness_delta (int): delta of brightness. + contrast_range (sequence): range of contrast. + saturation_range (sequence): range of saturation. + hue_delta (int): delta of hue. + """ + + def __init__(self, + brightness_delta: int = 32, + contrast_range: Sequence[Number] = (0.5, 1.5), + saturation_range: Sequence[Number] = (0.5, 1.5), + hue_delta: int = 18) -> None: + self.brightness_delta = brightness_delta + self.contrast_lower, self.contrast_upper = contrast_range + self.saturation_lower, self.saturation_upper = saturation_range + self.hue_delta = hue_delta + + @cache_randomness + def _random_flags(self) -> Sequence[Number]: + mode = random.randint(2) + brightness_flag = random.randint(2) + contrast_flag = random.randint(2) + saturation_flag = random.randint(2) + hue_flag = random.randint(2) + swap_flag = random.randint(2) + delta_value = random.uniform(-self.brightness_delta, + self.brightness_delta) + alpha_value = random.uniform(self.contrast_lower, self.contrast_upper) + saturation_value = random.uniform(self.saturation_lower, + self.saturation_upper) + hue_value = random.uniform(-self.hue_delta, self.hue_delta) + swap_value = random.permutation(3) + + return (mode, brightness_flag, contrast_flag, saturation_flag, + hue_flag, swap_flag, delta_value, alpha_value, + saturation_value, hue_value, swap_value) + + def transform(self, results: dict) -> dict: + """Transform function to perform photometric distortion on images. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images distorted. + """ + assert 'img' in results, '`img` is not found in results' + img = results['img'] + img = img.astype(np.float32) + + (mode, brightness_flag, contrast_flag, saturation_flag, hue_flag, + swap_flag, delta_value, alpha_value, saturation_value, hue_value, + swap_value) = self._random_flags() + + # random brightness + if brightness_flag: + img += delta_value + + # mode == 0 --> do random contrast first + # mode == 1 --> do random contrast last + if mode == 1: + if contrast_flag: + img *= alpha_value + + # convert color from BGR to HSV + img = mmcv.bgr2hsv(img) + + # random saturation + if saturation_flag: + img[..., 1] *= saturation_value + # For image(type=float32), after convert bgr to hsv by opencv, + # valid saturation value range is [0, 1] + if saturation_value > 1: + img[..., 1] = img[..., 1].clip(0, 1) + + # random hue + if hue_flag: + img[..., 0] += hue_value + img[..., 0][img[..., 0] > 360] -= 360 + img[..., 0][img[..., 0] < 0] += 360 + + # convert color from HSV to BGR + img = mmcv.hsv2bgr(img) + + # random contrast + if mode == 0: + if contrast_flag: + img *= alpha_value + + # randomly swap channels + if swap_flag: + img = img[..., swap_value] + + results['img'] = img + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(brightness_delta={self.brightness_delta}, ' + repr_str += 'contrast_range=' + repr_str += f'{(self.contrast_lower, self.contrast_upper)}, ' + repr_str += 'saturation_range=' + repr_str += f'{(self.saturation_lower, self.saturation_upper)}, ' + repr_str += f'hue_delta={self.hue_delta})' + return repr_str + + +@TRANSFORMS.register_module() +class Expand(BaseTransform): + """Random expand the image & bboxes & masks & segmentation map. + + Randomly place the original image on a canvas of ``ratio`` x original image + size filled with mean values. The ratio is in the range of ratio_range. + + Required Keys: + + - img + - img_shape + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_masks + - gt_seg_map + + + Args: + mean (sequence): mean value of dataset. + to_rgb (bool): if need to convert the order of mean to align with RGB. + ratio_range (sequence)): range of expand ratio. + seg_ignore_label (int): label of ignore segmentation map. + prob (float): probability of applying this transformation + """ + + def __init__(self, + mean: Sequence[Number] = (0, 0, 0), + to_rgb: bool = True, + ratio_range: Sequence[Number] = (1, 4), + seg_ignore_label: int = None, + prob: float = 0.5) -> None: + self.to_rgb = to_rgb + self.ratio_range = ratio_range + if to_rgb: + self.mean = mean[::-1] + else: + self.mean = mean + self.min_ratio, self.max_ratio = ratio_range + self.seg_ignore_label = seg_ignore_label + self.prob = prob + + @cache_randomness + def _random_prob(self) -> float: + return random.uniform(0, 1) + + @cache_randomness + def _random_ratio(self) -> float: + return random.uniform(self.min_ratio, self.max_ratio) + + @cache_randomness + def _random_left_top(self, ratio: float, h: int, + w: int) -> Tuple[int, int]: + left = int(random.uniform(0, w * ratio - w)) + top = int(random.uniform(0, h * ratio - h)) + return left, top + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to expand images, bounding boxes, masks, + segmentation map. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images, bounding boxes, masks, segmentation + map expanded. + """ + if self._random_prob() > self.prob: + return results + assert 'img' in results, '`img` is not found in results' + img = results['img'] + h, w, c = img.shape + ratio = self._random_ratio() + # speedup expand when meets large image + if np.all(self.mean == self.mean[0]): + expand_img = np.empty((int(h * ratio), int(w * ratio), c), + img.dtype) + expand_img.fill(self.mean[0]) + else: + expand_img = np.full((int(h * ratio), int(w * ratio), c), + self.mean, + dtype=img.dtype) + left, top = self._random_left_top(ratio, h, w) + expand_img[top:top + h, left:left + w] = img + results['img'] = expand_img + results['img_shape'] = expand_img.shape[:2] + + # expand bboxes + if results.get('gt_bboxes', None) is not None: + results['gt_bboxes'].translate_([left, top]) + + # expand masks + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'].expand( + int(h * ratio), int(w * ratio), top, left) + + # expand segmentation map + if results.get('gt_seg_map', None) is not None: + gt_seg = results['gt_seg_map'] + expand_gt_seg = np.full((int(h * ratio), int(w * ratio)), + self.seg_ignore_label, + dtype=gt_seg.dtype) + expand_gt_seg[top:top + h, left:left + w] = gt_seg + results['gt_seg_map'] = expand_gt_seg + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(mean={self.mean}, to_rgb={self.to_rgb}, ' + repr_str += f'ratio_range={self.ratio_range}, ' + repr_str += f'seg_ignore_label={self.seg_ignore_label}, ' + repr_str += f'prob={self.prob})' + return repr_str + + +@TRANSFORMS.register_module() +class MinIoURandomCrop(BaseTransform): + """Random crop the image & bboxes & masks & segmentation map, the cropped + patches have minimum IoU requirement with original image & bboxes & masks. + + & segmentation map, the IoU threshold is randomly selected from min_ious. + + + Required Keys: + + - img + - img_shape + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - gt_ignore_flags (bool) (optional) + - gt_seg_map (np.uint8) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes + - gt_bboxes_labels + - gt_masks + - gt_ignore_flags + - gt_seg_map + + + Args: + min_ious (Sequence[float]): minimum IoU threshold for all intersections + with bounding boxes. + min_crop_size (float): minimum crop's size (i.e. h,w := a*h, a*w, + where a >= min_crop_size). + bbox_clip_border (bool, optional): Whether clip the objects outside + the border of the image. Defaults to True. + """ + + def __init__(self, + min_ious: Sequence[float] = (0.1, 0.3, 0.5, 0.7, 0.9), + min_crop_size: float = 0.3, + bbox_clip_border: bool = True) -> None: + + self.min_ious = min_ious + self.sample_mode = (1, *min_ious, 0) + self.min_crop_size = min_crop_size + self.bbox_clip_border = bbox_clip_border + + @cache_randomness + def _random_mode(self) -> Number: + return random.choice(self.sample_mode) + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to crop images and bounding boxes with minimum + IoU constraint. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images and bounding boxes cropped, \ + 'img_shape' key is updated. + """ + assert 'img' in results, '`img` is not found in results' + assert 'gt_bboxes' in results, '`gt_bboxes` is not found in results' + img = results['img'] + boxes = results['gt_bboxes'] + h, w, c = img.shape + while True: + mode = self._random_mode() + self.mode = mode + if mode == 1: + return results + + min_iou = self.mode + for i in range(50): + new_w = random.uniform(self.min_crop_size * w, w) + new_h = random.uniform(self.min_crop_size * h, h) + + # h / w in [0.5, 2] + if new_h / new_w < 0.5 or new_h / new_w > 2: + continue + + left = random.uniform(w - new_w) + top = random.uniform(h - new_h) + + patch = np.array( + (int(left), int(top), int(left + new_w), int(top + new_h))) + # Line or point crop is not allowed + if patch[2] == patch[0] or patch[3] == patch[1]: + continue + overlaps = boxes.overlaps( + HorizontalBoxes(patch.reshape(-1, 4).astype(np.float32)), + boxes).numpy().reshape(-1) + if len(overlaps) > 0 and overlaps.min() < min_iou: + continue + + # center of boxes should inside the crop img + # only adjust boxes and instance masks when the gt is not empty + if len(overlaps) > 0: + # adjust boxes + def is_center_of_bboxes_in_patch(boxes, patch): + centers = boxes.centers.numpy() + mask = ((centers[:, 0] > patch[0]) * + (centers[:, 1] > patch[1]) * + (centers[:, 0] < patch[2]) * + (centers[:, 1] < patch[3])) + return mask + + mask = is_center_of_bboxes_in_patch(boxes, patch) + if not mask.any(): + continue + if results.get('gt_bboxes', None) is not None: + boxes = results['gt_bboxes'] + mask = is_center_of_bboxes_in_patch(boxes, patch) + boxes = boxes[mask] + boxes.translate_([-patch[0], -patch[1]]) + if self.bbox_clip_border: + boxes.clip_( + [patch[3] - patch[1], patch[2] - patch[0]]) + results['gt_bboxes'] = boxes + + # ignore_flags + if results.get('gt_ignore_flags', None) is not None: + results['gt_ignore_flags'] = \ + results['gt_ignore_flags'][mask] + + # labels + if results.get('gt_bboxes_labels', None) is not None: + results['gt_bboxes_labels'] = results[ + 'gt_bboxes_labels'][mask] + + # mask fields + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'][ + mask.nonzero()[0]].crop(patch) + # adjust the img no matter whether the gt is empty before crop + img = img[patch[1]:patch[3], patch[0]:patch[2]] + results['img'] = img + results['img_shape'] = img.shape[:2] + + # seg fields + if results.get('gt_seg_map', None) is not None: + results['gt_seg_map'] = results['gt_seg_map'][ + patch[1]:patch[3], patch[0]:patch[2]] + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(min_ious={self.min_ious}, ' + repr_str += f'min_crop_size={self.min_crop_size}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + +@TRANSFORMS.register_module() +class Corrupt(BaseTransform): + """Corruption augmentation. + + Corruption transforms implemented based on + `imagecorruptions `_. + + Required Keys: + + - img (np.uint8) + + + Modified Keys: + + - img (np.uint8) + + + Args: + corruption (str): Corruption name. + severity (int): The severity of corruption. Defaults to 1. + """ + + def __init__(self, corruption: str, severity: int = 1) -> None: + self.corruption = corruption + self.severity = severity + + def transform(self, results: dict) -> dict: + """Call function to corrupt image. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Result dict with images corrupted. + """ + + if corrupt is None: + raise RuntimeError('imagecorruptions is not installed') + results['img'] = corrupt( + results['img'].astype(np.uint8), + corruption_name=self.corruption, + severity=self.severity) + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(corruption={self.corruption}, ' + repr_str += f'severity={self.severity})' + return repr_str + + +@TRANSFORMS.register_module() +@avoid_cache_randomness +class Albu(BaseTransform): + """Albumentation augmentation. + + Adds custom transformations from Albumentations library. + Please, visit `https://albumentations.readthedocs.io` + to get more information. + + Required Keys: + + - img (np.uint8) + - gt_bboxes (HorizontalBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + + Modified Keys: + + - img (np.uint8) + - gt_bboxes (HorizontalBoxes[torch.float32]) (optional) + - gt_masks (BitmapMasks | PolygonMasks) (optional) + - img_shape (tuple) + + An example of ``transforms`` is as followed: + + .. code-block:: + + [ + dict( + type='ShiftScaleRotate', + shift_limit=0.0625, + scale_limit=0.0, + rotate_limit=0, + interpolation=1, + p=0.5), + dict( + type='RandomBrightnessContrast', + brightness_limit=[0.1, 0.3], + contrast_limit=[0.1, 0.3], + p=0.2), + dict(type='ChannelShuffle', p=0.1), + dict( + type='OneOf', + transforms=[ + dict(type='Blur', blur_limit=3, p=1.0), + dict(type='MedianBlur', blur_limit=3, p=1.0) + ], + p=0.1), + ] + + Args: + transforms (list[dict]): A list of albu transformations + bbox_params (dict, optional): Bbox_params for albumentation `Compose` + keymap (dict, optional): Contains + {'input key':'albumentation-style key'} + skip_img_without_anno (bool): Whether to skip the image if no ann left + after aug. Defaults to False. + """ + + def __init__(self, + transforms: List[dict], + bbox_params: Optional[dict] = None, + keymap: Optional[dict] = None, + skip_img_without_anno: bool = False) -> None: + if Compose is None: + raise RuntimeError('albumentations is not installed') + + # Args will be modified later, copying it will be safer + transforms = copy.deepcopy(transforms) + if bbox_params is not None: + bbox_params = copy.deepcopy(bbox_params) + if keymap is not None: + keymap = copy.deepcopy(keymap) + self.transforms = transforms + self.filter_lost_elements = False + self.skip_img_without_anno = skip_img_without_anno + + # A simple workaround to remove masks without boxes + if (isinstance(bbox_params, dict) and 'label_fields' in bbox_params + and 'filter_lost_elements' in bbox_params): + self.filter_lost_elements = True + self.origin_label_fields = bbox_params['label_fields'] + bbox_params['label_fields'] = ['idx_mapper'] + del bbox_params['filter_lost_elements'] + + self.bbox_params = ( + self.albu_builder(bbox_params) if bbox_params else None) + self.aug = Compose([self.albu_builder(t) for t in self.transforms], + bbox_params=self.bbox_params) + + if not keymap: + self.keymap_to_albu = { + 'img': 'image', + 'gt_masks': 'masks', + 'gt_bboxes': 'bboxes' + } + else: + self.keymap_to_albu = keymap + self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()} + + def albu_builder(self, cfg: dict) -> albumentations: + """Import a module from albumentations. + + It inherits some of :func:`build_from_cfg` logic. + + Args: + cfg (dict): Config dict. It should at least contain the key "type". + + Returns: + obj: The constructed object. + """ + + assert isinstance(cfg, dict) and 'type' in cfg + args = cfg.copy() + obj_type = args.pop('type') + if is_str(obj_type): + if albumentations is None: + raise RuntimeError('albumentations is not installed') + obj_cls = getattr(albumentations, obj_type) + elif inspect.isclass(obj_type): + obj_cls = obj_type + else: + raise TypeError( + f'type must be a str or valid type, but got {type(obj_type)}') + + if 'transforms' in args: + args['transforms'] = [ + self.albu_builder(transform) + for transform in args['transforms'] + ] + + return obj_cls(**args) + + @staticmethod + def mapper(d: dict, keymap: dict) -> dict: + """Dictionary mapper. Renames keys according to keymap provided. + + Args: + d (dict): old dict + keymap (dict): {'old_key':'new_key'} + Returns: + dict: new dict. + """ + updated_dict = {} + for k, v in zip(d.keys(), d.values()): + new_k = keymap.get(k, k) + updated_dict[new_k] = d[k] + return updated_dict + + @autocast_box_type() + def transform(self, results: dict) -> Union[dict, None]: + """Transform function of Albu.""" + # TODO: gt_seg_map is not currently supported + # dict to albumentations format + results = self.mapper(results, self.keymap_to_albu) + results, ori_masks = self._preprocess_results(results) + results = self.aug(**results) + results = self._postprocess_results(results, ori_masks) + if results is None: + return None + # back to the original format + results = self.mapper(results, self.keymap_back) + results['img_shape'] = results['img'].shape[:2] + return results + + def _preprocess_results(self, results: dict) -> tuple: + """Pre-processing results to facilitate the use of Albu.""" + if 'bboxes' in results: + # to list of boxes + if not isinstance(results['bboxes'], HorizontalBoxes): + raise NotImplementedError( + 'Albu only supports horizontal boxes now') + bboxes = results['bboxes'].numpy() + results['bboxes'] = [x for x in bboxes] + # add pseudo-field for filtration + if self.filter_lost_elements: + results['idx_mapper'] = np.arange(len(results['bboxes'])) + + # TODO: Support mask structure in albu + ori_masks = None + if 'masks' in results: + if isinstance(results['masks'], PolygonMasks): + raise NotImplementedError( + 'Albu only supports BitMap masks now') + ori_masks = results['masks'] + if albumentations.__version__ < '0.5': + results['masks'] = results['masks'].masks + else: + results['masks'] = [mask for mask in results['masks'].masks] + + return results, ori_masks + + def _postprocess_results( + self, + results: dict, + ori_masks: Optional[Union[BitmapMasks, + PolygonMasks]] = None) -> dict: + """Post-processing Albu output.""" + # albumentations may return np.array or list on different versions + if 'gt_bboxes_labels' in results and isinstance( + results['gt_bboxes_labels'], list): + results['gt_bboxes_labels'] = np.array( + results['gt_bboxes_labels'], dtype=np.int64) + if 'gt_ignore_flags' in results and isinstance( + results['gt_ignore_flags'], list): + results['gt_ignore_flags'] = np.array( + results['gt_ignore_flags'], dtype=bool) + + if 'bboxes' in results: + if isinstance(results['bboxes'], list): + results['bboxes'] = np.array( + results['bboxes'], dtype=np.float32) + results['bboxes'] = results['bboxes'].reshape(-1, 4) + results['bboxes'] = HorizontalBoxes(results['bboxes']) + + # filter label_fields + if self.filter_lost_elements: + + for label in self.origin_label_fields: + results[label] = np.array( + [results[label][i] for i in results['idx_mapper']]) + if 'masks' in results: + assert ori_masks is not None + results['masks'] = np.array( + [results['masks'][i] for i in results['idx_mapper']]) + results['masks'] = ori_masks.__class__( + results['masks'], + results['masks'][0].shape[0], + results['masks'][0].shape[1], + ) + if (not len(results['idx_mapper']) + and self.skip_img_without_anno): + return None + elif 'masks' in results: + results['masks'] = ori_masks.__class__(results['masks'], + ori_masks.height, + ori_masks.width) + + return results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + f'(transforms={self.transforms})' + return repr_str + + +@TRANSFORMS.register_module() +@avoid_cache_randomness +class RandomCenterCropPad(BaseTransform): + """Random center crop and random around padding for CornerNet. + + This operation generates randomly cropped image from the original image and + pads it simultaneously. Different from :class:`RandomCrop`, the output + shape may not equal to ``crop_size`` strictly. We choose a random value + from ``ratios`` and the output shape could be larger or smaller than + ``crop_size``. The padding operation is also different from :class:`Pad`, + here we use around padding instead of right-bottom padding. + + The relation between output image (padding image) and original image: + + .. code:: text + + output image + + +----------------------------+ + | padded area | + +------|----------------------------|----------+ + | | cropped area | | + | | +---------------+ | | + | | | . center | | | original image + | | | range | | | + | | +---------------+ | | + +------|----------------------------|----------+ + | padded area | + +----------------------------+ + + There are 5 main areas in the figure: + + - output image: output image of this operation, also called padding + image in following instruction. + - original image: input image of this operation. + - padded area: non-intersect area of output image and original image. + - cropped area: the overlap of output image and original image. + - center range: a smaller area where random center chosen from. + center range is computed by ``border`` and original image's shape + to avoid our random center is too close to original image's border. + + Also this operation act differently in train and test mode, the summary + pipeline is listed below. + + Train pipeline: + + 1. Choose a ``random_ratio`` from ``ratios``, the shape of padding image + will be ``random_ratio * crop_size``. + 2. Choose a ``random_center`` in center range. + 3. Generate padding image with center matches the ``random_center``. + 4. Initialize the padding image with pixel value equals to ``mean``. + 5. Copy the cropped area to padding image. + 6. Refine annotations. + + Test pipeline: + + 1. Compute output shape according to ``test_pad_mode``. + 2. Generate padding image with center matches the original image + center. + 3. Initialize the padding image with pixel value equals to ``mean``. + 4. Copy the ``cropped area`` to padding image. + + Required Keys: + + - img (np.float32) + - img_shape (tuple) + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - img (np.float32) + - img_shape (tuple) + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + + Args: + crop_size (tuple, optional): expected size after crop, final size will + computed according to ratio. Requires (width, height) + in train mode, and None in test mode. + ratios (tuple, optional): random select a ratio from tuple and crop + image to (crop_size[0] * ratio) * (crop_size[1] * ratio). + Only available in train mode. Defaults to (0.9, 1.0, 1.1). + border (int, optional): max distance from center select area to image + border. Only available in train mode. Defaults to 128. + mean (sequence, optional): Mean values of 3 channels. + std (sequence, optional): Std values of 3 channels. + to_rgb (bool, optional): Whether to convert the image from BGR to RGB. + test_mode (bool): whether involve random variables in transform. + In train mode, crop_size is fixed, center coords and ratio is + random selected from predefined lists. In test mode, crop_size + is image's original shape, center coords and ratio is fixed. + Defaults to False. + test_pad_mode (tuple, optional): padding method and padding shape + value, only available in test mode. Default is using + 'logical_or' with 127 as padding shape value. + + - 'logical_or': final_shape = input_shape | padding_shape_value + - 'size_divisor': final_shape = int( + ceil(input_shape / padding_shape_value) * padding_shape_value) + + Defaults to ('logical_or', 127). + test_pad_add_pix (int): Extra padding pixel in test mode. + Defaults to 0. + bbox_clip_border (bool): Whether clip the objects outside + the border of the image. Defaults to True. + """ + + def __init__(self, + crop_size: Optional[tuple] = None, + ratios: Optional[tuple] = (0.9, 1.0, 1.1), + border: Optional[int] = 128, + mean: Optional[Sequence] = None, + std: Optional[Sequence] = None, + to_rgb: Optional[bool] = None, + test_mode: bool = False, + test_pad_mode: Optional[tuple] = ('logical_or', 127), + test_pad_add_pix: int = 0, + bbox_clip_border: bool = True) -> None: + if test_mode: + assert crop_size is None, 'crop_size must be None in test mode' + assert ratios is None, 'ratios must be None in test mode' + assert border is None, 'border must be None in test mode' + assert isinstance(test_pad_mode, (list, tuple)) + assert test_pad_mode[0] in ['logical_or', 'size_divisor'] + else: + assert isinstance(crop_size, (list, tuple)) + assert crop_size[0] > 0 and crop_size[1] > 0, ( + 'crop_size must > 0 in train mode') + assert isinstance(ratios, (list, tuple)) + assert test_pad_mode is None, ( + 'test_pad_mode must be None in train mode') + + self.crop_size = crop_size + self.ratios = ratios + self.border = border + # We do not set default value to mean, std and to_rgb because these + # hyper-parameters are easy to forget but could affect the performance. + # Please use the same setting as Normalize for performance assurance. + assert mean is not None and std is not None and to_rgb is not None + self.to_rgb = to_rgb + self.input_mean = mean + self.input_std = std + if to_rgb: + self.mean = mean[::-1] + self.std = std[::-1] + else: + self.mean = mean + self.std = std + self.test_mode = test_mode + self.test_pad_mode = test_pad_mode + self.test_pad_add_pix = test_pad_add_pix + self.bbox_clip_border = bbox_clip_border + + def _get_border(self, border, size): + """Get final border for the target size. + + This function generates a ``final_border`` according to image's shape. + The area between ``final_border`` and ``size - final_border`` is the + ``center range``. We randomly choose center from the ``center range`` + to avoid our random center is too close to original image's border. + Also ``center range`` should be larger than 0. + + Args: + border (int): The initial border, default is 128. + size (int): The width or height of original image. + Returns: + int: The final border. + """ + k = 2 * border / size + i = pow(2, np.ceil(np.log2(np.ceil(k))) + (k == int(k))) + return border // i + + def _filter_boxes(self, patch, boxes): + """Check whether the center of each box is in the patch. + + Args: + patch (list[int]): The cropped area, [left, top, right, bottom]. + boxes (numpy array, (N x 4)): Ground truth boxes. + + Returns: + mask (numpy array, (N,)): Each box is inside or outside the patch. + """ + center = boxes.centers.numpy() + mask = (center[:, 0] > patch[0]) * (center[:, 1] > patch[1]) * ( + center[:, 0] < patch[2]) * ( + center[:, 1] < patch[3]) + return mask + + def _crop_image_and_paste(self, image, center, size): + """Crop image with a given center and size, then paste the cropped + image to a blank image with two centers align. + + This function is equivalent to generating a blank image with ``size`` + as its shape. Then cover it on the original image with two centers ( + the center of blank image and the random center of original image) + aligned. The overlap area is paste from the original image and the + outside area is filled with ``mean pixel``. + + Args: + image (np array, H x W x C): Original image. + center (list[int]): Target crop center coord. + size (list[int]): Target crop size. [target_h, target_w] + + Returns: + cropped_img (np array, target_h x target_w x C): Cropped image. + border (np array, 4): The distance of four border of + ``cropped_img`` to the original image area, [top, bottom, + left, right] + patch (list[int]): The cropped area, [left, top, right, bottom]. + """ + center_y, center_x = center + target_h, target_w = size + img_h, img_w, img_c = image.shape + + x0 = max(0, center_x - target_w // 2) + x1 = min(center_x + target_w // 2, img_w) + y0 = max(0, center_y - target_h // 2) + y1 = min(center_y + target_h // 2, img_h) + patch = np.array((int(x0), int(y0), int(x1), int(y1))) + + left, right = center_x - x0, x1 - center_x + top, bottom = center_y - y0, y1 - center_y + + cropped_center_y, cropped_center_x = target_h // 2, target_w // 2 + cropped_img = np.zeros((target_h, target_w, img_c), dtype=image.dtype) + for i in range(img_c): + cropped_img[:, :, i] += self.mean[i] + y_slice = slice(cropped_center_y - top, cropped_center_y + bottom) + x_slice = slice(cropped_center_x - left, cropped_center_x + right) + cropped_img[y_slice, x_slice, :] = image[y0:y1, x0:x1, :] + + border = np.array([ + cropped_center_y - top, cropped_center_y + bottom, + cropped_center_x - left, cropped_center_x + right + ], + dtype=np.float32) + + return cropped_img, border, patch + + def _train_aug(self, results): + """Random crop and around padding the original image. + + Args: + results (dict): Image infomations in the augment pipeline. + + Returns: + results (dict): The updated dict. + """ + img = results['img'] + h, w, c = img.shape + gt_bboxes = results['gt_bboxes'] + while True: + scale = random.choice(self.ratios) + new_h = int(self.crop_size[1] * scale) + new_w = int(self.crop_size[0] * scale) + h_border = self._get_border(self.border, h) + w_border = self._get_border(self.border, w) + + for i in range(50): + center_x = random.randint(low=w_border, high=w - w_border) + center_y = random.randint(low=h_border, high=h - h_border) + + cropped_img, border, patch = self._crop_image_and_paste( + img, [center_y, center_x], [new_h, new_w]) + + if len(gt_bboxes) == 0: + results['img'] = cropped_img + results['img_shape'] = cropped_img.shape[:2] + return results + + # if image do not have valid bbox, any crop patch is valid. + mask = self._filter_boxes(patch, gt_bboxes) + if not mask.any(): + continue + + results['img'] = cropped_img + results['img_shape'] = cropped_img.shape[:2] + + x0, y0, x1, y1 = patch + + left_w, top_h = center_x - x0, center_y - y0 + cropped_center_x, cropped_center_y = new_w // 2, new_h // 2 + + # crop bboxes accordingly and clip to the image boundary + gt_bboxes = gt_bboxes[mask] + gt_bboxes.translate_([ + cropped_center_x - left_w - x0, + cropped_center_y - top_h - y0 + ]) + if self.bbox_clip_border: + gt_bboxes.clip_([new_h, new_w]) + keep = gt_bboxes.is_inside([new_h, new_w]).numpy() + gt_bboxes = gt_bboxes[keep] + + results['gt_bboxes'] = gt_bboxes + + # ignore_flags + if results.get('gt_ignore_flags', None) is not None: + gt_ignore_flags = results['gt_ignore_flags'][mask] + results['gt_ignore_flags'] = \ + gt_ignore_flags[keep] + + # labels + if results.get('gt_bboxes_labels', None) is not None: + gt_labels = results['gt_bboxes_labels'][mask] + results['gt_bboxes_labels'] = gt_labels[keep] + + if 'gt_masks' in results or 'gt_seg_map' in results: + raise NotImplementedError( + 'RandomCenterCropPad only supports bbox.') + + return results + + def _test_aug(self, results): + """Around padding the original image without cropping. + + The padding mode and value are from ``test_pad_mode``. + + Args: + results (dict): Image infomations in the augment pipeline. + + Returns: + results (dict): The updated dict. + """ + img = results['img'] + h, w, c = img.shape + if self.test_pad_mode[0] in ['logical_or']: + # self.test_pad_add_pix is only used for centernet + target_h = (h | self.test_pad_mode[1]) + self.test_pad_add_pix + target_w = (w | self.test_pad_mode[1]) + self.test_pad_add_pix + elif self.test_pad_mode[0] in ['size_divisor']: + divisor = self.test_pad_mode[1] + target_h = int(np.ceil(h / divisor)) * divisor + target_w = int(np.ceil(w / divisor)) * divisor + else: + raise NotImplementedError( + 'RandomCenterCropPad only support two testing pad mode:' + 'logical-or and size_divisor.') + + cropped_img, border, _ = self._crop_image_and_paste( + img, [h // 2, w // 2], [target_h, target_w]) + results['img'] = cropped_img + results['img_shape'] = cropped_img.shape[:2] + results['border'] = border + return results + + @autocast_box_type() + def transform(self, results: dict) -> dict: + img = results['img'] + assert img.dtype == np.float32, ( + 'RandomCenterCropPad needs the input image of dtype np.float32,' + ' please set "to_float32=True" in "LoadImageFromFile" pipeline') + h, w, c = img.shape + assert c == len(self.mean) + if self.test_mode: + return self._test_aug(results) + else: + return self._train_aug(results) + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(crop_size={self.crop_size}, ' + repr_str += f'ratios={self.ratios}, ' + repr_str += f'border={self.border}, ' + repr_str += f'mean={self.input_mean}, ' + repr_str += f'std={self.input_std}, ' + repr_str += f'to_rgb={self.to_rgb}, ' + repr_str += f'test_mode={self.test_mode}, ' + repr_str += f'test_pad_mode={self.test_pad_mode}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + +@TRANSFORMS.register_module() +class CutOut(BaseTransform): + """CutOut operation. + + Randomly drop some regions of image used in + `Cutout `_. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + n_holes (int or tuple[int, int]): Number of regions to be dropped. + If it is given as a list, number of holes will be randomly + selected from the closed interval [``n_holes[0]``, ``n_holes[1]``]. + cutout_shape (tuple[int, int] or list[tuple[int, int]], optional): + The candidate shape of dropped regions. It can be + ``tuple[int, int]`` to use a fixed cutout shape, or + ``list[tuple[int, int]]`` to randomly choose shape + from the list. Defaults to None. + cutout_ratio (tuple[float, float] or list[tuple[float, float]], + optional): The candidate ratio of dropped regions. It can be + ``tuple[float, float]`` to use a fixed ratio or + ``list[tuple[float, float]]`` to randomly choose ratio + from the list. Please note that ``cutout_shape`` and + ``cutout_ratio`` cannot be both given at the same time. + Defaults to None. + fill_in (tuple[float, float, float] or tuple[int, int, int]): The value + of pixel to fill in the dropped regions. Defaults to (0, 0, 0). + """ + + def __init__( + self, + n_holes: Union[int, Tuple[int, int]], + cutout_shape: Optional[Union[Tuple[int, int], + List[Tuple[int, int]]]] = None, + cutout_ratio: Optional[Union[Tuple[float, float], + List[Tuple[float, float]]]] = None, + fill_in: Union[Tuple[float, float, float], Tuple[int, int, + int]] = (0, 0, 0) + ) -> None: + + assert (cutout_shape is None) ^ (cutout_ratio is None), \ + 'Either cutout_shape or cutout_ratio should be specified.' + assert (isinstance(cutout_shape, (list, tuple)) + or isinstance(cutout_ratio, (list, tuple))) + if isinstance(n_holes, tuple): + assert len(n_holes) == 2 and 0 <= n_holes[0] < n_holes[1] + else: + n_holes = (n_holes, n_holes) + self.n_holes = n_holes + self.fill_in = fill_in + self.with_ratio = cutout_ratio is not None + self.candidates = cutout_ratio if self.with_ratio else cutout_shape + if not isinstance(self.candidates, list): + self.candidates = [self.candidates] + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Call function to drop some regions of image.""" + h, w, c = results['img'].shape + n_holes = np.random.randint(self.n_holes[0], self.n_holes[1] + 1) + for _ in range(n_holes): + x1 = np.random.randint(0, w) + y1 = np.random.randint(0, h) + index = np.random.randint(0, len(self.candidates)) + if not self.with_ratio: + cutout_w, cutout_h = self.candidates[index] + else: + cutout_w = int(self.candidates[index][0] * w) + cutout_h = int(self.candidates[index][1] * h) + + x2 = np.clip(x1 + cutout_w, 0, w) + y2 = np.clip(y1 + cutout_h, 0, h) + results['img'][y1:y2, x1:x2, :] = self.fill_in + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(n_holes={self.n_holes}, ' + repr_str += (f'cutout_ratio={self.candidates}, ' if self.with_ratio + else f'cutout_shape={self.candidates}, ') + repr_str += f'fill_in={self.fill_in})' + return repr_str + + +@TRANSFORMS.register_module() +class Mosaic(BaseTransform): + """Mosaic augmentation. + + Given 4 images, mosaic transform combines them into + one output image. The output image is composed of the parts from each sub- + image. + + .. code:: text + + mosaic transform + center_x + +------------------------------+ + | pad | pad | + | +-----------+ | + | | | | + | | image1 |--------+ | + | | | | | + | | | image2 | | + center_y |----+-------------+-----------| + | | cropped | | + |pad | image3 | image4 | + | | | | + +----|-------------+-----------+ + | | + +-------------+ + + The mosaic transform steps are as follows: + + 1. Choose the mosaic center as the intersections of 4 images + 2. Get the left top image according to the index, and randomly + sample another 3 images from the custom dataset. + 3. Sub image will be cropped if image is larger than mosaic patch + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - mix_results (List[dict]) + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + Args: + img_scale (Sequence[int]): Image size before mosaic pipeline of single + image. The shape order should be (width, height). + Defaults to (640, 640). + center_ratio_range (Sequence[float]): Center ratio range of mosaic + output. Defaults to (0.5, 1.5). + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + pad_val (int): Pad value. Defaults to 114. + prob (float): Probability of applying this transformation. + Defaults to 1.0. + """ + + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + center_ratio_range: Tuple[float, float] = (0.5, 1.5), + bbox_clip_border: bool = True, + pad_val: float = 114.0, + prob: float = 1.0) -> None: + assert isinstance(img_scale, tuple) + assert 0 <= prob <= 1.0, 'The probability should be in range [0,1]. ' \ + f'got {prob}.' + + log_img_scale(img_scale, skip_square=True, shape_order='wh') + self.img_scale = img_scale + self.center_ratio_range = center_ratio_range + self.bbox_clip_border = bbox_clip_border + self.pad_val = pad_val + self.prob = prob + + @cache_randomness + def get_indexes(self, dataset: BaseDataset) -> int: + """Call function to collect indexes. + + Args: + dataset (:obj:`MultiImageMixDataset`): The dataset. + + Returns: + list: indexes. + """ + + indexes = [random.randint(0, len(dataset)) for _ in range(3)] + return indexes + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Mosaic transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + if random.uniform(0, 1) > self.prob: + return results + + assert 'mix_results' in results + mosaic_bboxes = [] + mosaic_bboxes_labels = [] + mosaic_ignore_flags = [] + if len(results['img'].shape) == 3: + mosaic_img = np.full( + (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2), 3), + self.pad_val, + dtype=results['img'].dtype) + else: + mosaic_img = np.full( + (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2)), + self.pad_val, + dtype=results['img'].dtype) + + # mosaic center x, y + center_x = int( + random.uniform(*self.center_ratio_range) * self.img_scale[0]) + center_y = int( + random.uniform(*self.center_ratio_range) * self.img_scale[1]) + center_position = (center_x, center_y) + + loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') + for i, loc in enumerate(loc_strs): + if loc == 'top_left': + results_patch = copy.deepcopy(results) + else: + results_patch = copy.deepcopy(results['mix_results'][i - 1]) + + img_i = results_patch['img'] + h_i, w_i = img_i.shape[:2] + # keep_ratio resize + scale_ratio_i = min(self.img_scale[1] / h_i, + self.img_scale[0] / w_i) + img_i = mmcv.imresize( + img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i))) + + # compute the combine parameters + paste_coord, crop_coord = self._mosaic_combine( + loc, center_position, img_i.shape[:2][::-1]) + x1_p, y1_p, x2_p, y2_p = paste_coord + x1_c, y1_c, x2_c, y2_c = crop_coord + + # crop and paste image + mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c] + + # adjust coordinate + gt_bboxes_i = results_patch['gt_bboxes'] + gt_bboxes_labels_i = results_patch['gt_bboxes_labels'] + gt_ignore_flags_i = results_patch['gt_ignore_flags'] + + padw = x1_p - x1_c + padh = y1_p - y1_c + gt_bboxes_i.rescale_([scale_ratio_i, scale_ratio_i]) + gt_bboxes_i.translate_([padw, padh]) + mosaic_bboxes.append(gt_bboxes_i) + mosaic_bboxes_labels.append(gt_bboxes_labels_i) + mosaic_ignore_flags.append(gt_ignore_flags_i) + + mosaic_bboxes = mosaic_bboxes[0].cat(mosaic_bboxes, 0) + mosaic_bboxes_labels = np.concatenate(mosaic_bboxes_labels, 0) + mosaic_ignore_flags = np.concatenate(mosaic_ignore_flags, 0) + + if self.bbox_clip_border: + mosaic_bboxes.clip_([2 * self.img_scale[1], 2 * self.img_scale[0]]) + # remove outside bboxes + inside_inds = mosaic_bboxes.is_inside( + [2 * self.img_scale[1], 2 * self.img_scale[0]]).numpy() + mosaic_bboxes = mosaic_bboxes[inside_inds] + mosaic_bboxes_labels = mosaic_bboxes_labels[inside_inds] + mosaic_ignore_flags = mosaic_ignore_flags[inside_inds] + + results['img'] = mosaic_img + results['img_shape'] = mosaic_img.shape[:2] + results['gt_bboxes'] = mosaic_bboxes + results['gt_bboxes_labels'] = mosaic_bboxes_labels + results['gt_ignore_flags'] = mosaic_ignore_flags + return results + + def _mosaic_combine( + self, loc: str, center_position_xy: Sequence[float], + img_shape_wh: Sequence[int]) -> Tuple[Tuple[int], Tuple[int]]: + """Calculate global coordinate of mosaic image and local coordinate of + cropped sub-image. + + Args: + loc (str): Index for the sub-image, loc in ('top_left', + 'top_right', 'bottom_left', 'bottom_right'). + center_position_xy (Sequence[float]): Mixing center for 4 images, + (x, y). + img_shape_wh (Sequence[int]): Width and height of sub-image + + Returns: + tuple[tuple[float]]: Corresponding coordinate of pasting and + cropping + - paste_coord (tuple): paste corner coordinate in mosaic image. + - crop_coord (tuple): crop corner coordinate in mosaic image. + """ + assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right') + if loc == 'top_left': + # index0 to top left part of image + x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ + max(center_position_xy[1] - img_shape_wh[1], 0), \ + center_position_xy[0], \ + center_position_xy[1] + crop_coord = img_shape_wh[0] - (x2 - x1), img_shape_wh[1] - ( + y2 - y1), img_shape_wh[0], img_shape_wh[1] + + elif loc == 'top_right': + # index1 to top right part of image + x1, y1, x2, y2 = center_position_xy[0], \ + max(center_position_xy[1] - img_shape_wh[1], 0), \ + min(center_position_xy[0] + img_shape_wh[0], + self.img_scale[0] * 2), \ + center_position_xy[1] + crop_coord = 0, img_shape_wh[1] - (y2 - y1), min( + img_shape_wh[0], x2 - x1), img_shape_wh[1] + + elif loc == 'bottom_left': + # index2 to bottom left part of image + x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ + center_position_xy[1], \ + center_position_xy[0], \ + min(self.img_scale[1] * 2, center_position_xy[1] + + img_shape_wh[1]) + crop_coord = img_shape_wh[0] - (x2 - x1), 0, img_shape_wh[0], min( + y2 - y1, img_shape_wh[1]) + + else: + # index3 to bottom right part of image + x1, y1, x2, y2 = center_position_xy[0], \ + center_position_xy[1], \ + min(center_position_xy[0] + img_shape_wh[0], + self.img_scale[0] * 2), \ + min(self.img_scale[1] * 2, center_position_xy[1] + + img_shape_wh[1]) + crop_coord = 0, 0, min(img_shape_wh[0], + x2 - x1), min(y2 - y1, img_shape_wh[1]) + + paste_coord = x1, y1, x2, y2 + return paste_coord, crop_coord + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(img_scale={self.img_scale}, ' + repr_str += f'center_ratio_range={self.center_ratio_range}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'prob={self.prob})' + return repr_str + + +@TRANSFORMS.register_module() +class MixUp(BaseTransform): + """MixUp data augmentation. + + .. code:: text + + mixup transform + +------------------------------+ + | mixup image | | + | +--------|--------+ | + | | | | | + |---------------+ | | + | | | | + | | image | | + | | | | + | | | | + | |-----------------+ | + | pad | + +------------------------------+ + + The mixup transform steps are as follows: + + 1. Another random image is picked by dataset and embedded in + the top left patch(after padding and resizing) + 2. The target of mixup transform is the weighted average of mixup + image and origin image. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - mix_results (List[dict]) + + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + + Args: + img_scale (Sequence[int]): Image output size after mixup pipeline. + The shape order should be (width, height). Defaults to (640, 640). + ratio_range (Sequence[float]): Scale ratio of mixup image. + Defaults to (0.5, 1.5). + flip_ratio (float): Horizontal flip ratio of mixup image. + Defaults to 0.5. + pad_val (int): Pad value. Defaults to 114. + max_iters (int): The maximum number of iterations. If the number of + iterations is greater than `max_iters`, but gt_bbox is still + empty, then the iteration is terminated. Defaults to 15. + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + """ + + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + ratio_range: Tuple[float, float] = (0.5, 1.5), + flip_ratio: float = 0.5, + pad_val: float = 114.0, + max_iters: int = 15, + bbox_clip_border: bool = True) -> None: + assert isinstance(img_scale, tuple) + log_img_scale(img_scale, skip_square=True, shape_order='wh') + self.dynamic_scale = img_scale + self.ratio_range = ratio_range + self.flip_ratio = flip_ratio + self.pad_val = pad_val + self.max_iters = max_iters + self.bbox_clip_border = bbox_clip_border + + @cache_randomness + def get_indexes(self, dataset: BaseDataset) -> int: + """Call function to collect indexes. + + Args: + dataset (:obj:`MultiImageMixDataset`): The dataset. + + Returns: + list: indexes. + """ + + for i in range(self.max_iters): + index = random.randint(0, len(dataset)) + gt_bboxes_i = dataset[index]['gt_bboxes'] + if len(gt_bboxes_i) != 0: + break + + return index + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """MixUp transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + + assert 'mix_results' in results + assert len( + results['mix_results']) == 1, 'MixUp only support 2 images now !' + + if results['mix_results'][0]['gt_bboxes'].shape[0] == 0: + # empty bbox + return results + + retrieve_results = results['mix_results'][0] + retrieve_img = retrieve_results['img'] + + jit_factor = random.uniform(*self.ratio_range) + is_flip = random.uniform(0, 1) > self.flip_ratio + + if len(retrieve_img.shape) == 3: + out_img = np.ones( + (self.dynamic_scale[1], self.dynamic_scale[0], 3), + dtype=retrieve_img.dtype) * self.pad_val + else: + out_img = np.ones( + self.dynamic_scale[::-1], + dtype=retrieve_img.dtype) * self.pad_val + + # 1. keep_ratio resize + scale_ratio = min(self.dynamic_scale[1] / retrieve_img.shape[0], + self.dynamic_scale[0] / retrieve_img.shape[1]) + retrieve_img = mmcv.imresize( + retrieve_img, (int(retrieve_img.shape[1] * scale_ratio), + int(retrieve_img.shape[0] * scale_ratio))) + + # 2. paste + out_img[:retrieve_img.shape[0], :retrieve_img.shape[1]] = retrieve_img + + # 3. scale jit + scale_ratio *= jit_factor + out_img = mmcv.imresize(out_img, (int(out_img.shape[1] * jit_factor), + int(out_img.shape[0] * jit_factor))) + + # 4. flip + if is_flip: + out_img = out_img[:, ::-1, :] + + # 5. random crop + ori_img = results['img'] + origin_h, origin_w = out_img.shape[:2] + target_h, target_w = ori_img.shape[:2] + padded_img = np.ones((max(origin_h, target_h), max( + origin_w, target_w), 3)) * self.pad_val + padded_img = padded_img.astype(np.uint8) + padded_img[:origin_h, :origin_w] = out_img + + x_offset, y_offset = 0, 0 + if padded_img.shape[0] > target_h: + y_offset = random.randint(0, padded_img.shape[0] - target_h) + if padded_img.shape[1] > target_w: + x_offset = random.randint(0, padded_img.shape[1] - target_w) + padded_cropped_img = padded_img[y_offset:y_offset + target_h, + x_offset:x_offset + target_w] + + # 6. adjust bbox + retrieve_gt_bboxes = retrieve_results['gt_bboxes'] + retrieve_gt_bboxes.rescale_([scale_ratio, scale_ratio]) + if self.bbox_clip_border: + retrieve_gt_bboxes.clip_([origin_h, origin_w]) + + if is_flip: + retrieve_gt_bboxes.flip_([origin_h, origin_w], + direction='horizontal') + + # 7. filter + cp_retrieve_gt_bboxes = retrieve_gt_bboxes.clone() + cp_retrieve_gt_bboxes.translate_([-x_offset, -y_offset]) + if self.bbox_clip_border: + cp_retrieve_gt_bboxes.clip_([target_h, target_w]) + + # 8. mix up + ori_img = ori_img.astype(np.float32) + mixup_img = 0.5 * ori_img + 0.5 * padded_cropped_img.astype(np.float32) + + retrieve_gt_bboxes_labels = retrieve_results['gt_bboxes_labels'] + retrieve_gt_ignore_flags = retrieve_results['gt_ignore_flags'] + + mixup_gt_bboxes = cp_retrieve_gt_bboxes.cat( + (results['gt_bboxes'], cp_retrieve_gt_bboxes), dim=0) + mixup_gt_bboxes_labels = np.concatenate( + (results['gt_bboxes_labels'], retrieve_gt_bboxes_labels), axis=0) + mixup_gt_ignore_flags = np.concatenate( + (results['gt_ignore_flags'], retrieve_gt_ignore_flags), axis=0) + + # remove outside bbox + inside_inds = mixup_gt_bboxes.is_inside([target_h, target_w]).numpy() + mixup_gt_bboxes = mixup_gt_bboxes[inside_inds] + mixup_gt_bboxes_labels = mixup_gt_bboxes_labels[inside_inds] + mixup_gt_ignore_flags = mixup_gt_ignore_flags[inside_inds] + + results['img'] = mixup_img.astype(np.uint8) + results['img_shape'] = mixup_img.shape[:2] + results['gt_bboxes'] = mixup_gt_bboxes + results['gt_bboxes_labels'] = mixup_gt_bboxes_labels + results['gt_ignore_flags'] = mixup_gt_ignore_flags + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(dynamic_scale={self.dynamic_scale}, ' + repr_str += f'ratio_range={self.ratio_range}, ' + repr_str += f'flip_ratio={self.flip_ratio}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'max_iters={self.max_iters}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomAffine(BaseTransform): + """Random affine transform data augmentation. + + This operation randomly generates affine transform matrix which including + rotation, translation, shear and scaling transforms. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + Args: + max_rotate_degree (float): Maximum degrees of rotation transform. + Defaults to 10. + max_translate_ratio (float): Maximum ratio of translation. + Defaults to 0.1. + scaling_ratio_range (tuple[float]): Min and max ratio of + scaling transform. Defaults to (0.5, 1.5). + max_shear_degree (float): Maximum degrees of shear + transform. Defaults to 2. + border (tuple[int]): Distance from width and height sides of input + image to adjust output shape. Only used in mosaic dataset. + Defaults to (0, 0). + border_val (tuple[int]): Border padding values of 3 channels. + Defaults to (114, 114, 114). + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + """ + + def __init__(self, + max_rotate_degree: float = 10.0, + max_translate_ratio: float = 0.1, + scaling_ratio_range: Tuple[float, float] = (0.5, 1.5), + max_shear_degree: float = 2.0, + border: Tuple[int, int] = (0, 0), + border_val: Tuple[int, int, int] = (114, 114, 114), + bbox_clip_border: bool = True) -> None: + assert 0 <= max_translate_ratio <= 1 + assert scaling_ratio_range[0] <= scaling_ratio_range[1] + assert scaling_ratio_range[0] > 0 + self.max_rotate_degree = max_rotate_degree + self.max_translate_ratio = max_translate_ratio + self.scaling_ratio_range = scaling_ratio_range + self.max_shear_degree = max_shear_degree + self.border = border + self.border_val = border_val + self.bbox_clip_border = bbox_clip_border + + @cache_randomness + def _get_random_homography_matrix(self, height, width): + # Rotation + rotation_degree = random.uniform(-self.max_rotate_degree, + self.max_rotate_degree) + rotation_matrix = self._get_rotation_matrix(rotation_degree) + + # Scaling + scaling_ratio = random.uniform(self.scaling_ratio_range[0], + self.scaling_ratio_range[1]) + scaling_matrix = self._get_scaling_matrix(scaling_ratio) + + # Shear + x_degree = random.uniform(-self.max_shear_degree, + self.max_shear_degree) + y_degree = random.uniform(-self.max_shear_degree, + self.max_shear_degree) + shear_matrix = self._get_shear_matrix(x_degree, y_degree) + + # Translation + trans_x = random.uniform(-self.max_translate_ratio, + self.max_translate_ratio) * width + trans_y = random.uniform(-self.max_translate_ratio, + self.max_translate_ratio) * height + translate_matrix = self._get_translation_matrix(trans_x, trans_y) + + warp_matrix = ( + translate_matrix @ shear_matrix @ rotation_matrix @ scaling_matrix) + return warp_matrix + + @autocast_box_type() + def transform(self, results: dict) -> dict: + img = results['img'] + height = img.shape[0] + self.border[1] * 2 + width = img.shape[1] + self.border[0] * 2 + + warp_matrix = self._get_random_homography_matrix(height, width) + + img = cv2.warpPerspective( + img, + warp_matrix, + dsize=(width, height), + borderValue=self.border_val) + results['img'] = img + results['img_shape'] = img.shape[:2] + + bboxes = results['gt_bboxes'] + num_bboxes = len(bboxes) + if num_bboxes: + bboxes.project_(warp_matrix) + if self.bbox_clip_border: + bboxes.clip_([height, width]) + # remove outside bbox + valid_index = bboxes.is_inside([height, width]).numpy() + results['gt_bboxes'] = bboxes[valid_index] + results['gt_bboxes_labels'] = results['gt_bboxes_labels'][ + valid_index] + results['gt_ignore_flags'] = results['gt_ignore_flags'][ + valid_index] + + if 'gt_masks' in results: + raise NotImplementedError('RandomAffine only supports bbox.') + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(max_rotate_degree={self.max_rotate_degree}, ' + repr_str += f'max_translate_ratio={self.max_translate_ratio}, ' + repr_str += f'scaling_ratio_range={self.scaling_ratio_range}, ' + repr_str += f'max_shear_degree={self.max_shear_degree}, ' + repr_str += f'border={self.border}, ' + repr_str += f'border_val={self.border_val}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border})' + return repr_str + + @staticmethod + def _get_rotation_matrix(rotate_degrees: float) -> np.ndarray: + radian = math.radians(rotate_degrees) + rotation_matrix = np.array( + [[np.cos(radian), -np.sin(radian), 0.], + [np.sin(radian), np.cos(radian), 0.], [0., 0., 1.]], + dtype=np.float32) + return rotation_matrix + + @staticmethod + def _get_scaling_matrix(scale_ratio: float) -> np.ndarray: + scaling_matrix = np.array( + [[scale_ratio, 0., 0.], [0., scale_ratio, 0.], [0., 0., 1.]], + dtype=np.float32) + return scaling_matrix + + @staticmethod + def _get_shear_matrix(x_shear_degrees: float, + y_shear_degrees: float) -> np.ndarray: + x_radian = math.radians(x_shear_degrees) + y_radian = math.radians(y_shear_degrees) + shear_matrix = np.array([[1, np.tan(x_radian), 0.], + [np.tan(y_radian), 1, 0.], [0., 0., 1.]], + dtype=np.float32) + return shear_matrix + + @staticmethod + def _get_translation_matrix(x: float, y: float) -> np.ndarray: + translation_matrix = np.array([[1, 0., x], [0., 1, y], [0., 0., 1.]], + dtype=np.float32) + return translation_matrix + + +@TRANSFORMS.register_module() +class YOLOXHSVRandomAug(BaseTransform): + """Apply HSV augmentation to image sequentially. It is referenced from + https://github.com/Megvii- + BaseDetection/YOLOX/blob/main/yolox/data/data_augment.py#L21. + + Required Keys: + + - img + + Modified Keys: + + - img + + Args: + hue_delta (int): delta of hue. Defaults to 5. + saturation_delta (int): delta of saturation. Defaults to 30. + value_delta (int): delat of value. Defaults to 30. + """ + + def __init__(self, + hue_delta: int = 5, + saturation_delta: int = 30, + value_delta: int = 30) -> None: + self.hue_delta = hue_delta + self.saturation_delta = saturation_delta + self.value_delta = value_delta + + @cache_randomness + def _get_hsv_gains(self): + hsv_gains = np.random.uniform(-1, 1, 3) * [ + self.hue_delta, self.saturation_delta, self.value_delta + ] + # random selection of h, s, v + hsv_gains *= np.random.randint(0, 2, 3) + # prevent overflow + hsv_gains = hsv_gains.astype(np.int16) + return hsv_gains + + def transform(self, results: dict) -> dict: + img = results['img'] + hsv_gains = self._get_hsv_gains() + img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype(np.int16) + + img_hsv[..., 0] = (img_hsv[..., 0] + hsv_gains[0]) % 180 + img_hsv[..., 1] = np.clip(img_hsv[..., 1] + hsv_gains[1], 0, 255) + img_hsv[..., 2] = np.clip(img_hsv[..., 2] + hsv_gains[2], 0, 255) + cv2.cvtColor(img_hsv.astype(img.dtype), cv2.COLOR_HSV2BGR, dst=img) + + results['img'] = img + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(hue_delta={self.hue_delta}, ' + repr_str += f'saturation_delta={self.saturation_delta}, ' + repr_str += f'value_delta={self.value_delta})' + return repr_str + + +@TRANSFORMS.register_module() +class CopyPaste(BaseTransform): + """Simple Copy-Paste is a Strong Data Augmentation Method for Instance + Segmentation The simple copy-paste transform steps are as follows: + + 1. The destination image is already resized with aspect ratio kept, + cropped and padded. + 2. Randomly select a source image, which is also already resized + with aspect ratio kept, cropped and padded in a similar way + as the destination image. + 3. Randomly select some objects from the source image. + 4. Paste these source objects to the destination image directly, + due to the source and destination image have the same size. + 5. Update object masks of the destination image, for some origin objects + may be occluded. + 6. Generate bboxes from the updated destination masks and + filter some objects which are totally occluded, and adjust bboxes + which are partly occluded. + 7. Append selected source bboxes, masks, and labels. + + Required Keys: + + - img + - gt_bboxes (BaseBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - gt_masks (BitmapMasks) (optional) + + Modified Keys: + + - img + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + - gt_masks (optional) + + Args: + max_num_pasted (int): The maximum number of pasted objects. + Defaults to 100. + bbox_occluded_thr (int): The threshold of occluded bbox. + Defaults to 10. + mask_occluded_thr (int): The threshold of occluded mask. + Defaults to 300. + selected (bool): Whether select objects or not. If select is False, + all objects of the source image will be pasted to the + destination image. + Defaults to True. + paste_by_box (bool): Whether use boxes as masks when masks are not + available. + Defaults to False. + """ + + def __init__( + self, + max_num_pasted: int = 100, + bbox_occluded_thr: int = 10, + mask_occluded_thr: int = 300, + selected: bool = True, + paste_by_box: bool = False, + ) -> None: + self.max_num_pasted = max_num_pasted + self.bbox_occluded_thr = bbox_occluded_thr + self.mask_occluded_thr = mask_occluded_thr + self.selected = selected + self.paste_by_box = paste_by_box + + @cache_randomness + def get_indexes(self, dataset: BaseDataset) -> int: + """Call function to collect indexes.s. + + Args: + dataset (:obj:`MultiImageMixDataset`): The dataset. + Returns: + list: Indexes. + """ + return random.randint(0, len(dataset)) + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to make a copy-paste of image. + + Args: + results (dict): Result dict. + Returns: + dict: Result dict with copy-paste transformed. + """ + + assert 'mix_results' in results + num_images = len(results['mix_results']) + assert num_images == 1, \ + f'CopyPaste only supports processing 2 images, got {num_images}' + if self.selected: + selected_results = self._select_object(results['mix_results'][0]) + else: + selected_results = results['mix_results'][0] + return self._copy_paste(results, selected_results) + + @cache_randomness + def _get_selected_inds(self, num_bboxes: int) -> np.ndarray: + max_num_pasted = min(num_bboxes + 1, self.max_num_pasted) + num_pasted = np.random.randint(0, max_num_pasted) + return np.random.choice(num_bboxes, size=num_pasted, replace=False) + + def get_gt_masks(self, results: dict) -> BitmapMasks: + """Get gt_masks originally or generated based on bboxes. + + If gt_masks is not contained in results, + it will be generated based on gt_bboxes. + Args: + results (dict): Result dict. + Returns: + BitmapMasks: gt_masks, originally or generated based on bboxes. + """ + if results.get('gt_masks', None) is not None: + if self.paste_by_box: + warnings.warn('gt_masks is already contained in results, ' + 'so paste_by_box is disabled.') + return results['gt_masks'] + else: + if not self.paste_by_box: + raise RuntimeError('results does not contain masks.') + return results['gt_bboxes'].create_masks(results['img'].shape[:2]) + + def _select_object(self, results: dict) -> dict: + """Select some objects from the source results.""" + bboxes = results['gt_bboxes'] + labels = results['gt_bboxes_labels'] + masks = self.get_gt_masks(results) + ignore_flags = results['gt_ignore_flags'] + + selected_inds = self._get_selected_inds(bboxes.shape[0]) + + selected_bboxes = bboxes[selected_inds] + selected_labels = labels[selected_inds] + selected_masks = masks[selected_inds] + selected_ignore_flags = ignore_flags[selected_inds] + + results['gt_bboxes'] = selected_bboxes + results['gt_bboxes_labels'] = selected_labels + results['gt_masks'] = selected_masks + results['gt_ignore_flags'] = selected_ignore_flags + return results + + def _copy_paste(self, dst_results: dict, src_results: dict) -> dict: + """CopyPaste transform function. + + Args: + dst_results (dict): Result dict of the destination image. + src_results (dict): Result dict of the source image. + Returns: + dict: Updated result dict. + """ + dst_img = dst_results['img'] + dst_bboxes = dst_results['gt_bboxes'] + dst_labels = dst_results['gt_bboxes_labels'] + dst_masks = self.get_gt_masks(dst_results) + dst_ignore_flags = dst_results['gt_ignore_flags'] + + src_img = src_results['img'] + src_bboxes = src_results['gt_bboxes'] + src_labels = src_results['gt_bboxes_labels'] + src_masks = src_results['gt_masks'] + src_ignore_flags = src_results['gt_ignore_flags'] + + if len(src_bboxes) == 0: + return dst_results + + # update masks and generate bboxes from updated masks + composed_mask = np.where(np.any(src_masks.masks, axis=0), 1, 0) + updated_dst_masks = self._get_updated_masks(dst_masks, composed_mask) + updated_dst_bboxes = updated_dst_masks.get_bboxes(type(dst_bboxes)) + assert len(updated_dst_bboxes) == len(updated_dst_masks) + + # filter totally occluded objects + l1_distance = (updated_dst_bboxes.tensor - dst_bboxes.tensor).abs() + bboxes_inds = (l1_distance <= self.bbox_occluded_thr).all( + dim=-1).numpy() + masks_inds = updated_dst_masks.masks.sum( + axis=(1, 2)) > self.mask_occluded_thr + valid_inds = bboxes_inds | masks_inds + + # Paste source objects to destination image directly + img = dst_img * (1 - composed_mask[..., np.newaxis] + ) + src_img * composed_mask[..., np.newaxis] + bboxes = src_bboxes.cat([updated_dst_bboxes[valid_inds], src_bboxes]) + labels = np.concatenate([dst_labels[valid_inds], src_labels]) + masks = np.concatenate( + [updated_dst_masks.masks[valid_inds], src_masks.masks]) + ignore_flags = np.concatenate( + [dst_ignore_flags[valid_inds], src_ignore_flags]) + + dst_results['img'] = img + dst_results['gt_bboxes'] = bboxes + dst_results['gt_bboxes_labels'] = labels + dst_results['gt_masks'] = BitmapMasks(masks, masks.shape[1], + masks.shape[2]) + dst_results['gt_ignore_flags'] = ignore_flags + + return dst_results + + def _get_updated_masks(self, masks: BitmapMasks, + composed_mask: np.ndarray) -> BitmapMasks: + """Update masks with composed mask.""" + assert masks.masks.shape[-2:] == composed_mask.shape[-2:], \ + 'Cannot compare two arrays of different size' + masks.masks = np.where(composed_mask, 0, masks.masks) + return masks + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(max_num_pasted={self.max_num_pasted}, ' + repr_str += f'bbox_occluded_thr={self.bbox_occluded_thr}, ' + repr_str += f'mask_occluded_thr={self.mask_occluded_thr}, ' + repr_str += f'selected={self.selected}), ' + repr_str += f'paste_by_box={self.paste_by_box})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomErasing(BaseTransform): + """RandomErasing operation. + + Random Erasing randomly selects a rectangle region + in an image and erases its pixels with random values. + `RandomErasing `_. + + Required Keys: + + - img + - gt_bboxes (HorizontalBoxes[torch.float32]) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - gt_masks (BitmapMasks) (optional) + + Modified Keys: + - img + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + - gt_masks (optional) + + Args: + n_patches (int or tuple[int, int]): Number of regions to be dropped. + If it is given as a tuple, number of patches will be randomly + selected from the closed interval [``n_patches[0]``, + ``n_patches[1]``]. + ratio (float or tuple[float, float]): The ratio of erased regions. + It can be ``float`` to use a fixed ratio or ``tuple[float, float]`` + to randomly choose ratio from the interval. + squared (bool): Whether to erase square region. Defaults to True. + bbox_erased_thr (float): The threshold for the maximum area proportion + of the bbox to be erased. When the proportion of the area where the + bbox is erased is greater than the threshold, the bbox will be + removed. Defaults to 0.9. + img_border_value (int or float or tuple): The filled values for + image border. If float, the same fill value will be used for + all the three channels of image. If tuple, it should be 3 elements. + Defaults to 128. + mask_border_value (int): The fill value used for masks. Defaults to 0. + seg_ignore_label (int): The fill value used for segmentation map. + Note this value must equals ``ignore_label`` in ``semantic_head`` + of the corresponding config. Defaults to 255. + """ + + def __init__( + self, + n_patches: Union[int, Tuple[int, int]], + ratio: Union[float, Tuple[float, float]], + squared: bool = True, + bbox_erased_thr: float = 0.9, + img_border_value: Union[int, float, tuple] = 128, + mask_border_value: int = 0, + seg_ignore_label: int = 255, + ) -> None: + if isinstance(n_patches, tuple): + assert len(n_patches) == 2 and 0 <= n_patches[0] < n_patches[1] + else: + n_patches = (n_patches, n_patches) + if isinstance(ratio, tuple): + assert len(ratio) == 2 and 0 <= ratio[0] < ratio[1] <= 1 + else: + ratio = (ratio, ratio) + + self.n_patches = n_patches + self.ratio = ratio + self.squared = squared + self.bbox_erased_thr = bbox_erased_thr + self.img_border_value = img_border_value + self.mask_border_value = mask_border_value + self.seg_ignore_label = seg_ignore_label + + @cache_randomness + def _get_patches(self, img_shape: Tuple[int, int]) -> List[list]: + """Get patches for random erasing.""" + patches = [] + n_patches = np.random.randint(self.n_patches[0], self.n_patches[1] + 1) + for _ in range(n_patches): + if self.squared: + ratio = np.random.random() * (self.ratio[1] - + self.ratio[0]) + self.ratio[0] + ratio = (ratio, ratio) + else: + ratio = (np.random.random() * (self.ratio[1] - self.ratio[0]) + + self.ratio[0], np.random.random() * + (self.ratio[1] - self.ratio[0]) + self.ratio[0]) + ph, pw = int(img_shape[0] * ratio[0]), int(img_shape[1] * ratio[1]) + px1, py1 = np.random.randint(0, + img_shape[1] - pw), np.random.randint( + 0, img_shape[0] - ph) + px2, py2 = px1 + pw, py1 + ph + patches.append([px1, py1, px2, py2]) + return np.array(patches) + + def _transform_img(self, results: dict, patches: List[list]) -> None: + """Random erasing the image.""" + for patch in patches: + px1, py1, px2, py2 = patch + results['img'][py1:py2, px1:px2, :] = self.img_border_value + + def _transform_bboxes(self, results: dict, patches: List[list]) -> None: + """Random erasing the bboxes.""" + bboxes = results['gt_bboxes'] + # TODO: unify the logic by using operators in BaseBoxes. + assert isinstance(bboxes, HorizontalBoxes) + bboxes = bboxes.numpy() + left_top = np.maximum(bboxes[:, None, :2], patches[:, :2]) + right_bottom = np.minimum(bboxes[:, None, 2:], patches[:, 2:]) + wh = np.maximum(right_bottom - left_top, 0) + inter_areas = wh[:, :, 0] * wh[:, :, 1] + bbox_areas = (bboxes[:, 2] - bboxes[:, 0]) * ( + bboxes[:, 3] - bboxes[:, 1]) + bboxes_erased_ratio = inter_areas.sum(-1) / (bbox_areas + 1e-7) + valid_inds = bboxes_erased_ratio < self.bbox_erased_thr + results['gt_bboxes'] = HorizontalBoxes(bboxes[valid_inds]) + results['gt_bboxes_labels'] = results['gt_bboxes_labels'][valid_inds] + results['gt_ignore_flags'] = results['gt_ignore_flags'][valid_inds] + if results.get('gt_masks', None) is not None: + results['gt_masks'] = results['gt_masks'][valid_inds] + + def _transform_masks(self, results: dict, patches: List[list]) -> None: + """Random erasing the masks.""" + for patch in patches: + px1, py1, px2, py2 = patch + results['gt_masks'].masks[:, py1:py2, + px1:px2] = self.mask_border_value + + def _transform_seg(self, results: dict, patches: List[list]) -> None: + """Random erasing the segmentation map.""" + for patch in patches: + px1, py1, px2, py2 = patch + results['gt_seg_map'][py1:py2, px1:px2] = self.seg_ignore_label + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Transform function to erase some regions of image.""" + patches = self._get_patches(results['img_shape']) + self._transform_img(results, patches) + if results.get('gt_bboxes', None) is not None: + self._transform_bboxes(results, patches) + if results.get('gt_masks', None) is not None: + self._transform_masks(results, patches) + if results.get('gt_seg_map', None) is not None: + self._transform_seg(results, patches) + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(n_patches={self.n_patches}, ' + repr_str += f'ratio={self.ratio}, ' + repr_str += f'squared={self.squared}, ' + repr_str += f'bbox_erased_thr={self.bbox_erased_thr}, ' + repr_str += f'img_border_value={self.img_border_value}, ' + repr_str += f'mask_border_value={self.mask_border_value}, ' + repr_str += f'seg_ignore_label={self.seg_ignore_label})' + return repr_str + + +@TRANSFORMS.register_module() +class CachedMosaic(Mosaic): + """Cached mosaic augmentation. + + Cached mosaic transform will random select images from the cache + and combine them into one output image. + + .. code:: text + + mosaic transform + center_x + +------------------------------+ + | pad | pad | + | +-----------+ | + | | | | + | | image1 |--------+ | + | | | | | + | | | image2 | | + center_y |----+-------------+-----------| + | | cropped | | + |pad | image3 | image4 | + | | | | + +----|-------------+-----------+ + | | + +-------------+ + + The cached mosaic transform steps are as follows: + + 1. Append the results from the last transform into the cache. + 2. Choose the mosaic center as the intersections of 4 images + 3. Get the left top image according to the index, and randomly + sample another 3 images from the result cache. + 4. Sub image will be cropped if image is larger than mosaic patch + + Required Keys: + + - img + - gt_bboxes (np.float32) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + Args: + img_scale (Sequence[int]): Image size before mosaic pipeline of single + image. The shape order should be (width, height). + Defaults to (640, 640). + center_ratio_range (Sequence[float]): Center ratio range of mosaic + output. Defaults to (0.5, 1.5). + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + pad_val (int): Pad value. Defaults to 114. + prob (float): Probability of applying this transformation. + Defaults to 1.0. + max_cached_images (int): The maximum length of the cache. The larger + the cache, the stronger the randomness of this transform. As a + rule of thumb, providing 10 caches for each image suffices for + randomness. Defaults to 40. + random_pop (bool): Whether to randomly pop a result from the cache + when the cache is full. If set to False, use FIFO popping method. + Defaults to True. + """ + + def __init__(self, + *args, + max_cached_images: int = 40, + random_pop: bool = True, + **kwargs) -> None: + super().__init__(*args, **kwargs) + self.results_cache = [] + self.random_pop = random_pop + assert max_cached_images >= 4, 'The length of cache must >= 4, ' \ + f'but got {max_cached_images}.' + self.max_cached_images = max_cached_images + + @cache_randomness + def get_indexes(self, cache: list) -> list: + """Call function to collect indexes. + + Args: + cache (list): The results cache. + + Returns: + list: indexes. + """ + + indexes = [random.randint(0, len(cache) - 1) for _ in range(3)] + return indexes + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """Mosaic transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + # cache and pop images + self.results_cache.append(copy.deepcopy(results)) + if len(self.results_cache) > self.max_cached_images: + if self.random_pop: + index = random.randint(0, len(self.results_cache) - 1) + else: + index = 0 + self.results_cache.pop(index) + + if len(self.results_cache) <= 4: + return results + + if random.uniform(0, 1) > self.prob: + return results + indices = self.get_indexes(self.results_cache) + mix_results = [copy.deepcopy(self.results_cache[i]) for i in indices] + + # TODO: refactor mosaic to reuse these code. + mosaic_bboxes = [] + mosaic_bboxes_labels = [] + mosaic_ignore_flags = [] + mosaic_masks = [] + with_mask = True if 'gt_masks' in results else False + + if len(results['img'].shape) == 3: + mosaic_img = np.full( + (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2), 3), + self.pad_val, + dtype=results['img'].dtype) + else: + mosaic_img = np.full( + (int(self.img_scale[1] * 2), int(self.img_scale[0] * 2)), + self.pad_val, + dtype=results['img'].dtype) + + # mosaic center x, y + center_x = int( + random.uniform(*self.center_ratio_range) * self.img_scale[0]) + center_y = int( + random.uniform(*self.center_ratio_range) * self.img_scale[1]) + center_position = (center_x, center_y) + + loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') + for i, loc in enumerate(loc_strs): + if loc == 'top_left': + results_patch = copy.deepcopy(results) + else: + results_patch = copy.deepcopy(mix_results[i - 1]) + + img_i = results_patch['img'] + h_i, w_i = img_i.shape[:2] + # keep_ratio resize + scale_ratio_i = min(self.img_scale[1] / h_i, + self.img_scale[0] / w_i) + img_i = mmcv.imresize( + img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i))) + + # compute the combine parameters + paste_coord, crop_coord = self._mosaic_combine( + loc, center_position, img_i.shape[:2][::-1]) + x1_p, y1_p, x2_p, y2_p = paste_coord + x1_c, y1_c, x2_c, y2_c = crop_coord + + # crop and paste image + mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c] + + # adjust coordinate + gt_bboxes_i = results_patch['gt_bboxes'] + gt_bboxes_labels_i = results_patch['gt_bboxes_labels'] + gt_ignore_flags_i = results_patch['gt_ignore_flags'] + + padw = x1_p - x1_c + padh = y1_p - y1_c + gt_bboxes_i.rescale_([scale_ratio_i, scale_ratio_i]) + gt_bboxes_i.translate_([padw, padh]) + mosaic_bboxes.append(gt_bboxes_i) + mosaic_bboxes_labels.append(gt_bboxes_labels_i) + mosaic_ignore_flags.append(gt_ignore_flags_i) + if with_mask and results_patch.get('gt_masks', None) is not None: + gt_masks_i = results_patch['gt_masks'] + gt_masks_i = gt_masks_i.rescale(float(scale_ratio_i)) + gt_masks_i = gt_masks_i.translate( + out_shape=(int(self.img_scale[0] * 2), + int(self.img_scale[1] * 2)), + offset=padw, + direction='horizontal') + gt_masks_i = gt_masks_i.translate( + out_shape=(int(self.img_scale[0] * 2), + int(self.img_scale[1] * 2)), + offset=padh, + direction='vertical') + mosaic_masks.append(gt_masks_i) + + mosaic_bboxes = mosaic_bboxes[0].cat(mosaic_bboxes, 0) + mosaic_bboxes_labels = np.concatenate(mosaic_bboxes_labels, 0) + mosaic_ignore_flags = np.concatenate(mosaic_ignore_flags, 0) + + if self.bbox_clip_border: + mosaic_bboxes.clip_([2 * self.img_scale[1], 2 * self.img_scale[0]]) + # remove outside bboxes + inside_inds = mosaic_bboxes.is_inside( + [2 * self.img_scale[1], 2 * self.img_scale[0]]).numpy() + mosaic_bboxes = mosaic_bboxes[inside_inds] + mosaic_bboxes_labels = mosaic_bboxes_labels[inside_inds] + mosaic_ignore_flags = mosaic_ignore_flags[inside_inds] + + results['img'] = mosaic_img + results['img_shape'] = mosaic_img.shape[:2] + results['gt_bboxes'] = mosaic_bboxes + results['gt_bboxes_labels'] = mosaic_bboxes_labels + results['gt_ignore_flags'] = mosaic_ignore_flags + + if with_mask: + mosaic_masks = mosaic_masks[0].cat(mosaic_masks) + results['gt_masks'] = mosaic_masks[inside_inds] + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(img_scale={self.img_scale}, ' + repr_str += f'center_ratio_range={self.center_ratio_range}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'prob={self.prob}, ' + repr_str += f'max_cached_images={self.max_cached_images}, ' + repr_str += f'random_pop={self.random_pop})' + return repr_str + + +@TRANSFORMS.register_module() +class CachedMixUp(BaseTransform): + """Cached mixup data augmentation. + + .. code:: text + + mixup transform + +------------------------------+ + | mixup image | | + | +--------|--------+ | + | | | | | + |---------------+ | | + | | | | + | | image | | + | | | | + | | | | + | |-----------------+ | + | pad | + +------------------------------+ + + The cached mixup transform steps are as follows: + + 1. Append the results from the last transform into the cache. + 2. Another random image is picked from the cache and embedded in + the top left patch(after padding and resizing) + 3. The target of mixup transform is the weighted average of mixup + image and origin image. + + Required Keys: + + - img + - gt_bboxes (np.float32) (optional) + - gt_bboxes_labels (np.int64) (optional) + - gt_ignore_flags (bool) (optional) + - mix_results (List[dict]) + + + Modified Keys: + + - img + - img_shape + - gt_bboxes (optional) + - gt_bboxes_labels (optional) + - gt_ignore_flags (optional) + + + Args: + img_scale (Sequence[int]): Image output size after mixup pipeline. + The shape order should be (width, height). Defaults to (640, 640). + ratio_range (Sequence[float]): Scale ratio of mixup image. + Defaults to (0.5, 1.5). + flip_ratio (float): Horizontal flip ratio of mixup image. + Defaults to 0.5. + pad_val (int): Pad value. Defaults to 114. + max_iters (int): The maximum number of iterations. If the number of + iterations is greater than `max_iters`, but gt_bbox is still + empty, then the iteration is terminated. Defaults to 15. + bbox_clip_border (bool, optional): Whether to clip the objects outside + the border of the image. In some dataset like MOT17, the gt bboxes + are allowed to cross the border of images. Therefore, we don't + need to clip the gt bboxes in these cases. Defaults to True. + max_cached_images (int): The maximum length of the cache. The larger + the cache, the stronger the randomness of this transform. As a + rule of thumb, providing 10 caches for each image suffices for + randomness. Defaults to 20. + random_pop (bool): Whether to randomly pop a result from the cache + when the cache is full. If set to False, use FIFO popping method. + Defaults to True. + prob (float): Probability of applying this transformation. + Defaults to 1.0. + """ + + def __init__(self, + img_scale: Tuple[int, int] = (640, 640), + ratio_range: Tuple[float, float] = (0.5, 1.5), + flip_ratio: float = 0.5, + pad_val: float = 114.0, + max_iters: int = 15, + bbox_clip_border: bool = True, + max_cached_images: int = 20, + random_pop: bool = True, + prob: float = 1.0) -> None: + assert isinstance(img_scale, tuple) + assert max_cached_images >= 2, 'The length of cache must >= 2, ' \ + f'but got {max_cached_images}.' + assert 0 <= prob <= 1.0, 'The probability should be in range [0,1]. ' \ + f'got {prob}.' + self.dynamic_scale = img_scale + self.ratio_range = ratio_range + self.flip_ratio = flip_ratio + self.pad_val = pad_val + self.max_iters = max_iters + self.bbox_clip_border = bbox_clip_border + self.results_cache = [] + + self.max_cached_images = max_cached_images + self.random_pop = random_pop + self.prob = prob + + @cache_randomness + def get_indexes(self, cache: list) -> int: + """Call function to collect indexes. + + Args: + cache (list): The result cache. + + Returns: + int: index. + """ + + for i in range(self.max_iters): + index = random.randint(0, len(cache) - 1) + gt_bboxes_i = cache[index]['gt_bboxes'] + if len(gt_bboxes_i) != 0: + break + return index + + @autocast_box_type() + def transform(self, results: dict) -> dict: + """MixUp transform function. + + Args: + results (dict): Result dict. + + Returns: + dict: Updated result dict. + """ + # cache and pop images + self.results_cache.append(copy.deepcopy(results)) + if len(self.results_cache) > self.max_cached_images: + if self.random_pop: + index = random.randint(0, len(self.results_cache) - 1) + else: + index = 0 + self.results_cache.pop(index) + + if len(self.results_cache) <= 1: + return results + + if random.uniform(0, 1) > self.prob: + return results + + index = self.get_indexes(self.results_cache) + retrieve_results = copy.deepcopy(self.results_cache[index]) + + # TODO: refactor mixup to reuse these code. + if retrieve_results['gt_bboxes'].shape[0] == 0: + # empty bbox + return results + + retrieve_img = retrieve_results['img'] + with_mask = True if 'gt_masks' in results else False + + jit_factor = random.uniform(*self.ratio_range) + is_flip = random.uniform(0, 1) > self.flip_ratio + + if len(retrieve_img.shape) == 3: + out_img = np.ones( + (self.dynamic_scale[1], self.dynamic_scale[0], 3), + dtype=retrieve_img.dtype) * self.pad_val + else: + out_img = np.ones( + self.dynamic_scale[::-1], + dtype=retrieve_img.dtype) * self.pad_val + + # 1. keep_ratio resize + scale_ratio = min(self.dynamic_scale[1] / retrieve_img.shape[0], + self.dynamic_scale[0] / retrieve_img.shape[1]) + retrieve_img = mmcv.imresize( + retrieve_img, (int(retrieve_img.shape[1] * scale_ratio), + int(retrieve_img.shape[0] * scale_ratio))) + + # 2. paste + out_img[:retrieve_img.shape[0], :retrieve_img.shape[1]] = retrieve_img + + # 3. scale jit + scale_ratio *= jit_factor + out_img = mmcv.imresize(out_img, (int(out_img.shape[1] * jit_factor), + int(out_img.shape[0] * jit_factor))) + + # 4. flip + if is_flip: + out_img = out_img[:, ::-1, :] + + # 5. random crop + ori_img = results['img'] + origin_h, origin_w = out_img.shape[:2] + target_h, target_w = ori_img.shape[:2] + padded_img = np.ones((max(origin_h, target_h), max( + origin_w, target_w), 3)) * self.pad_val + padded_img = padded_img.astype(np.uint8) + padded_img[:origin_h, :origin_w] = out_img + + x_offset, y_offset = 0, 0 + if padded_img.shape[0] > target_h: + y_offset = random.randint(0, padded_img.shape[0] - target_h) + if padded_img.shape[1] > target_w: + x_offset = random.randint(0, padded_img.shape[1] - target_w) + padded_cropped_img = padded_img[y_offset:y_offset + target_h, + x_offset:x_offset + target_w] + + # 6. adjust bbox + retrieve_gt_bboxes = retrieve_results['gt_bboxes'] + retrieve_gt_bboxes.rescale_([scale_ratio, scale_ratio]) + if with_mask: + retrieve_gt_masks = retrieve_results['gt_masks'].rescale( + scale_ratio) + + if self.bbox_clip_border: + retrieve_gt_bboxes.clip_([origin_h, origin_w]) + + if is_flip: + retrieve_gt_bboxes.flip_([origin_h, origin_w], + direction='horizontal') + if with_mask: + retrieve_gt_masks = retrieve_gt_masks.flip() + + # 7. filter + cp_retrieve_gt_bboxes = retrieve_gt_bboxes.clone() + cp_retrieve_gt_bboxes.translate_([-x_offset, -y_offset]) + if with_mask: + retrieve_gt_masks = retrieve_gt_masks.translate( + out_shape=(target_h, target_w), + offset=-x_offset, + direction='horizontal') + retrieve_gt_masks = retrieve_gt_masks.translate( + out_shape=(target_h, target_w), + offset=-y_offset, + direction='vertical') + + if self.bbox_clip_border: + cp_retrieve_gt_bboxes.clip_([target_h, target_w]) + + # 8. mix up + ori_img = ori_img.astype(np.float32) + mixup_img = 0.5 * ori_img + 0.5 * padded_cropped_img.astype(np.float32) + + retrieve_gt_bboxes_labels = retrieve_results['gt_bboxes_labels'] + retrieve_gt_ignore_flags = retrieve_results['gt_ignore_flags'] + + mixup_gt_bboxes = cp_retrieve_gt_bboxes.cat( + (results['gt_bboxes'], cp_retrieve_gt_bboxes), dim=0) + mixup_gt_bboxes_labels = np.concatenate( + (results['gt_bboxes_labels'], retrieve_gt_bboxes_labels), axis=0) + mixup_gt_ignore_flags = np.concatenate( + (results['gt_ignore_flags'], retrieve_gt_ignore_flags), axis=0) + if with_mask: + mixup_gt_masks = retrieve_gt_masks.cat( + [results['gt_masks'], retrieve_gt_masks]) + + # remove outside bbox + inside_inds = mixup_gt_bboxes.is_inside([target_h, target_w]).numpy() + mixup_gt_bboxes = mixup_gt_bboxes[inside_inds] + mixup_gt_bboxes_labels = mixup_gt_bboxes_labels[inside_inds] + mixup_gt_ignore_flags = mixup_gt_ignore_flags[inside_inds] + if with_mask: + mixup_gt_masks = mixup_gt_masks[inside_inds] + + results['img'] = mixup_img.astype(np.uint8) + results['img_shape'] = mixup_img.shape[:2] + results['gt_bboxes'] = mixup_gt_bboxes + results['gt_bboxes_labels'] = mixup_gt_bboxes_labels + results['gt_ignore_flags'] = mixup_gt_ignore_flags + if with_mask: + results['gt_masks'] = mixup_gt_masks + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(dynamic_scale={self.dynamic_scale}, ' + repr_str += f'ratio_range={self.ratio_range}, ' + repr_str += f'flip_ratio={self.flip_ratio}, ' + repr_str += f'pad_val={self.pad_val}, ' + repr_str += f'max_iters={self.max_iters}, ' + repr_str += f'bbox_clip_border={self.bbox_clip_border}, ' + repr_str += f'max_cached_images={self.max_cached_images}, ' + repr_str += f'random_pop={self.random_pop}, ' + repr_str += f'prob={self.prob})' + return repr_str diff --git a/mmdet_code/mmdetection/mmdet/datasets/transforms/wrappers.py b/mmdet_code/mmdetection/mmdet/datasets/transforms/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..3a17711c06bfbd4dc0038dce9ea7796d1476c37e --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/transforms/wrappers.py @@ -0,0 +1,277 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +from typing import Callable, Dict, List, Optional, Union + +import numpy as np +from mmcv.transforms import BaseTransform, Compose +from mmcv.transforms.utils import cache_random_params, cache_randomness + +from mmdet.registry import TRANSFORMS + + +@TRANSFORMS.register_module() +class MultiBranch(BaseTransform): + r"""Multiple branch pipeline wrapper. + + Generate multiple data-augmented versions of the same image. + `MultiBranch` needs to specify the branch names of all + pipelines of the dataset, perform corresponding data augmentation + for the current branch, and return None for other branches, + which ensures the consistency of return format across + different samples. + + Args: + branch_field (list): List of branch names. + branch_pipelines (dict): Dict of different pipeline configs + to be composed. + + Examples: + >>> branch_field = ['sup', 'unsup_teacher', 'unsup_student'] + >>> sup_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadAnnotations', with_bbox=True), + >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True), + >>> dict(type='RandomFlip', prob=0.5), + >>> dict( + >>> type='MultiBranch', + >>> branch_field=branch_field, + >>> sup=dict(type='PackDetInputs')) + >>> ] + >>> weak_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadAnnotations', with_bbox=True), + >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True), + >>> dict(type='RandomFlip', prob=0.0), + >>> dict( + >>> type='MultiBranch', + >>> branch_field=branch_field, + >>> sup=dict(type='PackDetInputs')) + >>> ] + >>> strong_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadAnnotations', with_bbox=True), + >>> dict(type='Resize', scale=(1333, 800), keep_ratio=True), + >>> dict(type='RandomFlip', prob=1.0), + >>> dict( + >>> type='MultiBranch', + >>> branch_field=branch_field, + >>> sup=dict(type='PackDetInputs')) + >>> ] + >>> unsup_pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadEmptyAnnotations'), + >>> dict( + >>> type='MultiBranch', + >>> branch_field=branch_field, + >>> unsup_teacher=weak_pipeline, + >>> unsup_student=strong_pipeline) + >>> ] + >>> from mmcv.transforms import Compose + >>> sup_branch = Compose(sup_pipeline) + >>> unsup_branch = Compose(unsup_pipeline) + >>> print(sup_branch) + >>> Compose( + >>> LoadImageFromFile(ignore_empty=False, to_float32=False, color_type='color', imdecode_backend='cv2') # noqa + >>> LoadAnnotations(with_bbox=True, with_label=True, with_mask=False, with_seg=False, poly2mask=True, imdecode_backend='cv2') # noqa + >>> Resize(scale=(1333, 800), scale_factor=None, keep_ratio=True, clip_object_border=True), backend=cv2), interpolation=bilinear) # noqa + >>> RandomFlip(prob=0.5, direction=horizontal) + >>> MultiBranch(branch_pipelines=['sup']) + >>> ) + >>> print(unsup_branch) + >>> Compose( + >>> LoadImageFromFile(ignore_empty=False, to_float32=False, color_type='color', imdecode_backend='cv2') # noqa + >>> LoadEmptyAnnotations(with_bbox=True, with_label=True, with_mask=False, with_seg=False, seg_ignore_label=255) # noqa + >>> MultiBranch(branch_pipelines=['unsup_teacher', 'unsup_student']) + >>> ) + """ + + def __init__(self, branch_field: List[str], + **branch_pipelines: dict) -> None: + self.branch_field = branch_field + self.branch_pipelines = { + branch: Compose(pipeline) + for branch, pipeline in branch_pipelines.items() + } + + def transform(self, results: dict) -> dict: + """Transform function to apply transforms sequentially. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: + + - 'inputs' (Dict[str, obj:`torch.Tensor`]): The forward data of + models from different branches. + - 'data_sample' (Dict[str,obj:`DetDataSample`]): The annotation + info of the sample from different branches. + """ + + multi_results = {} + for branch in self.branch_field: + multi_results[branch] = {'inputs': None, 'data_samples': None} + for branch, pipeline in self.branch_pipelines.items(): + branch_results = pipeline(copy.deepcopy(results)) + # If one branch pipeline returns None, + # it will sample another data from dataset. + if branch_results is None: + return None + multi_results[branch] = branch_results + + format_results = {} + for branch, results in multi_results.items(): + for key in results.keys(): + if format_results.get(key, None) is None: + format_results[key] = {branch: results[key]} + else: + format_results[key][branch] = results[key] + return format_results + + def __repr__(self) -> str: + repr_str = self.__class__.__name__ + repr_str += f'(branch_pipelines={list(self.branch_pipelines.keys())})' + return repr_str + + +@TRANSFORMS.register_module() +class RandomOrder(Compose): + """Shuffle the transform Sequence.""" + + @cache_randomness + def _random_permutation(self): + return np.random.permutation(len(self.transforms)) + + def transform(self, results: Dict) -> Optional[Dict]: + """Transform function to apply transforms in random order. + + Args: + results (dict): A result dict contains the results to transform. + + Returns: + dict or None: Transformed results. + """ + inds = self._random_permutation() + for idx in inds: + t = self.transforms[idx] + results = t(results) + if results is None: + return None + return results + + def __repr__(self): + """Compute the string representation.""" + format_string = self.__class__.__name__ + '(' + for t in self.transforms: + format_string += f'{t.__class__.__name__}, ' + format_string += ')' + return format_string + + +@TRANSFORMS.register_module() +class ProposalBroadcaster(BaseTransform): + """A transform wrapper to apply the wrapped transforms to process both + `gt_bboxes` and `proposals` without adding any codes. It will do the + following steps: + + 1. Scatter the broadcasting targets to a list of inputs of the wrapped + transforms. The type of the list should be list[dict, dict], which + the first is the original inputs, the second is the processing + results that `gt_bboxes` being rewritten by the `proposals`. + 2. Apply ``self.transforms``, with same random parameters, which is + sharing with a context manager. The type of the outputs is a + list[dict, dict]. + 3. Gather the outputs, update the `proposals` in the first item of + the outputs with the `gt_bboxes` in the second . + + Args: + transforms (list, optional): Sequence of transform + object or config dict to be wrapped. Defaults to []. + + Note: The `TransformBroadcaster` in MMCV can achieve the same operation as + `ProposalBroadcaster`, but need to set more complex parameters. + + Examples: + >>> pipeline = [ + >>> dict(type='LoadImageFromFile'), + >>> dict(type='LoadProposals', num_max_proposals=2000), + >>> dict(type='LoadAnnotations', with_bbox=True), + >>> dict( + >>> type='ProposalBroadcaster', + >>> transforms=[ + >>> dict(type='Resize', scale=(1333, 800), + >>> keep_ratio=True), + >>> dict(type='RandomFlip', prob=0.5), + >>> ]), + >>> dict(type='PackDetInputs')] + """ + + def __init__(self, transforms: List[Union[dict, Callable]] = []) -> None: + self.transforms = Compose(transforms) + + def transform(self, results: dict) -> dict: + """Apply wrapped transform functions to process both `gt_bboxes` and + `proposals`. + + Args: + results (dict): Result dict from loading pipeline. + + Returns: + dict: Updated result dict. + """ + assert results.get('proposals', None) is not None, \ + '`proposals` should be in the results, please delete ' \ + '`ProposalBroadcaster` in your configs, or check whether ' \ + 'you have load proposals successfully.' + + inputs = self._process_input(results) + outputs = self._apply_transforms(inputs) + outputs = self._process_output(outputs) + return outputs + + def _process_input(self, data: dict) -> list: + """Scatter the broadcasting targets to a list of inputs of the wrapped + transforms. + + Args: + data (dict): The original input data. + + Returns: + list[dict]: A list of input data. + """ + cp_data = copy.deepcopy(data) + cp_data['gt_bboxes'] = cp_data['proposals'] + scatters = [data, cp_data] + return scatters + + def _apply_transforms(self, inputs: list) -> list: + """Apply ``self.transforms``. + + Args: + inputs (list[dict, dict]): list of input data. + + Returns: + list[dict]: The output of the wrapped pipeline. + """ + assert len(inputs) == 2 + ctx = cache_random_params + with ctx(self.transforms): + output_scatters = [self.transforms(_input) for _input in inputs] + return output_scatters + + def _process_output(self, output_scatters: list) -> dict: + """Gathering and renaming data items. + + Args: + output_scatters (list[dict, dict]): The output of the wrapped + pipeline. + + Returns: + dict: Updated result dict. + """ + assert isinstance(output_scatters, list) and \ + isinstance(output_scatters[0], dict) and \ + len(output_scatters) == 2 + outputs = output_scatters[0] + outputs['proposals'] = output_scatters[1]['gt_bboxes'] + return outputs diff --git a/mmdet_code/mmdetection/mmdet/datasets/utils.py b/mmdet_code/mmdetection/mmdet/datasets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d794eb4b06ec9db56ff3a5fc7b817d1d9332a989 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/utils.py @@ -0,0 +1,48 @@ +# Copyright (c) OpenMMLab. All rights reserved. + +from mmcv.transforms import LoadImageFromFile + +from mmdet.datasets.transforms import LoadAnnotations, LoadPanopticAnnotations +from mmdet.registry import TRANSFORMS + + +def get_loading_pipeline(pipeline): + """Only keep loading image and annotations related configuration. + + Args: + pipeline (list[dict]): Data pipeline configs. + + Returns: + list[dict]: The new pipeline list with only keep + loading image and annotations related configuration. + + Examples: + >>> pipelines = [ + ... dict(type='LoadImageFromFile'), + ... dict(type='LoadAnnotations', with_bbox=True), + ... dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), + ... dict(type='RandomFlip', flip_ratio=0.5), + ... dict(type='Normalize', **img_norm_cfg), + ... dict(type='Pad', size_divisor=32), + ... dict(type='DefaultFormatBundle'), + ... dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) + ... ] + >>> expected_pipelines = [ + ... dict(type='LoadImageFromFile'), + ... dict(type='LoadAnnotations', with_bbox=True) + ... ] + >>> assert expected_pipelines ==\ + ... get_loading_pipeline(pipelines) + """ + loading_pipeline_cfg = [] + for cfg in pipeline: + obj_cls = TRANSFORMS.get(cfg['type']) + # TODO:use more elegant way to distinguish loading modules + if obj_cls is not None and obj_cls in (LoadImageFromFile, + LoadAnnotations, + LoadPanopticAnnotations): + loading_pipeline_cfg.append(cfg) + assert len(loading_pipeline_cfg) == 2, \ + 'The data pipeline in your config file must include ' \ + 'loading image and annotations related pipeline.' + return loading_pipeline_cfg diff --git a/mmdet_code/mmdetection/mmdet/datasets/v3det.py b/mmdet_code/mmdetection/mmdet/datasets/v3det.py new file mode 100644 index 0000000000000000000000000000000000000000..25bfe3bc718841143653c54954240186c3376955 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/v3det.py @@ -0,0 +1,32 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path +from typing import Optional + +import mmengine + +from mmdet.registry import DATASETS +from .coco import CocoDataset + + +@DATASETS.register_module() +class V3DetDataset(CocoDataset): + """Dataset for V3Det.""" + + METAINFO = { + 'classes': None, + 'palette': None, + } + + def __init__( + self, + *args, + metainfo: Optional[dict] = None, + data_root: str = '', + label_file='annotations/category_name_13204_v3det_2023_v1.txt', # noqa + **kwargs) -> None: + class_names = tuple( + mmengine.list_from_file(os.path.join(data_root, label_file))) + if metainfo is None: + metainfo = {'classes': class_names} + super().__init__( + *args, data_root=data_root, metainfo=metainfo, **kwargs) diff --git a/mmdet_code/mmdetection/mmdet/datasets/voc.py b/mmdet_code/mmdetection/mmdet/datasets/voc.py new file mode 100644 index 0000000000000000000000000000000000000000..65e73f2f0bd4f2b16d5237cd3b5f342e44cf0438 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/voc.py @@ -0,0 +1,31 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .xml_style import XMLDataset + + +@DATASETS.register_module() +class VOCDataset(XMLDataset): + """Dataset for PASCAL VOC.""" + + METAINFO = { + 'classes': + ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', + 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', + 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'), + # palette is a list of color tuples, which is used for visualization. + 'palette': [(106, 0, 228), (119, 11, 32), (165, 42, 42), (0, 0, 192), + (197, 226, 255), (0, 60, 100), (0, 0, 142), (255, 77, 255), + (153, 69, 1), (120, 166, 157), (0, 182, 199), + (0, 226, 252), (182, 182, 255), (0, 0, 230), (220, 20, 60), + (163, 255, 0), (0, 82, 0), (3, 95, 161), (0, 80, 100), + (183, 130, 88)] + } + + def __init__(self, **kwargs): + super().__init__(**kwargs) + if 'VOC2007' in self.sub_data_root: + self._metainfo['dataset_type'] = 'VOC2007' + elif 'VOC2012' in self.sub_data_root: + self._metainfo['dataset_type'] = 'VOC2012' + else: + self._metainfo['dataset_type'] = None diff --git a/mmdet_code/mmdetection/mmdet/datasets/wider_face.py b/mmdet_code/mmdetection/mmdet/datasets/wider_face.py new file mode 100644 index 0000000000000000000000000000000000000000..62c7fff869ab970b6f96908a998ba6feb25ea205 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/wider_face.py @@ -0,0 +1,90 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import xml.etree.ElementTree as ET + +from mmengine.dist import is_main_process +from mmengine.fileio import get_local_path, list_from_file +from mmengine.utils import ProgressBar + +from mmdet.registry import DATASETS +from mmdet.utils.typing_utils import List, Union +from .xml_style import XMLDataset + + +@DATASETS.register_module() +class WIDERFaceDataset(XMLDataset): + """Reader for the WIDER Face dataset in PASCAL VOC format. + + Conversion scripts can be found in + https://github.com/sovrasov/wider-face-pascal-voc-annotations + """ + METAINFO = {'classes': ('face', ), 'palette': [(0, 255, 0)]} + + def load_data_list(self) -> List[dict]: + """Load annotation from XML style ann_file. + + Returns: + list[dict]: Annotation info from XML file. + """ + assert self._metainfo.get('classes', None) is not None, \ + 'classes in `XMLDataset` can not be None.' + self.cat2label = { + cat: i + for i, cat in enumerate(self._metainfo['classes']) + } + + data_list = [] + img_ids = list_from_file(self.ann_file, backend_args=self.backend_args) + + # loading process takes around 10 mins + if is_main_process(): + prog_bar = ProgressBar(len(img_ids)) + + for img_id in img_ids: + raw_img_info = {} + raw_img_info['img_id'] = img_id + raw_img_info['file_name'] = f'{img_id}.jpg' + parsed_data_info = self.parse_data_info(raw_img_info) + data_list.append(parsed_data_info) + + if is_main_process(): + prog_bar.update() + return data_list + + def parse_data_info(self, img_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + img_info (dict): Raw image information, usually it includes + `img_id`, `file_name`, and `xml_path`. + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + data_info = {} + img_id = img_info['img_id'] + xml_path = osp.join(self.data_prefix['img'], 'Annotations', + f'{img_id}.xml') + data_info['img_id'] = img_id + data_info['xml_path'] = xml_path + + # deal with xml file + with get_local_path( + xml_path, backend_args=self.backend_args) as local_path: + raw_ann_info = ET.parse(local_path) + root = raw_ann_info.getroot() + size = root.find('size') + width = int(size.find('width').text) + height = int(size.find('height').text) + folder = root.find('folder').text + img_path = osp.join(self.data_prefix['img'], folder, + img_info['file_name']) + data_info['img_path'] = img_path + + data_info['height'] = height + data_info['width'] = width + + # Coordinates are in range [0, width - 1 or height - 1] + data_info['instances'] = self._parse_instance_info( + raw_ann_info, minus_one=False) + return data_info diff --git a/mmdet_code/mmdetection/mmdet/datasets/xml_style.py b/mmdet_code/mmdetection/mmdet/datasets/xml_style.py new file mode 100644 index 0000000000000000000000000000000000000000..06045ea0092238abdac9622511b336586858f8f5 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/xml_style.py @@ -0,0 +1,186 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import xml.etree.ElementTree as ET +from typing import List, Optional, Union + +import mmcv +from mmengine.fileio import get, get_local_path, list_from_file + +from mmdet.registry import DATASETS +from .base_det_dataset import BaseDetDataset + + +@DATASETS.register_module() +class XMLDataset(BaseDetDataset): + """XML dataset for detection. + + Args: + img_subdir (str): Subdir where images are stored. Default: JPEGImages. + ann_subdir (str): Subdir where annotations are. Default: Annotations. + backend_args (dict, optional): Arguments to instantiate the + corresponding backend. Defaults to None. + """ + + def __init__(self, + img_subdir: str = 'JPEGImages', + ann_subdir: str = 'Annotations', + **kwargs) -> None: + self.img_subdir = img_subdir + self.ann_subdir = ann_subdir + super().__init__(**kwargs) + + @property + def sub_data_root(self) -> str: + """Return the sub data root.""" + return self.data_prefix.get('sub_data_root', '') + + def load_data_list(self) -> List[dict]: + """Load annotation from XML style ann_file. + + Returns: + list[dict]: Annotation info from XML file. + """ + assert self._metainfo.get('classes', None) is not None, \ + '`classes` in `XMLDataset` can not be None.' + self.cat2label = { + cat: i + for i, cat in enumerate(self._metainfo['classes']) + } + + data_list = [] + img_ids = list_from_file(self.ann_file, backend_args=self.backend_args) + for img_id in img_ids: + file_name = osp.join(self.img_subdir, f'{img_id}.jpg') + xml_path = osp.join(self.sub_data_root, self.ann_subdir, + f'{img_id}.xml') + + raw_img_info = {} + raw_img_info['img_id'] = img_id + raw_img_info['file_name'] = file_name + raw_img_info['xml_path'] = xml_path + + parsed_data_info = self.parse_data_info(raw_img_info) + data_list.append(parsed_data_info) + return data_list + + @property + def bbox_min_size(self) -> Optional[int]: + """Return the minimum size of bounding boxes in the images.""" + if self.filter_cfg is not None: + return self.filter_cfg.get('bbox_min_size', None) + else: + return None + + def parse_data_info(self, img_info: dict) -> Union[dict, List[dict]]: + """Parse raw annotation to target format. + + Args: + img_info (dict): Raw image information, usually it includes + `img_id`, `file_name`, and `xml_path`. + + Returns: + Union[dict, List[dict]]: Parsed annotation. + """ + data_info = {} + img_path = osp.join(self.sub_data_root, img_info['file_name']) + data_info['img_path'] = img_path + data_info['img_id'] = img_info['img_id'] + data_info['xml_path'] = img_info['xml_path'] + + # deal with xml file + with get_local_path( + img_info['xml_path'], + backend_args=self.backend_args) as local_path: + raw_ann_info = ET.parse(local_path) + root = raw_ann_info.getroot() + size = root.find('size') + if size is not None: + width = int(size.find('width').text) + height = int(size.find('height').text) + else: + img_bytes = get(img_path, backend_args=self.backend_args) + img = mmcv.imfrombytes(img_bytes, backend='cv2') + height, width = img.shape[:2] + del img, img_bytes + + data_info['height'] = height + data_info['width'] = width + + data_info['instances'] = self._parse_instance_info( + raw_ann_info, minus_one=True) + + return data_info + + def _parse_instance_info(self, + raw_ann_info: ET, + minus_one: bool = True) -> List[dict]: + """parse instance information. + + Args: + raw_ann_info (ElementTree): ElementTree object. + minus_one (bool): Whether to subtract 1 from the coordinates. + Defaults to True. + + Returns: + List[dict]: List of instances. + """ + instances = [] + for obj in raw_ann_info.findall('object'): + instance = {} + name = obj.find('name').text + if name not in self._metainfo['classes']: + continue + difficult = obj.find('difficult') + difficult = 0 if difficult is None else int(difficult.text) + bnd_box = obj.find('bndbox') + bbox = [ + int(float(bnd_box.find('xmin').text)), + int(float(bnd_box.find('ymin').text)), + int(float(bnd_box.find('xmax').text)), + int(float(bnd_box.find('ymax').text)) + ] + + # VOC needs to subtract 1 from the coordinates + if minus_one: + bbox = [x - 1 for x in bbox] + + ignore = False + if self.bbox_min_size is not None: + assert not self.test_mode + w = bbox[2] - bbox[0] + h = bbox[3] - bbox[1] + if w < self.bbox_min_size or h < self.bbox_min_size: + ignore = True + if difficult or ignore: + instance['ignore_flag'] = 1 + else: + instance['ignore_flag'] = 0 + instance['bbox'] = bbox + instance['bbox_label'] = self.cat2label[name] + instances.append(instance) + return instances + + def filter_data(self) -> List[dict]: + """Filter annotations according to filter_cfg. + + Returns: + List[dict]: Filtered results. + """ + if self.test_mode: + return self.data_list + + filter_empty_gt = self.filter_cfg.get('filter_empty_gt', False) \ + if self.filter_cfg is not None else False + min_size = self.filter_cfg.get('min_size', 0) \ + if self.filter_cfg is not None else 0 + + valid_data_infos = [] + for i, data_info in enumerate(self.data_list): + width = data_info['width'] + height = data_info['height'] + if filter_empty_gt and len(data_info['instances']) == 0: + continue + if min(width, height) >= min_size: + valid_data_infos.append(data_info) + + return valid_data_infos diff --git a/mmdet_code/mmdetection/mmdet/datasets/youtube_vis_dataset.py b/mmdet_code/mmdetection/mmdet/datasets/youtube_vis_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..38c3d3909f1b8fd795c181546094056c54c9c4b2 --- /dev/null +++ b/mmdet_code/mmdetection/mmdet/datasets/youtube_vis_dataset.py @@ -0,0 +1,52 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmdet.registry import DATASETS +from .base_video_dataset import BaseVideoDataset + + +@DATASETS.register_module() +class YouTubeVISDataset(BaseVideoDataset): + """YouTube VIS dataset for video instance segmentation. + + Args: + dataset_version (str): Select dataset year version. + """ + + def __init__(self, dataset_version: str, *args, **kwargs): + self.set_dataset_classes(dataset_version) + super().__init__(*args, **kwargs) + + @classmethod + def set_dataset_classes(cls, dataset_version: str) -> None: + """Pass the category of the corresponding year to metainfo. + + Args: + dataset_version (str): Select dataset year version. + """ + classes_2019_version = ('person', 'giant_panda', 'lizard', 'parrot', + 'skateboard', 'sedan', 'ape', 'dog', 'snake', + 'monkey', 'hand', 'rabbit', 'duck', 'cat', + 'cow', 'fish', 'train', 'horse', 'turtle', + 'bear', 'motorbike', 'giraffe', 'leopard', + 'fox', 'deer', 'owl', 'surfboard', 'airplane', + 'truck', 'zebra', 'tiger', 'elephant', + 'snowboard', 'boat', 'shark', 'mouse', 'frog', + 'eagle', 'earless_seal', 'tennis_racket') + + classes_2021_version = ('airplane', 'bear', 'bird', 'boat', 'car', + 'cat', 'cow', 'deer', 'dog', 'duck', + 'earless_seal', 'elephant', 'fish', + 'flying_disc', 'fox', 'frog', 'giant_panda', + 'giraffe', 'horse', 'leopard', 'lizard', + 'monkey', 'motorbike', 'mouse', 'parrot', + 'person', 'rabbit', 'shark', 'skateboard', + 'snake', 'snowboard', 'squirrel', 'surfboard', + 'tennis_racket', 'tiger', 'train', 'truck', + 'turtle', 'whale', 'zebra') + + if dataset_version == '2019': + cls.METAINFO = dict(classes=classes_2019_version) + elif dataset_version == '2021': + cls.METAINFO = dict(classes=classes_2021_version) + else: + raise NotImplementedError('Not supported YouTubeVIS dataset' + f'version: {dataset_version}') diff --git a/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/__init__.cpython-313.pyc b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca6e56584e7806c28d8835834aa7802176d789d3 Binary files /dev/null and b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/__init__.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/__init__.cpython-314.pyc b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8de0e5b7f812c224f769bf32f86a2df6cdaafba8 Binary files /dev/null and b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/__init__.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-313.pyc b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..779133aef7a9c1ed0571b6c3a915652d914dc1b4 Binary files /dev/null and b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-314.pyc b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0990c885f62219e1ed18ceeea3af7b51cd5a622 Binary files /dev/null and b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/__init__.cpython-313.pyc b/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..058daf176657014f4ef4ba2498c2d552278200bb Binary files /dev/null and b/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/__init__.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/dala_assigner.cpython-313.pyc b/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/dala_assigner.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b0ff7824f3d093fa5b81aaf36efdcf046d74707 Binary files /dev/null and b/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/dala_assigner.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/dala_assigner.cpython-314.pyc b/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/dala_assigner.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b803de59f3d845ed1aee4a9d7e79ec3e99836795 Binary files /dev/null and b/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/dala_assigner.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_8xb16-crop512-300e_coco.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_8xb16-crop512-300e_coco.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..103de89f1e3dc765872bddbd5282f8cfdfdee347 Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_8xb16-crop512-300e_coco.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.cpython-313.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2edd169565eaff8578e406ad7ac02582a88b8205 Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91e262196ba3c9c84dc39aee40fcfb0dbac807c8 Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-crop512-300e_coco.cpython-313.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-crop512-300e_coco.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eea516460ee76433ae39c11c8524dea7b8061224 Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-crop512-300e_coco.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-crop512-300e_coco.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-crop512-300e_coco.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2491a26b646a19d1d98d3a8c102782d5ac72ccee Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-crop512-300e_coco.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-crop512-300e_coco.cpython-313.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-crop512-300e_coco.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08b944854dc91084d3d13b527b0aae06b3b3eead Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-crop512-300e_coco.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-crop512-300e_coco.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-crop512-300e_coco.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9da360b3afeda177da489a1b8778c1bd99320ed3 Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-crop512-300e_coco.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb2_bifpn_8xb16-crop512-300e_coco.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb2_bifpn_8xb16-crop512-300e_coco.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2c6ef75aad253d1b87897f5d3dce1b9b3fe2466 Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb2_bifpn_8xb16-crop512-300e_coco.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb2_bifpn_dala_8xb16-crop512-300e_coco.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb2_bifpn_dala_8xb16-crop512-300e_coco.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b940eb7de2ad60d9392541af4d3c69db1ce2cfb Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb2_bifpn_dala_8xb16-crop512-300e_coco.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/efficientdet/__pycache__/__init__.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/efficientdet/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..037ed51d9694c97f7690dcdd5456b8d0db6bbb9a Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/efficientdet/__pycache__/__init__.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/efficientdet/__pycache__/efficientdet_head.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/efficientdet/__pycache__/efficientdet_head.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bebf25349114707a36cc3e7112c54f4c913e8f0c Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/efficientdet/__pycache__/efficientdet_head.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-313.pyc b/mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc501cd9262bce911fb71f84f799d8e6d684ec5b Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-314.pyc b/mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb43e5ec7c391b333d037ffbee9f846c98f51b6d Binary files /dev/null and b/mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/projects/EfficientDet/tests/test_dala_efficientdet_head.py b/mmdet_code/mmdetection/projects/EfficientDet/tests/test_dala_efficientdet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..76f167ca3441053911aa625186d80fa8e8e44007 --- /dev/null +++ b/mmdet_code/mmdetection/projects/EfficientDet/tests/test_dala_efficientdet_head.py @@ -0,0 +1,110 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine.structures import InstanceData + +from projects.EfficientDet.efficientdet import DalaEfficientDetSepBNHead + + +def test_dala_efficientdet_assignment_and_dwl_targets(): + head = DalaEfficientDetSepBNHead( + num_classes=1, + num_ins=1, + in_channels=8, + feat_channels=8, + stacked_convs=1, + norm_cfg=dict(type='BN'), + anchor_generator=dict( + type='AnchorGenerator', + scales=[1], + ratios=[1.0], + strides=[8]), + train_cfg=dict( + assigner=dict(type='DalaAssigner', sync_stats=False), + sampler=dict(type='PseudoSampler'), + allowed_border=-1, + pos_weight=-1)) + + anchors = torch.tensor([ + [0., 0., 10., 10.], + [1., 1., 9., 9.], + [20., 20., 40., 40.], + [22., 22., 38., 38.], + [50., 50., 60., 60.], + ]) + gt_instances = InstanceData( + bboxes=torch.tensor([[0., 0., 10., 10.], [20., 20., 40., 40.]]), + labels=torch.tensor([0, 0])) + + (labels, label_weights, _, bbox_weights, pos_inds, neg_inds, + _) = head._get_targets_single( + anchors, + torch.ones(5, dtype=torch.bool), + gt_instances, + dict(img_shape=(64, 64, 3)), + unmap_outputs=False) + + # RLA keeps the exact-match anchor for each GT, ignores the other two + # inside candidates, and treats the anchor outside all GTs as negative. + assert torch.equal(pos_inds, torch.tensor([0, 2])) + assert torch.equal(neg_inds, torch.tensor([4])) + assert torch.equal(labels, torch.tensor([0, 1, 0, 1, 1])) + assert torch.equal(label_weights[[1, 3]], torch.zeros(2)) + + # DWL upweights the smaller GT, downweights the larger GT, and assigns the + # positive-weight mean to the true negative classification target. + assert label_weights[0] > 1 + assert label_weights[2] < 1 + assert torch.allclose(label_weights[4], label_weights[pos_inds].mean()) + assert torch.allclose(bbox_weights[pos_inds, 0], + label_weights[pos_inds]) + + +def test_dala_efficientdet_s3_preserves_fpn_level_ids(): + head = DalaEfficientDetSepBNHead( + num_classes=1, + num_ins=2, + in_channels=8, + feat_channels=8, + stacked_convs=1, + norm_cfg=dict(type='BN'), + anchor_generator=dict( + type='AnchorGenerator', + scales=[1], + ratios=[1.0], + strides=[8, 16]), + train_cfg=dict( + assigner=dict( + type='DalaAssigner', + similarity_mode='s3', + level_lambda=1.0, + sync_stats=False), + sampler=dict(type='PseudoSampler'), + allowed_border=-1, + pos_weight=-1)) + + anchor_list = [[ + # P3: correct scale but a poor centre. P4: oversized but perfectly + # centred. S0 slightly prefers P4; the S3 level prior should flip it. + torch.tensor([[9., 9., 29., 29.]]), + torch.tensor([[-5., -5., 25., 25.]]) + ]] + valid_flag_list = [[ + torch.ones(1, dtype=torch.bool), + torch.ones(1, dtype=torch.bool) + ]] + gt_instances = [ + InstanceData( + bboxes=torch.tensor([[0., 0., 20., 20.]]), + labels=torch.tensor([0])) + ] + + labels, label_weights, _, _, _ = head.get_targets( + anchor_list, valid_flag_list, gt_instances, + [dict(img_shape=(32, 32, 3))]) + + # Both centres lie inside the GT. The correctly scaled P3 candidate is + # positive and the oversized P4 candidate is ignored. + assert labels[0].item() == 0 + assert label_weights[0].item() > 0 + assert labels[1].item() == 1 + assert label_weights[1].item() == 0 diff --git a/mmdet_code/mmdetection/tests/test_apis/test_det_inferencer.py b/mmdet_code/mmdetection/tests/test_apis/test_det_inferencer.py new file mode 100644 index 0000000000000000000000000000000000000000..9f89b9bdc09022f8d2d703e975192dd6308b5888 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_apis/test_det_inferencer.py @@ -0,0 +1,165 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile +from unittest import TestCase, mock +from unittest.mock import Mock, patch + +import mmcv +import mmengine +import numpy as np +import torch +from mmengine.structures import InstanceData +from mmengine.utils import is_list_of +from parameterized import parameterized + +from mmdet.apis import DetInferencer +from mmdet.evaluation.functional import get_classes +from mmdet.structures import DetDataSample + + +class TestDetInferencer(TestCase): + + @mock.patch('mmengine.infer.infer._load_checkpoint', return_value=None) + def test_init(self, mock): + # init from metafile + DetInferencer('rtmdet-t') + # init from cfg + DetInferencer('configs/yolox/yolox_tiny_8xb8-300e_coco.py') + + def assert_predictions_equal(self, preds1, preds2): + for pred1, pred2 in zip(preds1, preds2): + if 'bboxes' in pred1: + self.assertTrue( + np.allclose(pred1['bboxes'], pred2['bboxes'], 0.1)) + if 'scores' in pred1: + self.assertTrue( + np.allclose(pred1['scores'], pred2['scores'], 0.1)) + if 'labels' in pred1: + self.assertTrue(np.allclose(pred1['labels'], pred2['labels'])) + if 'panoptic_seg_path' in pred1: + self.assertTrue( + pred1['panoptic_seg_path'] == pred2['panoptic_seg_path']) + + @parameterized.expand([ + 'rtmdet-t', 'mask-rcnn_r50_fpn_1x_coco', 'panoptic_fpn_r50_fpn_1x_coco' + ]) + def test_call(self, model): + # single img + img_path = 'tests/data/color.jpg' + + mock_load = Mock(return_value=None) + with patch('mmengine.infer.infer._load_checkpoint', mock_load): + inferencer = DetInferencer(model) + + # In the case of not loading the pretrained weight, the category + # defaults to COCO 80, so it needs to be replaced. + if model == 'panoptic_fpn_r50_fpn_1x_coco': + inferencer.visualizer.dataset_meta = { + 'classes': get_classes('coco_panoptic'), + 'palette': 'random' + } + + res_path = inferencer(img_path, return_vis=True) + # ndarray + img = mmcv.imread(img_path) + res_ndarray = inferencer(img, return_vis=True) + self.assert_predictions_equal(res_path['predictions'], + res_ndarray['predictions']) + self.assertIn('visualization', res_path) + self.assertIn('visualization', res_ndarray) + + # multiple images + img_paths = ['tests/data/color.jpg', 'tests/data/gray.jpg'] + res_path = inferencer(img_paths, return_vis=True) + # list of ndarray + imgs = [mmcv.imread(p) for p in img_paths] + res_ndarray = inferencer(imgs, return_vis=True) + self.assert_predictions_equal(res_path['predictions'], + res_ndarray['predictions']) + self.assertIn('visualization', res_path) + self.assertIn('visualization', res_ndarray) + + # img dir, test different batch sizes + img_dir = 'tests/data/VOCdevkit/VOC2007/JPEGImages/' + res_bs1 = inferencer(img_dir, batch_size=1, return_vis=True) + res_bs3 = inferencer(img_dir, batch_size=3, return_vis=True) + self.assert_predictions_equal(res_bs1['predictions'], + res_bs3['predictions']) + + # There is a jitter operation when the mask is drawn, + # so it cannot be asserted. + if model == 'rtmdet-t': + for res_bs1_vis, res_bs3_vis in zip(res_bs1['visualization'], + res_bs3['visualization']): + self.assertTrue(np.allclose(res_bs1_vis, res_bs3_vis)) + + @parameterized.expand([ + 'rtmdet-t', 'mask-rcnn_r50_fpn_1x_coco', 'panoptic_fpn_r50_fpn_1x_coco' + ]) + def test_visualize(self, model): + img_paths = ['tests/data/color.jpg', 'tests/data/gray.jpg'] + + mock_load = Mock(return_value=None) + with patch('mmengine.infer.infer._load_checkpoint', mock_load): + inferencer = DetInferencer(model) + + # In the case of not loading the pretrained weight, the category + # defaults to COCO 80, so it needs to be replaced. + if model == 'panoptic_fpn_r50_fpn_1x_coco': + inferencer.visualizer.dataset_meta = { + 'classes': get_classes('coco_panoptic'), + 'palette': 'random' + } + + with tempfile.TemporaryDirectory() as tmp_dir: + inferencer(img_paths, out_dir=tmp_dir) + for img_dir in ['color.jpg', 'gray.jpg']: + self.assertTrue(osp.exists(osp.join(tmp_dir, 'vis', img_dir))) + + @parameterized.expand([ + 'rtmdet-t', 'mask-rcnn_r50_fpn_1x_coco', 'panoptic_fpn_r50_fpn_1x_coco' + ]) + def test_postprocess(self, model): + # return_datasamples + img_path = 'tests/data/color.jpg' + + mock_load = Mock(return_value=None) + with patch('mmengine.infer.infer._load_checkpoint', mock_load): + inferencer = DetInferencer(model) + + # In the case of not loading the pretrained weight, the category + # defaults to COCO 80, so it needs to be replaced. + if model == 'panoptic_fpn_r50_fpn_1x_coco': + inferencer.visualizer.dataset_meta = { + 'classes': get_classes('coco_panoptic'), + 'palette': 'random' + } + + res = inferencer(img_path, return_datasamples=True) + self.assertTrue(is_list_of(res['predictions'], DetDataSample)) + + with tempfile.TemporaryDirectory() as tmp_dir: + res = inferencer(img_path, out_dir=tmp_dir, no_save_pred=False) + dumped_res = mmengine.load( + osp.join(tmp_dir, 'preds', 'color.json')) + self.assertEqual(res['predictions'][0], dumped_res) + + @mock.patch('mmengine.infer.infer._load_checkpoint', return_value=None) + def test_pred2dict(self, mock): + data_sample = DetDataSample() + data_sample.pred_instances = InstanceData() + + data_sample.pred_instances.bboxes = np.array([[0, 0, 1, 1]]) + data_sample.pred_instances.labels = np.array([0]) + data_sample.pred_instances.scores = torch.FloatTensor([0.9]) + res = DetInferencer('rtmdet-t').pred2dict(data_sample) + self.assertListAlmostEqual(res['bboxes'], [[0, 0, 1, 1]]) + self.assertListAlmostEqual(res['labels'], [0]) + self.assertListAlmostEqual(res['scores'], [0.9]) + + def assertListAlmostEqual(self, list1, list2, places=7): + for i in range(len(list1)): + if isinstance(list1[i], list): + self.assertListAlmostEqual(list1[i], list2[i], places=places) + else: + self.assertAlmostEqual(list1[i], list2[i], places=places) diff --git a/mmdet_code/mmdetection/tests/test_apis/test_inference.py b/mmdet_code/mmdetection/tests/test_apis/test_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e42f86c64e89b4778ec38f14f93bbabf414eb844 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_apis/test_inference.py @@ -0,0 +1,76 @@ +import os +from pathlib import Path + +import numpy as np +import pytest +import torch + +from mmdet.apis import inference_detector, init_detector +from mmdet.structures import DetDataSample +from mmdet.utils import register_all_modules + +# TODO: Waiting to fix multiple call error bug +register_all_modules() + + +@pytest.mark.parametrize('config,devices', + [('configs/retinanet/retinanet_r18_fpn_1x_coco.py', + ('cpu', 'cuda'))]) +def test_init_detector(config, devices): + assert all([device in ['cpu', 'cuda'] for device in devices]) + + project_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + project_dir = os.path.join(project_dir, '..') + + config_file = os.path.join(project_dir, config) + + # test init_detector with config_file: str and cfg_options + cfg_options = dict( + model=dict( + backbone=dict( + depth=18, + init_cfg=dict( + type='Pretrained', checkpoint='torchvision://resnet18')))) + + for device in devices: + if device == 'cuda' and not torch.cuda.is_available(): + pytest.skip('test requires GPU and torch+cuda') + + model = init_detector( + config_file, device=device, cfg_options=cfg_options) + + # test init_detector with :obj:`Path` + config_path_object = Path(config_file) + model = init_detector(config_path_object, device=device) + + # test init_detector with undesirable type + with pytest.raises(TypeError): + config_list = [config_file] + model = init_detector(config_list) # noqa: F841 + + +@pytest.mark.parametrize('config,devices', + [('configs/retinanet/retinanet_r18_fpn_1x_coco.py', + ('cpu', 'cuda'))]) +def test_inference_detector(config, devices): + assert all([device in ['cpu', 'cuda'] for device in devices]) + + project_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + project_dir = os.path.join(project_dir, '..') + + config_file = os.path.join(project_dir, config) + + # test init_detector with config_file: str and cfg_options + rng = np.random.RandomState(0) + img1 = rng.randint(0, 255, (32, 32, 3), dtype=np.uint8) + img2 = rng.randint(0, 255, (32, 32, 3), dtype=np.uint8) + + for device in devices: + if device == 'cuda' and not torch.cuda.is_available(): + pytest.skip('test requires GPU and torch+cuda') + + model = init_detector(config_file, device=device) + result = inference_detector(model, img1) + assert isinstance(result, DetDataSample) + result = inference_detector(model, [img1, img2]) + assert isinstance(result, list) and len(result) == 2 diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_cityscapes.py b/mmdet_code/mmdetection/tests/test_datasets/test_cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..71a7f9ec170335bfee31b304bfd4a66a9dbe1f38 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_cityscapes.py @@ -0,0 +1,206 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import unittest + +from mmengine.fileio import dump + +from mmdet.datasets import CityscapesDataset + + +class TestCityscapesDataset(unittest.TestCase): + + def setUp(self) -> None: + image1 = { + 'file_name': 'munster/munster_000102_000019_leftImg8bit.png', + 'height': 1024, + 'width': 2048, + 'segm_file': 'munster/munster_000102_000019_gtFine_labelIds.png', + 'id': 0 + } + image2 = { + 'file_name': 'munster/munster_000157_000019_leftImg8bit.png', + 'height': 1024, + 'width': 2048, + 'segm_file': 'munster/munster_000157_000019_gtFine_labelIds.png', + 'id': 1 + } + image3 = { + 'file_name': 'munster/munster_000139_000019_leftImg8bit.png', + 'height': 1024, + 'width': 2048, + 'segm_file': 'munster/munster_000139_000019_gtFine_labelIds.png', + 'id': 2 + } + image4 = { + 'file_name': 'munster/munster_000034_000019_leftImg8bit.png', + 'height': 31, + 'width': 15, + 'segm_file': 'munster/munster_000034_000019_gtFine_labelIds.png', + 'id': 3 + } + + images = [image1, image2, image3, image4] + + categories = [{ + 'id': 24, + 'name': 'person' + }, { + 'id': 25, + 'name': 'rider' + }, { + 'id': 26, + 'name': 'car' + }] + + annotations = [ + { + 'iscrowd': 0, + 'category_id': 24, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 0 + }, + { + 'iscrowd': 0, + 'category_id': 25, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': -1, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 1 + }, + { + 'iscrowd': 0, + 'category_id': 26, + 'bbox': [379.0, 435.0, -1, 124.0], + 'area': 2, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 2 + }, + { + 'iscrowd': 0, + 'category_id': 24, + 'bbox': [379.0, 435.0, 52.0, -1], + 'area': 2, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 3 + }, + { + 'iscrowd': 0, + 'category_id': 1, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 0, + 'id': 4 + }, + { + 'iscrowd': 1, + 'category_id': 26, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 1, + 'id': 5 + }, + { + 'iscrowd': 0, + 'category_id': 26, + 'bbox': [379.0, 435.0, 10, 2], + 'area': 2595, + 'segmentation': { + 'size': [1024, 2048], + 'counts': 'xxx' + }, + 'image_id': 3, + 'id': 6 + }, + ] + fake_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories + } + self.json_name = 'cityscapes.json' + dump(fake_json, self.json_name) + + self.metainfo = dict(classes=('person', 'rider', 'car')) + + def tearDown(self): + os.remove(self.json_name) + + def test_cityscapes_dataset(self): + dataset = CityscapesDataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 1) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = CityscapesDataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + def test_cityscapes_dataset_without_filter_cfg(self): + dataset = CityscapesDataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=None, + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = CityscapesDataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=None, + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_coco.py b/mmdet_code/mmdetection/tests/test_datasets/test_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..97fb2c95eaad6204e10be2e2d04b3e81dca91d37 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_coco.py @@ -0,0 +1,48 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import CocoDataset + + +class TestCocoDataset(unittest.TestCase): + + def test_coco_dataset(self): + # test CocoDataset + metainfo = dict(classes=('bus', 'car'), task_name='new_task') + dataset = CocoDataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('bus', 'car')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + self.assertListEqual(dataset.get_cat_ids(0), [0, 1]) + + def test_coco_dataset_without_filter_cfg(self): + # test CocoDataset without filter_cfg + dataset = CocoDataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + pipeline=[]) + self.assertEqual(len(dataset), 4) + + # test with test_mode = True + dataset = CocoDataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + test_mode=True, + pipeline=[]) + self.assertEqual(len(dataset), 4) + + def test_coco_annotation_ids_unique(self): + # test annotation ids not unique error + metainfo = dict(classes=('car', ), task_name='new_task') + with self.assertRaisesRegex(AssertionError, 'are not unique!'): + CocoDataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_wrong_format_sample.json', + metainfo=metainfo, + pipeline=[]) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_coco_api_wrapper.py b/mmdet_code/mmdetection/tests/test_datasets/test_coco_api_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..c3df8ac22cd5c3c0bd4b3c708634624f1b94e297 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_coco_api_wrapper.py @@ -0,0 +1,67 @@ +import os.path as osp +import tempfile +import unittest + +from mmengine.fileio import dump + +from mmdet.datasets.api_wrappers import COCOPanoptic + + +class TestCOCOPanoptic(unittest.TestCase): + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_create_index(self): + ann_json = {'test': ['test', 'createIndex']} + annotation_file = osp.join(self.tmp_dir.name, 'createIndex.json') + dump(ann_json, annotation_file) + COCOPanoptic(annotation_file) + + def test_load_anns(self): + categories = [{ + 'id': 0, + 'name': 'person', + 'supercategory': 'person', + 'isthing': 1 + }] + + images = [{ + 'id': 0, + 'width': 80, + 'height': 60, + 'file_name': 'fake_name1.jpg', + }] + + annotations = [{ + 'segments_info': [ + { + 'id': 1, + 'category_id': 0, + 'area': 400, + 'bbox': [10, 10, 10, 40], + 'iscrowd': 0 + }, + ], + 'file_name': + 'fake_name1.png', + 'image_id': + 0 + }] + + ann_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories, + } + + annotation_file = osp.join(self.tmp_dir.name, 'load_anns.json') + dump(ann_json, annotation_file) + + api = COCOPanoptic(annotation_file) + api.load_anns(1) + + self.assertIsNone(api.load_anns(0.1)) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_coco_panoptic.py b/mmdet_code/mmdetection/tests/test_datasets/test_coco_panoptic.py new file mode 100644 index 0000000000000000000000000000000000000000..20d585dcaa4fae9d51b1ec68d8c139d528ada39b --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_coco_panoptic.py @@ -0,0 +1,249 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import unittest + +from mmengine.fileio import dump + +from mmdet.datasets import CocoPanopticDataset + + +class TestCocoPanopticDataset(unittest.TestCase): + + def setUp(self): + image1 = { + 'id': 0, + 'width': 640, + 'height': 640, + 'file_name': 'fake_name1.jpg', + } + + image2 = { + 'id': 1, + 'width': 640, + 'height': 800, + 'file_name': 'fake_name2.jpg', + } + + image3 = { + 'id': 2, + 'width': 31, + 'height': 40, + 'file_name': 'fake_name3.jpg', + } + + image4 = { + 'id': 3, + 'width': 400, + 'height': 400, + 'file_name': 'fake_name4.jpg', + } + images = [image1, image2, image3, image4] + + annotations = [ + { + 'segments_info': [{ + 'id': 1, + 'category_id': 0, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'iscrowd': 0 + }, { + 'id': 2, + 'category_id': 1, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'iscrowd': 0 + }, { + 'id': 3, + 'category_id': 2, + 'iscrowd': 0, + 'bbox': [1, 189, 612, 285], + 'area': 70036 + }], + 'file_name': + 'fake_name1.jpg', + 'image_id': + 0 + }, + { + 'segments_info': [ + { + # Different to instance style json, there + # are duplicate ids in panoptic style json + 'id': 1, + 'category_id': 0, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'iscrowd': 0 + }, + { + 'id': 4, + 'category_id': 1, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'iscrowd': 1 + }, + { + 'id': 5, + 'category_id': 2, + 'iscrowd': 0, + 'bbox': [100, 200, 200, 300], + 'area': 66666 + }, + { + 'id': 6, + 'category_id': 0, + 'iscrowd': 0, + 'bbox': [1, 189, -10, 285], + 'area': -2 + }, + { + 'id': 10, + 'category_id': 0, + 'iscrowd': 0, + 'bbox': [1, 189, 10, -285], + 'area': 100 + } + ], + 'file_name': + 'fake_name2.jpg', + 'image_id': + 1 + }, + { + 'segments_info': [{ + 'id': 7, + 'category_id': 0, + 'area': 25, + 'bbox': [0, 0, 5, 5], + 'iscrowd': 0 + }], + 'file_name': + 'fake_name3.jpg', + 'image_id': + 2 + }, + { + 'segments_info': [{ + 'id': 8, + 'category_id': 0, + 'area': 25, + 'bbox': [0, 0, 400, 400], + 'iscrowd': 1 + }], + 'file_name': + 'fake_name4.jpg', + 'image_id': + 3 + } + ] + + categories = [{ + 'id': 0, + 'name': 'car', + 'supercategory': 'car', + 'isthing': 1 + }, { + 'id': 1, + 'name': 'person', + 'supercategory': 'person', + 'isthing': 1 + }, { + 'id': 2, + 'name': 'wall', + 'supercategory': 'wall', + 'isthing': 0 + }] + + fake_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories + } + self.json_name = 'coco_panoptic.json' + dump(fake_json, self.json_name) + + self.metainfo = dict( + classes=('person', 'car', 'wall'), + thing_classes=('person', 'car'), + stuff_classes=('wall', )) + + def tearDown(self): + os.remove(self.json_name) + + def test_coco_panoptic_dataset(self): + dataset = CocoPanopticDataset( + data_root='./', + ann_file=self.json_name, + data_prefix=dict(img='imgs', seg='seg'), + metainfo=self.metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + self.assertEqual(dataset.metainfo['thing_classes'], + self.metainfo['thing_classes']) + self.assertEqual(dataset.metainfo['stuff_classes'], + self.metainfo['stuff_classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 2) + self.assertEqual(len(dataset.load_data_list()), 4) + # test mode + dataset = CocoPanopticDataset( + data_root='./', + ann_file=self.json_name, + data_prefix=dict(img='imgs', seg='seg'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + self.assertEqual(dataset.metainfo['thing_classes'], + self.metainfo['thing_classes']) + self.assertEqual(dataset.metainfo['stuff_classes'], + self.metainfo['stuff_classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + def test_coco_panoptic_dataset_without_filter_cfg(self): + dataset = CocoPanopticDataset( + data_root='./', + ann_file=self.json_name, + data_prefix=dict(img='imgs', seg='seg'), + metainfo=self.metainfo, + filter_cfg=None, + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + self.assertEqual(dataset.metainfo['thing_classes'], + self.metainfo['thing_classes']) + self.assertEqual(dataset.metainfo['stuff_classes'], + self.metainfo['stuff_classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + # test mode + dataset = CocoPanopticDataset( + data_root='./', + ann_file=self.json_name, + data_prefix=dict(img='imgs', seg='seg'), + metainfo=self.metainfo, + filter_cfg=None, + test_mode=True, + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + self.assertEqual(dataset.metainfo['thing_classes'], + self.metainfo['thing_classes']) + self.assertEqual(dataset.metainfo['stuff_classes'], + self.metainfo['stuff_classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_crowdhuman.py b/mmdet_code/mmdetection/tests/test_datasets/test_crowdhuman.py new file mode 100644 index 0000000000000000000000000000000000000000..1ccacf3a291403a74ef3b39a8e661e18bf37d2d2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_crowdhuman.py @@ -0,0 +1,16 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import CrowdHumanDataset + + +class TestCrowdHumanDataset(unittest.TestCase): + + def test_crowdhuman_init(self): + dataset = CrowdHumanDataset( + data_root='tests/data/crowdhuman_dataset/', + ann_file='test_annotation_train.odgt', + data_prefix=dict(img='Images/'), + pipeline=[]) + self.assertEqual(len(dataset), 1) + self.assertEqual(dataset.metainfo['classes'], ('person', )) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_dsdldet.py b/mmdet_code/mmdetection/tests/test_datasets/test_dsdldet.py new file mode 100644 index 0000000000000000000000000000000000000000..b92bfe4fc03068a4482604287de5ab1d05fa93ae --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_dsdldet.py @@ -0,0 +1,25 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import DSDLDetDataset + +try: + from dsdl.dataset import DSDLDataset +except ImportError: + DSDLDataset = None + + +class TestDSDLDetDataset(unittest.TestCase): + + def test_dsdldet_init(self): + if DSDLDataset is not None: + dataset = DSDLDetDataset( + data_root='tests/data/dsdl_det', + ann_file='set-train/train.yaml') + dataset.full_init() + + self.assertEqual(len(dataset), 2) + self.assertEqual(len(dataset[0]['instances']), 4) + self.assertEqual(dataset.get_cat_ids(0), [3, 0, 0, 1]) + else: + ImportWarning('Package `dsdl` is not installed.') diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_lvis.py b/mmdet_code/mmdetection/tests/test_datasets/test_lvis.py new file mode 100644 index 0000000000000000000000000000000000000000..e1d908f078d0c097cac85a80400d95a447c6562a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_lvis.py @@ -0,0 +1,231 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import unittest + +from mmengine.fileio import dump + +from mmdet.datasets import LVISV1Dataset, LVISV05Dataset + +try: + import lvis +except ImportError: + lvis = None + + +class TestLVISDataset(unittest.TestCase): + + def setUp(self) -> None: + + image1 = { + # ``coco_url`` for v1 only. + 'coco_url': 'http://images.cocodataset.org/train2017/0.jpg', + # ``file_name`` for v0.5 only. + 'file_name': '0.jpg', + 'height': 1024, + 'width': 2048, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'id': 0 + } + image2 = { + 'coco_url': 'http://images.cocodataset.org/train2017/1.jpg', + 'file_name': '1.jpg', + 'height': 1024, + 'width': 2048, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'id': 1 + } + image3 = { + 'coco_url': 'http://images.cocodataset.org/train2017/2.jpg', + 'file_name': '2.jpg', + 'height': 1024, + 'width': 2048, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'id': 2 + } + image4 = { + 'coco_url': 'http://images.cocodataset.org/train2017/3.jpg', + 'file_name': '3.jpg', + 'height': 31, + 'width': 15, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'id': 3 + } + + images = [image1, image2, image3, image4] + + categories = [{ + 'id': 1, + 'name': 'aerosol_can', + 'frequency': 'c', + 'image_count': 64 + }, { + 'id': 2, + 'name': 'air_conditioner', + 'frequency': 'f', + 'image_count': 364 + }, { + 'id': 3, + 'name': 'airplane', + 'frequency': 'f', + 'image_count': 1911 + }] + + annotations = [ + { + 'category_id': 1, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 0 + }, + { + 'category_id': 2, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': -1, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 1 + }, + { + 'category_id': 3, + 'bbox': [379.0, 435.0, -1, 124.0], + 'area': 2, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 2 + }, + { + 'category_id': 1, + 'bbox': [379.0, 435.0, 52.0, -1], + 'area': 2, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 3 + }, + { + 'category_id': 1, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': [[0.0, 0.0]], + 'image_id': 0, + 'id': 4 + }, + { + 'category_id': 3, + 'bbox': [379.0, 435.0, 52.0, 124.0], + 'area': 2595, + 'segmentation': [[0.0, 0.0]], + 'image_id': 1, + 'id': 5 + }, + { + 'category_id': 3, + 'bbox': [379.0, 435.0, 10, 2], + 'area': 2595, + 'segmentation': [[0.0, 0.0]], + 'image_id': 3, + 'id': 6 + }, + ] + fake_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories + } + self.json_name = 'lvis.json' + dump(fake_json, self.json_name) + + self.metainfo = dict( + classes=('aerosol_can', 'air_conditioner', 'airplane')) + + def tearDown(self): + os.remove(self.json_name) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_lvis05_dataset(self): + dataset = LVISV05Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 2) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = LVISV05Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_lvis1_dataset(self): + dataset = LVISV1Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 2) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = LVISV1Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_lvis1_dataset_without_filter_cfg(self): + dataset = LVISV1Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + filter_cfg=None, + pipeline=[]) + self.assertEqual(dataset.metainfo['classes'], self.metainfo['classes']) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) + + dataset = LVISV1Dataset( + ann_file=self.json_name, + data_prefix=dict(img='imgs'), + metainfo=self.metainfo, + test_mode=True, + filter_cfg=None, + pipeline=[]) + dataset.full_init() + # filter images of small size and images + # with all illegal annotations + self.assertEqual(len(dataset), 4) + self.assertEqual(len(dataset.load_data_list()), 4) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_mot_challenge_dataset.py b/mmdet_code/mmdetection/tests/test_datasets/test_mot_challenge_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9f61b40906ec61390b0e6de2a89ec3925536e4 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_mot_challenge_dataset.py @@ -0,0 +1,37 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import MOTChallengeDataset + + +class TestMOTChallengeDataset(unittest.TestCase): + + def test_mot_challenge_dataset(self): + # test CocoDataset + metainfo = dict(classes=('pedestrian'), task_name='new_task') + dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('pedestrian')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + self.assertListEqual(dataset.get_cat_ids((0, 1)), [0, 0]) + self.assertListEqual(dataset.get_cat_ids(0), [0, 0, 0, 0, 0, 0]) + self.assertEqual(len(dataset), 2) + self.assertEqual(dataset.num_all_imgs, 5) + self.assertEqual(len(dataset[0]['images'][2]['instances']), 2) + + def test_mot_challenge_dataset_with_visibility(self): + dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + visibility_thr=0.5, + pipeline=[]) + self.assertEqual(dataset.num_all_imgs, 5) + self.assertEqual(len(dataset[0]['images'][2]['instances']), 1) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_objects365.py b/mmdet_code/mmdetection/tests/test_datasets/test_objects365.py new file mode 100644 index 0000000000000000000000000000000000000000..1e01bf27c03d09d1e66df8e6569b89c7d26f90c9 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_objects365.py @@ -0,0 +1,79 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import Objects365V1Dataset, Objects365V2Dataset + + +class TestObjects365V1Dataset(unittest.TestCase): + + def test_obj365v1_dataset(self): + # test Objects365V1Dataset + metainfo = dict(classes=('bus', 'car'), task_name='new_task') + dataset = Objects365V1Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('bus', 'car')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + self.assertListEqual(dataset.get_cat_ids(0), [0, 1]) + self.assertEqual(dataset.cat_ids, [1, 2]) + + def test_obj365v1_with_unsorted_annotation(self): + # test Objects365V1Dataset with unsorted annotations + metainfo = dict(classes=('bus', 'car'), task_name='new_task') + dataset = Objects365V1Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/Objects365/unsorted_obj365_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('bus', 'car')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + # sort the unsorted annotations + self.assertListEqual(dataset.get_cat_ids(0), [0, 1]) + self.assertEqual(dataset.cat_ids, [1, 2]) + + def test_obj365v1_annotation_ids_unique(self): + # test annotation ids not unique error + metainfo = dict(classes=('car', ), task_name='new_task') + with self.assertRaisesRegex(AssertionError, 'are not unique!'): + Objects365V1Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_wrong_format_sample.json', + metainfo=metainfo, + pipeline=[]) + + +class TestObjects365V2Dataset(unittest.TestCase): + + def test_obj365v2_dataset(self): + # test Objects365V2Dataset + metainfo = dict(classes=('bus', 'car'), task_name='new_task') + dataset = Objects365V2Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_sample.json', + metainfo=metainfo, + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[], + serialize_data=False, + lazy_init=False) + self.assertEqual(dataset.metainfo['classes'], ('bus', 'car')) + self.assertEqual(dataset.metainfo['task_name'], 'new_task') + self.assertListEqual(dataset.get_cat_ids(0), [0, 1]) + self.assertEqual(dataset.cat_ids, [1, 2]) + + def test_obj365v1_annotation_ids_unique(self): + # test annotation ids not unique error + metainfo = dict(classes=('car', ), task_name='new_task') + with self.assertRaisesRegex(AssertionError, 'are not unique!'): + Objects365V2Dataset( + data_prefix=dict(img='imgs'), + ann_file='tests/data/coco_wrong_format_sample.json', + metainfo=metainfo, + pipeline=[]) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_openimages.py b/mmdet_code/mmdetection/tests/test_datasets/test_openimages.py new file mode 100644 index 0000000000000000000000000000000000000000..dcd751ec46c8c9dcb77b555e23a38a8a024774fc --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_openimages.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import OpenImagesChallengeDataset, OpenImagesDataset + + +class TestOpenImagesDataset(unittest.TestCase): + + def test_init(self): + dataset = OpenImagesDataset( + data_root='tests/data/OpenImages/', + ann_file='annotations/oidv6-train-annotations-bbox.csv', + data_prefix=dict(img='OpenImages/train/'), + label_file='annotations/class-descriptions-boxable.csv', + hierarchy_file='annotations/bbox_labels_600_hierarchy.json', + meta_file='annotations/image-metas.pkl', + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + self.assertEqual(dataset.metainfo['classes'], ['Airplane']) + + +class TestOpenImagesChallengeDataset(unittest.TestCase): + + def test_init(self): + dataset = OpenImagesChallengeDataset( + data_root='tests/data/OpenImages/', + ann_file='challenge2019/challenge-2019-train-detection-bbox.txt', + data_prefix=dict(img='OpenImages/train/'), + label_file='challenge2019/cls-label-description.csv', + hierarchy_file='challenge2019/class_label_tree.np', + meta_file='annotations/image-metas.pkl', + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + self.assertEqual(dataset.metainfo['classes'], ['Airplane']) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_pascal_voc.py b/mmdet_code/mmdetection/tests/test_datasets/test_pascal_voc.py new file mode 100644 index 0000000000000000000000000000000000000000..7188d41e976725f6df2db10707b25148ffb430eb --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_pascal_voc.py @@ -0,0 +1,38 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +from mmdet.datasets import VOCDataset + + +class TestVOCDataset(unittest.TestCase): + + def test_voc2007_init(self): + dataset = VOCDataset( + data_root='tests/data/VOCdevkit/', + ann_file='VOC2007/ImageSets/Main/trainval.txt', + data_prefix=dict(sub_data_root='VOC2007/'), + filter_cfg=dict( + filter_empty_gt=True, min_size=32, bbox_min_size=32), + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + + data_list = dataset.load_data_list() + self.assertEqual(len(data_list), 1) + self.assertEqual(len(data_list[0]['instances']), 2) + self.assertEqual(dataset.get_cat_ids(0), [11, 14]) + + def test_voc2012_init(self): + dataset = VOCDataset( + data_root='tests/data/VOCdevkit/', + ann_file='VOC2012/ImageSets/Main/trainval.txt', + data_prefix=dict(sub_data_root='VOC2012/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + + data_list = dataset.load_data_list() + self.assertEqual(len(data_list), 1) + self.assertEqual(len(data_list[0]['instances']), 1) + self.assertEqual(dataset.get_cat_ids(0), [18]) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_reid_dataset.py b/mmdet_code/mmdetection/tests/test_datasets/test_reid_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..c4083612c47026bbaae9df743f19cb977868221f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_reid_dataset.py @@ -0,0 +1,64 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from unittest import TestCase + +from mmdet.datasets import ReIDDataset + +PREFIX = osp.join(osp.dirname(__file__), '../data') +# This is a demo annotation file for ReIDDataset. +REID_ANN_FILE = f'{PREFIX}/demo_reid_data/mot17_reid/ann.txt' + + +class TestReIDDataset(TestCase): + + @classmethod + def setUpClass(cls): + cls.num_ids = 8 + cls.ins_per_id = 4 + cls.dataset = ReIDDataset( + pipeline=[], ann_file=REID_ANN_FILE, data_prefix=dict(img_path='')) + cls.dataset_triplet = ReIDDataset( + pipeline=[], + triplet_sampler=dict( + num_ids=cls.num_ids, ins_per_id=cls.ins_per_id), + ann_file=REID_ANN_FILE, + data_prefix=dict(img_path='')) + + def test_get_data_info(self): + # id 0 has 21 objects + img_id = 0 + data_list = [ + self.dataset.get_data_info(i) for i in range(len(self.dataset)) + ] + assert len([ + data_info for data_info in data_list + if data_info['gt_label'] == img_id + ]) == 21 + # id 11 doesn't have objects + img_id = 11 + assert len([ + data_info for data_info in data_list + if data_info['gt_label'] == img_id + ]) == 0 + + def test_len(self): + assert len(self.dataset) == 704 + assert len(self.dataset_triplet) == 704 + + def test_getitem(self): + for i in range(len(self.dataset)): + results = self.dataset[i] + assert isinstance(results, dict) # no triplet -> dict + assert 'img_path' in results + assert 'gt_label' in results + for i in range(len(self.dataset_triplet)): + num = self.num_ids * self.ins_per_id + results = self.dataset_triplet[i] + assert isinstance(results, dict) # triplet -> dict + assert len(results['img_path']) == num + assert 'img_path' in results + assert 'gt_label' in results + for idx in range(num - 1): + if (idx + 1) % self.ins_per_id != 0: + assert results['gt_label'][idx] == \ + results['gt_label'][idx + 1] diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_batch_sampler.py b/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_batch_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..e4cb2ee09b8b05de2327fe2a90fc1d04d4b3f377 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_batch_sampler.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. + +from unittest import TestCase +from unittest.mock import patch + +import numpy as np +from mmengine.dataset import DefaultSampler +from torch.utils.data import Dataset + +from mmdet.datasets.samplers import AspectRatioBatchSampler + + +class DummyDataset(Dataset): + + def __init__(self, length): + self.length = length + self.shapes = np.random.random((length, 2)) + + def __len__(self): + return self.length + + def __getitem__(self, idx): + return self.shapes[idx] + + def get_data_info(self, idx): + return dict(width=self.shapes[idx][0], height=self.shapes[idx][1]) + + +class TestAspectRatioBatchSampler(TestCase): + + @patch('mmengine.dist.get_dist_info', return_value=(0, 1)) + def setUp(self, mock): + self.length = 100 + self.dataset = DummyDataset(self.length) + self.sampler = DefaultSampler(self.dataset, shuffle=False) + + def test_invalid_inputs(self): + with self.assertRaisesRegex( + ValueError, 'batch_size should be a positive integer value'): + AspectRatioBatchSampler(self.sampler, batch_size=-1) + + with self.assertRaisesRegex( + TypeError, 'sampler should be an instance of ``Sampler``'): + AspectRatioBatchSampler(None, batch_size=1) + + def test_divisible_batch(self): + batch_size = 5 + batch_sampler = AspectRatioBatchSampler( + self.sampler, batch_size=batch_size, drop_last=True) + self.assertEqual(len(batch_sampler), self.length // batch_size) + for batch_idxs in batch_sampler: + self.assertEqual(len(batch_idxs), batch_size) + batch = [self.dataset[idx] for idx in batch_idxs] + flag = batch[0][0] < batch[0][1] + for i in range(1, batch_size): + self.assertEqual(batch[i][0] < batch[i][1], flag) + + def test_indivisible_batch(self): + batch_size = 7 + batch_sampler = AspectRatioBatchSampler( + self.sampler, batch_size=batch_size, drop_last=False) + all_batch_idxs = list(batch_sampler) + self.assertEqual( + len(batch_sampler), (self.length + batch_size - 1) // batch_size) + self.assertEqual( + len(all_batch_idxs), (self.length + batch_size - 1) // batch_size) + + batch_sampler = AspectRatioBatchSampler( + self.sampler, batch_size=batch_size, drop_last=True) + all_batch_idxs = list(batch_sampler) + self.assertEqual(len(batch_sampler), self.length // batch_size) + self.assertEqual(len(all_batch_idxs), self.length // batch_size) + + # the last batch may not have the same aspect ratio + for batch_idxs in all_batch_idxs[:-1]: + self.assertEqual(len(batch_idxs), batch_size) + batch = [self.dataset[idx] for idx in batch_idxs] + flag = batch[0][0] < batch[0][1] + for i in range(1, batch_size): + self.assertEqual(batch[i][0] < batch[i][1], flag) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_multi_source_sampler.py b/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_multi_source_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..19609d5f2fdb9cb7704b3faf96d099911add9ef1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_multi_source_sampler.py @@ -0,0 +1,107 @@ +# Copyright (c) OpenMMLab. All rights reserved. + +import bisect +from unittest import TestCase +from unittest.mock import patch + +import numpy as np +from torch.utils.data import ConcatDataset, Dataset + +from mmdet.datasets.samplers import GroupMultiSourceSampler, MultiSourceSampler + + +class DummyDataset(Dataset): + + def __init__(self, length, flag): + self.length = length + self.flag = flag + self.shapes = np.random.random((length, 2)) + + def __len__(self): + return self.length + + def __getitem__(self, idx): + return self.shapes[idx] + + def get_data_info(self, idx): + return dict( + width=self.shapes[idx][0], + height=self.shapes[idx][1], + flag=self.flag) + + +class DummyConcatDataset(ConcatDataset): + + def _get_ori_dataset_idx(self, idx): + dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) + sample_idx = idx if dataset_idx == 0 else idx - self.cumulative_sizes[ + dataset_idx - 1] + return dataset_idx, sample_idx + + def get_data_info(self, idx: int): + dataset_idx, sample_idx = self._get_ori_dataset_idx(idx) + return self.datasets[dataset_idx].get_data_info(sample_idx) + + +class TestMultiSourceSampler(TestCase): + + @patch('mmengine.dist.get_dist_info', return_value=(7, 8)) + def setUp(self, mock): + self.length_a = 100 + self.dataset_a = DummyDataset(self.length_a, flag='a') + self.length_b = 1000 + self.dataset_b = DummyDataset(self.length_b, flag='b') + self.dataset = DummyConcatDataset([self.dataset_a, self.dataset_b]) + + def test_multi_source_sampler(self): + # test dataset is not ConcatDataset + with self.assertRaises(AssertionError): + MultiSourceSampler( + self.dataset_a, batch_size=5, source_ratio=[1, 4]) + # test invalid batch_size + with self.assertRaises(AssertionError): + MultiSourceSampler( + self.dataset_a, batch_size=-5, source_ratio=[1, 4]) + # test source_ratio longer then dataset + with self.assertRaises(AssertionError): + MultiSourceSampler( + self.dataset, batch_size=5, source_ratio=[1, 2, 4]) + sampler = MultiSourceSampler( + self.dataset, batch_size=5, source_ratio=[1, 4]) + sampler = iter(sampler) + flags = [] + for i in range(100): + idx = next(sampler) + flags.append(self.dataset.get_data_info(idx)['flag']) + flags_gt = ['a', 'b', 'b', 'b', 'b'] * 20 + self.assertEqual(flags, flags_gt) + + +class TestGroupMultiSourceSampler(TestCase): + + @patch('mmengine.dist.get_dist_info', return_value=(7, 8)) + def setUp(self, mock): + self.length_a = 100 + self.dataset_a = DummyDataset(self.length_a, flag='a') + self.length_b = 1000 + self.dataset_b = DummyDataset(self.length_b, flag='b') + self.dataset = DummyConcatDataset([self.dataset_a, self.dataset_b]) + + def test_group_multi_source_sampler(self): + sampler = GroupMultiSourceSampler( + self.dataset, batch_size=5, source_ratio=[1, 4]) + sampler = iter(sampler) + flags = [] + groups = [] + for i in range(100): + idx = next(sampler) + data_info = self.dataset.get_data_info(idx) + flags.append(data_info['flag']) + group = 0 if data_info['width'] < data_info['height'] else 1 + groups.append(group) + flags_gt = ['a', 'b', 'b', 'b', 'b'] * 20 + self.assertEqual(flags, flags_gt) + groups = set( + [sum(x) for x in (groups[k:k + 5] for k in range(0, 100, 5))]) + groups_gt = set([0, 5]) + self.assertEqual(groups, groups_gt) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_track_img_sampler.py b/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_track_img_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..0273aa08fbbd4493042a9f3b707a6dff002e727a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_samplers/test_track_img_sampler.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from collections.abc import Iterable +from copy import deepcopy +from unittest import TestCase + +from mmengine.dataset import ClassBalancedDataset, ConcatDataset + +from mmdet.datasets import MOTChallengeDataset, TrackImgSampler + + +class TestTrackImgSampler(TestCase): + + def test_iter_base_video_dataset(self): + # train mode + dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + test_mode=False, + pipeline=[]) + video_sampler = TrackImgSampler(dataset) + assert len(video_sampler) == 5 + iterator = iter(video_sampler) + assert isinstance(iterator, Iterable) + for index in iterator: + assert isinstance(index, tuple) + video_index, frame_index = index + assert video_index < 2 + if video_index == 0: + assert frame_index >= 0 and frame_index < 3 + else: + assert frame_index >= 0 and frame_index < 2 + + # test mode + dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + test_mode=True, + pipeline=[]) + video_sampler = TrackImgSampler(dataset) + assert len(video_sampler) == 5 + assert len(video_sampler.indices) == 1 + + def test_iter_concat_dataset(self): + single_dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + test_mode=False, + pipeline=[]) + + dataset = ConcatDataset([single_dataset, deepcopy(single_dataset)]) + video_sampler = TrackImgSampler(dataset) + assert len(video_sampler) == 10 + iterator = iter(video_sampler) + assert isinstance(iterator, Iterable) + for index in iterator: + assert isinstance(index, tuple) + video_index, frame_index = index + assert video_index < 4 + if video_index == 0: + assert frame_index >= 0 and frame_index < 3 + elif video_index == 3: + assert frame_index >= 0 and frame_index < 2 + + def test_iter_class_balanced_dataset(self): + single_dataset = MOTChallengeDataset( + data_prefix=dict(img_path='imgs'), + ann_file='tests/data/mot_sample.json', + metainfo=dict(classes=('pedestrian', 'person_on_vehicle')), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + visibility_thr=0.1, + test_mode=False, + pipeline=[]) + + dataset = ClassBalancedDataset(single_dataset, oversample_thr=0.6) + video_sampler = TrackImgSampler(dataset) + assert len(video_sampler) == 8 + iterator = iter(video_sampler) + assert isinstance(iterator, Iterable) + for index in iterator: + assert isinstance(index, tuple) + video_index, frame_index = index + assert video_index < 3 + if video_index == 0 or video_index == 2: + assert frame_index >= 0 and frame_index < 3 + else: + assert frame_index >= 0 and frame_index < 2 diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/__init__.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1daf8fce080d3dbbe1e2f2794168f6e39e65a7f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .utils import construct_toy_data, create_full_masks, create_random_bboxes + +__all__ = ['create_random_bboxes', 'create_full_masks', 'construct_toy_data'] diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_augment_wrappers.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_augment_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..4e0f75346e49224652e559db9d948fdbd0cc17c7 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_augment_wrappers.py @@ -0,0 +1,249 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import unittest + +from mmdet.datasets.transforms import (AutoAugment, AutoContrast, Brightness, + Color, Contrast, Equalize, Invert, + Posterize, RandAugment, Rotate, + Sharpness, ShearX, ShearY, Solarize, + SolarizeAdd, TranslateX, TranslateY) +from mmdet.utils import register_all_modules +from .utils import check_result_same, construct_toy_data + +register_all_modules() + + +class TestAutoAugment(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map', + 'homography_matrix') + self.results_mask = construct_toy_data(poly2mask=True) + self.img_fill_val = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_autoaugment(self): + # test AutoAugment equipped with Shear + policies = [[ + dict(type='ShearX', prob=1.0, level=3, reversal_prob=0.0), + dict(type='ShearY', prob=1.0, level=7, reversal_prob=1.0) + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_shearx = ShearX(prob=1.0, level=3, reversal_prob=0.0) + transform_sheary = ShearY(prob=1.0, level=7, reversal_prob=1.0) + results_sheared = transform_sheary( + transform_shearx(copy.deepcopy(self.results_mask))) + check_result_same(results_sheared, results_auto, self.check_keys) + + # test AutoAugment equipped with Rotate + policies = [[ + dict(type='Rotate', prob=1.0, level=10, reversal_prob=0.0), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_rotate = Rotate(prob=1.0, level=10, reversal_prob=0.0) + results_rotated = transform_rotate(copy.deepcopy(self.results_mask)) + check_result_same(results_rotated, results_auto, self.check_keys) + + # test AutoAugment equipped with Translate + policies = [[ + dict( + type='TranslateX', + prob=1.0, + level=10, + max_mag=1.0, + reversal_prob=0.0), + dict( + type='TranslateY', + prob=1.0, + level=10, + max_mag=1.0, + reversal_prob=1.0) + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_translatex = TranslateX( + prob=1.0, level=10, max_mag=1.0, reversal_prob=0.0) + transform_translatey = TranslateY( + prob=1.0, level=10, max_mag=1.0, reversal_prob=1.0) + results_translated = transform_translatey( + transform_translatex(copy.deepcopy(self.results_mask))) + check_result_same(results_translated, results_auto, self.check_keys) + + # test AutoAugment equipped with Brightness + policies = [[ + dict(type='Brightness', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_brightness = Brightness(prob=1.0, level=3) + results_brightness = transform_brightness( + copy.deepcopy(self.results_mask)) + check_result_same(results_brightness, results_auto, self.check_keys) + + # test AutoAugment equipped with Color + policies = [[ + dict(type='Color', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_color = Color(prob=1.0, level=3) + results_colored = transform_color(copy.deepcopy(self.results_mask)) + check_result_same(results_colored, results_auto, self.check_keys) + + # test AutoAugment equipped with Contrast + policies = [[ + dict(type='Contrast', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_contrast = Contrast(prob=1.0, level=3) + results_contrasted = transform_contrast( + copy.deepcopy(self.results_mask)) + check_result_same(results_contrasted, results_auto, self.check_keys) + + # test AutoAugment equipped with Sharpness + policies = [[ + dict(type='Sharpness', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_sharpness = Sharpness(prob=1.0, level=3) + results_sharpness = transform_sharpness( + copy.deepcopy(self.results_mask)) + check_result_same(results_sharpness, results_auto, self.check_keys) + + # test AutoAugment equipped with Solarize + policies = [[ + dict(type='Solarize', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_solarize = Solarize(prob=1.0, level=3) + results_solarized = transform_solarize( + copy.deepcopy(self.results_mask)) + check_result_same(results_solarized, results_auto, self.check_keys) + + # test AutoAugment equipped with SolarizeAdd + policies = [[ + dict(type='SolarizeAdd', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_solarizeadd = SolarizeAdd(prob=1.0, level=3) + results_solarizeadded = transform_solarizeadd( + copy.deepcopy(self.results_mask)) + check_result_same(results_solarizeadded, results_auto, self.check_keys) + + # test AutoAugment equipped with Posterize + policies = [[ + dict(type='Posterize', prob=1.0, level=3), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_posterize = Posterize(prob=1.0, level=3) + results_posterized = transform_posterize( + copy.deepcopy(self.results_mask)) + check_result_same(results_posterized, results_auto, self.check_keys) + + # test AutoAugment equipped with Equalize + policies = [[ + dict(type='Equalize', prob=1.0), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_equalize = Equalize(prob=1.0) + results_equalized = transform_equalize( + copy.deepcopy(self.results_mask)) + check_result_same(results_equalized, results_auto, self.check_keys) + + # test AutoAugment equipped with AutoContrast + policies = [[ + dict(type='AutoContrast', prob=1.0), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_autocontrast = AutoContrast(prob=1.0) + results_autocontrast = transform_autocontrast( + copy.deepcopy(self.results_mask)) + check_result_same(results_autocontrast, results_auto, self.check_keys) + + # test AutoAugment equipped with Invert + policies = [[ + dict(type='Invert', prob=1.0), + ]] + transform_auto = AutoAugment(policies=policies) + results_auto = transform_auto(copy.deepcopy(self.results_mask)) + transform_invert = Invert(prob=1.0) + results_inverted = transform_invert(copy.deepcopy(self.results_mask)) + check_result_same(results_inverted, results_auto, self.check_keys) + + # test AutoAugment equipped with default policies + transform_auto = AutoAugment() + transform_auto(copy.deepcopy(self.results_mask)) + + def test_repr(self): + policies = [[ + dict(type='Rotate', prob=1.0, level=10, reversal_prob=0.0), + dict(type='Invert', prob=1.0), + ]] + transform = AutoAugment(policies=policies) + self.assertEqual( + repr(transform), ('AutoAugment(' + 'policies=[[' + "{'type': 'Rotate', 'prob': 1.0, " + "'level': 10, 'reversal_prob': 0.0}, " + "{'type': 'Invert', 'prob': 1.0}]], " + 'prob=None)')) + + +class TestRandAugment(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map', + 'homography_matrix') + self.results_mask = construct_toy_data(poly2mask=True) + self.img_fill_val = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_randaugment(self): + # test RandAugment equipped with Rotate + aug_space = [[ + dict(type='Rotate', prob=1.0, level=10, reversal_prob=0.0) + ]] + transform_rand = RandAugment(aug_space=aug_space, aug_num=1) + results_rand = transform_rand(copy.deepcopy(self.results_mask)) + transform_rotate = Rotate(prob=1.0, level=10, reversal_prob=0.0) + results_rotated = transform_rotate(copy.deepcopy(self.results_mask)) + check_result_same(results_rotated, results_rand, self.check_keys) + + # test RandAugment equipped with default augmentation space + transform_rand = RandAugment() + transform_rand(copy.deepcopy(self.results_mask)) + + def test_repr(self): + aug_space = [ + [dict(type='Rotate')], + [dict(type='Invert')], + ] + transform = RandAugment(aug_space=aug_space) + self.assertEqual( + repr(transform), ('RandAugment(' + 'aug_space=[' + "[{'type': 'Rotate'}], " + "[{'type': 'Invert'}]], " + 'aug_num=2, ' + 'prob=None)')) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_colorspace.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_colorspace.py new file mode 100644 index 0000000000000000000000000000000000000000..468461b41799f27b29342091185294b7b2a98896 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_colorspace.py @@ -0,0 +1,365 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import unittest + +from mmdet.datasets.transforms import (AutoContrast, Brightness, Color, + ColorTransform, Contrast, Equalize, + Invert, Posterize, Sharpness, Solarize, + SolarizeAdd) +from .utils import check_result_same, construct_toy_data + + +class TestColorTransform(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_colortransform(self): + # test assertion for invalid value of level + with self.assertRaises(AssertionError): + transform = ColorTransform(level=-1) + + # test assertion for invalid prob + with self.assertRaises(AssertionError): + transform = ColorTransform(level=1, prob=-0.5) + + # test case when no translation is called (prob=0) + transform = ColorTransform(prob=0.0, level=10) + results_wo_color = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_color, self.check_keys) + + def test_repr(self): + transform = ColorTransform(level=10, prob=1.) + self.assertEqual( + repr(transform), ('ColorTransform(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestColor(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_color(self): + # test case when level=5 (without color aug) + transform = Color(prob=1.0, level=5) + results_wo_color = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_color, self.check_keys) + # test case when level=0 + transform = Color(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + # test case when level=10 + transform = Color(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Color(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Color(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestBrightness(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_brightness(self): + # test case when level=5 (without Brightness aug) + transform = Brightness(level=5, prob=1.0) + results_wo_brightness = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_brightness, + self.check_keys) + # test case when level=0 + transform = Brightness(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + # test case when level=10 + transform = Brightness(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Brightness(prob=1.0, level=10) + self.assertEqual( + repr(transform), ('Brightness(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestContrast(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_contrast(self): + # test case when level=5 (without Contrast aug) + transform = Contrast(prob=1.0, level=5) + results_wo_contrast = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_contrast, + self.check_keys) + # test case when level=0 + transform = Contrast(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + # test case when level=10 + transform = Contrast(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Contrast(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Contrast(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestSharpness(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_sharpness(self): + # test case when level=5 (without Sharpness aug) + transform = Sharpness(prob=1.0, level=5) + results_wo_sharpness = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_sharpness, + self.check_keys) + # test case when level=0 + transform = Sharpness(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + # test case when level=10 + transform = Sharpness(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Sharpness(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Sharpness(prob=1.0, ' + 'level=10, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestSolarize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_solarize(self): + # test case when level=10 (without Solarize aug) + transform = Solarize(prob=1.0, level=10) + results_wo_solarize = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_solarize, + self.check_keys) + # test case when level=0 + transform = Solarize(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Solarize(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Solarize(prob=1.0, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=256.0)')) + + +class TestSolarizeAdd(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_solarize(self): + # test case when level=0 (without Solarize aug) + transform = SolarizeAdd(prob=1.0, level=0) + results_wo_solarizeadd = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_solarizeadd, + self.check_keys) + # test case when level=10 + transform = SolarizeAdd(prob=1.0, level=10) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = SolarizeAdd(level=10, prob=1.) + self.assertEqual( + repr(transform), ('SolarizeAdd(prob=1.0, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=110.0)')) + + +class TestPosterize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_posterize(self): + # test case when level=10 (without Posterize aug) + transform = Posterize(prob=1.0, level=10, max_mag=8.0) + results_wo_posterize = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_posterize, + self.check_keys) + # test case when level=0 + transform = Posterize(prob=1.0, level=0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Posterize(level=10, prob=1.) + self.assertEqual( + repr(transform), ('Posterize(prob=1.0, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=4.0)')) + + +class TestEqualize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_equalize(self): + # test case when no translation is called (prob=0) + transform = Equalize(prob=0.0) + results_wo_equalize = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_equalize, + self.check_keys) + # test case when translation is called + transform = Equalize(prob=1.0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Equalize(prob=1.0) + self.assertEqual( + repr(transform), ('Equalize(prob=1.0, ' + 'level=None, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestAutoContrast(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_autocontrast(self): + # test case when no translation is called (prob=0) + transform = AutoContrast(prob=0.0) + results_wo_autocontrast = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_autocontrast, + self.check_keys) + # test case when translation is called + transform = AutoContrast(prob=1.0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = AutoContrast(prob=1.0) + self.assertEqual( + repr(transform), ('AutoContrast(prob=1.0, ' + 'level=None, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) + + +class TestInvert(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + + def test_invert(self): + # test case when no translation is called (prob=0) + transform = Invert(prob=0.0) + results_wo_invert = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_invert, + self.check_keys) + # test case when translation is called + transform = Invert(prob=1.0) + transform(copy.deepcopy(self.results_mask)) + + def test_repr(self): + transform = Invert(prob=1.0) + self.assertEqual( + repr(transform), ('Invert(prob=1.0, ' + 'level=None, ' + 'min_mag=0.1, ' + 'max_mag=1.9)')) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_formatting.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..63719fc4b85341de489fc0f73be82addf743807c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_formatting.py @@ -0,0 +1,246 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +import unittest + +import numpy as np +import torch +from mmengine.structures import InstanceData, LabelData, PixelData + +from mmdet.datasets.transforms import (PackDetInputs, PackReIDInputs, + PackTrackInputs) +from mmdet.structures import DetDataSample, ReIDDataSample +from mmdet.structures.mask import BitmapMasks + + +class TestPackDetInputs(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + data_prefix = osp.join(osp.dirname(__file__), '../../data') + img_path = osp.join(data_prefix, 'color.jpg') + rng = np.random.RandomState(0) + self.results1 = { + 'img_id': 1, + 'img_path': img_path, + 'ori_shape': (300, 400), + 'img_shape': (600, 800), + 'scale_factor': 2.0, + 'flip': False, + 'img': rng.rand(300, 400), + 'gt_seg_map': rng.rand(300, 400), + 'gt_masks': + BitmapMasks(rng.rand(3, 300, 400), height=300, width=400), + 'gt_bboxes_labels': rng.rand(3, ), + 'gt_ignore_flags': np.array([0, 0, 1], dtype=bool), + 'proposals': rng.rand(2, 4), + 'proposals_scores': rng.rand(2, ) + } + self.results2 = { + 'img_id': 1, + 'img_path': img_path, + 'ori_shape': (300, 400), + 'img_shape': (600, 800), + 'scale_factor': 2.0, + 'flip': False, + 'img': rng.rand(300, 400), + 'gt_seg_map': rng.rand(300, 400), + 'gt_masks': + BitmapMasks(rng.rand(3, 300, 400), height=300, width=400), + 'gt_bboxes_labels': rng.rand(3, ), + 'proposals': rng.rand(2, 4), + 'proposals_scores': rng.rand(2, ) + } + self.meta_keys = ('img_id', 'img_path', 'ori_shape', 'scale_factor', + 'flip') + + def test_transform(self): + transform = PackDetInputs(meta_keys=self.meta_keys) + results = transform(copy.deepcopy(self.results1)) + self.assertIn('data_samples', results) + self.assertIsInstance(results['data_samples'], DetDataSample) + self.assertIsInstance(results['data_samples'].gt_instances, + InstanceData) + self.assertIsInstance(results['data_samples'].ignored_instances, + InstanceData) + self.assertEqual(len(results['data_samples'].gt_instances), 2) + self.assertEqual(len(results['data_samples'].ignored_instances), 1) + self.assertIsInstance(results['data_samples'].gt_sem_seg, PixelData) + self.assertIsInstance(results['data_samples'].proposals, InstanceData) + self.assertEqual(len(results['data_samples'].proposals), 2) + self.assertIsInstance(results['data_samples'].proposals.bboxes, + torch.Tensor) + self.assertIsInstance(results['data_samples'].proposals.scores, + torch.Tensor) + + def test_transform_without_ignore(self): + transform = PackDetInputs(meta_keys=self.meta_keys) + results = transform(copy.deepcopy(self.results2)) + self.assertIn('data_samples', results) + self.assertIsInstance(results['data_samples'], DetDataSample) + self.assertIsInstance(results['data_samples'].gt_instances, + InstanceData) + self.assertIsInstance(results['data_samples'].ignored_instances, + InstanceData) + self.assertEqual(len(results['data_samples'].gt_instances), 3) + self.assertEqual(len(results['data_samples'].ignored_instances), 0) + self.assertIsInstance(results['data_samples'].gt_sem_seg, PixelData) + self.assertIsInstance(results['data_samples'].proposals, InstanceData) + self.assertEqual(len(results['data_samples'].proposals), 2) + self.assertIsInstance(results['data_samples'].proposals.bboxes, + torch.Tensor) + self.assertIsInstance(results['data_samples'].proposals.scores, + torch.Tensor) + + def test_repr(self): + transform = PackDetInputs(meta_keys=self.meta_keys) + self.assertEqual( + repr(transform), f'PackDetInputs(meta_keys={self.meta_keys})') + + +class TestPackTrackInputs(unittest.TestCase): + + def setUp(self): + self.H, self.W = 5, 10 + self.img = np.zeros((self.H, self.W, 3)) + self.gt_bboxes = np.zeros((2, 4)) + self.gt_masks = BitmapMasks( + np.random.rand(2, self.H, self.W), height=self.H, width=self.W) + self.gt_bboxes_labels = [ + np.zeros((2, )), + np.zeros((2, )) + 1, + np.zeros((2, )) - 1 + ] + self.gt_instances_ids = [ + np.ones((2, ), dtype=np.int32), + np.ones((2, ), dtype=np.int32) - 1, + np.ones((2, ), dtype=np.int32) + 1 + ] + self.frame_id = [0, 1, 2] + self.scale_factor = [1.0, 1.5, 2.0] + self.flip = [False] * 3 + self.ori_shape = [(self.H, self.W)] * 3 + self.img_id = [0, 1, 2] + self.results_1 = dict( + img=[self.img.copy(), + self.img.copy(), + self.img.copy()], + gt_bboxes=[ + self.gt_bboxes.copy(), + self.gt_bboxes.copy(), + self.gt_bboxes.copy() + ], + gt_bboxes_labels=copy.deepcopy(self.gt_bboxes_labels), + gt_instances_ids=copy.deepcopy(self.gt_instances_ids), + gt_masks=[ + copy.deepcopy(self.gt_masks), + copy.deepcopy(self.gt_masks), + copy.deepcopy(self.gt_masks) + ], + frame_id=self.frame_id, + ori_shape=self.ori_shape, + scale_factor=self.scale_factor, + flip=self.flip, + img_id=self.img_id, + key_frame_flags=[False, True, False]) + + self.results_2 = copy.deepcopy(self.results_1) + self.gt_ignore_flags = [ + np.array([0, 1], dtype=np.bool), + np.array([1, 0], dtype=np.bool), + np.array([0, 0], dtype=np.bool) + ] + self.results_2.update( + dict(gt_ignore_flags=copy.deepcopy(self.gt_ignore_flags))) + + self.meta_keys = ('frame_id', 'ori_shape', 'scale_factor', 'flip') + self.pack_track_inputs = PackTrackInputs(meta_keys=self.meta_keys) + + def test_transform_without_ignore(self): + track_results = self.pack_track_inputs(self.results_1) + assert isinstance(track_results, dict) + + inputs = track_results['inputs'] + assert isinstance(inputs, torch.Tensor) + assert inputs.shape == (3, 3, self.H, self.W) + + track_data_sample = track_results['data_samples'] + assert len(track_data_sample) == 3 + assert 'key_frames_inds' in track_data_sample.metainfo and \ + track_data_sample.key_frames_inds == [1] + assert 'ref_frames_inds' in track_data_sample.metainfo and \ + track_data_sample.ref_frames_inds == [0, 2] + for i, data_sample in enumerate(track_data_sample): + assert data_sample.gt_instances.bboxes.shape == (2, 4) + assert len(data_sample.gt_instances.masks) == 2 + assert (data_sample.gt_instances.labels.numpy() == + self.gt_bboxes_labels[i]).all() + assert (data_sample.gt_instances.instances_ids.numpy() == + self.gt_instances_ids[i]).all() + for key in self.meta_keys: + assert data_sample.metainfo[key] == getattr(self, key)[i] + + def test_transform_with_ignore(self): + track_results = self.pack_track_inputs(self.results_2) + assert isinstance(track_results, dict) + + inputs = track_results['inputs'] + assert isinstance(inputs, torch.Tensor) + assert inputs.shape == (3, 3, self.H, self.W) + + track_data_sample = track_results['data_samples'] + assert len(track_data_sample) == 3 + for i, data_sample in enumerate(track_data_sample): + valid_mask = ~self.gt_ignore_flags[i] + valid_len = valid_mask.sum().item() + assert data_sample.gt_instances.bboxes.shape == (valid_len, 4) + assert len(data_sample.gt_instances.masks) == valid_len + assert (data_sample.gt_instances.labels.numpy() == + self.gt_bboxes_labels[i][valid_mask]).all() + assert (data_sample.gt_instances.instances_ids.numpy() == + self.gt_instances_ids[i][valid_mask]).all() + for key in self.meta_keys: + assert data_sample.metainfo[key] == getattr(self, key)[i] + + +class TestPackReIDInputs(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.results = dict( + img=np.random.randn(256, 128, 3), + gt_label=0, + img_path='', + ori_shape=(128, 128), + img_shape=(256, 128), + scale=(128, 256), + scale_factor=(1., 2.), + flip=False, + flip_direction=None) + cls.pack_reid_inputs = PackReIDInputs( + meta_keys=('flip', 'flip_direction')) + + def test_transform(self): + results = self.pack_reid_inputs(self.results) + self.assertIn('inputs', results) + self.assertIsInstance(results['inputs'], torch.Tensor) + self.assertIn('data_samples', results) + data_sample = results['data_samples'] + self.assertIsInstance(data_sample, ReIDDataSample) + self.assertIsInstance(data_sample.gt_label, LabelData) + self.assertEqual(data_sample.img_path, '') + self.assertEqual(data_sample.ori_shape, (128, 128)) + self.assertEqual(data_sample.img_shape, (256, 128)) + self.assertEqual(data_sample.scale, (128, 256)) + self.assertEqual(data_sample.scale_factor, (1., 2.)) + self.assertEqual(data_sample.flip, False) + self.assertIsNone(data_sample.flip_direction) + + def test_repr(self): + self.assertEqual( + repr(self.pack_reid_inputs), + f'PackReIDInputs(meta_keys={self.pack_reid_inputs.meta_keys})') diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_frame_sampling.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_frame_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..fa995e3c769b7d0d74fa0ad97950abf65331cd4e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_frame_sampling.py @@ -0,0 +1,119 @@ +import unittest + +import numpy as np + +from mmdet.datasets.transforms import BaseFrameSample, UniformRefFrameSample + + +class TestFrameSample(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() + -> tearDown() -> cleanUp() + """ + self.H, self.W = 5, 8 + self.img = np.zeros((self.H, self.W, 3)) + self.gt_bboxes = np.zeros((2, 4)) + self.gt_bboxes_labels = [ + np.zeros((2, )), + np.zeros((2, )) + 1, + np.zeros((2, )) - 1 + ] + self.gt_instances_id = [ + np.ones((2, ), dtype=np.int32), + np.ones((2, ), dtype=np.int32) - 1, + np.ones((2, ), dtype=np.int32) + 1 + ] + self.frame_id = [0, 1, 2] + self.scale_factor = [1.0, 1.5, 2.0] + self.flip = [False] * 3 + self.ori_shape = [(self.H, self.W)] * 3 + self.img_id = [0, 1, 2] + + self.video_infos = dict(video_id=0, video_length=10, key_frame_id=4) + self.video_infos['images'] = [] + self.info_keys = [ + 'video_id', 'video_length', 'img', 'gt_bboxes', 'gt_bboxes_labels', + 'gt_instances_id', 'img_id', 'frame_id' + ] + for i in range(10): + frame_info = dict( + img=np.zeros((self.H, self.W, 3)) + i, + gt_bboxes=np.zeros((2, 4)) + i, + gt_bboxes_labels=np.zeros((2, )) + i, + gt_instances_id=np.zeros((2, ), dtype=np.int32) + i, + ori_shape=(self.H + i, self.W + i), + frame_id=i, + img_id=i) + self.video_infos['images'].append(frame_info) + + def test_base_frame_sample(self): + sampler = BaseFrameSample() + results = sampler(self.video_infos) + assert isinstance(results, dict) + for key in self.info_keys: + assert key in results + assert len(results[key]) == 1 + if key == 'frame_id': + assert results[key] == [4] + + key_frame_id = self.video_infos['key_frame_id'] + assert (results['img'][0] == np.zeros( + (self.H, self.W, 3)) + key_frame_id).all() + assert (results['gt_bboxes'][0] == np.zeros( + (2, 4)) + key_frame_id).all() + assert (results['gt_bboxes_labels'][0] == np.zeros( + (2, )) + key_frame_id).all() + assert (results['gt_instances_id'][0] == np.zeros( + (2, )) + key_frame_id).all() + assert results['ori_shape'][0] == (self.H + key_frame_id, + self.W + key_frame_id) + assert results['img_id'][0] == key_frame_id + + def test_uniform_ref_frame_sample(self): + sampler = UniformRefFrameSample( + num_ref_imgs=2, frame_range=[-1, 1], filter_key_img=True) + results = sampler(self.video_infos) + assert isinstance(results, dict) + for key in self.info_keys: + assert key in results + assert len(results[key]) == 3 + if key == 'frame_id': + assert results[key] == [3, 4, 5] + + key_frame_id = self.video_infos['key_frame_id'] + assert (results['img'][1] == np.zeros( + (self.H, self.W, 3)) + key_frame_id).all() + assert (results['gt_bboxes'][1] == np.zeros( + (2, 4)) + key_frame_id).all() + assert (results['gt_bboxes_labels'][1] == np.zeros( + (2, )) + key_frame_id).all() + assert (results['gt_instances_id'][1] == np.zeros( + (2, )) + key_frame_id).all() + assert results['ori_shape'][1] == (self.H + key_frame_id, + self.W + key_frame_id) + assert results['img_id'][1] == key_frame_id + + # test the filter_key_img and the correctness of returned frame index + sampler = UniformRefFrameSample( + num_ref_imgs=2, frame_range=[0, 1], filter_key_img=False) + results = sampler(self.video_infos) + assert 4 in results['img_id'] and results['img_id'].count(4) == 2 + assert 5 in results['img_id'] and results['img_id'].count(5) == 1 + assert results['key_frame_flags'] == [True, False, False] + + def test_repr(self): + transform = BaseFrameSample() + self.assertEqual( + repr(transform), + "BaseFrameSample(collect_video_keys=['video_id', 'video_length'])") + + transform = UniformRefFrameSample( + num_ref_imgs=2, frame_range=10, filter_key_img=True) + self.assertEqual( + repr(transform), + ('UniformRefFrameSample(num_ref_imgs=2, ' + 'frame_range=[-10, 10], filter_key_img=True, ' + "collect_video_keys=['video_id', 'video_length'])")) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_geometric.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_geometric.py new file mode 100644 index 0000000000000000000000000000000000000000..e13b13d75aa1502966195076dc29c57039d04ce7 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_geometric.py @@ -0,0 +1,752 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import unittest + +import numpy as np + +from mmdet.datasets.transforms import (GeomTransform, Rotate, ShearX, ShearY, + TranslateX, TranslateY) +from mmdet.structures.bbox import HorizontalBoxes +from mmdet.structures.mask import BitmapMasks, PolygonMasks +from .utils import check_result_same, construct_toy_data + + +class TestGeomTransform(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_geomtransform(self): + # test assertion for invalid prob + with self.assertRaises(AssertionError): + transform = GeomTransform( + prob=-0.5, level=1, min_mag=0.0, max_mag=1.0) + + # test assertion for invalid value of level + with self.assertRaises(AssertionError): + transform = GeomTransform( + prob=0.5, level=-1, min_mag=0.0, max_mag=1.0) + + # test assertion for invalid value of min_mag and max_mag + with self.assertRaises(AssertionError): + transform = ShearX(prob=0.5, level=2, min_mag=1.0, max_mag=0.0) + + # test assertion for the num of elements in tuple img_border_value + with self.assertRaises(AssertionError): + transform = GeomTransform( + prob=0.5, + level=1, + min_mag=0.0, + max_mag=1.0, + img_border_value=(128, 128, 128, 128)) + + # test ValueError for invalid type of img_border_value + with self.assertRaises(ValueError): + transform = GeomTransform( + prob=0.5, + level=1, + min_mag=0.0, + max_mag=1.0, + img_border_value=[128, 128, 128]) + + # test assertion for invalid value of img_border_value + with self.assertRaises(AssertionError): + transform = GeomTransform( + prob=0.5, + level=1, + min_mag=0.0, + max_mag=1.0, + img_border_value=(128, -1, 256)) + + # test case when no aug (prob=0) + transform = GeomTransform( + prob=0., + level=10, + min_mag=0.0, + max_mag=1.0, + img_border_value=self.img_border_value) + results_wo_aug = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_aug, self.check_keys) + + def test_repr(self): + transform = GeomTransform( + prob=0.5, + level=5, + min_mag=0.0, + max_mag=1.0, + ) + self.assertEqual( + repr(transform), ('GeomTransform(prob=0.5, ' + 'level=5, ' + 'min_mag=0.0, ' + 'max_mag=1.0, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestShearX(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_shearx(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = ShearX(prob=0.5, level=2, min_mag=-30.) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = ShearX(prob=0.5, level=2, max_mag=100.) + + # test case when no shear horizontally (level=0) + transform = ShearX( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_shearx = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_shearx, + self.check_keys) + + # test shear horizontally, magnitude=-1 + transform = ShearX( + prob=1.0, + level=10, + max_mag=45., + reversal_prob=1.0, + img_border_value=self.img_border_value) + results_sheared = transform(copy.deepcopy(self.results_mask)) + results_gt = copy.deepcopy(self.results_mask) + img_gt = np.array([[1, 2, 3, 4], [0, 5, 6, 7], [0, 0, 9, 10]], + dtype=np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + img_gt[1, 0, :] = np.array(self.img_border_value) + img_gt[2, 0, :] = np.array(self.img_border_value) + img_gt[2, 1, :] = np.array(self.img_border_value) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[1, 0, 4, 2]], dtype=np.float32) + results_gt['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + gt_masks = np.array([[0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 255, 13, 13], [255, 255, 255, 13]], + dtype=self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_sheared, self.check_keys) + + # test PolygonMasks with shear horizontally, magnitude=1 + results_sheared = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([3, 2, 1, 0, 3, 1], dtype=np.float32)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_sheared, self.check_keys) + + def test_shearx_use_box_type(self): + # test case when no shear horizontally (level=0) + transform = ShearX( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_shearx = transform(copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_shearx, + self.check_keys) + + # test shear horizontally, magnitude=-1 + transform = ShearX( + prob=1.0, + level=10, + max_mag=45., + reversal_prob=1.0, + img_border_value=self.img_border_value) + results_sheared = transform(copy.deepcopy(self.results_mask_boxtype)) + results_gt = copy.deepcopy(self.results_mask_boxtype) + img_gt = np.array([[1, 2, 3, 4], [0, 5, 6, 7], [0, 0, 9, 10]], + dtype=np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + img_gt[1, 0, :] = np.array(self.img_border_value) + img_gt[2, 0, :] = np.array(self.img_border_value) + img_gt[2, 1, :] = np.array(self.img_border_value) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[1, 0, 4, 2]], dtype=np.float32)) + results_gt['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + gt_masks = np.array([[0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 255, 13, 13], [255, 255, 255, 13]], + dtype=self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_sheared, self.check_keys) + + def test_repr(self): + transform = ShearX(prob=0.5, level=10) + self.assertEqual( + repr(transform), ('ShearX(prob=0.5, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=30.0, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestShearY(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_sheary(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = ShearY(prob=0.5, level=2, min_mag=-30.) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = ShearY(prob=0.5, level=2, max_mag=100.) + + # test case when no shear vertically (level=0) + transform = ShearY( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_sheary = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_sheary, + self.check_keys) + + # test shear vertically, magnitude=1 + transform = ShearY(prob=1., level=10, max_mag=45., reversal_prob=0.) + results_sheared = transform(copy.deepcopy(self.results_mask)) + results_gt = copy.deepcopy(self.results_mask) + img_gt = np.array( + [[1, 6, 11, 128], [5, 10, 128, 128], [9, 128, 128, 128]], + dtype=np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[1, 0, 2, 1]], dtype=np.float32) + results_gt['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + gt_masks = np.array([[0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 13, 255, 255], [255, 255, 255, 255]], + dtype=self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_sheared, self.check_keys) + + # test PolygonMasks with shear vertically, magnitude=-1 + results_sheared = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([1, 1, 1, 0, 2, 0], dtype=np.float32)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_sheared, self.check_keys) + + def test_sheary_use_box_type(self): + # test case when no shear vertically (level=0) + transform = ShearY( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_sheary = transform(copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_sheary, + self.check_keys) + + # test shear vertically, magnitude=1 + transform = ShearY(prob=1., level=10, max_mag=45., reversal_prob=0.) + results_sheared = transform(copy.deepcopy(self.results_mask_boxtype)) + results_gt = copy.deepcopy(self.results_mask_boxtype) + img_gt = np.array( + [[1, 6, 11, 128], [5, 10, 128, 128], [9, 128, 128, 128]], + dtype=np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[1, 0, 2, 1]], dtype=np.float32)) + results_gt['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + gt_masks = np.array([[0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 13, 255, 255], [255, 255, 255, 255]], + dtype=self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_sheared, self.check_keys) + + def test_repr(self): + transform = ShearY(prob=0.5, level=10) + self.assertEqual( + repr(transform), ('ShearY(prob=0.5, ' + 'level=10, ' + 'min_mag=0.0, ' + 'max_mag=30.0, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestRotate(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_rotate(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = ShearY(prob=0.5, level=2, min_mag=-90.0) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = ShearY(prob=0.5, level=2, max_mag=270.0) + + # test case when no rotate aug (level=0) + transform = Rotate( + prob=1., + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_rotate = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_rotate, + self.check_keys) + + # test clockwise rotation with angle 90 + transform = Rotate( + prob=1., + level=10, + max_mag=90.0, + # set reversal_prob to 1 for clockwise rotation + reversal_prob=1., + ) + results_rotated = transform(copy.deepcopy(self.results_mask)) + # The image, masks, and semantic segmentation map + # will be bilinearly interpolated. + img_gt = np.array([[69, 8, 4, 65], [69, 9, 5, 65], + [70, 10, 6, 66]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[0.5, 0.5, 2.5, 1.5]], + dtype=np.float32) + gt_masks = np.array([[0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 13, 13], [255, 255, 13, 255], + [255, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_rotated, self.check_keys) + + # test clockwise rotation with angle 90, PolygonMasks + results_rotated = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([0, 1, 0, 1, 0, 2], dtype=np.float)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_rotated, self.check_keys) + + # test counter-clockwise rotation with angle 90 + transform = Rotate( + prob=1.0, + level=10, + max_mag=90.0, + # set reversal_prob to 0 for counter-clockwise rotation + reversal_prob=0.0, + ) + results_rotated = transform(copy.deepcopy(self.results_mask)) + # The image, masks, and semantic segmentation map + # will be bilinearly interpolated. + img_gt = np.array([[66, 6, 10, 70], [65, 5, 9, 69], + [65, 4, 8, 69]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[0.5, 0.5, 2.5, 1.5]], + dtype=np.float32) + gt_masks = np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 255, 255, 255], [255, 13, 255, 255], + [13, 13, 13, 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_rotated, self.check_keys) + + # test counter-clockwise rotation with angle 90, PolygonMasks + results_rotated = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([2, 0, 0, 0, 1, 0], dtype=np.float)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_rotated, self.check_keys) + + def test_rotate_use_box_type(self): + # test case when no rotate aug (level=0) + transform = Rotate( + prob=1., + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label, + ) + results_wo_rotate = transform(copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_rotate, + self.check_keys) + + # test clockwise rotation with angle 90 + transform = Rotate( + prob=1., + level=10, + max_mag=90.0, + # set reversal_prob to 1 for clockwise rotation + reversal_prob=1., + ) + results_rotated = transform(copy.deepcopy(self.results_mask_boxtype)) + # The image, masks, and semantic segmentation map + # will be bilinearly interpolated. + img_gt = np.array([[69, 8, 4, 65], [69, 9, 5, 65], + [70, 10, 6, 66]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask_boxtype) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[0.5, 0.5, 2.5, 1.5]], dtype=np.float32)) + gt_masks = np.array([[0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 13, 13], [255, 255, 13, 255], + [255, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_rotated, self.check_keys) + + # test counter-clockwise rotation with angle 90 + transform = Rotate( + prob=1.0, + level=10, + max_mag=90.0, + # set reversal_prob to 0 for counter-clockwise rotation + reversal_prob=0.0, + ) + results_rotated = transform(copy.deepcopy(self.results_mask_boxtype)) + # The image, masks, and semantic segmentation map + # will be bilinearly interpolated. + img_gt = np.array([[66, 6, 10, 70], [65, 5, 9, 69], + [65, 4, 8, 69]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask_boxtype) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[0.5, 0.5, 2.5, 1.5]], dtype=np.float32)) + gt_masks = np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 255, 255, 255], [255, 13, 255, 255], + [13, 13, 13, 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_rotated, self.check_keys) + + def test_repr(self): + transform = Rotate(prob=0.5, level=5) + self.assertEqual( + repr(transform), ('Rotate(prob=0.5, ' + 'level=5, ' + 'min_mag=0.0, ' + 'max_mag=30.0, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestTranslateX(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_translatex(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = TranslateX(prob=0.5, level=2, min_mag=-1.) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = TranslateX(prob=0.5, level=2, max_mag=1.1) + + # test case when level=0 (without translate aug) + transform = TranslateX( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_wo_translatex = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_translatex, + self.check_keys) + + # test translate horizontally, magnitude=-1 + transform = TranslateX( + prob=1.0, + level=10, + max_mag=0.3, + reversal_prob=0.0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_translated = transform(copy.deepcopy(self.results_mask)) + img_gt = np.array([[2, 3, 4, 0], [6, 7, 8, 0], [10, 11, 12, + 0]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + img_gt[:, 3, :] = np.array(self.img_border_value) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[0, 0, 1, 2]], dtype=np.float32) + gt_masks = np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[13, 255, 255, 255], [13, 13, 255, 255], + [13, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_translated, self.check_keys) + + # test PolygonMasks with translate horizontally. + results_translated = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([0, 2, 0, 0, 1, 1], dtype=np.float32)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_translated, self.check_keys) + + def test_translatex_use_box_type(self): + # test case when level=0 (without translate aug) + transform = TranslateX( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_wo_translatex = transform( + copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_translatex, + self.check_keys) + + # test translate horizontally, magnitude=-1 + transform = TranslateX( + prob=1.0, + level=10, + max_mag=0.3, + reversal_prob=0.0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_translated = transform( + copy.deepcopy(self.results_mask_boxtype)) + img_gt = np.array([[2, 3, 4, 0], [6, 7, 8, 0], [10, 11, 12, + 0]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + img_gt[:, 3, :] = np.array(self.img_border_value) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[0, 0, 1, 2]], dtype=np.float32)) + gt_masks = np.array([[1, 0, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[13, 255, 255, 255], [13, 13, 255, 255], + [13, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_translated, self.check_keys) + + def test_repr(self): + transform = TranslateX(prob=0.5, level=5) + self.assertEqual( + repr(transform), ('TranslateX(prob=0.5, ' + 'level=5, ' + 'min_mag=0.0, ' + 'max_mag=0.1, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) + + +class TestTranslateY(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.check_keys = ('img', 'gt_bboxes', 'gt_bboxes_labels', 'gt_masks', + 'gt_ignore_flags', 'gt_seg_map') + self.results_mask = construct_toy_data(poly2mask=True) + self.results_poly = construct_toy_data(poly2mask=False) + self.results_mask_boxtype = construct_toy_data( + poly2mask=True, use_box_type=True) + self.img_border_value = (104, 116, 124) + self.seg_ignore_label = 255 + + def test_translatey(self): + # test assertion for invalid value of min_mag + with self.assertRaises(AssertionError): + transform = TranslateY(prob=0.5, level=2, min_mag=-1.0) + # test assertion for invalid value of max_mag + with self.assertRaises(AssertionError): + transform = TranslateY(prob=0.5, level=2, max_mag=1.1) + + # test case when level=0 (without translate aug) + transform = TranslateY( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_wo_translatey = transform(copy.deepcopy(self.results_mask)) + check_result_same(self.results_mask, results_wo_translatey, + self.check_keys) + + # test translate vertically, magnitude=-1 + transform = TranslateY( + prob=1.0, + level=10, + max_mag=0.4, + reversal_prob=0.0, + seg_ignore_label=self.seg_ignore_label) + + results_translated = transform(copy.deepcopy(self.results_mask)) + img_gt = np.array([[5, 6, 7, 8], [9, 10, 11, 12], + [128, 128, 128, 128]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = np.array([[1, 0, 2, 1]], dtype=np.float32) + gt_masks = np.array([[0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 13, 255], [255, 13, 255, 255], + [255, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_translated, self.check_keys) + + # test PolygonMasks with translate vertically. + results_translated = transform(copy.deepcopy(self.results_poly)) + gt_masks = [[np.array([1, 1, 1, 0, 2, 0], dtype=np.float32)]] + results_gt['gt_masks'] = PolygonMasks(gt_masks, 3, 4) + check_result_same(results_gt, results_translated, self.check_keys) + + def test_translatey_use_box_type(self): + # test case when level=0 (without translate aug) + transform = TranslateY( + prob=1.0, + level=0, + img_border_value=self.img_border_value, + seg_ignore_label=self.seg_ignore_label) + results_wo_translatey = transform( + copy.deepcopy(self.results_mask_boxtype)) + check_result_same(self.results_mask_boxtype, results_wo_translatey, + self.check_keys) + + # test translate vertically, magnitude=-1 + transform = TranslateY( + prob=1.0, + level=10, + max_mag=0.4, + reversal_prob=0.0, + seg_ignore_label=self.seg_ignore_label) + + results_translated = transform( + copy.deepcopy(self.results_mask_boxtype)) + img_gt = np.array([[5, 6, 7, 8], [9, 10, 11, 12], + [128, 128, 128, 128]]).astype(np.uint8) + img_gt = np.stack([img_gt, img_gt, img_gt], axis=-1) + results_gt = copy.deepcopy(self.results_mask_boxtype) + results_gt['img'] = img_gt + results_gt['gt_bboxes'] = HorizontalBoxes( + np.array([[1, 0, 2, 1]], dtype=np.float32)) + gt_masks = np.array([[0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]], + dtype=np.uint8)[None, :, :] + results_gt['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + results_gt['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results_gt['gt_seg_map'] = np.array( + [[255, 13, 13, 255], [255, 13, 255, 255], + [255, 255, 255, + 255]]).astype(self.results_mask['gt_seg_map'].dtype) + check_result_same(results_gt, results_translated, self.check_keys) + + def test_repr(self): + transform = TranslateX(prob=0.5, level=5) + self.assertEqual( + repr(transform), ('TranslateX(prob=0.5, ' + 'level=5, ' + 'min_mag=0.0, ' + 'max_mag=0.1, ' + 'reversal_prob=0.5, ' + 'img_border_value=(128.0, 128.0, 128.0), ' + 'mask_border_value=0, ' + 'seg_ignore_label=255, ' + 'interpolation=bilinear)')) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_instaboost.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_instaboost.py new file mode 100644 index 0000000000000000000000000000000000000000..325b737ea6002d9d824c831ce8a7d43f7a38e5c4 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_instaboost.py @@ -0,0 +1,58 @@ +import os.path as osp +import unittest + +import numpy as np + +from mmdet.registry import TRANSFORMS +from mmdet.utils import register_all_modules + +register_all_modules() + + +class TestInstaboost(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + img_path = osp.join(osp.dirname(__file__), '../../data/gray.jpg') + self.results = { + 'img_path': + img_path, + 'img_shape': (300, 400), + 'instances': [{ + 'bbox': [0, 0, 10, 20], + 'bbox_label': 1, + 'mask': [[0, 0, 0, 20, 10, 20, 10, 0]], + 'ignore_flag': 0 + }, { + 'bbox': [10, 10, 110, 120], + 'bbox_label': 2, + 'mask': [[10, 10, 110, 10, 110, 120, 110, 10]], + 'ignore_flag': 0 + }, { + 'bbox': [50, 50, 60, 80], + 'bbox_label': 2, + 'mask': [[50, 50, 60, 50, 60, 80, 50, 80]], + 'ignore_flag': 1 + }] + } + + def test_transform(self): + load = TRANSFORMS.build(dict(type='LoadImageFromFile')) + instaboost_transform = TRANSFORMS.build(dict(type='InstaBoost')) + + # Execute transforms + results = load(self.results) + results = instaboost_transform(results) + + self.assertEqual(results['img'].dtype, np.uint8) + self.assertIn('instances', results) + + def test_repr(self): + instaboost_transform = TRANSFORMS.build(dict(type='InstaBoost')) + + self.assertEqual( + repr(instaboost_transform), 'InstaBoost(aug_ratio=0.5)') diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_loading.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..840ad51c4ed85782d80ddcbb42803e39732ab456 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_loading.py @@ -0,0 +1,539 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os +import os.path as osp +import sys +import unittest +from unittest.mock import MagicMock, Mock, patch + +import mmcv +import numpy as np + +from mmdet.datasets.transforms import (FilterAnnotations, LoadAnnotations, + LoadEmptyAnnotations, + LoadImageFromNDArray, + LoadMultiChannelImageFromFiles, + LoadProposals, LoadTrackAnnotations) +from mmdet.evaluation import INSTANCE_OFFSET +from mmdet.structures.mask import BitmapMasks, PolygonMasks + +try: + import panopticapi +except ImportError: + panopticapi = None + + +class TestLoadAnnotations(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + data_prefix = osp.join(osp.dirname(__file__), '../../data') + seg_map = osp.join(data_prefix, 'gray.jpg') + self.results = { + 'ori_shape': (300, 400), + 'seg_map_path': + seg_map, + 'instances': [{ + 'bbox': [0, 0, 10, 20], + 'bbox_label': 1, + 'mask': [[0, 0, 0, 20, 10, 20, 10, 0]], + 'ignore_flag': 0 + }, { + 'bbox': [10, 10, 110, 120], + 'bbox_label': 2, + 'mask': [[10, 10, 110, 10, 110, 120, 110, 10]], + 'ignore_flag': 0 + }, { + 'bbox': [50, 50, 60, 80], + 'bbox_label': 2, + 'mask': [[50, 50, 60, 50, 60, 80, 50, 80]], + 'ignore_flag': 1 + }] + } + + def test_load_bboxes(self): + transform = LoadAnnotations( + with_bbox=True, + with_label=False, + with_seg=False, + with_mask=False, + box_type=None) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_bboxes', results) + self.assertTrue((results['gt_bboxes'] == np.array([[0, 0, 10, 20], + [10, 10, 110, 120], + [50, 50, 60, + 80]])).all()) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + self.assertTrue((results['gt_ignore_flags'] == np.array([0, 0, + 1])).all()) + self.assertEqual(results['gt_ignore_flags'].dtype, bool) + + def test_load_labels(self): + transform = LoadAnnotations( + with_bbox=False, + with_label=True, + with_seg=False, + with_mask=False, + ) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_bboxes_labels', results) + self.assertTrue((results['gt_bboxes_labels'] == np.array([1, 2, + 2])).all()) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + + def test_load_mask(self): + transform = LoadAnnotations( + with_bbox=False, + with_label=False, + with_seg=False, + with_mask=True, + poly2mask=False) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_masks', results) + self.assertEqual(len(results['gt_masks']), 3) + self.assertIsInstance(results['gt_masks'], PolygonMasks) + + def test_load_mask_poly2mask(self): + transform = LoadAnnotations( + with_bbox=False, + with_label=False, + with_seg=False, + with_mask=True, + poly2mask=True) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_masks', results) + self.assertEqual(len(results['gt_masks']), 3) + self.assertIsInstance(results['gt_masks'], BitmapMasks) + + def test_load_semseg(self): + transform = LoadAnnotations( + with_bbox=False, with_label=False, with_seg=True, with_mask=False) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_seg_map', results) + self.assertIn('ignore_index', results) + self.assertEqual(results['gt_seg_map'].shape, (288, 512)) + + # test reduce_zero_label and ignore_index + transform = LoadAnnotations( + with_bbox=False, + with_label=False, + with_seg=True, + with_mask=False, + reduce_zero_label=True, + ignore_index=10) + results = transform(copy.deepcopy(self.results)) + self.assertIn('gt_seg_map', results) + self.assertIn('ignore_index', results) + self.assertEqual(results['ignore_index'], 10) + self.assertEqual(results['gt_seg_map'].shape, (288, 512)) + + def test_repr(self): + transform = LoadAnnotations( + with_bbox=True, + with_label=False, + with_seg=False, + with_mask=False, + ) + self.assertEqual( + repr(transform), ('LoadAnnotations(with_bbox=True, ' + 'with_label=False, with_mask=False, ' + 'with_seg=False, poly2mask=True, ' + "imdecode_backend='cv2', " + 'backend_args=None)')) + + +class TestFilterAnnotations(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]]), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=np.bool8), + 'gt_masks': + BitmapMasks(rng.rand(3, 224, 224), height=224, width=224), + } + + def test_transform(self): + # test keep_empty = True + transform = FilterAnnotations( + min_gt_bbox_wh=(50, 50), + keep_empty=True, + ) + results = transform(copy.deepcopy(self.results)) + self.assertIsNone(results) + + # test keep_empty = False + transform = FilterAnnotations( + min_gt_bbox_wh=(50, 50), + keep_empty=False, + ) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(isinstance(results, dict)) + + # test filter annotations + transform = FilterAnnotations(min_gt_bbox_wh=(15, 15), ) + results = transform(copy.deepcopy(self.results)) + + self.assertIsInstance(results, dict) + self.assertTrue((results['gt_bboxes_labels'] == np.array([2, + 3])).all()) + self.assertTrue((results['gt_bboxes'] == np.array([[20, 20, 40, 40], + [40, 40, 80, + 80]])).all()) + self.assertEqual(len(results['gt_masks']), 2) + self.assertEqual(len(results['gt_ignore_flags']), 2) + + def test_repr(self): + transform = FilterAnnotations( + min_gt_bbox_wh=(1, 1), + keep_empty=False, + ) + self.assertEqual( + repr(transform), ('FilterAnnotations(min_gt_bbox_wh=(1, 1), ' + 'keep_empty=False)')) + + +class TestLoadPanopticAnnotations(unittest.TestCase): + + def setUp(self): + seg_map = np.zeros((10, 10), dtype=np.int32) + seg_map[:5, :10] = 1 + 10 * INSTANCE_OFFSET + seg_map[5:10, :5] = 4 + 11 * INSTANCE_OFFSET + seg_map[5:10, 5:10] = 6 + 0 * INSTANCE_OFFSET + rgb_seg_map = np.zeros((10, 10, 3), dtype=np.uint8) + rgb_seg_map[:, :, 0] = seg_map / (256 * 256) + rgb_seg_map[:, :, 1] = seg_map % (256 * 256) / 256 + rgb_seg_map[:, :, 2] = seg_map % 256 + self.seg_map_path = './1.png' + mmcv.imwrite(rgb_seg_map, self.seg_map_path) + + self.seg_map = seg_map + self.rgb_seg_map = rgb_seg_map + self.results = { + 'ori_shape': (10, 10), + 'instances': [{ + 'bbox': [0, 0, 10, 5], + 'bbox_label': 0, + 'ignore_flag': 0, + }, { + 'bbox': [0, 5, 5, 10], + 'bbox_label': 1, + 'ignore_flag': 1, + }], + 'segments_info': [ + { + 'id': 1 + 10 * INSTANCE_OFFSET, + 'category': 0, + 'is_thing': True, + }, + { + 'id': 4 + 11 * INSTANCE_OFFSET, + 'category': 1, + 'is_thing': True, + }, + { + 'id': 6 + 0 * INSTANCE_OFFSET, + 'category': 2, + 'is_thing': False, + }, + ], + 'seg_map_path': + self.seg_map_path + } + + self.gt_mask = BitmapMasks([ + (seg_map == 1 + 10 * INSTANCE_OFFSET).astype(np.uint8), + (seg_map == 4 + 11 * INSTANCE_OFFSET).astype(np.uint8), + ], 10, 10) + self.gt_bboxes = np.array([[0, 0, 10, 5], [0, 5, 5, 10]], + dtype=np.float32) + self.gt_bboxes_labels = np.array([0, 1], dtype=np.int64) + self.gt_ignore_flags = np.array([0, 1], dtype=bool) + self.gt_seg_map = np.zeros((10, 10), dtype=np.int32) + self.gt_seg_map[:5, :10] = 0 + self.gt_seg_map[5:10, :5] = 1 + self.gt_seg_map[5:10, 5:10] = 2 + + def tearDown(self): + os.remove(self.seg_map_path) + + @unittest.skipIf(panopticapi is not None, 'panopticapi is installed') + def test_init_without_panopticapi(self): + # test if panopticapi is not installed + from mmdet.datasets.transforms import LoadPanopticAnnotations + with self.assertRaisesRegex( + ImportError, + 'panopticapi is not installed, please install it by'): + LoadPanopticAnnotations() + + def test_transform(self): + sys.modules['panopticapi'] = MagicMock() + sys.modules['panopticapi.utils'] = MagicMock() + from mmdet.datasets.transforms import LoadPanopticAnnotations + mock_rgb2id = Mock(return_value=self.seg_map) + with patch('panopticapi.utils.rgb2id', mock_rgb2id): + # test with all False + transform = LoadPanopticAnnotations( + with_bbox=False, + with_label=False, + with_mask=False, + with_seg=False) + results = transform(copy.deepcopy(self.results)) + self.assertDictEqual(results, self.results) + # test with with_mask=True + transform = LoadPanopticAnnotations( + with_bbox=False, + with_label=False, + with_mask=True, + with_seg=False) + results = transform(copy.deepcopy(self.results)) + self.assertTrue( + (results['gt_masks'].masks == self.gt_mask.masks).all()) + + # test with with_seg=True + transform = LoadPanopticAnnotations( + with_bbox=False, + with_label=False, + with_mask=False, + with_seg=True) + results = transform(copy.deepcopy(self.results)) + self.assertNotIn('gt_masks', results) + self.assertTrue((results['gt_seg_map'] == self.gt_seg_map).all()) + + # test with all True + transform = LoadPanopticAnnotations( + with_bbox=True, + with_label=True, + with_mask=True, + with_seg=True, + box_type=None) + results = transform(copy.deepcopy(self.results)) + self.assertTrue( + (results['gt_masks'].masks == self.gt_mask.masks).all()) + self.assertTrue((results['gt_bboxes'] == self.gt_bboxes).all()) + self.assertTrue( + (results['gt_bboxes_labels'] == self.gt_bboxes_labels).all()) + self.assertTrue( + (results['gt_ignore_flags'] == self.gt_ignore_flags).all()) + self.assertTrue((results['gt_seg_map'] == self.gt_seg_map).all()) + + +class TestLoadImageFromNDArray(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.results = {'img': np.zeros((256, 256, 3), dtype=np.uint8)} + + def test_transform(self): + transform = LoadImageFromNDArray() + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape, (256, 256, 3)) + self.assertEqual(results['img'].dtype, np.uint8) + self.assertEqual(results['img_shape'], (256, 256)) + self.assertEqual(results['ori_shape'], (256, 256)) + + # to_float32 + transform = LoadImageFromNDArray(to_float32=True) + results = transform(copy.deepcopy(results)) + self.assertEqual(results['img'].dtype, np.float32) + + def test_repr(self): + transform = LoadImageFromNDArray() + self.assertEqual( + repr(transform), ('LoadImageFromNDArray(' + 'ignore_empty=False, ' + 'to_float32=False, ' + "color_type='color', " + "imdecode_backend='cv2', " + 'backend_args=None)')) + + +class TestLoadMultiChannelImageFromFiles(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.img_path = [] + for i in range(4): + img_channel_path = f'./part_{i}.jpg' + img_channel = np.zeros((10, 10), dtype=np.uint8) + mmcv.imwrite(img_channel, img_channel_path) + self.img_path.append(img_channel_path) + self.results = {'img_path': self.img_path} + + def tearDown(self): + for filename in self.img_path: + os.remove(filename) + + def test_transform(self): + transform = LoadMultiChannelImageFromFiles() + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape, (10, 10, 4)) + self.assertEqual(results['img'].dtype, np.uint8) + self.assertEqual(results['img_shape'], (10, 10)) + self.assertEqual(results['ori_shape'], (10, 10)) + + # to_float32 + transform = LoadMultiChannelImageFromFiles(to_float32=True) + results = transform(copy.deepcopy(results)) + self.assertEqual(results['img'].dtype, np.float32) + + def test_rper(self): + transform = LoadMultiChannelImageFromFiles() + self.assertEqual( + repr(transform), ('LoadMultiChannelImageFromFiles(' + 'to_float32=False, ' + "color_type='unchanged', " + "imdecode_backend='cv2', " + 'backend_args=None)')) + + +class TestLoadProposals(unittest.TestCase): + + def test_transform(self): + transform = LoadProposals() + results = { + 'proposals': + dict( + bboxes=np.zeros((5, 4), dtype=np.int64), + scores=np.zeros((5, ), dtype=np.int64)) + } + results = transform(results) + self.assertEqual(results['proposals'].dtype, np.float32) + self.assertEqual(results['proposals'].shape[-1], 4) + self.assertEqual(results['proposals_scores'].dtype, np.float32) + + # bboxes.shape[1] should be 4 + results = {'proposals': dict(bboxes=np.zeros((5, 5), dtype=np.int64))} + with self.assertRaises(AssertionError): + transform(results) + + # bboxes.shape[0] should equal to scores.shape[0] + results = { + 'proposals': + dict( + bboxes=np.zeros((5, 4), dtype=np.int64), + scores=np.zeros((3, ), dtype=np.int64)) + } + with self.assertRaises(AssertionError): + transform(results) + + # empty bboxes + results = { + 'proposals': dict(bboxes=np.zeros((0, 4), dtype=np.float32)) + } + results = transform(results) + excepted_proposals = np.zeros((0, 4), dtype=np.float32) + excepted_proposals_scores = np.zeros(0, dtype=np.float32) + self.assertTrue((results['proposals'] == excepted_proposals).all()) + self.assertTrue( + (results['proposals_scores'] == excepted_proposals_scores).all()) + + transform = LoadProposals(num_max_proposals=2) + results = { + 'proposals': + dict( + bboxes=np.zeros((5, 4), dtype=np.int64), + scores=np.zeros((5, ), dtype=np.int64)) + } + results = transform(results) + self.assertEqual(results['proposals'].shape[0], 2) + + def test_repr(self): + transform = LoadProposals() + self.assertEqual( + repr(transform), 'LoadProposals(num_max_proposals=None)') + + +class TestLoadEmptyAnnotations(unittest.TestCase): + + def test_transform(self): + transform = LoadEmptyAnnotations( + with_bbox=True, with_label=True, with_mask=True, with_seg=True) + results = {'img_shape': (224, 224)} + results = transform(results) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + self.assertEqual(results['gt_bboxes'].shape[-1], 4) + self.assertEqual(results['gt_ignore_flags'].dtype, bool) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + self.assertEqual(results['gt_masks'].masks.dtype, np.uint8) + self.assertEqual(results['gt_masks'].masks.shape[-2:], + results['img_shape']) + self.assertEqual(results['gt_seg_map'].dtype, np.uint8) + self.assertEqual(results['gt_seg_map'].shape, results['img_shape']) + + def test_repr(self): + transform = LoadEmptyAnnotations() + self.assertEqual( + repr(transform), 'LoadEmptyAnnotations(with_bbox=True, ' + 'with_label=True, ' + 'with_mask=False, ' + 'with_seg=False, ' + 'seg_ignore_label=255)') + + +class TestLoadTrackAnnotations(unittest.TestCase): + + def setUp(self): + data_prefix = osp.join(osp.dirname(__file__), '../data') + seg_map = osp.join(data_prefix, 'grayscale.jpg') + self.results = { + 'seg_map_path': + seg_map, + 'instances': [{ + 'bbox': [0, 0, 10, 20], + 'bbox_label': 1, + 'instance_id': 100, + 'keypoints': [1, 2, 3] + }, { + 'bbox': [10, 10, 110, 120], + 'bbox_label': 2, + 'instance_id': 102, + 'keypoints': [4, 5, 6] + }] + } + + def test_load_instances_id(self): + transform = LoadTrackAnnotations( + with_bbox=False, + with_label=True, + with_seg=False, + with_keypoints=False, + ) + results = transform(copy.deepcopy(self.results)) + assert 'gt_instances_ids' in results + assert (results['gt_instances_ids'] == np.array([100, 102])).all() + assert results['gt_instances_ids'].dtype == np.int32 + + def test_repr(self): + transform = LoadTrackAnnotations( + with_bbox=True, with_label=False, with_seg=False, with_mask=False) + assert repr(transform) == ('LoadTrackAnnotations(with_bbox=True, ' + 'with_label=False, with_mask=False,' + ' with_seg=False, poly2mask=True,' + " imdecode_backend='cv2', " + 'file_client_args=None)') diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_transforms.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..134e5de8a7ccf6fe1d5988b80792b064d13d0148 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_transforms.py @@ -0,0 +1,1790 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os.path as osp +import unittest + +import mmcv +import numpy as np +import torch +from mmcv.transforms import LoadImageFromFile + +# yapf:disable +from mmdet.datasets.transforms import (CopyPaste, CutOut, Expand, + FixScaleResize, FixShapeResize, + MinIoURandomCrop, MixUp, Mosaic, Pad, + PhotoMetricDistortion, RandomAffine, + RandomCenterCropPad, RandomCrop, + RandomErasing, RandomFlip, RandomShift, + Resize, ResizeShortestEdge, SegRescale, + YOLOXHSVRandomAug) +# yapf:enable +from mmdet.evaluation import bbox_overlaps +from mmdet.registry import TRANSFORMS +from mmdet.structures.bbox import HorizontalBoxes, bbox_project +from mmdet.structures.mask import BitmapMasks +from .utils import construct_toy_data, create_full_masks, create_random_bboxes + +try: + import albumentations + from albumentations import Compose +except ImportError: + albumentations = None + Compose = None +# yapf:enable + + +class TestResize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() + -> tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.data_info1 = dict( + img=np.random.random((400, 500, 3)), + gt_seg_map=np.random.random((400, 500, 3)), + gt_bboxes=np.array([[0, 0, 112, 112]], dtype=np.float32), + gt_masks=BitmapMasks(rng.rand(1, 400, 500), height=400, width=500)) + self.data_info2 = dict( + img=np.random.random((200, 100, 3)), + gt_bboxes=np.array([[20, 15, 60, 45]], dtype=np.float32), + dtype=np.float32) + self.data_info3 = dict(img=np.random.random((200, 100, 3))) + + def test_resize(self): + # test keep_ratio is True + transform = Resize(scale=(100, 100), keep_ratio=True) + results = transform(copy.deepcopy(self.data_info1)) + self.assertEqual(results['img_shape'], (80, 100)) + self.assertEqual(results['scale_factor'], (80 / 400, 100 / 500)) + + # test resize_bboxes/seg/masks + transform = Resize(scale_factor=(1.5, 2)) + results = transform(copy.deepcopy(self.data_info1)) + self.assertTrue( + (results['gt_bboxes'] == np.array([[0., 0., 168., 224.]])).all()) + self.assertEqual(results['gt_masks'].height, 800) + self.assertEqual(results['gt_masks'].width, 750) + self.assertEqual(results['gt_seg_map'].shape[:2], (800, 750)) + + # test clip_object_border = False + transform = Resize(scale=(200, 150), clip_object_border=False) + results = transform(self.data_info2) + self.assertTrue( + (results['gt_bboxes'] == np.array([40., 11.25, 120., + 33.75])).all()) + + # test only with image + transform = Resize(scale=(200, 150), clip_object_border=False) + results = transform(self.data_info3) + self.assertTupleEqual(results['img'].shape[:2], (150, 200)) + + # test geometric transformation with homography matrix + transform = Resize(scale_factor=(1.5, 2)) + results = transform(copy.deepcopy(self.data_info1)) + self.assertTrue((bbox_project( + copy.deepcopy(self.data_info1['gt_bboxes']), + results['homography_matrix']) == results['gt_bboxes']).all()) + + def test_resize_use_box_type(self): + data_info1 = copy.deepcopy(self.data_info1) + data_info1['gt_bboxes'] = HorizontalBoxes(data_info1['gt_bboxes']) + data_info2 = copy.deepcopy(self.data_info2) + data_info2['gt_bboxes'] = HorizontalBoxes(data_info2['gt_bboxes']) + # test keep_ratio is True + transform = Resize(scale=(100, 150), keep_ratio=True) + results = transform(copy.deepcopy(data_info1)) + self.assertEqual(results['img_shape'], (100, 125)) + self.assertEqual(results['scale_factor'], (100 / 400, 125 / 500)) + + # test resize_bboxes/seg/masks + transform = Resize(scale_factor=(1.5, 2)) + results = transform(copy.deepcopy(data_info1)) + self.assertTrue( + (results['gt_bboxes'].numpy() == np.array([[0, 0, 168, + 224]])).all()) + self.assertEqual(results['gt_masks'].height, 800) + self.assertEqual(results['gt_masks'].width, 750) + self.assertEqual(results['gt_seg_map'].shape[:2], (800, 750)) + + # test clip_object_border = False + transform = Resize(scale=(200, 150), clip_object_border=False) + results = transform(data_info2) + self.assertTrue((results['gt_bboxes'].numpy() == np.array( + [40., 11.25, 120., 33.75])).all()) + + # test geometric transformation with homography matrix + transform = Resize(scale_factor=(1.5, 2)) + results = transform(copy.deepcopy(data_info1)) + self.assertTrue((bbox_project( + copy.deepcopy(data_info1['gt_bboxes'].numpy()), + results['homography_matrix']) == results['gt_bboxes'].numpy() + ).all()) + + def test_repr(self): + transform = Resize(scale=(100, 100), keep_ratio=True) + self.assertEqual( + repr(transform), ('Resize(scale=(100, 100), ' + 'scale_factor=None, keep_ratio=True, ' + 'clip_object_border=True), backend=cv2), ' + 'interpolation=bilinear)')) + + +class TestFixScaleResize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() + -> tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.data_info1 = dict( + img=np.random.random((200, 300, 3)), + gt_seg_map=np.random.random((200, 300, 3)), + gt_bboxes=np.array([[0, 0, 112, 112]], dtype=np.float32), + gt_masks=BitmapMasks(rng.rand(1, 200, 300), height=200, width=300)) + + def test_resize(self): + # test keep_ratio is True + transform = FixScaleResize(scale=(101, 201), keep_ratio=True) + results = transform(copy.deepcopy(self.data_info1)) + self.assertEqual(results['img_shape'], (101, 151)) + self.assertEqual(results['scale_factor'], (151 / 300, 101 / 200)) + + +class TestFixShapeResize(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.data_info1 = dict( + img=np.random.random((200, 300, 3)), + gt_seg_map=np.random.random((200, 300, 3)), + gt_bboxes=np.array([[0, 0, 112, 133]], dtype=np.float32), + gt_masks=BitmapMasks(rng.rand(1, 200, 300), height=200, width=300)) + self.data_info2 = dict( + img=np.random.random((300, 400, 3)), + gt_bboxes=np.array([[200, 150, 600, 450]], dtype=np.float32), + dtype=np.float32) + self.data_info3 = dict(img=np.random.random((300, 400, 3))) + self.data_info4 = dict( + img=np.random.random((400, 450, 3)), + gt_bboxes=np.array([[200, 150, 300, 400]], dtype=np.float32), + dtype=np.float32) + + def test_resize(self): + # test keep_ratio is True + transform = FixShapeResize(width=100, height=50, keep_ratio=True) + results = transform(copy.deepcopy(self.data_info1)) + self.assertEqual(results['img_shape'], (50, 100)) + self.assertEqual(results['scale_factor'], (50 / 200, 50 / 200)) + # test resize_bboxes/seg/masks + transform = FixShapeResize(width=120, height=100, keep_ratio=False) + results = transform(copy.deepcopy(self.data_info1)) + self.assertEqual(results['gt_masks'].height, 100) + self.assertEqual(results['gt_masks'].width, 120) + self.assertEqual(results['gt_seg_map'].shape[:2], (100, 120)) + + # test clip_object_border = False + transform = FixShapeResize( + width=200, height=150, clip_object_border=False) + results = transform(copy.deepcopy(self.data_info2)) + self.assertTrue((results['gt_bboxes'] == np.array([100, 75, 300, + 225])).all()) + + # test only with image + transform = FixShapeResize( + width=200, height=150, clip_object_border=False) + results = transform(self.data_info3) + self.assertTupleEqual(results['img'].shape[:2], (150, 200)) + + # test geometric transformation with homography matrix + transform = FixShapeResize(width=400, height=300) + results = transform(copy.deepcopy(self.data_info4)) + self.assertTrue((bbox_project( + copy.deepcopy(self.data_info4['gt_bboxes']), + results['homography_matrix']) == results['gt_bboxes']).all()) + + def test_resize_with_boxlist(self): + data_info1 = copy.deepcopy(self.data_info1) + data_info1['gt_bboxes'] = HorizontalBoxes(data_info1['gt_bboxes']) + data_info2 = copy.deepcopy(self.data_info2) + data_info2['gt_bboxes'] = HorizontalBoxes(data_info2['gt_bboxes']) + data_info4 = copy.deepcopy(self.data_info4) + data_info4['gt_bboxes'] = HorizontalBoxes(data_info4['gt_bboxes']) + # test keep_ratio is True + transform = FixShapeResize(width=100, height=200, keep_ratio=True) + results = transform(copy.deepcopy(data_info1)) + self.assertEqual(results['img_shape'], (200, 100)) + self.assertEqual(results['scale_factor'], (100 / 300, 100 / 300)) + + # test resize_bboxes/seg/masks + transform = FixShapeResize(width=150, height=200, keep_ratio=False) + results = transform(copy.deepcopy(data_info1)) + self.assertTrue( + (results['gt_bboxes'].numpy() == np.array([[0, 0, 56, + 133]])).all()) + self.assertEqual(results['gt_masks'].height, 200) + self.assertEqual(results['gt_masks'].width, 150) + self.assertEqual(results['gt_seg_map'].shape[:2], (200, 150)) + + # test clip_object_border = False + transform = FixShapeResize( + width=200, height=150, clip_object_border=False) + results = transform(copy.deepcopy(data_info2)) + self.assertTrue( + (results['gt_bboxes'].numpy() == np.array([100, 75, 300, + 225])).all()) + + # test only with image + transform = FixShapeResize( + width=200, height=150, clip_object_border=False) + results = transform(self.data_info3) + self.assertTupleEqual(results['img'].shape[:2], (150, 200)) + + # test geometric transformation with homography matrix + transform = FixShapeResize(width=400, height=300) + results = transform(copy.deepcopy(data_info4)) + self.assertTrue((bbox_project( + copy.deepcopy(self.data_info4['gt_bboxes']), + results['homography_matrix']) == results['gt_bboxes'].numpy() + ).all()) + + def test_repr(self): + transform = FixShapeResize(width=100, height=50, keep_ratio=True) + self.assertEqual( + repr(transform), ('FixShapeResize(width=100, height=50, ' + 'keep_ratio=True, ' + 'clip_object_border=True), backend=cv2), ' + 'interpolation=bilinear)')) + + +class TestRandomFlip(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results1 = { + 'img': np.random.random((224, 224, 3)), + 'gt_bboxes': np.array([[0, 1, 100, 101]], dtype=np.float32), + 'gt_masks': + BitmapMasks(rng.rand(1, 224, 224), height=224, width=224), + 'gt_seg_map': np.random.random((224, 224)) + } + + self.results2 = {'img': self.results1['img']} + + def test_transform(self): + # test with image, gt_bboxes, gt_masks, gt_seg_map + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(self.results1)) + self.assertTrue( + (results_update['gt_bboxes'] == np.array([[124, 1, 224, + 101]])).all()) + # test only with image + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(self.results2)) + self.assertTrue( + (results_update['img'] == self.results2['img'][:, ::-1]).all()) + + # test geometric transformation with homography matrix + # (1) Horizontal Flip + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(self.results1)) + bboxes = copy.deepcopy(self.results1['gt_bboxes']) + self.assertTrue((bbox_project( + bboxes, + results_update['homography_matrix']) == results_update['gt_bboxes'] + ).all()) + # (2) Vertical Flip + transform = RandomFlip(1.0, direction='vertical') + results_update = transform.transform(copy.deepcopy(self.results1)) + bboxes = copy.deepcopy(self.results1['gt_bboxes']) + self.assertTrue((bbox_project( + bboxes, + results_update['homography_matrix']) == results_update['gt_bboxes'] + ).all()) + # (3) Diagonal Flip + transform = RandomFlip(1.0, direction='diagonal') + results_update = transform.transform(copy.deepcopy(self.results1)) + bboxes = copy.deepcopy(self.results1['gt_bboxes']) + self.assertTrue((bbox_project( + bboxes, + results_update['homography_matrix']) == results_update['gt_bboxes'] + ).all()) + + def test_transform_use_box_type(self): + results1 = copy.deepcopy(self.results1) + results1['gt_bboxes'] = HorizontalBoxes(results1['gt_bboxes']) + # test with image, gt_bboxes, gt_masks, gt_seg_map + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(results1)) + self.assertTrue((results_update['gt_bboxes'].numpy() == np.array( + [[124, 1, 224, 101]])).all()) + + # test geometric transformation with homography matrix + # (1) Horizontal Flip + transform = RandomFlip(1.0) + results_update = transform.transform(copy.deepcopy(results1)) + bboxes = copy.deepcopy(results1['gt_bboxes'].numpy()) + self.assertTrue((bbox_project(bboxes, + results_update['homography_matrix']) == + results_update['gt_bboxes'].numpy()).all()) + # (2) Vertical Flip + transform = RandomFlip(1.0, direction='vertical') + results_update = transform.transform(copy.deepcopy(results1)) + bboxes = copy.deepcopy(results1['gt_bboxes'].numpy()) + self.assertTrue((bbox_project(bboxes, + results_update['homography_matrix']) == + results_update['gt_bboxes'].numpy()).all()) + # (3) Diagonal Flip + transform = RandomFlip(1.0, direction='diagonal') + results_update = transform.transform(copy.deepcopy(results1)) + bboxes = copy.deepcopy(results1['gt_bboxes'].numpy()) + self.assertTrue((bbox_project(bboxes, + results_update['homography_matrix']) == + results_update['gt_bboxes'].numpy()).all()) + + def test_repr(self): + transform = RandomFlip(0.1) + transform_str = str(transform) + self.assertIsInstance(transform_str, str) + + +class TestPad(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': np.random.random((100, 80, 3)), + 'gt_masks': + BitmapMasks(rng.rand(4, 100, 80), height=100, width=80) + } + + def test_transform(self): + # test pad img/gt_masks with size + transform = Pad(size=(120, 110)) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (110, 120)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (110, 120)) + + # test pad img/gt_masks with size_divisor + transform = Pad(size_divisor=11) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (110, 88)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (110, 88)) + + # test pad img/gt_masks with pad_to_square + transform = Pad(pad_to_square=True) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (100, 100)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (100, 100)) + + # test pad img/gt_masks with pad_to_square and size_divisor + transform = Pad(pad_to_square=True, size_divisor=11) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (110, 110)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (110, 110)) + + # test pad img/gt_masks with pad_to_square and size_divisor + transform = Pad(pad_to_square=True, size_divisor=11) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img'].shape[:2], (110, 110)) + self.assertEqual(results['gt_masks'].masks.shape[1:], (110, 110)) + + def test_repr(self): + transform = Pad( + pad_to_square=True, size_divisor=11, padding_mode='edge') + self.assertEqual( + repr(transform), + ('Pad(size=None, size_divisor=11, pad_to_square=True, ' + "pad_val={'img': 0, 'seg': 255}), padding_mode=edge)")) + + +class TestMinIoURandomCrop(unittest.TestCase): + + def test_transform(self): + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + results['img'] = img + results['img_shape'] = img.shape[:2] + gt_bboxes = create_random_bboxes(1, results['img_shape'][1], + results['img_shape'][0]) + results['gt_labels'] = np.ones(gt_bboxes.shape[0], dtype=np.int64) + results['gt_bboxes'] = gt_bboxes + transform = MinIoURandomCrop() + results = transform.transform(copy.deepcopy(results)) + + self.assertEqual(results['gt_labels'].shape[0], + results['gt_bboxes'].shape[0]) + self.assertEqual(results['gt_labels'].dtype, np.int64) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + patch = np.array( + [0, 0, results['img_shape'][1], results['img_shape'][0]]) + ious = bbox_overlaps(patch.reshape(-1, 4), + results['gt_bboxes']).reshape(-1) + mode = transform.mode + if mode == 1: + self.assertTrue(np.equal(results['gt_bboxes'], gt_bboxes).all()) + else: + self.assertTrue((ious >= mode).all()) + + def test_transform_use_box_type(self): + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + results['img'] = img + results['img_shape'] = img.shape[:2] + gt_bboxes = create_random_bboxes(1, results['img_shape'][1], + results['img_shape'][0]) + results['gt_labels'] = np.ones(gt_bboxes.shape[0], dtype=np.int64) + results['gt_bboxes'] = HorizontalBoxes(gt_bboxes) + transform = MinIoURandomCrop() + results = transform.transform(copy.deepcopy(results)) + + self.assertEqual(results['gt_labels'].shape[0], + results['gt_bboxes'].shape[0]) + self.assertEqual(results['gt_labels'].dtype, np.int64) + self.assertEqual(results['gt_bboxes'].dtype, torch.float32) + + patch = np.array( + [0, 0, results['img_shape'][1], results['img_shape'][0]]) + ious = bbox_overlaps( + patch.reshape(-1, 4), results['gt_bboxes'].numpy()).reshape(-1) + mode = transform.mode + if mode == 1: + self.assertTrue((results['gt_bboxes'].numpy() == gt_bboxes).all()) + else: + self.assertTrue((ious >= mode).all()) + + def test_repr(self): + transform = MinIoURandomCrop() + self.assertEqual( + repr(transform), ('MinIoURandomCrop' + '(min_ious=(0.1, 0.3, 0.5, 0.7, 0.9), ' + 'min_crop_size=0.3, ' + 'bbox_clip_border=True)')) + + +class TestPhotoMetricDistortion(unittest.TestCase): + + def test_transform(self): + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + transform = PhotoMetricDistortion() + + # test uint8 input + results = dict() + results['img'] = img + results = transform.transform(copy.deepcopy(results)) + self.assertEqual(results['img'].dtype, np.float32) + + # test float32 input + results = dict() + results['img'] = img.astype(np.float32) + results = transform.transform(copy.deepcopy(results)) + self.assertEqual(results['img'].dtype, np.float32) + + def test_repr(self): + transform = PhotoMetricDistortion() + self.assertEqual( + repr(transform), ('PhotoMetricDistortion' + '(brightness_delta=32, ' + 'contrast_range=(0.5, 1.5), ' + 'saturation_range=(0.5, 1.5), ' + 'hue_delta=18)')) + + +class TestExpand(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes': np.array([[0, 1, 100, 101]]), + 'gt_masks': + BitmapMasks(rng.rand(1, 224, 224), height=224, width=224), + 'gt_seg_map': np.random.random((224, 224)) + } + + def test_transform(self): + transform = Expand() + results = transform.transform(copy.deepcopy(self.results)) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + self.assertEqual( + results['img_shape'], + (results['gt_masks'].height, results['gt_masks'].width)) + self.assertEqual(results['img_shape'], results['gt_seg_map'].shape) + + def test_transform_use_box_type(self): + results = copy.deepcopy(self.results) + results['gt_bboxes'] = HorizontalBoxes(results['gt_bboxes']) + transform = Expand() + results = transform.transform(results) + self.assertEqual( + results['img_shape'], + (results['gt_masks'].height, results['gt_masks'].width)) + self.assertEqual(results['img_shape'], results['gt_seg_map'].shape) + + def test_repr(self): + transform = Expand() + self.assertEqual( + repr(transform), ('Expand' + '(mean=(0, 0, 0), to_rgb=True, ' + 'ratio_range=(1, 4), ' + 'seg_ignore_label=None, ' + 'prob=0.5)')) + + +class TestSegRescale(unittest.TestCase): + + def setUp(self) -> None: + seg_map = np.random.randint(0, 255, size=(32, 32), dtype=np.int32) + self.results = {'gt_seg_map': seg_map} + + def test_transform(self): + # test scale_factor != 1 + transform = SegRescale(scale_factor=2) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['gt_seg_map'].shape[:2], (64, 64)) + # test scale_factor = 1 + transform = SegRescale(scale_factor=1) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['gt_seg_map'].shape[:2], (32, 32)) + + def test_repr(self): + transform = SegRescale(scale_factor=2) + self.assertEqual( + repr(transform), ('SegRescale(scale_factor=2, backend=cv2)')) + + +class TestRandomCrop(unittest.TestCase): + + def test_init(self): + # test invalid crop_type + with self.assertRaisesRegex(ValueError, 'Invalid crop_type'): + RandomCrop(crop_size=(10, 10), crop_type='unknown') + + crop_type_list = ['absolute', 'absolute_range'] + for crop_type in crop_type_list: + # test h > 0 and w > 0 + for crop_size in [(0, 0), (0, 1), (1, 0)]: + with self.assertRaises(AssertionError): + RandomCrop(crop_size=crop_size, crop_type=crop_type) + # test type(h) = int and type(w) = int + for crop_size in [(1.0, 1), (1, 1.0), (1.0, 1.0)]: + with self.assertRaises(AssertionError): + RandomCrop(crop_size=crop_size, crop_type=crop_type) + + # test crop_size[0] <= crop_size[1] + with self.assertRaises(AssertionError): + RandomCrop(crop_size=(10, 5), crop_type='absolute_range') + + # test h in (0, 1] and w in (0, 1] + crop_type_list = ['relative_range', 'relative'] + for crop_type in crop_type_list: + for crop_size in [(0, 1), (1, 0), (1.1, 0.5), (0.5, 1.1)]: + with self.assertRaises(AssertionError): + RandomCrop(crop_size=crop_size, crop_type=crop_type) + + def test_transform(self): + # test relative and absolute crop + src_results = { + 'img': np.random.randint(0, 255, size=(24, 32), dtype=np.int32) + } + target_shape = (12, 16) + for crop_type, crop_size in zip(['relative', 'absolute'], [(0.5, 0.5), + (16, 12)]): + transform = RandomCrop(crop_size=crop_size, crop_type=crop_type) + results = transform(copy.deepcopy(src_results)) + print(results['img'].shape[:2]) + self.assertEqual(results['img'].shape[:2], target_shape) + + # test absolute_range crop + transform = RandomCrop(crop_size=(10, 20), crop_type='absolute_range') + results = transform(copy.deepcopy(src_results)) + h, w = results['img'].shape + self.assertTrue(10 <= w <= 20) + self.assertTrue(10 <= h <= 20) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + # test relative_range crop + transform = RandomCrop( + crop_size=(0.5, 0.5), crop_type='relative_range') + results = transform(copy.deepcopy(src_results)) + h, w = results['img'].shape + self.assertTrue(16 <= w <= 32) + self.assertTrue(12 <= h <= 24) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + # test with gt_bboxes, gt_bboxes_labels, gt_ignore_flags, + # gt_masks, gt_seg_map, gt_instances_ids + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = np.array([[0, 0, 7, 7], [2, 3, 9, 9]], dtype=np.float32) + gt_bboxes_labels = np.array([0, 1], dtype=np.int64) + gt_ignore_flags = np.array([0, 1], dtype=bool) + gt_masks_ = np.zeros((2, 10, 10), np.uint8) + gt_masks_[0, 0:7, 0:7] = 1 + gt_masks_[1, 2:7, 3:8] = 1 + gt_masks = BitmapMasks(gt_masks_.copy(), height=10, width=10) + gt_seg_map = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_instances_ids = np.array([0, 1], dtype=np.int64) + src_results = { + 'img': img, + 'gt_bboxes': gt_bboxes, + 'gt_bboxes_labels': gt_bboxes_labels, + 'gt_ignore_flags': gt_ignore_flags, + 'gt_masks': gt_masks, + 'gt_seg_map': gt_seg_map, + 'gt_instances_ids': gt_instances_ids + } + transform = RandomCrop( + crop_size=(7, 5), + allow_negative_crop=False, + recompute_bbox=False, + bbox_clip_border=True) + results = transform(copy.deepcopy(src_results)) + h, w = results['img'].shape + self.assertEqual(h, 5) + self.assertEqual(w, 7) + self.assertEqual(results['gt_bboxes'].shape[0], 2) + self.assertEqual(results['gt_bboxes_labels'].shape[0], 2) + self.assertEqual(results['gt_ignore_flags'].shape[0], 2) + self.assertTupleEqual(results['gt_seg_map'].shape[:2], (5, 7)) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + self.assertEqual(results['gt_instances_ids'].shape[0], 2) + + # test geometric transformation with homography matrix + bboxes = copy.deepcopy(src_results['gt_bboxes']) + self.assertTrue((bbox_project(bboxes, results['homography_matrix'], + (5, 7)) == results['gt_bboxes']).all()) + + # test recompute_bbox = True + gt_masks_ = np.zeros((2, 10, 10), np.uint8) + gt_masks = BitmapMasks(gt_masks_.copy(), height=10, width=10) + gt_bboxes = np.array([[0.1, 0.1, 0.2, 0.2]]) + src_results = { + 'img': img, + 'gt_bboxes': gt_bboxes, + 'gt_masks': gt_masks + } + target_gt_bboxes = np.zeros((1, 4), dtype=np.float32) + transform = RandomCrop( + crop_size=(10, 11), + allow_negative_crop=False, + recompute_bbox=True, + bbox_clip_border=True) + results = transform(copy.deepcopy(src_results)) + self.assertTrue((results['gt_bboxes'] == target_gt_bboxes).all()) + + # test bbox_clip_border = False + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop( + crop_size=(10, 11), + allow_negative_crop=False, + recompute_bbox=True, + bbox_clip_border=False) + results = transform(copy.deepcopy(src_results)) + self.assertTrue( + (results['gt_bboxes'] == src_results['gt_bboxes']).all()) + + # test the crop does not contain any gt-bbox + # allow_negative_crop = False + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = np.zeros((0, 4), dtype=np.float32) + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop(crop_size=(5, 3), allow_negative_crop=False) + results = transform(copy.deepcopy(src_results)) + self.assertIsNone(results) + + # allow_negative_crop = True + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = np.zeros((0, 4), dtype=np.float32) + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop(crop_size=(5, 3), allow_negative_crop=True) + results = transform(copy.deepcopy(src_results)) + self.assertTrue(isinstance(results, dict)) + + def test_transform_use_box_type(self): + # test with gt_bboxes, gt_bboxes_labels, gt_ignore_flags, + # gt_masks, gt_seg_map + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = np.array([[0, 0, 7, 7], [2, 3, 9, 9]], dtype=np.float32) + gt_bboxes_labels = np.array([0, 1], dtype=np.int64) + gt_ignore_flags = np.array([0, 1], dtype=bool) + gt_masks_ = np.zeros((2, 10, 10), np.uint8) + gt_masks_[0, 0:7, 0:7] = 1 + gt_masks_[1, 2:7, 3:8] = 1 + gt_masks = BitmapMasks(gt_masks_.copy(), height=10, width=10) + gt_seg_map = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_instances_ids = np.array([0, 1], dtype=np.int64) + src_results = { + 'img': img, + 'gt_bboxes': HorizontalBoxes(gt_bboxes), + 'gt_bboxes_labels': gt_bboxes_labels, + 'gt_ignore_flags': gt_ignore_flags, + 'gt_masks': gt_masks, + 'gt_seg_map': gt_seg_map, + 'gt_instances_ids': gt_instances_ids + } + transform = RandomCrop( + crop_size=(7, 5), + allow_negative_crop=False, + recompute_bbox=False, + bbox_clip_border=True) + results = transform(copy.deepcopy(src_results)) + h, w = results['img'].shape + self.assertEqual(h, 5) + self.assertEqual(w, 7) + self.assertEqual(results['gt_bboxes'].shape[0], 2) + self.assertEqual(results['gt_bboxes_labels'].shape[0], 2) + self.assertEqual(results['gt_ignore_flags'].shape[0], 2) + self.assertTupleEqual(results['gt_seg_map'].shape[:2], (5, 7)) + self.assertEqual(results['gt_instances_ids'].shape[0], 2) + + # test geometric transformation with homography matrix + bboxes = copy.deepcopy(src_results['gt_bboxes'].numpy()) + print(bboxes, results['gt_bboxes']) + self.assertTrue( + (bbox_project(bboxes, results['homography_matrix'], + (5, 7)) == results['gt_bboxes'].numpy()).all()) + + # test recompute_bbox = True + gt_masks_ = np.zeros((2, 10, 10), np.uint8) + gt_masks = BitmapMasks(gt_masks_.copy(), height=10, width=10) + gt_bboxes = HorizontalBoxes(np.array([[0.1, 0.1, 0.2, 0.2]])) + src_results = { + 'img': img, + 'gt_bboxes': gt_bboxes, + 'gt_masks': gt_masks + } + target_gt_bboxes = np.zeros((1, 4), dtype=np.float32) + transform = RandomCrop( + crop_size=(10, 11), + allow_negative_crop=False, + recompute_bbox=True, + bbox_clip_border=True) + results = transform(copy.deepcopy(src_results)) + self.assertTrue( + (results['gt_bboxes'].numpy() == target_gt_bboxes).all()) + + # test bbox_clip_border = False + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop( + crop_size=(10, 10), + allow_negative_crop=False, + recompute_bbox=True, + bbox_clip_border=False) + results = transform(copy.deepcopy(src_results)) + self.assertTrue( + (results['gt_bboxes'].numpy() == src_results['gt_bboxes'].numpy() + ).all()) + + # test the crop does not contain any gt-bbox + # allow_negative_crop = False + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = HorizontalBoxes(np.zeros((0, 4), dtype=np.float32)) + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop(crop_size=(5, 2), allow_negative_crop=False) + results = transform(copy.deepcopy(src_results)) + self.assertIsNone(results) + + # allow_negative_crop = True + img = np.random.randint(0, 255, size=(10, 10), dtype=np.uint8) + gt_bboxes = HorizontalBoxes(np.zeros((0, 4), dtype=np.float32)) + src_results = {'img': img, 'gt_bboxes': gt_bboxes} + transform = RandomCrop(crop_size=(5, 2), allow_negative_crop=True) + results = transform(copy.deepcopy(src_results)) + self.assertTrue(isinstance(results, dict)) + + def test_repr(self): + crop_type = 'absolute' + crop_size = (10, 5) + allow_negative_crop = False + recompute_bbox = True + bbox_clip_border = False + transform = RandomCrop( + crop_size=crop_size, + crop_type=crop_type, + allow_negative_crop=allow_negative_crop, + recompute_bbox=recompute_bbox, + bbox_clip_border=bbox_clip_border) + self.assertEqual( + repr(transform), + f'RandomCrop(crop_size={crop_size}, crop_type={crop_type}, ' + f'allow_negative_crop={allow_negative_crop}, ' + f'recompute_bbox={recompute_bbox}, ' + f'bbox_clip_border={bbox_clip_border})') + + +class TestCutOut(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + self.results = {'img': img} + + def test_transform(self): + # test n_holes + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=(5, 3), cutout_shape=(8, 8)) + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=(3, 4, 5), cutout_shape=(8, 8)) + + # test cutout_shape and cutout_ratio + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=1, cutout_shape=8) + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=1, cutout_ratio=0.2) + + # either of cutout_shape and cutout_ratio should be given + with self.assertRaises(AssertionError): + transform = CutOut(n_holes=1) + with self.assertRaises(AssertionError): + transform = CutOut( + n_holes=1, cutout_shape=(2, 2), cutout_ratio=(0.4, 0.4)) + + transform = CutOut(n_holes=1, cutout_shape=(10, 10)) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() < self.results['img'].sum()) + + transform = CutOut( + n_holes=(2, 4), + cutout_shape=[(10, 10), (15, 15)], + fill_in=(255, 255, 255)) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() > self.results['img'].sum()) + + transform = CutOut( + n_holes=1, cutout_ratio=(0.8, 0.8), fill_in=(255, 255, 255)) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() > self.results['img'].sum()) + + def test_repr(self): + transform = CutOut(n_holes=1, cutout_shape=(10, 10)) + self.assertEqual( + repr(transform), ('CutOut(n_holes=(1, 1), ' + 'cutout_shape=[(10, 10)], ' + 'fill_in=(0, 0, 0))')) + transform = CutOut( + n_holes=1, cutout_ratio=(0.8, 0.8), fill_in=(255, 255, 255)) + self.assertEqual( + repr(transform), ('CutOut(n_holes=(1, 1), ' + 'cutout_ratio=[(0.8, 0.8)], ' + 'fill_in=(255, 255, 255))')) + + +class TestMosaic(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + 'gt_masks': + BitmapMasks(rng.rand(3, 224, 224), height=224, width=224), + } + + def test_transform(self): + # test assertion for invalid img_scale + with self.assertRaises(AssertionError): + transform = Mosaic(img_scale=640) + + # test assertion for invalid probability + with self.assertRaises(AssertionError): + transform = Mosaic(prob=1.5) + + transform = Mosaic(img_scale=(12, 10)) + # test assertion for invalid mix_results + with self.assertRaises(AssertionError): + results = transform(copy.deepcopy(self.results)) + + self.results['mix_results'] = [copy.deepcopy(self.results)] * 3 + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].shape[:2] == (20, 24)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + def test_transform_with_no_gt(self): + self.results['gt_bboxes'] = np.empty((0, 4), dtype=np.float32) + self.results['gt_bboxes_labels'] = np.empty((0, ), dtype=np.int64) + self.results['gt_ignore_flags'] = np.empty((0, ), dtype=bool) + transform = Mosaic(img_scale=(12, 10)) + self.results['mix_results'] = [copy.deepcopy(self.results)] * 3 + results = transform(copy.deepcopy(self.results)) + self.assertIsInstance(results, dict) + self.assertTrue(results['img'].shape[:2] == (20, 24)) + self.assertTrue( + results['gt_bboxes_labels'].shape[0] == results['gt_bboxes']. + shape[0] == results['gt_ignore_flags'].shape[0] == 0) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_transform_use_box_type(self): + transform = Mosaic(img_scale=(12, 10)) + results = copy.deepcopy(self.results) + results['gt_bboxes'] = HorizontalBoxes(results['gt_bboxes']) + results['mix_results'] = [results] * 3 + results = transform(results) + self.assertTrue(results['img'].shape[:2] == (20, 24)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == torch.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_repr(self): + transform = Mosaic(img_scale=(640, 640), ) + self.assertEqual( + repr(transform), ('Mosaic(img_scale=(640, 640), ' + 'center_ratio_range=(0.5, 1.5), ' + 'pad_val=114.0, ' + 'prob=1.0)')) + + +class TestMixUp(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + 'gt_masks': + BitmapMasks(rng.rand(3, 224, 224), height=224, width=224), + } + + def test_transform(self): + # test assertion for invalid img_scale + with self.assertRaises(AssertionError): + transform = MixUp(img_scale=640) + + transform = MixUp(img_scale=(12, 10)) + # test assertion for invalid mix_results + with self.assertRaises(AssertionError): + results = transform(copy.deepcopy(self.results)) + + with self.assertRaises(AssertionError): + self.results['mix_results'] = [copy.deepcopy(self.results)] * 2 + results = transform(copy.deepcopy(self.results)) + + self.results['mix_results'] = [copy.deepcopy(self.results)] + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].shape[:2] == (224, 224)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + def test_transform_use_box_type(self): + results = copy.deepcopy(self.results) + results['gt_bboxes'] = HorizontalBoxes(results['gt_bboxes']) + + transform = MixUp(img_scale=(12, 10)) + results['mix_results'] = [results] + results = transform(results) + self.assertTrue(results['img'].shape[:2] == (224, 224)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == torch.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_repr(self): + transform = MixUp( + img_scale=(640, 640), + ratio_range=(0.8, 1.6), + pad_val=114.0, + ) + self.assertEqual( + repr(transform), ('MixUp(dynamic_scale=(640, 640), ' + 'ratio_range=(0.8, 1.6), ' + 'flip_ratio=0.5, ' + 'pad_val=114.0, ' + 'max_iters=15, ' + 'bbox_clip_border=True)')) + + +class TestRandomAffine(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + } + + def test_transform(self): + # test assertion for invalid translate_ratio + with self.assertRaises(AssertionError): + transform = RandomAffine(max_translate_ratio=1.5) + + # test assertion for invalid scaling_ratio_range + with self.assertRaises(AssertionError): + transform = RandomAffine(scaling_ratio_range=(1.5, 0.5)) + + with self.assertRaises(AssertionError): + transform = RandomAffine(scaling_ratio_range=(0, 0.5)) + + transform = RandomAffine() + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].shape[:2] == (224, 224)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + def test_transform_use_box_type(self): + results = copy.deepcopy(self.results) + results['gt_bboxes'] = HorizontalBoxes(results['gt_bboxes']) + + transform = RandomAffine() + results = transform(copy.deepcopy(results)) + self.assertTrue(results['img'].shape[:2] == (224, 224)) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == torch.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_repr(self): + transform = RandomAffine( + scaling_ratio_range=(0.1, 2), + border=(-320, -320), + ) + self.assertEqual( + repr(transform), ('RandomAffine(max_rotate_degree=10.0, ' + 'max_translate_ratio=0.1, ' + 'scaling_ratio_range=(0.1, 2), ' + 'max_shear_degree=2.0, ' + 'border=(-320, -320), ' + 'border_val=(114, 114, 114), ' + 'bbox_clip_border=True)')) + + +class TestYOLOXHSVRandomAug(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + self.results = { + 'img': + img, + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + } + + def test_transform(self): + transform = YOLOXHSVRandomAug() + results = transform(copy.deepcopy(self.results)) + self.assertTrue( + results['img'].shape[:2] == self.results['img'].shape[:2]) + self.assertTrue(results['gt_bboxes_labels'].shape[0] == + results['gt_bboxes'].shape[0]) + self.assertTrue(results['gt_bboxes_labels'].dtype == np.int64) + self.assertTrue(results['gt_bboxes'].dtype == np.float32) + self.assertTrue(results['gt_ignore_flags'].dtype == bool) + + def test_repr(self): + transform = YOLOXHSVRandomAug() + self.assertEqual( + repr(transform), ('YOLOXHSVRandomAug(hue_delta=5, ' + 'saturation_delta=30, ' + 'value_delta=30)')) + + +class TestRandomCenterCropPad(unittest.TestCase): + + def test_init(self): + # test assertion for invalid crop_size while test_mode=False + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=(-1, 0), test_mode=False, test_pad_mode=None) + + # test assertion for invalid ratios while test_mode=False + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=(511, 511), + ratios=(1.0, 1.0), + test_mode=False, + test_pad_mode=None) + + # test assertion for invalid mean, std and to_rgb + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=(511, 511), + mean=None, + std=None, + to_rgb=None, + test_mode=False, + test_pad_mode=None) + + # test assertion for invalid crop_size while test_mode=True + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=(511, 511), + ratios=None, + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + + # test assertion for invalid ratios while test_mode=True + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=None, + ratios=(0.9, 1.0, 1.1), + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + + # test assertion for invalid border while test_mode=True + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=None, + ratios=None, + border=128, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + + # test assertion for invalid test_pad_mode while test_mode=True + with self.assertRaises(AssertionError): + RandomCenterCropPad( + crop_size=None, + ratios=None, + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('do_nothing', 100)) + + def test_transform(self): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../../data/color.jpg')) + + load = LoadImageFromFile(to_float32=True) + results = load(results) + test_results = copy.deepcopy(results) + + h, w = results['img_shape'] + gt_bboxes = create_random_bboxes(4, w, h) + gt_bboxes_labels = np.array([1, 2, 3, 1], dtype=np.int64) + gt_ignore_flags = np.array([0, 0, 1, 1], dtype=bool) + results['gt_bboxes'] = gt_bboxes + results['gt_bboxes_labels'] = gt_bboxes_labels + results['gt_ignore_flags'] = gt_ignore_flags + crop_module = RandomCenterCropPad( + crop_size=(w - 20, h - 20), + ratios=(1.0, ), + border=128, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=False, + test_pad_mode=None) + train_results = crop_module(results) + assert train_results['img'].shape[:2] == (h - 20, w - 20) + # All bboxes should be reserved after crop + assert train_results['img_shape'][:2] == (h - 20, w - 20) + assert train_results['gt_bboxes'].shape[0] == 4 + assert train_results['gt_bboxes'].dtype == np.float32 + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + crop_module = RandomCenterCropPad( + crop_size=None, + ratios=None, + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + test_results = crop_module(test_results) + assert test_results['img'].shape[:2] == (h | 127, w | 127) + assert test_results['img_shape'][:2] == (h | 127, w | 127) + assert 'border' in test_results + + def test_transform_use_box_type(self): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../../data/color.jpg')) + + load = LoadImageFromFile(to_float32=True) + results = load(results) + test_results = copy.deepcopy(results) + + h, w = results['img_shape'] + gt_bboxes = create_random_bboxes(4, w, h) + gt_bboxes_labels = np.array([1, 2, 3, 1], dtype=np.int64) + gt_ignore_flags = np.array([0, 0, 1, 1], dtype=bool) + results['gt_bboxes'] = HorizontalBoxes(gt_bboxes) + results['gt_bboxes_labels'] = gt_bboxes_labels + results['gt_ignore_flags'] = gt_ignore_flags + crop_module = RandomCenterCropPad( + crop_size=(w - 20, h - 20), + ratios=(1.0, ), + border=128, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=False, + test_pad_mode=None) + train_results = crop_module(results) + assert train_results['img'].shape[:2] == (h - 20, w - 20) + # All bboxes should be reserved after crop + assert train_results['img_shape'][:2] == (h - 20, w - 20) + assert train_results['gt_bboxes'].shape[0] == 4 + assert train_results['gt_bboxes'].dtype == torch.float32 + + crop_module = RandomCenterCropPad( + crop_size=None, + ratios=None, + border=None, + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True, + test_mode=True, + test_pad_mode=('logical_or', 127)) + test_results = crop_module(test_results) + assert test_results['img'].shape[:2] == (h | 127, w | 127) + assert test_results['img_shape'][:2] == (h | 127, w | 127) + assert 'border' in test_results + + +class TestCopyPaste(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + h, w, _ = img.shape + dst_bboxes = np.array([[0.2 * w, 0.2 * h, 0.4 * w, 0.4 * h], + [0.5 * w, 0.5 * h, 0.6 * w, 0.6 * h]], + dtype=np.float32) + src_bboxes = np.array([[0.1 * w, 0.1 * h, 0.3 * w, 0.5 * h], + [0.4 * w, 0.4 * h, 0.7 * w, 0.7 * h], + [0.8 * w, 0.8 * h, 0.9 * w, 0.9 * h]], + dtype=np.float32) + + self.dst_results = { + 'img': img.copy(), + 'gt_bboxes': dst_bboxes, + 'gt_bboxes_labels': np.ones(dst_bboxes.shape[0], dtype=np.int64), + 'gt_masks': create_full_masks(dst_bboxes, w, h), + 'gt_ignore_flags': np.array([0, 1], dtype=bool), + } + self.src_results = { + 'img': img.copy(), + 'gt_bboxes': src_bboxes, + 'gt_bboxes_labels': + np.ones(src_bboxes.shape[0], dtype=np.int64) * 2, + 'gt_masks': create_full_masks(src_bboxes, w, h), + 'gt_ignore_flags': np.array([0, 0, 1], dtype=bool), + } + + def test_transform(self): + transform = CopyPaste(selected=False) + # test assertion for invalid mix_results + with self.assertRaises(AssertionError): + results = transform(copy.deepcopy(self.dst_results)) + + results = copy.deepcopy(self.dst_results) + results['mix_results'] = [copy.deepcopy(self.src_results)] + results = transform(results) + + self.assertEqual(results['img'].shape[:2], + self.dst_results['img'].shape[:2]) + + # one object of destination image is totally occluded + self.assertEqual( + results['gt_bboxes'].shape[0], + self.dst_results['gt_bboxes'].shape[0] + + self.src_results['gt_bboxes'].shape[0] - 1) + self.assertEqual( + results['gt_bboxes_labels'].shape[0], + self.dst_results['gt_bboxes_labels'].shape[0] + + self.src_results['gt_bboxes_labels'].shape[0] - 1) + self.assertEqual( + results['gt_masks'].masks.shape[0], + self.dst_results['gt_masks'].masks.shape[0] + + self.src_results['gt_masks'].masks.shape[0] - 1) + self.assertEqual( + results['gt_ignore_flags'].shape[0], + self.dst_results['gt_ignore_flags'].shape[0] + + self.src_results['gt_ignore_flags'].shape[0] - 1) + + # the object of destination image is partially occluded + ori_bbox = self.dst_results['gt_bboxes'][0] + occ_bbox = results['gt_bboxes'][0] + ori_mask = self.dst_results['gt_masks'].masks[0] + occ_mask = results['gt_masks'].masks[0] + self.assertTrue(ori_mask.sum() > occ_mask.sum()) + self.assertTrue( + np.all(np.abs(occ_bbox - ori_bbox) <= transform.bbox_occluded_thr) + or occ_mask.sum() > transform.mask_occluded_thr) + + # test copypaste with selected objects + transform = CopyPaste() + results = copy.deepcopy(self.dst_results) + results['mix_results'] = [copy.deepcopy(self.src_results)] + results = transform(results) + + # test copypaste with an empty source image + results = copy.deepcopy(self.dst_results) + valid_inds = [False] * self.src_results['gt_bboxes'].shape[0] + results['mix_results'] = [{ + 'img': + self.src_results['img'].copy(), + 'gt_bboxes': + self.src_results['gt_bboxes'][valid_inds], + 'gt_bboxes_labels': + self.src_results['gt_bboxes_labels'][valid_inds], + 'gt_masks': + self.src_results['gt_masks'][valid_inds], + 'gt_ignore_flags': + self.src_results['gt_ignore_flags'][valid_inds], + }] + results = transform(results) + + # test copypaste with an empty mask results + transform = CopyPaste() + results = copy.deepcopy(self.dst_results) + results = {k: v for k, v in results.items() if 'mask' not in k} + results['mix_results'] = [copy.deepcopy(self.src_results)] + with self.assertRaises(RuntimeError): + results = transform(results) + + # test copypaste with boxes as masks + transform = CopyPaste(paste_by_box=True) + results = copy.deepcopy(self.dst_results) + results = {k: v for k, v in results.items() if 'mask' not in k} + src_results = copy.deepcopy(self.src_results) + src_results = {k: v for k, v in src_results.items() if 'mask' not in k} + results['mix_results'] = [src_results] + results = transform(results) + + self.assertEqual(results['img'].shape[:2], + self.dst_results['img'].shape[:2]) + + def test_transform_use_box_type(self): + src_results = copy.deepcopy(self.src_results) + src_results['gt_bboxes'] = HorizontalBoxes(src_results['gt_bboxes']) + dst_results = copy.deepcopy(self.dst_results) + dst_results['gt_bboxes'] = HorizontalBoxes(dst_results['gt_bboxes']) + transform = CopyPaste(selected=False) + + results = copy.deepcopy(dst_results) + results['mix_results'] = [copy.deepcopy(src_results)] + results = transform(results) + + self.assertEqual(results['img'].shape[:2], + self.dst_results['img'].shape[:2]) + + # one object of destination image is totally occluded + self.assertEqual( + results['gt_bboxes'].shape[0], + self.dst_results['gt_bboxes'].shape[0] + + self.src_results['gt_bboxes'].shape[0] - 1) + self.assertEqual( + results['gt_bboxes_labels'].shape[0], + self.dst_results['gt_bboxes_labels'].shape[0] + + self.src_results['gt_bboxes_labels'].shape[0] - 1) + self.assertEqual( + results['gt_masks'].masks.shape[0], + self.dst_results['gt_masks'].masks.shape[0] + + self.src_results['gt_masks'].masks.shape[0] - 1) + self.assertEqual( + results['gt_ignore_flags'].shape[0], + self.dst_results['gt_ignore_flags'].shape[0] + + self.src_results['gt_ignore_flags'].shape[0] - 1) + + # the object of destination image is partially occluded + ori_bbox = dst_results['gt_bboxes'][0].numpy() + occ_bbox = results['gt_bboxes'][0].numpy() + ori_mask = dst_results['gt_masks'].masks[0] + occ_mask = results['gt_masks'].masks[0] + self.assertTrue(ori_mask.sum() > occ_mask.sum()) + self.assertTrue( + np.all(np.abs(occ_bbox - ori_bbox) <= transform.bbox_occluded_thr) + or occ_mask.sum() > transform.mask_occluded_thr) + + # test copypaste with selected objects + transform = CopyPaste() + results = copy.deepcopy(dst_results) + results['mix_results'] = [copy.deepcopy(src_results)] + results = transform(results) + + # test copypaste with an empty source image + results = copy.deepcopy(dst_results) + valid_inds = [False] * self.src_results['gt_bboxes'].shape[0] + results['mix_results'] = [{ + 'img': + src_results['img'].copy(), + 'gt_bboxes': + src_results['gt_bboxes'][valid_inds], + 'gt_bboxes_labels': + src_results['gt_bboxes_labels'][valid_inds], + 'gt_masks': + src_results['gt_masks'][valid_inds], + 'gt_ignore_flags': + src_results['gt_ignore_flags'][valid_inds], + }] + results = transform(results) + + def test_repr(self): + transform = CopyPaste() + self.assertEqual( + repr(transform), ('CopyPaste(max_num_pasted=100, ' + 'bbox_occluded_thr=10, ' + 'mask_occluded_thr=300, ' + 'selected=True), ' + 'paste_by_box=False)')) + + +class TestAlbu(unittest.TestCase): + + @unittest.skipIf(albumentations is None, 'albumentations is not installed') + def test_transform(self): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../../data/color.jpg')) + + # Define simple pipeline + load = dict(type='LoadImageFromFile') + load = TRANSFORMS.build(load) + + albu_transform = dict( + type='Albu', transforms=[dict(type='ChannelShuffle', p=1)]) + albu_transform = TRANSFORMS.build(albu_transform) + + # Execute transforms + results = load(results) + results = albu_transform(results) + + self.assertEqual(results['img'].dtype, np.uint8) + + # test bbox + albu_transform = dict( + type='Albu', + transforms=[dict(type='ChannelShuffle', p=1)], + bbox_params=dict( + type='BboxParams', + format='pascal_voc', + label_fields=['gt_bboxes_labels', 'gt_ignore_flags']), + keymap={ + 'img': 'image', + 'gt_bboxes': 'bboxes' + }) + albu_transform = TRANSFORMS.build(albu_transform) + results = { + 'img': + np.random.random((224, 224, 3)), + 'img_shape': (224, 224), + 'gt_bboxes_labels': + np.array([1, 2, 3], dtype=np.int64), + 'gt_bboxes': + np.array([[10, 10, 20, 20], [20, 20, 40, 40], [40, 40, 80, 80]], + dtype=np.float32), + 'gt_ignore_flags': + np.array([0, 0, 1], dtype=bool), + } + results = albu_transform(results) + self.assertEqual(results['img'].dtype, np.float64) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + self.assertEqual(results['gt_ignore_flags'].dtype, bool) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + self.assertEqual(results['img_shape'], results['img'].shape[:2]) + + @unittest.skipIf(albumentations is None, 'albumentations is not installed') + def test_repr(self): + albu_transform = dict( + type='Albu', transforms=[dict(type='ChannelShuffle', p=1)]) + albu_transform = TRANSFORMS.build(albu_transform) + + self.assertEqual( + repr(albu_transform), 'Albu(transforms=[' + '{\'type\': \'ChannelShuffle\', ' + '\'p\': 1}])') + + +class TestCorrupt(unittest.TestCase): + + def test_transform(self): + results = dict( + img_path=osp.join(osp.dirname(__file__), '../../data/color.jpg')) + + # Define simple pipeline + load = dict(type='LoadImageFromFile') + load = TRANSFORMS.build(load) + + corrupt_transform = dict(type='Corrupt', corruption='gaussian_blur') + corrupt_transform = TRANSFORMS.build(corrupt_transform) + + # Execute transforms + results = load(results) + results = corrupt_transform(results) + + self.assertEqual(results['img'].dtype, np.uint8) + + def test_repr(self): + corrupt_transform = dict(type='Corrupt', corruption='gaussian_blur') + corrupt_transform = TRANSFORMS.build(corrupt_transform) + + self.assertEqual( + repr(corrupt_transform), 'Corrupt(corruption=gaussian_blur, ' + 'severity=1)') + + +class TestRandomShift(unittest.TestCase): + + def test_init(self): + # test assertion for invalid shift_ratio + with self.assertRaises(AssertionError): + RandomShift(prob=1.5) + + # test assertion for invalid max_shift_px + with self.assertRaises(AssertionError): + RandomShift(max_shift_px=-1) + + def test_transform(self): + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + results['img'] = img + h, w, _ = img.shape + gt_bboxes = create_random_bboxes(8, w, h) + results['gt_bboxes_labels'] = np.ones( + gt_bboxes.shape[0], dtype=np.int64) + results['gt_bboxes'] = gt_bboxes + transform = RandomShift(prob=1.0) + results = transform(results) + + self.assertEqual(results['img'].shape[:2], (h, w)) + self.assertEqual(results['gt_bboxes_labels'].shape[0], + results['gt_bboxes'].shape[0]) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + self.assertEqual(results['gt_bboxes'].dtype, np.float32) + + def test_transform_use_box_type(self): + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../../data/color.jpg'), 'color') + results['img'] = img + h, w, _ = img.shape + gt_bboxes = create_random_bboxes(8, w, h) + results['gt_bboxes_labels'] = np.ones( + gt_bboxes.shape[0], dtype=np.int64) + results['gt_bboxes'] = HorizontalBoxes(gt_bboxes) + transform = RandomShift(prob=1.0) + results = transform(results) + + self.assertEqual(results['img'].shape[:2], (h, w)) + self.assertEqual(results['gt_bboxes_labels'].shape[0], + results['gt_bboxes'].shape[0]) + self.assertEqual(results['gt_bboxes_labels'].dtype, np.int64) + self.assertEqual(results['gt_bboxes'].dtype, torch.float32) + + def test_repr(self): + transform = RandomShift() + self.assertEqual( + repr(transform), ('RandomShift(prob=0.5, ' + 'max_shift_px=32, ' + 'filter_thr_px=1)')) + + +class TestRandomErasing(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.results = construct_toy_data(poly2mask=True) + + def test_transform(self): + transform = RandomErasing( + n_patches=(1, 5), ratio=(0.4, 0.8), img_border_value=0) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() < self.results['img'].sum()) + + transform = RandomErasing( + n_patches=1, ratio=0.999, img_border_value=255) + results = transform(copy.deepcopy(self.results)) + self.assertTrue(results['img'].sum() > self.results['img'].sum()) + # test empty results + empty_results = copy.deepcopy(self.results) + empty_results['gt_bboxes'] = np.zeros((0, 4), dtype=np.float32) + empty_results['gt_bboxes_labels'] = np.zeros((0, ), dtype=np.int64) + empty_results['gt_masks'] = empty_results['gt_masks'][False] + empty_results['gt_ignore_flags'] = np.zeros((0, ), dtype=bool) + empty_results['gt_seg_map'] = np.ones_like( + empty_results['gt_seg_map']) * 255 + results = transform(copy.deepcopy(empty_results)) + self.assertTrue(results['img'].sum() > self.results['img'].sum()) + + def test_transform_use_box_type(self): + src_results = copy.deepcopy(self.results) + src_results['gt_bboxes'] = HorizontalBoxes(src_results['gt_bboxes']) + + transform = RandomErasing( + n_patches=(1, 5), ratio=(0.4, 0.8), img_border_value=0) + results = transform(copy.deepcopy(src_results)) + self.assertTrue(results['img'].sum() < src_results['img'].sum()) + + transform = RandomErasing( + n_patches=1, ratio=0.999, img_border_value=255) + results = transform(copy.deepcopy(src_results)) + self.assertTrue(results['img'].sum() > src_results['img'].sum()) + # test empty results + empty_results = copy.deepcopy(src_results) + empty_results['gt_bboxes'] = HorizontalBoxes([], dtype=torch.float32) + empty_results['gt_bboxes_labels'] = np.zeros((0, ), dtype=np.int64) + empty_results['gt_masks'] = empty_results['gt_masks'][False] + empty_results['gt_ignore_flags'] = np.zeros((0, ), dtype=bool) + empty_results['gt_seg_map'] = np.ones_like( + empty_results['gt_seg_map']) * 255 + results = transform(copy.deepcopy(empty_results)) + self.assertTrue(results['img'].sum() > src_results['img'].sum()) + + def test_repr(self): + transform = RandomErasing(n_patches=(1, 5), ratio=(0, 0.2)) + self.assertEqual( + repr(transform), ('RandomErasing(n_patches=(1, 5), ' + 'ratio=(0, 0.2), ' + 'squared=True, ' + 'bbox_erased_thr=0.9, ' + 'img_border_value=128, ' + 'mask_border_value=0, ' + 'seg_ignore_label=255)')) + + +class TestResizeShortestEdge(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() + -> tearDown() -> cleanUp() + """ + rng = np.random.RandomState(0) + self.data_info = dict( + img=np.random.random((220, 100, 3)), + gt_seg_map=np.random.random((220, 100, 3)), + gt_bboxes=np.array([[0, 0, 112, 12]], dtype=np.float32), + gt_masks=BitmapMasks(rng.rand(1, 220, 100), height=220, width=100)) + + def test_resize(self): + transform = ResizeShortestEdge(scale=200) + results = transform(copy.deepcopy(self.data_info)) + self.assertEqual(results['img_shape'], (440, 200)) + self.assertEqual(results['scale_factor'], (200 / 100, 440 / 220)) + + transform = ResizeShortestEdge(scale=200, max_size=301) + results = transform(copy.deepcopy(self.data_info)) + self.assertEqual(results['img_shape'], (301, 137)) + self.assertEqual(results['scale_factor'], (137 / 100, 301 / 220)) + + transform = ResizeShortestEdge(scale=201, keep_ratio=True) + results = transform(copy.deepcopy(self.data_info)) + self.assertEqual(results['img_shape'], (442, 201)) + self.assertEqual(results['scale_factor'], (201 / 100, 442 / 220)) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_wrappers.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..4232fac1d4bb110953b7ce012f3e6ee92320f2e0 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/test_wrappers.py @@ -0,0 +1,173 @@ +import copy +import os.path as osp +import unittest + +from mmcv.transforms import Compose + +from mmdet.datasets.transforms import MultiBranch, RandomOrder +from mmdet.utils import register_all_modules +from .utils import construct_toy_data + +register_all_modules() + + +class TestMultiBranch(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + data_prefix = osp.join(osp.dirname(__file__), '../../data') + img_path = osp.join(data_prefix, 'color.jpg') + seg_map = osp.join(data_prefix, 'gray.jpg') + self.meta_keys = ('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor', 'flip', 'flip_direction', + 'homography_matrix') + self.results = { + 'img_path': + img_path, + 'img_id': + 12345, + 'img_shape': (300, 400), + 'seg_map_path': + seg_map, + 'instances': [{ + 'bbox': [0, 0, 10, 20], + 'bbox_label': 1, + 'mask': [[0, 0, 0, 20, 10, 20, 10, 0]], + 'ignore_flag': 0 + }, { + 'bbox': [10, 10, 110, 120], + 'bbox_label': 2, + 'mask': [[10, 10, 110, 10, 110, 120, 110, 10]], + 'ignore_flag': 0 + }, { + 'bbox': [50, 50, 60, 80], + 'bbox_label': 2, + 'mask': [[50, 50, 60, 50, 60, 80, 50, 80]], + 'ignore_flag': 1 + }] + } + self.branch_field = ['sup', 'sup_teacher', 'sup_student'] + self.weak_pipeline = [ + dict(type='ShearX'), + dict(type='PackDetInputs', meta_keys=self.meta_keys) + ] + self.strong_pipeline = [ + dict(type='ShearX'), + dict(type='ShearY'), + dict(type='PackDetInputs', meta_keys=self.meta_keys) + ] + self.labeled_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='LoadAnnotations', + with_bbox=True, + with_mask=True, + with_seg=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='MultiBranch', + branch_field=self.branch_field, + sup_teacher=self.weak_pipeline, + sup_student=self.strong_pipeline), + ] + self.unlabeled_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='MultiBranch', + branch_field=self.branch_field, + unsup_teacher=self.weak_pipeline, + unsup_student=self.strong_pipeline), + ] + + def test_transform(self): + labeled_pipeline = Compose(self.labeled_pipeline) + labeled_results = labeled_pipeline(copy.deepcopy(self.results)) + unlabeled_pipeline = Compose(self.unlabeled_pipeline) + unlabeled_results = unlabeled_pipeline(copy.deepcopy(self.results)) + + # test branch sup_teacher and sup_student + sup_branches = ['sup_teacher', 'sup_student'] + for branch in sup_branches: + self.assertIn(branch, labeled_results['data_samples']) + self.assertIn('homography_matrix', + labeled_results['data_samples'][branch]) + self.assertIn('labels', + labeled_results['data_samples'][branch].gt_instances) + self.assertIn('bboxes', + labeled_results['data_samples'][branch].gt_instances) + self.assertIn('masks', + labeled_results['data_samples'][branch].gt_instances) + self.assertIn('gt_sem_seg', + labeled_results['data_samples'][branch]) + # test branch unsup_teacher and unsup_student + unsup_branches = ['unsup_teacher', 'unsup_student'] + for branch in unsup_branches: + self.assertIn(branch, unlabeled_results['data_samples']) + self.assertIn('homography_matrix', + unlabeled_results['data_samples'][branch]) + self.assertNotIn( + 'labels', + unlabeled_results['data_samples'][branch].gt_instances) + self.assertNotIn( + 'bboxes', + unlabeled_results['data_samples'][branch].gt_instances) + self.assertNotIn( + 'masks', + unlabeled_results['data_samples'][branch].gt_instances) + self.assertNotIn('gt_sem_seg', + unlabeled_results['data_samples'][branch]) + + def test_repr(self): + pipeline = [dict(type='PackDetInputs', meta_keys=())] + transform = MultiBranch( + branch_field=self.branch_field, sup=pipeline, unsup=pipeline) + self.assertEqual( + repr(transform), + ("MultiBranch(branch_pipelines=['sup', 'unsup'])")) + + +class TestRandomOrder(unittest.TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.results = construct_toy_data(poly2mask=True) + self.pipeline = [ + dict(type='Sharpness'), + dict(type='Contrast'), + dict(type='Brightness'), + dict(type='Rotate'), + dict(type='ShearX'), + dict(type='TranslateY') + ] + + def test_transform(self): + transform = RandomOrder(self.pipeline) + results = transform(copy.deepcopy(self.results)) + self.assertEqual(results['img_shape'], self.results['img_shape']) + self.assertEqual(results['gt_bboxes'].shape, + self.results['gt_bboxes'].shape) + self.assertEqual(results['gt_bboxes_labels'], + self.results['gt_bboxes_labels']) + self.assertEqual(results['gt_ignore_flags'], + self.results['gt_ignore_flags']) + self.assertEqual(results['gt_masks'].masks.shape, + self.results['gt_masks'].masks.shape) + self.assertEqual(results['gt_seg_map'].shape, + self.results['gt_seg_map'].shape) + + def test_repr(self): + transform = RandomOrder(self.pipeline) + self.assertEqual( + repr(transform), ('RandomOrder(Sharpness, Contrast, ' + 'Brightness, Rotate, ShearX, TranslateY, )')) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_transforms/utils.py b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9c81f568e72603b2649fa8c6dfe78ce595af8939 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_transforms/utils.py @@ -0,0 +1,76 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +from mmengine.testing import assert_allclose + +from mmdet.structures.bbox import BaseBoxes, HorizontalBoxes +from mmdet.structures.mask import BitmapMasks, PolygonMasks + + +def create_random_bboxes(num_bboxes, img_w, img_h): + bboxes_left_top = np.random.uniform(0, 0.5, size=(num_bboxes, 2)) + bboxes_right_bottom = np.random.uniform(0.5, 1, size=(num_bboxes, 2)) + bboxes = np.concatenate((bboxes_left_top, bboxes_right_bottom), 1) + bboxes = (bboxes * np.array([img_w, img_h, img_w, img_h])).astype( + np.float32) + return bboxes + + +def create_full_masks(gt_bboxes, img_w, img_h): + xmin, ymin = gt_bboxes[:, 0:1], gt_bboxes[:, 1:2] + xmax, ymax = gt_bboxes[:, 2:3], gt_bboxes[:, 3:4] + gt_masks = np.zeros((len(gt_bboxes), img_h, img_w), dtype=np.uint8) + for i in range(len(gt_bboxes)): + gt_masks[i, int(ymin[i]):int(ymax[i]), int(xmin[i]):int(xmax[i])] = 1 + gt_masks = BitmapMasks(gt_masks, img_h, img_w) + return gt_masks + + +def construct_toy_data(poly2mask, use_box_type=False): + img = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], + dtype=np.uint8) + img = np.stack([img, img, img], axis=-1) + results = dict() + results['img'] = img + results['img_shape'] = img.shape[:2] + if use_box_type: + results['gt_bboxes'] = HorizontalBoxes( + np.array([[1, 0, 2, 2]], dtype=np.float32)) + else: + results['gt_bboxes'] = np.array([[1, 0, 2, 2]], dtype=np.float32) + results['gt_bboxes_labels'] = np.array([13], dtype=np.int64) + if poly2mask: + gt_masks = np.array([[0, 1, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0]], + dtype=np.uint8)[None, :, :] + results['gt_masks'] = BitmapMasks(gt_masks, 3, 4) + else: + raw_masks = [[np.array([1, 2, 1, 0, 2, 1], dtype=np.float32)]] + results['gt_masks'] = PolygonMasks(raw_masks, 3, 4) + results['gt_ignore_flags'] = np.array(np.array([1], dtype=bool)) + results['gt_seg_map'] = np.array( + [[255, 13, 255, 255], [255, 13, 13, 255], [255, 13, 255, 255]], + dtype=np.uint8) + return results + + +def check_result_same(results, pipeline_results, check_keys): + """Check whether the ``pipeline_results`` is the same with the predefined + ``results``. + + Args: + results (dict): Predefined results which should be the standard + output of the transform pipeline. + pipeline_results (dict): Results processed by the transform + pipeline. + check_keys (tuple): Keys that need to be checked between + results and pipeline_results. + """ + for key in check_keys: + if results.get(key, None) is None: + continue + if isinstance(results[key], (BitmapMasks, PolygonMasks)): + assert_allclose(pipeline_results[key].to_ndarray(), + results[key].to_ndarray()) + elif isinstance(results[key], BaseBoxes): + assert_allclose(pipeline_results[key].tensor, results[key].tensor) + else: + assert_allclose(pipeline_results[key], results[key]) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_tta.py b/mmdet_code/mmdetection/tests/test_datasets/test_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a5f23b09813f33394fbdd106b16657f203a231 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_tta.py @@ -0,0 +1,177 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from unittest import TestCase + +import mmcv +import pytest + +from mmdet.datasets.transforms import * # noqa +from mmdet.registry import TRANSFORMS + + +class TestMuitiScaleFlipAug(TestCase): + + def test_exception(self): + with pytest.raises(TypeError): + tta_transform = dict( + type='TestTimeAug', + transforms=[dict(type='Resize', keep_ratio=False)], + ) + TRANSFORMS.build(tta_transform) + + def test_multi_scale_flip_aug(self): + tta_transform = dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=scale, keep_ratio=False) + for scale in [(256, 256), (512, 512), (1024, 1024)] + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor')) + ]]) + tta_module = TRANSFORMS.build(tta_transform) + + results = dict() + img = mmcv.imread( + osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color') + results['img_id'] = '1' + results['img_path'] = 'data/color.jpg' + results['img'] = img + results['ori_shape'] = img.shape + results['ori_height'] = img.shape[0] + results['ori_width'] = img.shape[1] + # Set initial values for default meta_keys + results['pad_shape'] = img.shape + results['scale_factor'] = 1.0 + + tta_results = tta_module(results.copy()) + assert [img.shape + for img in tta_results['inputs']] == [(3, 256, 256), + (3, 512, 512), + (3, 1024, 1024)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [ + dict(type='Resize', scale=scale, keep_ratio=False) + for scale in [(256, 256), (512, 512), (1024, 1024)] + ], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results: dict = tta_module(results.copy()) + assert [img.shape + for img in tta_results['inputs']] == [(3, 256, 256), + (3, 256, 256), + (3, 512, 512), + (3, 512, 512), + (3, 1024, 1024), + (3, 1024, 1024)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True, False, True, False, True] + + tta_transform = dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale=(512, 512), keep_ratio=False) + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor')) + ]]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [tta_results['inputs'][0].shape] == [(3, 512, 512)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [dict(type='Resize', scale=(512, 512), keep_ratio=False)], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 512, 512), + (3, 512, 512)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True] + + tta_transform = dict( + type='TestTimeAug', + transforms=[[ + dict(type='Resize', scale_factor=r, keep_ratio=False) + for r in [0.5, 1.0, 2.0] + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor')) + ]]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 144, 256), + (3, 288, 512), + (3, 576, 1024)] + + tta_transform = dict( + type='TestTimeAug', + transforms=[ + [ + dict(type='Resize', scale_factor=r, keep_ratio=True) + for r in [0.5, 1.0, 2.0] + ], + [ + dict(type='RandomFlip', prob=0., direction='horizontal'), + dict(type='RandomFlip', prob=1., direction='horizontal') + ], + [ + dict( + type='mmdet.PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', + 'img_shape', 'scale_factor', 'flip', + 'flip_direction')) + ] + ]) + tta_module = TRANSFORMS.build(tta_transform) + tta_results = tta_module(results.copy()) + assert [img.shape for img in tta_results['inputs']] == [(3, 144, 256), + (3, 144, 256), + (3, 288, 512), + (3, 288, 512), + (3, 576, 1024), + (3, 576, 1024)] + assert [ + data_sample.metainfo['flip'] + for data_sample in tta_results['data_samples'] + ] == [False, True, False, True, False, True] diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_wider_face.py b/mmdet_code/mmdetection/tests/test_datasets/test_wider_face.py new file mode 100644 index 0000000000000000000000000000000000000000..aad3869b005e290310a73fa8fe40dd532bcc5040 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_wider_face.py @@ -0,0 +1,28 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import cv2 +import numpy as np + +from mmdet.datasets import WIDERFaceDataset + + +class TestWIDERFaceDataset(unittest.TestCase): + + def setUp(self) -> None: + img_path = 'tests/data/WIDERFace/WIDER_train/0--Parade/0_Parade_marchingband_1_5.jpg' # noqa: E501 + dummy_img = np.zeros((683, 1024, 3), dtype=np.uint8) + cv2.imwrite(img_path, dummy_img) + + def test_wider_face_dataset(self): + dataset = WIDERFaceDataset( + data_root='tests/data/WIDERFace', + ann_file='train.txt', + data_prefix=dict(img='WIDER_train'), + pipeline=[]) + dataset.full_init() + self.assertEqual(len(dataset), 1) + + data_list = dataset.load_data_list() + self.assertEqual(len(data_list), 1) + self.assertEqual(len(data_list[0]['instances']), 10) diff --git a/mmdet_code/mmdetection/tests/test_datasets/test_youtube_vis_dataset.py b/mmdet_code/mmdetection/tests/test_datasets/test_youtube_vis_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..6a32a0c1b79d42806e2ef1898f72ebb1e57ec9f1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_datasets/test_youtube_vis_dataset.py @@ -0,0 +1,17 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +from mmdet.datasets import YouTubeVISDataset + + +class TestYouTubeVISDataset(TestCase): + + @classmethod + def setUpClass(cls): + + cls.dataset = YouTubeVISDataset( + ann_file='tests/data/vis_sample.json', dataset_version='2019') + + def test_set_dataset_classes(self): + assert isinstance(self.dataset.metainfo, dict) + assert len(self.dataset.metainfo['classes']) == 40 diff --git a/mmdet_code/mmdetection/tests/test_engine/__init__.py b/mmdet_code/mmdetection/tests/test_engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_checkloss_hook.py b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_checkloss_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..3164f7328e9040f0a3fcf2e18a39832003e924e5 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_checkloss_hook.py @@ -0,0 +1,37 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock + +import torch + +from mmdet.engine.hooks import CheckInvalidLossHook + + +class TestCheckInvalidLossHook(TestCase): + + def test_after_train_iter(self): + n = 50 + hook = CheckInvalidLossHook(n) + runner = Mock() + runner.logger = Mock() + runner.logger.info = Mock() + + # Test `after_train_iter` function within the n iteration. + runner.iter = 10 + outputs = dict(loss=torch.LongTensor([2])) + hook.after_train_iter(runner, 10, outputs=outputs) + outputs = dict(loss=torch.tensor(float('nan'))) + hook.after_train_iter(runner, 10, outputs=outputs) + outputs = dict(loss=torch.tensor(float('inf'))) + hook.after_train_iter(runner, 10, outputs=outputs) + + # Test `after_train_iter` at the n iteration. + runner.iter = n - 1 + outputs = dict(loss=torch.LongTensor([2])) + hook.after_train_iter(runner, n - 1, outputs=outputs) + outputs = dict(loss=torch.tensor(float('nan'))) + with self.assertRaises(AssertionError): + hook.after_train_iter(runner, n - 1, outputs=outputs) + outputs = dict(loss=torch.tensor(float('inf'))) + with self.assertRaises(AssertionError): + hook.after_train_iter(runner, n - 1, outputs=outputs) diff --git a/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_mean_teacher_hook.py b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_mean_teacher_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..41d056e4071a70f8b02e6caa39620dbd6cc02e71 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_mean_teacher_hook.py @@ -0,0 +1,175 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile +from unittest import TestCase + +import torch +import torch.nn as nn +from mmengine.evaluator import BaseMetric +from mmengine.model import BaseModel +from mmengine.optim import OptimWrapper +from mmengine.registry import MODEL_WRAPPERS +from mmengine.runner import Runner +from torch.utils.data import Dataset + +from mmdet.registry import DATASETS +from mmdet.utils import register_all_modules + +register_all_modules() + + +class ToyModel(nn.Module): + + def __init__(self): + super().__init__() + self.linear = nn.Linear(2, 1) + + def forward(self, inputs, data_samples, mode='tensor'): + labels = torch.stack(data_samples) + inputs = torch.stack(inputs) + outputs = self.linear(inputs) + if mode == 'tensor': + return outputs + elif mode == 'loss': + loss = (labels - outputs).sum() + outputs = dict(loss=loss) + return outputs + else: + return outputs + + +class ToyModel1(BaseModel, ToyModel): + + def __init__(self): + super().__init__() + + def forward(self, *args, **kwargs): + return super(BaseModel, self).forward(*args, **kwargs) + + +class ToyModel2(BaseModel): + + def __init__(self): + super().__init__() + self.teacher = ToyModel1() + self.student = ToyModel1() + + def forward(self, *args, **kwargs): + return self.student(*args, **kwargs) + + +@DATASETS.register_module(force=True) +class DummyDataset(Dataset): + METAINFO = dict() # type: ignore + data = torch.randn(12, 2) + label = torch.ones(12) + + @property + def metainfo(self): + return self.METAINFO + + def __len__(self): + return self.data.size(0) + + def __getitem__(self, index): + return dict(inputs=self.data[index], data_samples=self.label[index]) + + +class ToyMetric1(BaseMetric): + + def __init__(self, collect_device='cpu', dummy_metrics=None): + super().__init__(collect_device=collect_device) + self.dummy_metrics = dummy_metrics + + def process(self, data_batch, predictions): + result = {'acc': 1} + self.results.append(result) + + def compute_metrics(self, results): + return dict(acc=1) + + +class TestMeanTeacherHook(TestCase): + + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.temp_dir.cleanup() + + def test_mean_teacher_hook(self): + device = 'cuda:0' if torch.cuda.is_available() else 'cpu' + model = ToyModel2().to(device) + runner = Runner( + model=model, + train_dataloader=dict( + dataset=DummyDataset(), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=3, + num_workers=0), + val_dataloader=dict( + dataset=DummyDataset(), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=0), + val_evaluator=[ToyMetric1()], + work_dir=self.temp_dir.name, + default_scope='mmdet', + optim_wrapper=OptimWrapper( + torch.optim.Adam(ToyModel().parameters())), + train_cfg=dict(by_epoch=True, max_epochs=2, val_interval=1), + val_cfg=dict(), + default_hooks=dict(logger=None), + custom_hooks=[dict(type='MeanTeacherHook')], + experiment_name='test1') + runner.train() + + self.assertTrue( + osp.exists(osp.join(self.temp_dir.name, 'epoch_2.pth'))) + # checkpoint = torch.load(osp.join(self.temp_dir.name, 'epoch_2.pth')) + + # load and testing + runner = Runner( + model=model, + test_dataloader=dict( + dataset=DummyDataset(), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=3, + num_workers=0), + test_evaluator=[ToyMetric1()], + test_cfg=dict(), + work_dir=self.temp_dir.name, + default_scope='mmdet', + load_from=osp.join(self.temp_dir.name, 'epoch_2.pth'), + default_hooks=dict(logger=None), + custom_hooks=[dict(type='MeanTeacherHook')], + experiment_name='test2') + runner.test() + + @MODEL_WRAPPERS.register_module() + class DummyWrapper(BaseModel): + + def __init__(self, model): + super().__init__() + self.module = model + + def forward(self, *args, **kwargs): + return self.module(*args, **kwargs) + + # with model wrapper + runner = Runner( + model=DummyWrapper(ToyModel2()), + test_dataloader=dict( + dataset=DummyDataset(), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=3, + num_workers=0), + test_evaluator=[ToyMetric1()], + test_cfg=dict(), + work_dir=self.temp_dir.name, + default_scope='mmdet', + load_from=osp.join(self.temp_dir.name, 'epoch_2.pth'), + default_hooks=dict(logger=None), + custom_hooks=[dict(type='MeanTeacherHook')], + experiment_name='test3') + runner.test() diff --git a/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_memory_profiler_hook.py b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_memory_profiler_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9711840f9662c01b7e7adfab2bf039e65f13e2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_memory_profiler_hook.py @@ -0,0 +1,38 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock + +from mmdet.engine.hooks import MemoryProfilerHook + + +class TestMemoryProfilerHook(TestCase): + + def test_after_train_iter(self): + hook = MemoryProfilerHook(2) + runner = Mock() + runner.logger = Mock() + runner.logger.info = Mock() + hook.after_train_iter(runner, 0) + runner.logger.info.assert_not_called() + hook.after_train_iter(runner, 1) + runner.logger.info.assert_called_once() + + def test_after_val_iter(self): + hook = MemoryProfilerHook(2) + runner = Mock() + runner.logger = Mock() + runner.logger.info = Mock() + hook.after_val_iter(runner, 0) + runner.logger.info.assert_not_called() + hook.after_val_iter(runner, 1) + runner.logger.info.assert_called_once() + + def test_after_test_iter(self): + hook = MemoryProfilerHook(2) + runner = Mock() + runner.logger = Mock() + runner.logger.info = Mock() + hook.after_test_iter(runner, 0) + runner.logger.info.assert_not_called() + hook.after_test_iter(runner, 1) + runner.logger.info.assert_called_once() diff --git a/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_num_class_check_hook.py b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_num_class_check_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..f2cd7a6d2eb3a3ec428e68e3f0ca23a8048dede8 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_num_class_check_hook.py @@ -0,0 +1,106 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from copy import deepcopy +from unittest import TestCase +from unittest.mock import Mock + +from mmcv.cnn import VGG +from mmengine.dataset import BaseDataset +from torch import nn + +from mmdet.engine.hooks import NumClassCheckHook +from mmdet.models.roi_heads.mask_heads import FusedSemanticHead + + +class TestNumClassCheckHook(TestCase): + + def setUp(self): + # Setup NumClassCheckHook + hook = NumClassCheckHook() + self.hook = hook + + # Setup runner mock + runner = Mock() + runner.model = Mock() + runner.logger = Mock() + runner.logger.warning = Mock() + runner.train_dataloader = Mock() + runner.val_dataloader = Mock() + self.runner = runner + + # Setup dataset + metainfo = dict(classes=None) + self.none_classmeta_dataset = BaseDataset( + metainfo=metainfo, lazy_init=True) + metainfo = dict(classes='class_name') + self.str_classmeta_dataset = BaseDataset( + metainfo=metainfo, lazy_init=True) + metainfo = dict(classes=('bus', 'car')) + self.normal_classmeta_dataset = BaseDataset( + metainfo=metainfo, lazy_init=True) + + # Setup valid model + valid_model = nn.Module() + valid_model.add_module('backbone', VGG(depth=11)) + fused_semantic_head = FusedSemanticHead( + num_ins=1, + fusion_level=0, + num_convs=1, + in_channels=1, + conv_out_channels=1) + valid_model.add_module('semantic_head', fused_semantic_head) + rpn_head = nn.Module() + rpn_head.num_classes = 1 + valid_model.add_module('rpn_head', rpn_head) + bbox_head = nn.Module() + bbox_head.num_classes = 2 + valid_model.add_module('bbox_head', bbox_head) + self.valid_model = valid_model + + # Setup invalid model + invalid_model = nn.Module() + bbox_head = nn.Module() + bbox_head.num_classes = 4 + invalid_model.add_module('bbox_head', bbox_head) + self.invalid_model = invalid_model + + def test_before_train_epch(self): + runner = deepcopy(self.runner) + + # Test when dataset.metainfo['classes'] is None + runner.train_dataloader.dataset = self.none_classmeta_dataset + self.hook.before_train_epoch(runner) + runner.logger.warning.assert_called_once() + # Test when dataset.metainfo['classes'] is a str + runner.train_dataloader.dataset = self.str_classmeta_dataset + with self.assertRaises(AssertionError): + self.hook.before_train_epoch(runner) + + runner.train_dataloader.dataset = self.normal_classmeta_dataset + # Test `num_classes` of model is compatible with dataset + runner.model = self.valid_model + self.hook.before_train_epoch(runner) + # Test `num_classes` of model is not compatible with dataset + runner.model = self.invalid_model + with self.assertRaises(AssertionError): + self.hook.before_train_epoch(runner) + + def test_before_val_epoch(self): + runner = deepcopy(self.runner) + + # Test when dataset.metainfo['classes'] is None + runner.val_dataloader.dataset = self.none_classmeta_dataset + self.hook.before_val_epoch(runner) + runner.logger.warning.assert_called_once() + # Test when dataset.metainfo['classes'] is a str + runner.val_dataloader.dataset = self.str_classmeta_dataset + with self.assertRaises(AssertionError): + self.hook.before_val_epoch(runner) + + runner.val_dataloader.dataset = self.normal_classmeta_dataset + # Test `num_classes` of model is compatible with dataset + runner.model = self.valid_model + self.hook.before_val_epoch(runner) + # Test `num_classes` of model is not compatible with dataset + runner.model = self.invalid_model + with self.assertRaises(AssertionError): + self.hook.before_val_epoch(runner) diff --git a/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_pipeline_switch_hook.py b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_pipeline_switch_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..067812c0d973eb39e3a603ae4558d9f4edf9f80a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_pipeline_switch_hook.py @@ -0,0 +1,84 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock + +from mmdet.engine.hooks import PipelineSwitchHook + + +class TestPipelineSwitchHook(TestCase): + + def test_persistent_workers_on(self): + runner = Mock() + runner.model = Mock() + runner.model.module = Mock() + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = True + runner.train_dataloader._DataLoader__initialized = True + + stage2 = [dict(type='RandomResize', scale=(1280, 1280))] + + runner.epoch = 284 # epoch < switch_epoch + hook = PipelineSwitchHook(switch_epoch=285, switch_pipeline=stage2) + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + runner.epoch = 285 # epoch == switch_epoch + hook.before_train_epoch(runner) + self.assertTrue(hook._restart_dataloader) + self.assertFalse(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) + + runner.epoch = 286 # epoch > switch_epoch + hook.before_train_epoch(runner) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) + + def test_persistent_workers_off(self): + runner = Mock() + runner.model = Mock() + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = False + runner.train_dataloader._DataLoader__initialized = True + + stage2 = [dict(type='RandomResize', scale=(1280, 1280))] + + runner.epoch = 284 # epoch < switch_epoch + hook = PipelineSwitchHook(switch_epoch=285, switch_pipeline=stage2) + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + runner.epoch = 285 # epoch == switch_epoch + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) + + runner.epoch = 286 # epoch > switch_epoch + hook.before_train_epoch(runner) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) + + def test_initialize_after_switching(self): + # This simulates the resumption after the switching. + runner = Mock() + runner.model = Mock() + runner.model.module = Mock() + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = True + runner.train_dataloader._DataLoader__initialized = True + + stage2 = [dict(type='RandomResize', scale=(1280, 1280))] + + runner.epoch = 286 # epoch > switch_epoch + hook = PipelineSwitchHook(switch_epoch=285, switch_pipeline=stage2) + hook.before_train_epoch(runner) + self.assertTrue(hook._restart_dataloader) + self.assertFalse(runner.train_dataloader._DataLoader__initialized) + self.assertTrue( + len(runner.train_dataloader.dataset.pipeline.transforms) == 1) diff --git a/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_sync_norm_hook.py b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_sync_norm_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..4664cf05359c4354b170a3478396c0155e9c12a3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_sync_norm_hook.py @@ -0,0 +1,41 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock, patch + +import torch.nn as nn + +from mmdet.engine.hooks import SyncNormHook + + +class TestSyncNormHook(TestCase): + + @patch( + 'mmdet.engine.hooks.sync_norm_hook.get_dist_info', return_value=(0, 1)) + def test_before_val_epoch_non_dist(self, mock): + model = nn.Sequential( + nn.Conv2d(1, 5, kernel_size=3), nn.BatchNorm2d(5, momentum=0.3), + nn.Linear(5, 10)) + runner = Mock() + runner.model = model + hook = SyncNormHook() + hook.before_val_epoch(runner) + + @patch( + 'mmdet.engine.hooks.sync_norm_hook.get_dist_info', return_value=(0, 2)) + def test_before_val_epoch_dist(self, mock): + model = nn.Sequential( + nn.Conv2d(1, 5, kernel_size=3), nn.BatchNorm2d(5, momentum=0.3), + nn.Linear(5, 10)) + runner = Mock() + runner.model = model + hook = SyncNormHook() + hook.before_val_epoch(runner) + + @patch( + 'mmdet.engine.hooks.sync_norm_hook.get_dist_info', return_value=(0, 2)) + def test_before_val_epoch_dist_no_norm(self, mock): + model = nn.Sequential(nn.Conv2d(1, 5, kernel_size=3), nn.Linear(5, 10)) + runner = Mock() + runner.model = model + hook = SyncNormHook() + hook.before_val_epoch(runner) diff --git a/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_visualization_hook.py b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_visualization_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..e7cd0771b28fd9fadbe0ba3e50bba89df6a7f721 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_visualization_hook.py @@ -0,0 +1,120 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import shutil +import time +from unittest import TestCase +from unittest.mock import Mock + +import torch +from mmengine.structures import InstanceData + +from mmdet.engine.hooks import DetVisualizationHook, TrackVisualizationHook +from mmdet.structures import DetDataSample, TrackDataSample +from mmdet.visualization import DetLocalVisualizer, TrackLocalVisualizer + + +def _rand_bboxes(num_boxes, h, w): + cx, cy, bw, bh = torch.rand(num_boxes, 4).T + + tl_x = ((cx * w) - (w * bw / 2)).clamp(0, w) + tl_y = ((cy * h) - (h * bh / 2)).clamp(0, h) + br_x = ((cx * w) + (w * bw / 2)).clamp(0, w) + br_y = ((cy * h) + (h * bh / 2)).clamp(0, h) + + bboxes = torch.stack([tl_x, tl_y, br_x, br_y], dim=0).T + return bboxes + + +class TestVisualizationHook(TestCase): + + def setUp(self) -> None: + DetLocalVisualizer.get_instance('current_visualizer') + + pred_instances = InstanceData() + pred_instances.bboxes = _rand_bboxes(5, 10, 12) + pred_instances.labels = torch.randint(0, 2, (5, )) + pred_instances.scores = torch.rand((5, )) + pred_det_data_sample = DetDataSample() + pred_det_data_sample.set_metainfo({ + 'img_path': + osp.join(osp.dirname(__file__), '../../data/color.jpg') + }) + pred_det_data_sample.pred_instances = pred_instances + self.outputs = [pred_det_data_sample] * 2 + + def test_after_val_iter(self): + runner = Mock() + runner.iter = 1 + hook = DetVisualizationHook() + hook.after_val_iter(runner, 1, {}, self.outputs) + + def test_after_test_iter(self): + runner = Mock() + runner.iter = 1 + hook = DetVisualizationHook(draw=True) + hook.after_test_iter(runner, 1, {}, self.outputs) + self.assertEqual(hook._test_index, 2) + + # test + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + test_out_dir = timestamp + '1' + runner.work_dir = timestamp + runner.timestamp = '1' + hook = DetVisualizationHook(draw=False, test_out_dir=test_out_dir) + hook.after_test_iter(runner, 1, {}, self.outputs) + self.assertTrue(not osp.exists(f'{timestamp}/1/{test_out_dir}')) + + hook = DetVisualizationHook(draw=True, test_out_dir=test_out_dir) + hook.after_test_iter(runner, 1, {}, self.outputs) + self.assertTrue(osp.exists(f'{timestamp}/1/{test_out_dir}')) + shutil.rmtree(f'{timestamp}') + + +class TestTrackVisualizationHook(TestCase): + + def setUp(self) -> None: + TrackLocalVisualizer.get_instance('visualizer') + # pseudo data_batch + self.data_batch = dict(data_samples=None, inputs=None) + + pred_instances_data = dict( + bboxes=torch.tensor([[100, 100, 200, 200], [150, 150, 400, 200]]), + instances_id=torch.tensor([1, 2]), + labels=torch.tensor([0, 1]), + scores=torch.tensor([0.955, 0.876])) + pred_instances = InstanceData(**pred_instances_data) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = pred_instances + img_data_sample.gt_instances = pred_instances + img_data_sample.set_metainfo( + dict( + img_path=osp.join( + osp.dirname(__file__), '../../data/color.jpg'), + scale_factor=(1.0, 1.0))) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + track_data_sample.set_metainfo(dict(ori_length=1)) + self.outputs = [track_data_sample] + + def test_after_val_iter_image(self): + runner = Mock() + runner.iter = 1 + hook = TrackVisualizationHook(frame_interval=10, draw=True) + hook.after_val_iter(runner, 9, self.data_batch, self.outputs) + + def test_after_test_iter(self): + runner = Mock() + runner.iter = 1 + hook = TrackVisualizationHook(frame_interval=10, draw=True) + hook.after_val_iter(runner, 9, self.data_batch, self.outputs) + + # test test_out_dir + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + test_out_dir = timestamp + '1' + runner.work_dir = timestamp + runner.timestamp = '1' + hook = TrackVisualizationHook( + frame_interval=10, draw=True, test_out_dir=test_out_dir) + hook.after_test_iter(runner, 9, self.data_batch, self.outputs) + self.assertTrue(osp.exists(f'{timestamp}/1/{test_out_dir}')) + shutil.rmtree(f'{timestamp}') diff --git a/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_yolox_mode_switch_hook.py b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_yolox_mode_switch_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..c6201872443498c392f6845b30232e39d61e3fe7 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_hooks/test_yolox_mode_switch_hook.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import Mock, patch + +from mmdet.engine.hooks import YOLOXModeSwitchHook + + +class TestYOLOXModeSwitchHook(TestCase): + + @patch('mmdet.engine.hooks.yolox_mode_switch_hook.is_model_wrapper') + def test_is_model_wrapper_and_persistent_workers_on( + self, mock_is_model_wrapper): + mock_is_model_wrapper.return_value = True + runner = Mock() + runner.model = Mock() + runner.model.module = Mock() + runner.model.module.detector.bbox_head.use_l1 = False + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = True + runner.train_dataloader._DataLoader__initialized = True + runner.epoch = 284 + runner.max_epochs = 300 + + hook = YOLOXModeSwitchHook(num_last_epochs=15) + hook.before_train_epoch(runner) + self.assertTrue(hook._restart_dataloader) + self.assertTrue(runner.model.module.detector.bbox_head.use_l1) + self.assertFalse(runner.train_dataloader._DataLoader__initialized) + + runner.epoch = 285 + hook.before_train_epoch(runner) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + def test_not_model_wrapper_and_persistent_workers_off(self): + runner = Mock() + runner.model = Mock() + runner.model.detector.bbox_head.use_l1 = False + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = False + runner.train_dataloader._DataLoader__initialized = True + runner.epoch = 284 + runner.max_epochs = 300 + + hook = YOLOXModeSwitchHook(num_last_epochs=15) + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.model.detector.bbox_head.use_l1) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + runner.epoch = 285 + hook.before_train_epoch(runner) + self.assertFalse(hook._restart_dataloader) + self.assertTrue(runner.train_dataloader._DataLoader__initialized) + + @patch('mmdet.engine.hooks.yolox_mode_switch_hook.is_model_wrapper') + def test_initialize_after_switching(self, mock_is_model_wrapper): + # This simulates the resumption after the switching. + mock_is_model_wrapper.return_value = True + runner = Mock() + runner.model = Mock() + runner.model.module = Mock() + runner.model.module.bbox_head.use_l1 = False + runner.train_dataloader = Mock() + runner.train_dataloader.persistent_workers = True + runner.train_dataloader._DataLoader__initialized = True + runner.epoch = 285 + runner.max_epochs = 300 + + # epoch + 1 > max_epochs - num_last_epochs . + hook = YOLOXModeSwitchHook(num_last_epochs=15) + hook.before_train_epoch(runner) + self.assertTrue(hook._restart_dataloader) + self.assertTrue(runner.model.module.detector.bbox_head.use_l1) + self.assertFalse(runner.train_dataloader._DataLoader__initialized) diff --git a/mmdet_code/mmdetection/tests/test_engine/test_optimizers/__init__.py b/mmdet_code/mmdetection/tests/test_engine/test_optimizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/mmdetection/tests/test_engine/test_optimizers/test_layer_decay_optimizer_constructor.py b/mmdet_code/mmdetection/tests/test_engine/test_optimizers/test_layer_decay_optimizer_constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..bac43e224d60cb8df49fa1b8eb09dd92ab33e6f5 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_optimizers/test_layer_decay_optimizer_constructor.py @@ -0,0 +1,168 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmdet.engine import LearningRateDecayOptimizerConstructor + +base_lr = 1 +decay_rate = 2 +base_wd = 0.05 +weight_decay = 0.05 + +expected_stage_wise_lr_wd_convnext = [{ + 'weight_decay': 0.0, + 'lr_scale': 128 +}, { + 'weight_decay': 0.0, + 'lr_scale': 1 +}, { + 'weight_decay': 0.05, + 'lr_scale': 64 +}, { + 'weight_decay': 0.0, + 'lr_scale': 64 +}, { + 'weight_decay': 0.05, + 'lr_scale': 32 +}, { + 'weight_decay': 0.0, + 'lr_scale': 32 +}, { + 'weight_decay': 0.05, + 'lr_scale': 16 +}, { + 'weight_decay': 0.0, + 'lr_scale': 16 +}, { + 'weight_decay': 0.05, + 'lr_scale': 8 +}, { + 'weight_decay': 0.0, + 'lr_scale': 8 +}, { + 'weight_decay': 0.05, + 'lr_scale': 128 +}, { + 'weight_decay': 0.05, + 'lr_scale': 1 +}] + +expected_layer_wise_lr_wd_convnext = [{ + 'weight_decay': 0.0, + 'lr_scale': 128 +}, { + 'weight_decay': 0.0, + 'lr_scale': 1 +}, { + 'weight_decay': 0.05, + 'lr_scale': 64 +}, { + 'weight_decay': 0.0, + 'lr_scale': 64 +}, { + 'weight_decay': 0.05, + 'lr_scale': 32 +}, { + 'weight_decay': 0.0, + 'lr_scale': 32 +}, { + 'weight_decay': 0.05, + 'lr_scale': 16 +}, { + 'weight_decay': 0.0, + 'lr_scale': 16 +}, { + 'weight_decay': 0.05, + 'lr_scale': 2 +}, { + 'weight_decay': 0.0, + 'lr_scale': 2 +}, { + 'weight_decay': 0.05, + 'lr_scale': 128 +}, { + 'weight_decay': 0.05, + 'lr_scale': 1 +}] + + +class ToyConvNeXt(nn.Module): + + def __init__(self): + super().__init__() + self.stages = nn.ModuleList() + for i in range(4): + stage = nn.Sequential(ConvModule(3, 4, kernel_size=1, bias=True)) + self.stages.append(stage) + self.norm0 = nn.BatchNorm2d(2) + + # add some variables to meet unit test coverate rate + self.cls_token = nn.Parameter(torch.ones(1)) + self.mask_token = nn.Parameter(torch.ones(1)) + self.pos_embed = nn.Parameter(torch.ones(1)) + self.stem_norm = nn.Parameter(torch.ones(1)) + self.downsample_norm0 = nn.BatchNorm2d(2) + self.downsample_norm1 = nn.BatchNorm2d(2) + self.downsample_norm2 = nn.BatchNorm2d(2) + self.lin = nn.Parameter(torch.ones(1)) + self.lin.requires_grad = False + self.downsample_layers = nn.ModuleList() + for _ in range(4): + stage = nn.Sequential(nn.Conv2d(3, 4, kernel_size=1, bias=True)) + self.downsample_layers.append(stage) + + +class ToyDetector(nn.Module): + + def __init__(self, backbone): + super().__init__() + self.backbone = backbone + self.head = nn.Conv2d(2, 2, kernel_size=1, groups=2) + + +class PseudoDataParallel(nn.Module): + + def __init__(self, model): + super().__init__() + self.module = model + + +def check_optimizer_lr_wd(optimizer, gt_lr_wd): + assert isinstance(optimizer, torch.optim.AdamW) + assert optimizer.defaults['lr'] == base_lr + assert optimizer.defaults['weight_decay'] == base_wd + param_groups = optimizer.param_groups + print(param_groups) + assert len(param_groups) == len(gt_lr_wd) + for i, param_dict in enumerate(param_groups): + assert param_dict['weight_decay'] == gt_lr_wd[i]['weight_decay'] + assert param_dict['lr_scale'] == gt_lr_wd[i]['lr_scale'] + assert param_dict['lr_scale'] == param_dict['lr'] + + +def test_learning_rate_decay_optimizer_constructor(): + + # Test lr wd for ConvNeXT + backbone = ToyConvNeXt() + model = PseudoDataParallel(ToyDetector(backbone)) + optim_wrapper_cfg = dict( + type='OptimWrapper', + optimizer=dict( + type='AdamW', lr=base_lr, betas=(0.9, 0.999), weight_decay=0.05)) + # stagewise decay + stagewise_paramwise_cfg = dict( + decay_rate=decay_rate, decay_type='stage_wise', num_layers=6) + optim_constructor = LearningRateDecayOptimizerConstructor( + optim_wrapper_cfg, stagewise_paramwise_cfg) + optim_wrapper = optim_constructor(model) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_stage_wise_lr_wd_convnext) + # layerwise decay + layerwise_paramwise_cfg = dict( + decay_rate=decay_rate, decay_type='layer_wise', num_layers=6) + optim_constructor = LearningRateDecayOptimizerConstructor( + optim_wrapper_cfg, layerwise_paramwise_cfg) + optim_wrapper = optim_constructor(model) + check_optimizer_lr_wd(optim_wrapper.optimizer, + expected_layer_wise_lr_wd_convnext) diff --git a/mmdet_code/mmdetection/tests/test_engine/test_runner/test_loops.py b/mmdet_code/mmdetection/tests/test_engine/test_runner/test_loops.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf9cb4795a802eb0beef60e04938056c2eefebf --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_runner/test_loops.py @@ -0,0 +1,113 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import tempfile +from unittest import TestCase +from unittest.mock import Mock + +import torch +import torch.nn as nn +from mmengine.evaluator import Evaluator +from mmengine.model import BaseModel +from mmengine.optim import OptimWrapper +from mmengine.runner import Runner +from torch.utils.data import Dataset + +from mmdet.registry import DATASETS +from mmdet.utils import register_all_modules + +register_all_modules() + + +class ToyModel(nn.Module): + + def __init__(self): + super().__init__() + self.linear = nn.Linear(2, 1) + + def forward(self, inputs, data_samples, mode='tensor'): + labels = torch.stack(data_samples) + inputs = torch.stack(inputs) + outputs = self.linear(inputs) + if mode == 'tensor': + return outputs + elif mode == 'loss': + loss = (labels - outputs).sum() + outputs = dict(loss=loss) + return outputs + else: + return outputs + + +class ToyModel1(BaseModel, ToyModel): + + def __init__(self): + super().__init__() + + def forward(self, *args, **kwargs): + return super(BaseModel, self).forward(*args, **kwargs) + + +class ToyModel2(BaseModel): + + def __init__(self): + super().__init__() + self.teacher = ToyModel1() + self.student = ToyModel1() + self.semi_test_cfg = dict(predict_on='teacher') + + def forward(self, *args, **kwargs): + return self.student(*args, **kwargs) + + +@DATASETS.register_module(force=True) +class DummyDataset(Dataset): + METAINFO = dict() # type: ignore + data = torch.randn(12, 2) + label = torch.ones(12) + + @property + def metainfo(self): + return self.METAINFO + + def __len__(self): + return self.data.size(0) + + def __getitem__(self, index): + return dict(inputs=self.data[index], data_samples=self.label[index]) + + +class TestTeacherStudentValLoop(TestCase): + + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.temp_dir.cleanup() + + def test_teacher_student_val_loop(self): + device = 'cuda:0' if torch.cuda.is_available() else 'cpu' + model = ToyModel2().to(device) + evaluator = Mock() + evaluator.evaluate = Mock(return_value=dict(acc=0.5)) + evaluator.__class__ = Evaluator + runner = Runner( + model=model, + train_dataloader=dict( + dataset=dict(type='DummyDataset'), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=3, + num_workers=0), + val_dataloader=dict( + dataset=dict(type='DummyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=0), + val_evaluator=evaluator, + work_dir=self.temp_dir.name, + default_scope='mmdet', + optim_wrapper=OptimWrapper( + torch.optim.Adam(ToyModel().parameters())), + train_cfg=dict(by_epoch=True, max_epochs=2, val_interval=1), + val_cfg=dict(type='TeacherStudentValLoop'), + default_hooks=dict(logger=dict(type='LoggerHook', interval=1)), + experiment_name='test1') + runner.train() diff --git a/mmdet_code/mmdetection/tests/test_engine/test_schedulers/test_quadratic_warmup.py b/mmdet_code/mmdetection/tests/test_engine/test_schedulers/test_quadratic_warmup.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec3c4e8ebb9e9980a72ac8fb2c0edc98c647185 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_engine/test_schedulers/test_quadratic_warmup.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +import torch.nn.functional as F +import torch.optim as optim +from mmengine.optim.scheduler import _ParamScheduler +from mmengine.testing import assert_allclose + +from mmdet.engine.schedulers import (QuadraticWarmupLR, + QuadraticWarmupMomentum, + QuadraticWarmupParamScheduler) + + +class ToyModel(torch.nn.Module): + + def __init__(self): + super().__init__() + self.conv1 = torch.nn.Conv2d(1, 1, 1) + self.conv2 = torch.nn.Conv2d(1, 1, 1) + + def forward(self, x): + return self.conv2(F.relu(self.conv1(x))) + + +class TestQuadraticWarmupScheduler(TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.model = ToyModel() + self.optimizer = optim.SGD( + self.model.parameters(), lr=0.05, momentum=0.01, weight_decay=5e-4) + + def _test_scheduler_value(self, + schedulers, + targets, + epochs=10, + param_name='lr'): + if isinstance(schedulers, _ParamScheduler): + schedulers = [schedulers] + for epoch in range(epochs): + for param_group, target in zip(self.optimizer.param_groups, + targets): + print(param_group[param_name]) + assert_allclose( + target[epoch], + param_group[param_name], + msg='{} is wrong in epoch {}: expected {}, got {}'.format( + param_name, epoch, target[epoch], + param_group[param_name]), + atol=1e-5, + rtol=0) + [scheduler.step() for scheduler in schedulers] + + def test_quadratic_warmup_scheduler(self): + with self.assertRaises(ValueError): + QuadraticWarmupParamScheduler(self.optimizer, param_name='lr') + epochs = 10 + iters = 5 + warmup_factor = [pow((i + 1) / float(iters), 2) for i in range(iters)] + single_targets = [x * 0.05 for x in warmup_factor] + [0.05] * ( + epochs - iters) + targets = [single_targets, [x * epochs for x in single_targets]] + scheduler = QuadraticWarmupParamScheduler( + self.optimizer, param_name='lr', end=iters) + self._test_scheduler_value(scheduler, targets, epochs) + + def test_quadratic_warmup_scheduler_convert_iterbased(self): + epochs = 10 + end = 5 + epoch_length = 11 + + iters = end * epoch_length + warmup_factor = [pow((i + 1) / float(iters), 2) for i in range(iters)] + single_targets = [x * 0.05 for x in warmup_factor] + [0.05] * ( + epochs * epoch_length - iters) + targets = [single_targets, [x * epochs for x in single_targets]] + scheduler = QuadraticWarmupParamScheduler.build_iter_from_epoch( + self.optimizer, + param_name='lr', + end=end, + epoch_length=epoch_length) + self._test_scheduler_value(scheduler, targets, epochs * epoch_length) + + def test_quadratic_warmup_lr(self): + epochs = 10 + iters = 5 + warmup_factor = [pow((i + 1) / float(iters), 2) for i in range(iters)] + single_targets = [x * 0.05 for x in warmup_factor] + [0.05] * ( + epochs - iters) + targets = [single_targets, [x * epochs for x in single_targets]] + scheduler = QuadraticWarmupLR(self.optimizer, end=iters) + self._test_scheduler_value(scheduler, targets, epochs) + + def test_quadratic_warmup_momentum(self): + epochs = 10 + iters = 5 + warmup_factor = [pow((i + 1) / float(iters), 2) for i in range(iters)] + single_targets = [x * 0.01 for x in warmup_factor] + [0.01] * ( + epochs - iters) + targets = [single_targets, [x * epochs for x in single_targets]] + scheduler = QuadraticWarmupMomentum(self.optimizer, end=iters) + self._test_scheduler_value( + scheduler, targets, epochs, param_name='momentum') diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/__init__.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_cityscapes_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_cityscapes_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ee6eb9ba4a1dbf5fdaa5b16a60c5699c1d9688 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_cityscapes_metric.py @@ -0,0 +1,102 @@ +import os +import os.path as osp +import tempfile +import unittest + +import numpy as np +import torch +from PIL import Image + +from mmdet.evaluation import CityScapesMetric + +try: + import cityscapesscripts +except ImportError: + cityscapesscripts = None + + +class TestCityScapesMetric(unittest.TestCase): + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + @unittest.skipIf(cityscapesscripts is None, + 'cityscapesscripts is not installed.') + def test_init(self): + # test with outfile_prefix = None + with self.assertRaises(AssertionError): + CityScapesMetric(outfile_prefix=None) + + @unittest.skipIf(cityscapesscripts is None, + 'cityscapesscripts is not installed.') + def test_evaluate(self): + dummy_mask1 = np.zeros((1, 20, 20), dtype=np.uint8) + dummy_mask1[:, :10, :10] = 1 + dummy_mask2 = np.zeros((1, 20, 20), dtype=np.uint8) + dummy_mask2[:, :10, :10] = 1 + + self.outfile_prefix = osp.join(self.tmp_dir.name, 'test') + self.seg_prefix = osp.join(self.tmp_dir.name, 'cityscapes/gtFine/val') + city = 'lindau' + sequenceNb = '000000' + frameNb = '000019' + img_name1 = f'{city}_{sequenceNb}_{frameNb}_gtFine_instanceIds.png' + img_path1 = osp.join(self.seg_prefix, city, img_name1) + + frameNb = '000020' + img_name2 = f'{city}_{sequenceNb}_{frameNb}_gtFine_instanceIds.png' + img_path2 = osp.join(self.seg_prefix, city, img_name2) + os.makedirs(osp.join(self.seg_prefix, city)) + + masks1 = np.zeros((20, 20), dtype=np.int32) + masks1[:10, :10] = 24 * 1000 + Image.fromarray(masks1).save(img_path1) + + masks2 = np.zeros((20, 20), dtype=np.int32) + masks2[:10, :10] = 24 * 1000 + 1 + Image.fromarray(masks2).save(img_path2) + + data_samples = [{ + 'img_path': img_path1, + 'pred_instances': { + 'scores': torch.from_numpy(np.array([1.0])), + 'labels': torch.from_numpy(np.array([0])), + 'masks': torch.from_numpy(dummy_mask1) + } + }, { + 'img_path': img_path2, + 'pred_instances': { + 'scores': torch.from_numpy(np.array([0.98])), + 'labels': torch.from_numpy(np.array([1])), + 'masks': torch.from_numpy(dummy_mask2) + } + }] + + target = {'cityscapes/mAP': 0.5, 'cityscapes/AP@50': 0.5} + metric = CityScapesMetric( + seg_prefix=self.seg_prefix, + format_only=False, + outfile_prefix=self.outfile_prefix) + metric.dataset_meta = dict( + classes=('person', 'rider', 'car', 'truck', 'bus', 'train', + 'motorcycle', 'bicycle')) + metric.process({}, data_samples) + results = metric.evaluate(size=2) + self.assertDictEqual(results, target) + del metric + self.assertTrue(not osp.exists('{self.outfile_prefix}.results')) + + # test format_only + metric = CityScapesMetric( + seg_prefix=self.seg_prefix, + format_only=True, + outfile_prefix=self.outfile_prefix) + metric.dataset_meta = dict( + classes=('person', 'rider', 'car', 'truck', 'bus', 'train', + 'motorcycle', 'bicycle')) + metric.process({}, data_samples) + results = metric.evaluate(size=2) + self.assertDictEqual(results, dict()) diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..547b8f21e0fcff5323162323aa3a31c9d60f4ee6 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_metric.py @@ -0,0 +1,401 @@ +import os.path as osp +import tempfile +from unittest import TestCase + +import numpy as np +import pycocotools.mask as mask_util +import torch +from mmengine.fileio import dump + +from mmdet.evaluation import CocoMetric + + +class TestCocoMetric(TestCase): + + def _create_dummy_coco_json(self, json_name): + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + image = { + 'id': 0, + 'width': 640, + 'height': 640, + 'file_name': 'fake_name.jpg', + } + + annotation_1 = { + 'id': 1, + 'image_id': 0, + 'category_id': 0, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_2 = { + 'id': 2, + 'image_id': 0, + 'category_id': 0, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_3 = { + 'id': 3, + 'image_id': 0, + 'category_id': 1, + 'area': 1600, + 'bbox': [150, 160, 40, 40], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_4 = { + 'id': 4, + 'image_id': 0, + 'category_id': 0, + 'area': 10000, + 'bbox': [250, 260, 100, 100], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + categories = [ + { + 'id': 0, + 'name': 'car', + 'supercategory': 'car', + }, + { + 'id': 1, + 'name': 'bicycle', + 'supercategory': 'bicycle', + }, + ] + + fake_json = { + 'images': [image], + 'annotations': + [annotation_1, annotation_2, annotation_3, annotation_4], + 'categories': categories + } + + dump(fake_json, json_name) + + def _create_dummy_results(self): + bboxes = np.array([[50, 60, 70, 80], [100, 120, 130, 150], + [150, 160, 190, 200], [250, 260, 350, 360]]) + scores = np.array([1.0, 0.98, 0.96, 0.95]) + labels = np.array([0, 0, 1, 0]) + dummy_mask = np.zeros((4, 10, 10), dtype=np.uint8) + dummy_mask[:, :5, :5] = 1 + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_init(self): + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + with self.assertRaisesRegex(KeyError, 'metric should be one of'): + CocoMetric(ann_file=fake_json_file, metric='unknown') + + def test_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single coco dataset evaluation + coco_metric = CocoMetric( + ann_file=fake_json_file, + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + + # test box and segm coco dataset evaluation + coco_metric = CocoMetric( + ann_file=fake_json_file, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/segm_mAP': 1.0, + 'coco/segm_mAP_50': 1.0, + 'coco/segm_mAP_75': 1.0, + 'coco/segm_mAP_s': 1.0, + 'coco/segm_mAP_m': 1.0, + 'coco/segm_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + + # test invalid custom metric_items + with self.assertRaisesRegex(KeyError, + 'metric item "invalid" is not supported'): + coco_metric = CocoMetric( + ann_file=fake_json_file, metric_items=['invalid']) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process({}, [ + dict( + pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640)) + ]) + coco_metric.evaluate(size=1) + + # test custom metric_items + coco_metric = CocoMetric( + ann_file=fake_json_file, metric_items=['mAP_m']) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = { + 'coco/bbox_mAP_m': 1.0, + } + self.assertDictEqual(eval_results, target) + + def test_classwise_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single coco dataset evaluation + coco_metric = CocoMetric( + ann_file=fake_json_file, metric='bbox', classwise=True) + # coco_metric1 = CocoMetric( + # ann_file=fake_json_file, metric='bbox', classwise=True) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/car_precision': 1.0, + 'coco/bicycle_precision': 1.0, + } + self.assertDictEqual(eval_results, target) + + def test_manually_set_iou_thrs(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + + # test single coco dataset evaluation + coco_metric = CocoMetric( + ann_file=fake_json_file, metric='bbox', iou_thrs=[0.3, 0.6]) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + self.assertEqual(coco_metric.iou_thrs, [0.3, 0.6]) + + def test_fast_eval_recall(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test default proposal nums + coco_metric = CocoMetric( + ann_file=fake_json_file, metric='proposal_fast') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = {'coco/AR@100': 1.0, 'coco/AR@300': 1.0, 'coco/AR@1000': 1.0} + self.assertDictEqual(eval_results, target) + + # test manually set proposal nums + coco_metric = CocoMetric( + ann_file=fake_json_file, + metric='proposal_fast', + proposal_nums=(2, 4)) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + target = {'coco/AR@2': 0.5, 'coco/AR@4': 1.0} + self.assertDictEqual(eval_results, target) + + def test_evaluate_proposal(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + coco_metric = CocoMetric(ann_file=fake_json_file, metric='proposal') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + print(eval_results) + target = { + 'coco/AR@100': 1, + 'coco/AR@300': 1.0, + 'coco/AR@1000': 1.0, + 'coco/AR_s@1000': 1.0, + 'coco/AR_m@1000': 1.0, + 'coco/AR_l@1000': 1.0 + } + self.assertDictEqual(eval_results, target) + + def test_empty_results(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + coco_metric = CocoMetric(ann_file=fake_json_file, metric='bbox') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + bboxes = np.zeros((0, 4)) + labels = np.array([]) + scores = np.array([]) + dummy_mask = np.zeros((0, 10, 10), dtype=np.uint8) + empty_pred = dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + coco_metric.process( + {}, + [dict(pred_instances=empty_pred, img_id=0, ori_shape=(640, 640))]) + # coco api Index error will be caught + coco_metric.evaluate(size=1) + + def test_evaluate_without_json(self): + dummy_pred = self._create_dummy_results() + + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + instances = [{ + 'bbox_label': 0, + 'bbox': [50, 60, 70, 80], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 0, + 'bbox': [100, 120, 130, 150], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 1, + 'bbox': [150, 160, 190, 200], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 0, + 'bbox': [250, 260, 350, 360], + 'ignore_flag': 0, + 'mask': rle_mask, + }] + coco_metric = CocoMetric( + ann_file=None, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process({}, [ + dict( + pred_instances=dummy_pred, + img_id=0, + ori_shape=(640, 640), + instances=instances) + ]) + eval_results = coco_metric.evaluate(size=1) + print(eval_results) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/segm_mAP': 1.0, + 'coco/segm_mAP_50': 1.0, + 'coco/segm_mAP_75': 1.0, + 'coco/segm_mAP_s': 1.0, + 'coco/segm_mAP_m': 1.0, + 'coco/segm_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.gt.json'))) + + def test_format_only(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + with self.assertRaises(AssertionError): + CocoMetric( + ann_file=fake_json_file, + classwise=False, + format_only=True, + outfile_prefix=None) + + coco_metric = CocoMetric( + ann_file=fake_json_file, + metric='bbox', + classwise=False, + format_only=True, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = coco_metric.evaluate(size=1) + self.assertDictEqual(eval_results, dict()) + self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.bbox.json')) diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_occluded_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_occluded_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..29c4d568554cbd60c7b5424109706f4d869ac184 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_occluded_metric.py @@ -0,0 +1,46 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +from tempfile import TemporaryDirectory + +import mmengine +import numpy as np + +from mmdet.datasets import CocoDataset +from mmdet.evaluation import CocoOccludedSeparatedMetric + + +def test_coco_occluded_separated_metric(): + ann = [[ + 'fake1.jpg', 'person', 8, [219.9, 176.12, 11.14, 34.23], { + 'size': [480, 640], + 'counts': b'nYW31n>2N2FNbA48Kf=?XBDe=m0OM3M4YOPB8_>L4JXao5' + } + ]] * 3 + dummy_mask = np.zeros((10, 10), dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle = { + 'size': [480, 640], + 'counts': b'nYW31n>2N2FNbA48Kf=?XBDe=m0OM3M4YOPB8_>L4JXao5' + } + res = [(None, + dict( + img_id=0, + bboxes=np.array([[50, 60, 70, 80]] * 2), + masks=[rle] * 2, + labels=np.array([0, 1], dtype=np.int64), + scores=np.array([0.77, 0.77])))] * 3 + + tempdir = TemporaryDirectory() + ann_path = osp.join(tempdir.name, 'coco_occluded.pkl') + mmengine.dump(ann, ann_path) + + metric = CocoOccludedSeparatedMetric( + ann_file='tests/data/coco_sample.json', + occluded_ann=ann_path, + separated_ann=ann_path, + metric=[]) + metric.dataset_meta = CocoDataset.METAINFO + eval_res = metric.compute_metrics(res) + assert isinstance(eval_res, dict) + assert eval_res['occluded_recall'] == 100 + assert eval_res['separated_recall'] == 100 diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_panoptic_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_panoptic_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..caae63e728b3db146e3ccda9c36b0e4ccb33658a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_panoptic_metric.py @@ -0,0 +1,285 @@ +import os +import os.path as osp +import tempfile +import unittest +from copy import deepcopy + +import mmcv +import numpy as np +import torch +from mmengine.fileio import dump + +from mmdet.evaluation import INSTANCE_OFFSET, CocoPanopticMetric + +try: + import panopticapi +except ImportError: + panopticapi = None + + +class TestCocoPanopticMetric(unittest.TestCase): + + def _create_panoptic_gt_annotations(self, ann_file, seg_map_dir): + categories = [{ + 'id': 0, + 'name': 'person', + 'supercategory': 'person', + 'isthing': 1 + }, { + 'id': 1, + 'name': 'cat', + 'supercategory': 'cat', + 'isthing': 1 + }, { + 'id': 2, + 'name': 'dog', + 'supercategory': 'dog', + 'isthing': 1 + }, { + 'id': 3, + 'name': 'wall', + 'supercategory': 'wall', + 'isthing': 0 + }] + + images = [{ + 'id': 0, + 'width': 80, + 'height': 60, + 'file_name': 'fake_name1.jpg', + }] + + annotations = [{ + 'segments_info': [{ + 'id': 1, + 'category_id': 0, + 'area': 400, + 'bbox': [10, 10, 10, 40], + 'iscrowd': 0 + }, { + 'id': 2, + 'category_id': 0, + 'area': 400, + 'bbox': [30, 10, 10, 40], + 'iscrowd': 0 + }, { + 'id': 3, + 'category_id': 2, + 'iscrowd': 0, + 'bbox': [50, 10, 10, 5], + 'area': 50 + }, { + 'id': 4, + 'category_id': 3, + 'iscrowd': 0, + 'bbox': [0, 0, 80, 60], + 'area': 3950 + }], + 'file_name': + 'fake_name1.png', + 'image_id': + 0 + }] + + gt_json = { + 'images': images, + 'annotations': annotations, + 'categories': categories + } + + # 4 is the id of the background class annotation. + gt = np.zeros((60, 80), dtype=np.int64) + 4 + gt_bboxes = np.array( + [[10, 10, 10, 40], [30, 10, 10, 40], [50, 10, 10, 5]], + dtype=np.int64) + for i in range(3): + x, y, w, h = gt_bboxes[i] + gt[y:y + h, x:x + w] = i + 1 # id starts from 1 + + rgb_gt_seg_map = np.zeros(gt.shape + (3, ), dtype=np.uint8) + rgb_gt_seg_map[:, :, 2] = gt // (256 * 256) + rgb_gt_seg_map[:, :, 1] = gt % (256 * 256) // 256 + rgb_gt_seg_map[:, :, 0] = gt % 256 + + img_path = osp.join(seg_map_dir, 'fake_name1.png') + mmcv.imwrite(rgb_gt_seg_map[:, :, ::-1], img_path) + dump(gt_json, ann_file) + + return gt_json + + def _create_panoptic_data_samples(self): + # predictions + # TP for background class, IoU=3576/4324=0.827 + # 2 the category id of the background class + pred = np.zeros((60, 80), dtype=np.int64) + 2 + pred_bboxes = np.array( + [ + [11, 11, 10, 40], # TP IoU=351/449=0.78 + [38, 10, 10, 40], # FP + [51, 10, 10, 5] # TP IoU=45/55=0.818 + ], + dtype=np.int64) + pred_labels = np.array([0, 0, 1], dtype=np.int64) + for i in range(3): + x, y, w, h = pred_bboxes[i] + pred[y:y + h, x:x + w] = (i + 1) * INSTANCE_OFFSET + pred_labels[i] + + data_samples = [{ + 'img_id': + 0, + 'ori_shape': (60, 80), + 'img_path': + 'xxx/fake_name1.jpg', + 'segments_info': [{ + 'id': 1, + 'category': 0, + 'is_thing': 1 + }, { + 'id': 2, + 'category': 0, + 'is_thing': 1 + }, { + 'id': 3, + 'category': 1, + 'is_thing': 1 + }, { + 'id': 4, + 'category': 2, + 'is_thing': 0 + }], + 'seg_map_path': + osp.join(self.gt_seg_dir, 'fake_name1.png'), + 'pred_panoptic_seg': { + 'sem_seg': torch.from_numpy(pred).unsqueeze(0) + }, + }] + + return data_samples + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + self.gt_json_path = osp.join(self.tmp_dir.name, 'gt.json') + self.gt_seg_dir = osp.join(self.tmp_dir.name, 'gt_seg') + os.mkdir(self.gt_seg_dir) + self._create_panoptic_gt_annotations(self.gt_json_path, + self.gt_seg_dir) + self.dataset_meta = { + 'classes': ('person', 'dog', 'wall'), + 'thing_classes': ('person', 'dog'), + 'stuff_classes': ('wall', ) + } + self.target = { + 'coco_panoptic/PQ': 67.86874803219071, + 'coco_panoptic/SQ': 80.89770126158936, + 'coco_panoptic/RQ': 83.33333333333334, + 'coco_panoptic/PQ_th': 60.45252075318891, + 'coco_panoptic/SQ_th': 79.9959505972869, + 'coco_panoptic/RQ_th': 75.0, + 'coco_panoptic/PQ_st': 82.70120259019427, + 'coco_panoptic/SQ_st': 82.70120259019427, + 'coco_panoptic/RQ_st': 100.0 + } + self.data_samples = self._create_panoptic_data_samples() + + def tearDown(self): + self.tmp_dir.cleanup() + + @unittest.skipIf(panopticapi is not None, 'panopticapi is installed') + def test_init(self): + with self.assertRaises(RuntimeError): + CocoPanopticMetric() + + @unittest.skipIf(panopticapi is None, 'panopticapi is not installed') + def test_evaluate_without_json(self): + # with tmpfile, without json + metric = CocoPanopticMetric( + ann_file=None, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + outfile_prefix=None) + + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + # without tmpfile and json + outfile_prefix = f'{self.tmp_dir.name}/test' + metric = CocoPanopticMetric( + ann_file=None, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + outfile_prefix=outfile_prefix) + + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + @unittest.skipIf(panopticapi is None, 'panopticapi is not installed') + def test_evaluate_with_json(self): + # with tmpfile and json + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + outfile_prefix=None) + + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + # classwise + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=True, + nproc=1, + outfile_prefix=None) + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + # without tmpfile, with json + outfile_prefix = f'{self.tmp_dir.name}/test1' + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + outfile_prefix=outfile_prefix) + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, self.target) + + @unittest.skipIf(panopticapi is None, 'panopticapi is not installed') + def test_format_only(self): + with self.assertRaises(AssertionError): + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + format_only=True, + outfile_prefix=None) + + outfile_prefix = f'{self.tmp_dir.name}/test' + metric = CocoPanopticMetric( + ann_file=self.gt_json_path, + seg_prefix=self.gt_seg_dir, + classwise=False, + nproc=1, + format_only=True, + outfile_prefix=outfile_prefix) + metric.dataset_meta = self.dataset_meta + metric.process({}, deepcopy(self.data_samples)) + eval_results = metric.evaluate(size=1) + self.assertDictEqual(eval_results, dict()) + self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.panoptic')) + self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.panoptic.json')) diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_video_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_video_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..a3d7d1f0c74e60d484c4ea2b34b0aa3f587f2b48 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_coco_video_metric.py @@ -0,0 +1,413 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile +from unittest import TestCase + +import numpy as np +import pycocotools.mask as mask_util +import torch +from mmengine.fileio import dump +from mmengine.structures import BaseDataElement, InstanceData + +from mmdet.evaluation import CocoVideoMetric +from mmdet.structures import DetDataSample, TrackDataSample + + +class TestCocoVideoMetric(TestCase): + + def _create_dummy_coco_json(self, json_name): + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + image = { + 'id': 0, + 'width': 640, + 'height': 640, + 'file_name': 'fake_name.jpg', + } + + annotation_1 = { + 'id': 1, + 'image_id': 0, + 'category_id': 0, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_2 = { + 'id': 2, + 'image_id': 0, + 'category_id': 0, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_3 = { + 'id': 3, + 'image_id': 0, + 'category_id': 1, + 'area': 1600, + 'bbox': [150, 160, 40, 40], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + annotation_4 = { + 'id': 4, + 'image_id': 0, + 'category_id': 0, + 'area': 10000, + 'bbox': [250, 260, 100, 100], + 'iscrowd': 0, + 'segmentation': rle_mask, + } + + categories = [ + { + 'id': 0, + 'name': 'car', + 'supercategory': 'car', + }, + { + 'id': 1, + 'name': 'bicycle', + 'supercategory': 'bicycle', + }, + ] + + fake_json = { + 'images': [image], + 'annotations': + [annotation_1, annotation_2, annotation_3, annotation_4], + 'categories': categories + } + + dump(fake_json, json_name) + + def _create_dummy_results(self): + bboxes = np.array([[50, 60, 70, 80], [100, 120, 130, 150], + [150, 160, 190, 200], [250, 260, 350, 360]]) + scores = np.array([1.0, 0.98, 0.96, 0.95]) + labels = np.array([0, 0, 1, 0]) + dummy_mask = np.zeros((4, 10, 10), dtype=np.uint8) + dummy_mask[:, :5, :5] = 1 + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_init(self): + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + with self.assertRaisesRegex(KeyError, 'metric should be one of'): + CocoVideoMetric(ann_file=fake_json_file, metric='unknown') + + def test_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single coco dataset evaluation + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + + # test box and segm coco dataset evaluation + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/segm_mAP': 1.0, + 'coco/segm_mAP_50': 1.0, + 'coco/segm_mAP_75': 1.0, + 'coco/segm_mAP_s': 1.0, + 'coco/segm_mAP_m': 1.0, + 'coco/segm_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + + # test invalid custom metric_items + with self.assertRaisesRegex(KeyError, + 'metric item "invalid" is not supported'): + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric_items=['invalid']) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process( + dict(inputs=None, data_samples=None), predictions) + coco_metric.evaluate() + + # test custom metric_items + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric_items=['mAP_m']) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = { + 'coco/bbox_mAP_m': 1.0, + } + self.assertDictEqual(eval_results, target) + + def test_classwise_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single coco dataset evaluation + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric='bbox', classwise=True) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/car_precision': 1.0, + 'coco/bicycle_precision': 1.0, + } + self.assertDictEqual(eval_results, target) + + def test_manually_set_iou_thrs(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + + # test single coco dataset evaluation + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric='bbox', iou_thrs=[0.3, 0.6]) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + self.assertEqual(coco_metric.iou_thrs, [0.3, 0.6]) + + def test_fast_eval_recall(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test default proposal nums + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric='proposal_fast') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = {'coco/AR@100': 1.0, 'coco/AR@300': 1.0, 'coco/AR@1000': 1.0} + self.assertDictEqual(eval_results, target) + + # test manually set proposal nums + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, + metric='proposal_fast', + proposal_nums=(2, 4)) + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + target = {'coco/AR@2': 0.5, 'coco/AR@4': 1.0} + self.assertDictEqual(eval_results, target) + + def test_evaluate_proposal(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + coco_metric = CocoVideoMetric( + ann_file=fake_json_file, metric='proposal') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + print(eval_results) + target = { + 'coco/AR@100': 1, + 'coco/AR@300': 1.0, + 'coco/AR@1000': 1.0, + 'coco/AR_s@1000': 1.0, + 'coco/AR_m@1000': 1.0, + 'coco/AR_l@1000': 1.0 + } + self.assertDictEqual(eval_results, target) + + def test_empty_results(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_coco_json(fake_json_file) + coco_metric = CocoVideoMetric(ann_file=fake_json_file, metric='bbox') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + bboxes = np.zeros((0, 4)) + labels = np.array([]) + scores = np.array([]) + dummy_mask = np.zeros((0, 10, 10), dtype=np.uint8) + empty_pred = dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + pred_det_instances = InstanceData(**empty_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + # coco api Index error will be caught + coco_metric.evaluate() + + def test_evaluate_without_json(self): + dummy_pred = self._create_dummy_results() + + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + instances = [{ + 'bbox_label': 0, + 'bbox': [50, 60, 70, 80], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 0, + 'bbox': [100, 120, 130, 150], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 1, + 'bbox': [150, 160, 190, 200], + 'ignore_flag': 0, + 'mask': rle_mask, + }, { + 'bbox_label': 0, + 'bbox': [250, 260, 350, 360], + 'ignore_flag': 0, + 'mask': rle_mask, + }] + coco_metric = CocoVideoMetric( + ann_file=None, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + coco_metric.dataset_meta = dict(classes=['car', 'bicycle']) + pred_det_instances = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_instances = pred_det_instances + img_data_sample.instances = instances + img_data_sample.set_metainfo( + dict(img_id=0, ori_shape=(640, 640), ori_video_length=1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + coco_metric.process(dict(inputs=None, data_samples=None), predictions) + eval_results = coco_metric.evaluate() + print(eval_results) + target = { + 'coco/bbox_mAP': 1.0, + 'coco/bbox_mAP_50': 1.0, + 'coco/bbox_mAP_75': 1.0, + 'coco/bbox_mAP_s': 1.0, + 'coco/bbox_mAP_m': 1.0, + 'coco/bbox_mAP_l': 1.0, + 'coco/segm_mAP': 1.0, + 'coco/segm_mAP_50': 1.0, + 'coco/segm_mAP_75': 1.0, + 'coco/segm_mAP_s': 1.0, + 'coco/segm_mAP_m': 1.0, + 'coco/segm_mAP_l': 1.0, + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.gt.json'))) diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_crowdhuman_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_crowdhuman_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5e04e1a9fbdf20e43cd4fa7cff179a6702082b --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_crowdhuman_metric.py @@ -0,0 +1,54 @@ +import os.path as osp +import tempfile +from unittest import TestCase + +import numpy as np +import torch + +from mmdet.evaluation import CrowdHumanMetric + + +class TestCrowdHumanMetric(TestCase): + + def _create_dummy_results(self): + bboxes = np.array([[1330, 317, 418, 1338], [792, 24, 723, 2017], + [693, 291, 307, 894], [522, 290, 285, 826], + [728, 336, 175, 602], [92, 337, 267, 681]]) + bboxes[:, 2:4] += bboxes[:, 0:2] + scores = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + return dict( + bboxes=torch.from_numpy(bboxes), scores=torch.from_numpy(scores)) + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + self.ann_file_path = \ + 'tests/data/crowdhuman_dataset/test_annotation_train.odgt', + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_init(self): + with self.assertRaisesRegex(KeyError, 'metric should be one of'): + CrowdHumanMetric(ann_file=self.ann_file_path[0], metric='unknown') + + def test_evaluate(self): + # create dummy data + dummy_pred = self._create_dummy_results() + + crowdhuman_metric = CrowdHumanMetric( + ann_file=self.ann_file_path[0], + outfile_prefix=f'{self.tmp_dir.name}/test') + crowdhuman_metric.process({}, [ + dict( + pred_instances=dummy_pred, + img_id='283554,35288000868e92d4', + ori_shape=(1640, 1640)) + ]) + eval_results = crowdhuman_metric.evaluate(size=1) + target = { + 'crowd_human/mAP': 0.8333, + 'crowd_human/mMR': 0.0, + 'crowd_human/JI': 1.0 + } + self.assertDictEqual(eval_results, target) + self.assertTrue(osp.isfile(osp.join(self.tmp_dir.name, 'test.json'))) diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_dump_det_results.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_dump_det_results.py new file mode 100644 index 0000000000000000000000000000000000000000..fc7932297304cb7120e9416a6c13038bb589df40 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_dump_det_results.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os.path as osp +import tempfile +from unittest import TestCase + +import torch +from mmengine.fileio import load +from torch import Tensor + +from mmdet.evaluation import DumpDetResults +from mmdet.structures.mask import encode_mask_results + + +class TestDumpResults(TestCase): + + def test_init(self): + with self.assertRaisesRegex(ValueError, + 'The output file must be a pkl file.'): + DumpDetResults(out_file_path='./results.json') + + def test_process(self): + metric = DumpDetResults(out_file_path='./results.pkl') + data_samples = [dict(data=(Tensor([1, 2, 3]), Tensor([4, 5, 6])))] + metric.process(None, data_samples) + self.assertEqual(len(metric.results), 1) + self.assertEqual(metric.results[0]['data'][0].device, + torch.device('cpu')) + + metric = DumpDetResults(out_file_path='./results.pkl') + masks = torch.zeros(10, 10, 4) + data_samples = [ + dict(pred_instances=dict(masks=masks), gt_instances=[]) + ] + metric.process(None, data_samples) + self.assertEqual(len(metric.results), 1) + self.assertEqual(metric.results[0]['pred_instances']['masks'], + encode_mask_results(masks.numpy())) + self.assertNotIn('gt_instances', metric.results[0]) + + def test_compute_metrics(self): + temp_dir = tempfile.TemporaryDirectory() + path = osp.join(temp_dir.name, 'results.pkl') + metric = DumpDetResults(out_file_path=path) + data_samples = [dict(data=(Tensor([1, 2, 3]), Tensor([4, 5, 6])))] + metric.process(None, data_samples) + metric.compute_metrics(metric.results) + self.assertTrue(osp.isfile(path)) + + results = load(path) + self.assertEqual(len(results), 1) + self.assertEqual(results[0]['data'][0].device, torch.device('cpu')) + + temp_dir.cleanup() diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_lvis_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_lvis_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..6f4eecc5144ac51a73122a641a60743be9aea05d --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_lvis_metric.py @@ -0,0 +1,363 @@ +import os.path as osp +import tempfile +import unittest + +import numpy as np +import pycocotools.mask as mask_util +import torch + +from mmdet.evaluation.metrics import LVISMetric + +try: + import lvis +except ImportError: + lvis = None + +from mmengine.fileio import dump + + +class TestLVISMetric(unittest.TestCase): + + def _create_dummy_lvis_json(self, json_name): + dummy_mask = np.zeros((10, 10), order='F', dtype=np.uint8) + dummy_mask[:5, :5] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + image = { + 'id': 0, + 'width': 640, + 'height': 640, + 'neg_category_ids': [], + 'not_exhaustive_category_ids': [], + 'coco_url': 'http://images.cocodataset.org/val2017/0.jpg', + } + + annotation_1 = { + 'id': 1, + 'image_id': 0, + 'category_id': 1, + 'area': 400, + 'bbox': [50, 60, 20, 20], + 'segmentation': rle_mask, + } + + annotation_2 = { + 'id': 2, + 'image_id': 0, + 'category_id': 1, + 'area': 900, + 'bbox': [100, 120, 30, 30], + 'segmentation': rle_mask, + } + + annotation_3 = { + 'id': 3, + 'image_id': 0, + 'category_id': 2, + 'area': 1600, + 'bbox': [150, 160, 40, 40], + 'segmentation': rle_mask, + } + + annotation_4 = { + 'id': 4, + 'image_id': 0, + 'category_id': 1, + 'area': 10000, + 'bbox': [250, 260, 100, 100], + 'segmentation': rle_mask, + } + + categories = [ + { + 'id': 1, + 'name': 'aerosol_can', + 'frequency': 'c', + 'image_count': 64 + }, + { + 'id': 2, + 'name': 'air_conditioner', + 'frequency': 'f', + 'image_count': 364 + }, + ] + + fake_json = { + 'images': [image], + 'annotations': + [annotation_1, annotation_2, annotation_3, annotation_4], + 'categories': categories + } + + dump(fake_json, json_name) + + def _create_dummy_results(self): + bboxes = np.array([[50, 60, 70, 80], [100, 120, 130, 150], + [150, 160, 190, 200], [250, 260, 350, 360]]) + scores = np.array([1.0, 0.98, 0.96, 0.95]) + labels = np.array([0, 0, 1, 0]) + dummy_mask = np.zeros((4, 10, 10), dtype=np.uint8) + dummy_mask[:, :5, :5] = 1 + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_init(self): + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + with self.assertRaisesRegex(KeyError, 'metric should be one of'): + LVISMetric(ann_file=fake_json_file, metric='unknown') + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single lvis dataset evaluation + lvis_metric = LVISMetric( + ann_file=fake_json_file, + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/bbox_AP': 1.0, + 'lvis/bbox_AP50': 1.0, + 'lvis/bbox_AP75': 1.0, + 'lvis/bbox_APs': 1.0, + 'lvis/bbox_APm': 1.0, + 'lvis/bbox_APl': 1.0, + 'lvis/bbox_APr': -1.0, + 'lvis/bbox_APc': 1.0, + 'lvis/bbox_APf': 1.0 + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + + # test box and segm lvis dataset evaluation + lvis_metric = LVISMetric( + ann_file=fake_json_file, + metric=['bbox', 'segm'], + classwise=False, + outfile_prefix=f'{self.tmp_dir.name}/test') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/bbox_AP': 1.0, + 'lvis/bbox_AP50': 1.0, + 'lvis/bbox_AP75': 1.0, + 'lvis/bbox_APs': 1.0, + 'lvis/bbox_APm': 1.0, + 'lvis/bbox_APl': 1.0, + 'lvis/bbox_APr': -1.0, + 'lvis/bbox_APc': 1.0, + 'lvis/bbox_APf': 1.0, + 'lvis/segm_AP': 1.0, + 'lvis/segm_AP50': 1.0, + 'lvis/segm_AP75': 1.0, + 'lvis/segm_APs': 1.0, + 'lvis/segm_APm': 1.0, + 'lvis/segm_APl': 1.0, + 'lvis/segm_APr': -1.0, + 'lvis/segm_APc': 1.0, + 'lvis/segm_APf': 1.0 + } + self.assertDictEqual(eval_results, target) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.bbox.json'))) + self.assertTrue( + osp.isfile(osp.join(self.tmp_dir.name, 'test.segm.json'))) + + # test invalid custom metric_items + with self.assertRaisesRegex( + KeyError, + "metric should be one of 'bbox', 'segm', 'proposal', " + "'proposal_fast', but got invalid."): + lvis_metric = LVISMetric( + ann_file=fake_json_file, metric=['invalid']) + lvis_metric.evaluate(size=1) + + # test custom metric_items + lvis_metric = LVISMetric(ann_file=fake_json_file, metric_items=['APm']) + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/bbox_APm': 1.0, + } + self.assertDictEqual(eval_results, target) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_classwise_evaluate(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test single lvis dataset evaluation + lvis_metric = LVISMetric( + ann_file=fake_json_file, metric='bbox', classwise=True) + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/bbox_AP': 1.0, + 'lvis/bbox_AP50': 1.0, + 'lvis/bbox_AP75': 1.0, + 'lvis/bbox_APs': 1.0, + 'lvis/bbox_APm': 1.0, + 'lvis/bbox_APl': 1.0, + 'lvis/bbox_APr': -1.0, + 'lvis/bbox_APc': 1.0, + 'lvis/bbox_APf': 1.0, + 'lvis/aerosol_can_precision': 1.0, + 'lvis/air_conditioner_precision': 1.0, + } + self.assertDictEqual(eval_results, target) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_manually_set_iou_thrs(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + + # test single lvis dataset evaluation + lvis_metric = LVISMetric( + ann_file=fake_json_file, metric='bbox', iou_thrs=[0.3, 0.6]) + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + self.assertEqual(lvis_metric.iou_thrs, [0.3, 0.6]) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_fast_eval_recall(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + # test default proposal nums + lvis_metric = LVISMetric( + ann_file=fake_json_file, metric='proposal_fast') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = {'lvis/AR@100': 1.0, 'lvis/AR@300': 1.0, 'lvis/AR@1000': 1.0} + self.assertDictEqual(eval_results, target) + + # test manually set proposal nums + lvis_metric = LVISMetric( + ann_file=fake_json_file, + metric='proposal_fast', + proposal_nums=(2, 4)) + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = {'lvis/AR@2': 0.5, 'lvis/AR@4': 1.0} + self.assertDictEqual(eval_results, target) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_evaluate_proposal(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + lvis_metric = LVISMetric(ann_file=fake_json_file, metric='proposal') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + target = { + 'lvis/AR@300': 1.0, + 'lvis/ARs@300': 1.0, + 'lvis/ARm@300': 1.0, + 'lvis/ARl@300': 1.0 + } + self.assertDictEqual(eval_results, target) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_empty_results(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + lvis_metric = LVISMetric(ann_file=fake_json_file, metric='bbox') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + bboxes = np.zeros((0, 4)) + labels = np.array([]) + scores = np.array([]) + dummy_mask = np.zeros((0, 10, 10), dtype=np.uint8) + empty_pred = dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + masks=torch.from_numpy(dummy_mask)) + lvis_metric.process( + {}, + [dict(pred_instances=empty_pred, img_id=0, ori_shape=(640, 640))]) + # lvis api Index error will be caught + lvis_metric.evaluate(size=1) + + @unittest.skipIf(lvis is None, 'lvis is not installed.') + def test_format_only(self): + # create dummy data + fake_json_file = osp.join(self.tmp_dir.name, 'fake_data.json') + self._create_dummy_lvis_json(fake_json_file) + dummy_pred = self._create_dummy_results() + + with self.assertRaises(AssertionError): + LVISMetric( + ann_file=fake_json_file, + classwise=False, + format_only=True, + outfile_prefix=None) + + lvis_metric = LVISMetric( + ann_file=fake_json_file, + metric='bbox', + classwise=False, + format_only=True, + outfile_prefix=f'{self.tmp_dir.name}/test') + lvis_metric.dataset_meta = dict( + classes=['aerosol_can', 'air_conditioner']) + lvis_metric.process( + {}, + [dict(pred_instances=dummy_pred, img_id=0, ori_shape=(640, 640))]) + eval_results = lvis_metric.evaluate(size=1) + self.assertDictEqual(eval_results, dict()) + self.assertTrue(osp.exists(f'{self.tmp_dir.name}/test.bbox.json')) diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_mot_challenge_metrics.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_mot_challenge_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4636b8e785a9db92938378781a5a46547eb94fa2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_mot_challenge_metrics.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import os +import tempfile +from unittest import TestCase + +import torch +from mmengine.structures import BaseDataElement, InstanceData + +from mmdet.evaluation import MOTChallengeMetric +from mmdet.structures import DetDataSample, TrackDataSample + + +class TestMOTChallengeMetric(TestCase): + + def test_init(self): + with self.assertRaisesRegex(KeyError, 'metric unknown is not'): + MOTChallengeMetric(metric='unknown') + with self.assertRaises(AssertionError): + MOTChallengeMetric(benchmark='MOT21') + + def __del__(self): + self.tmp_dir.cleanup() + + @staticmethod + def _get_predictions_demo(): + instances = [{ + 'bbox_label': 0, + 'bbox': [0, 0, 100, 100], + 'ignore_flag': 0, + 'instance_id': 1, + 'mot_conf': 1.0, + 'category_id': 1, + 'visibility': 1.0 + }, { + 'bbox_label': 0, + 'bbox': [0, 0, 100, 100], + 'ignore_flag': 0, + 'instance_id': 2, + 'mot_conf': 1.0, + 'category_id': 1, + 'visibility': 1.0 + }] + instances_2 = copy.deepcopy(instances) + sep = os.sep + pred_instances_data = dict( + bboxes=torch.tensor([ + [0, 0, 100, 100], + [0, 0, 100, 40], + ]), + instances_id=torch.tensor([1, 2]), + scores=torch.tensor([1.0, 1.0])) + pred_instances_data_2 = copy.deepcopy(pred_instances_data) + pred_instances = InstanceData(**pred_instances_data) + pred_instances_2 = InstanceData(**pred_instances_data_2) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = pred_instances + img_data_sample.instances = instances + img_data_sample.set_metainfo( + dict( + frame_id=0, + ori_video_length=2, + video_length=2, + img_id=1, + img_path=f'xxx{sep}MOT17-09-DPM{sep}img1{sep}000001.jpg', + )) + img_data_sample_2 = DetDataSample() + img_data_sample_2.pred_track_instances = pred_instances_2 + img_data_sample_2.instances = instances_2 + img_data_sample_2.set_metainfo( + dict( + frame_id=1, + ori_video_length=2, + video_length=2, + img_id=2, + img_path=f'xxx{sep}MOT17-09-DPM{sep}img1{sep}000002.jpg', + )) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [ + img_data_sample, img_data_sample_2 + ] + # [TrackDataSample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + return predictions + + def _test_evaluate(self, format_only, outfile_predix=None): + """Test using the metric in the same way as Evaluator.""" + metric = MOTChallengeMetric( + metric=['HOTA', 'CLEAR', 'Identity'], + format_only=format_only, + outfile_prefix=outfile_predix) + metric.dataset_meta = {'classes': ('pedestrian', )} + data_batch = dict(input=None, data_samples=None) + predictions = self._get_predictions_demo() + metric.process(data_batch, predictions) + eval_results = metric.evaluate() + return eval_results + + def test_evaluate(self): + eval_results = self._test_evaluate(False) + target = { + 'motchallenge-metric/IDF1': 0.5, + 'motchallenge-metric/MOTA': 0, + 'motchallenge-metric/HOTA': 0.755, + 'motchallenge-metric/IDSW': 0, + } + for key in target: + assert eval_results[key] - target[key] < 1e-3 + + def test_evaluate_format_only(self): + self.tmp_dir = tempfile.TemporaryDirectory() + eval_results = self._test_evaluate( + True, outfile_predix=self.tmp_dir.name) + assert eval_results == dict() diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_openimages_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_openimages_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..d64b1dfa2d6b10ce8afd734fcf37b95d5ab1f9e8 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_openimages_metric.py @@ -0,0 +1,72 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import numpy as np +import torch + +from mmdet.datasets import OpenImagesDataset +from mmdet.evaluation import OpenImagesMetric +from mmdet.utils import register_all_modules + + +class TestOpenImagesMetric(unittest.TestCase): + + def _create_dummy_results(self): + bboxes = np.array([[23.2172, 31.7541, 987.3413, 357.8443], + [100, 120, 130, 150], [150, 160, 190, 200], + [250, 260, 350, 360]]) + scores = np.array([1.0, 0.98, 0.96, 0.95]) + labels = np.array([0, 0, 0, 0]) + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels)) + + def test_init(self): + # test invalid iou_thrs + with self.assertRaises(AssertionError): + OpenImagesMetric(iou_thrs={'a', 0.5}, ioa_thrs={'b', 0.5}) + # test ioa and iou_thrs length not equal + with self.assertRaises(AssertionError): + OpenImagesMetric(iou_thrs=[0.5, 0.75], ioa_thrs=[0.5]) + + metric = OpenImagesMetric(iou_thrs=0.6) + self.assertEqual(metric.iou_thrs, [0.6]) + + def test_eval(self): + register_all_modules() + dataset = OpenImagesDataset( + data_root='tests/data/OpenImages/', + ann_file='annotations/oidv6-train-annotations-bbox.csv', + data_prefix=dict(img='OpenImages/train/'), + label_file='annotations/class-descriptions-boxable.csv', + hierarchy_file='annotations/bbox_labels_600_hierarchy.json', + meta_file='annotations/image-metas.pkl', + pipeline=[ + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'instances')) + ]) + dataset.full_init() + data_sample = dataset[0]['data_samples'].to_dict() + data_sample['pred_instances'] = self._create_dummy_results() + + metric = OpenImagesMetric() + metric.dataset_meta = dataset.metainfo + metric.process({}, [data_sample]) + results = metric.evaluate(size=len(dataset)) + targets = {'openimages/AP50': 1.0, 'openimages/mAP': 1.0} + self.assertDictEqual(results, targets) + + # test multi-threshold + metric = OpenImagesMetric(iou_thrs=[0.1, 0.5], ioa_thrs=[0.1, 0.5]) + metric.dataset_meta = dataset.metainfo + metric.process({}, [data_sample]) + results = metric.evaluate(size=len(dataset)) + targets = { + 'openimages/AP10': 1.0, + 'openimages/AP50': 1.0, + 'openimages/mAP': 1.0 + } + self.assertDictEqual(results, targets) diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_reid_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_reid_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc6218ad3f69ee8ebf8974a446c04028828ace9 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_reid_metric.py @@ -0,0 +1,55 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.registry import init_default_scope + +from mmdet.registry import METRICS +from mmdet.structures import ReIDDataSample + + +class TestReIDMetrics(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + def test_evaluate(self): + """Test using the metric in the same way as Evaluator.""" + data_samples = [ + ReIDDataSample().set_gt_label(i).to_dict() + for i in [0, 0, 1, 1, 1, 1] + ] + pred_batch = [ + dict(pred_feature=torch.tensor( + [1., .0, .1])), # [x,√,x,x,x],R1=0,R5=1,AP=0.50 + dict(pred_feature=torch.tensor( + [.8, .0, .0])), # [x,√,x,x,x],R1=0,R5=1,AP=0.50 + dict(pred_feature=torch.tensor( + [.1, 1., .1])), # [√,√,x,√,x],R1=1,R5=1,AP≈0.92 + dict(pred_feature=torch.tensor( + [.0, .9, .1])), # [√,√,√,x,x],R1=1,R5=1,AP=1.00 + dict(pred_feature=torch.tensor( + [.9, .1, .0])), # [x,x,√,√,√],R1=0,R5=1,AP≈0.48 + dict(pred_feature=torch.tensor( + [.0, .1, 1.])), # [√,√,x,√,x],R1=1,R5=1,AP≈0.92 + ] + # get union + for idx in range(len(data_samples)): + data_samples[idx] = {**data_samples[idx], **pred_batch[idx]} + + metric = METRICS.build( + dict( + type='ReIDMetrics', + metric=['mAP', 'CMC'], + metric_options=dict(rank_list=[1, 5], max_rank=5), + )) + + prefix = 'reid-metric' + data_batch = dict(input=None, data_samples=None) + metric.process(data_batch, data_samples) + results = metric.evaluate(6) + self.assertIsInstance(results, dict) + self.assertEqual(results[f'{prefix}/mAP'], 0.719) + self.assertEqual(results[f'{prefix}/R1'], 0.5) + self.assertEqual(results[f'{prefix}/R5'], 1.0) diff --git a/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_youtube_vis_metric.py b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_youtube_vis_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..dd46437c6efe447724775c09e7a876df2d0dbc90 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_evaluation/test_metrics/test_youtube_vis_metric.py @@ -0,0 +1,171 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import tempfile +from unittest import TestCase + +import numpy as np +import pycocotools.mask as mask_util +import torch +from mmengine.registry import init_default_scope +from mmengine.structures import BaseDataElement, InstanceData + +from mmdet.registry import METRICS +from mmdet.structures import DetDataSample, TrackDataSample + + +class TestYouTubeVISMetric(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + + def tearDown(self): + self.tmp_dir.cleanup() + + def _create_dummy_results(self, track_id): + bboxes = np.array([[100, 100, 150, 150]]) + scores = np.array([1.0]) + labels = np.array([0]) + instance_id = np.array([track_id]) + dummy_mask = np.zeros((1, 720, 1280), dtype=np.uint8) + dummy_mask[:, 100:150, 100:150] = 1 + return dict( + bboxes=torch.from_numpy(bboxes), + scores=torch.from_numpy(scores), + labels=torch.from_numpy(labels), + instances_id=torch.from_numpy(instance_id), + masks=torch.from_numpy(dummy_mask)) + + def test_format_only(self): + outfile_prefix = f'{self.tmp_dir.name}/result' + vis_metric = METRICS.build( + dict( + type='YouTubeVISMetric', + format_only=True, + outfile_prefix=outfile_prefix, + )) + dummy_pred = self._create_dummy_results(track_id=0) + dummy_mask = np.zeros((720, 1280), order='F', dtype=np.uint8) + dummy_mask[100:150, 100:150] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + instances = [{ + 'bbox_label': 0, + 'bbox': [100, 100, 150, 150], + 'ignore_flag': 0, + 'instance_id': 1, + 'mask': rle_mask, + }] + vis_metric.dataset_meta = dict(classes=['car', 'train']) + data_batch = dict(inputs=None, data_samples=None) + gt_insatnce = InstanceData(**dummy_pred) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = gt_insatnce + img_data_sample.set_metainfo( + dict( + img_id=0, + video_id=1, + ori_video_length=1, + ori_shape=(720, 1280), + instances=instances)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + vis_metric.process(data_batch, predictions) + vis_metric.evaluate(size=1) + assert os.path.exists(f'{outfile_prefix}.json') + assert os.path.exists(f'{outfile_prefix}.submission_file.zip') + + def test_evaluate(self): + """Test using the metric in the same way as Evaluator.""" + dummy_pred_1 = self._create_dummy_results(track_id=1) + dummy_pred_2 = self._create_dummy_results(track_id=1) + dummy_pred_3 = self._create_dummy_results(track_id=2) + + dummy_mask = np.zeros((720, 1280), order='F', dtype=np.uint8) + dummy_mask[100:150, 100:150] = 1 + rle_mask = mask_util.encode(dummy_mask) + rle_mask['counts'] = rle_mask['counts'].decode('utf-8') + instances_1 = [{ + 'bbox_label': 0, + 'bbox': [100, 100, 150, 150], + 'ignore_flag': 0, + 'instance_id': 1, + 'mask': rle_mask, + }] + instances_2 = [{ + 'bbox_label': 0, + 'bbox': [100, 100, 150, 150], + 'ignore_flag': 0, + 'instance_id': 2, + 'mask': rle_mask, + }] + vis_metric = METRICS.build( + dict( + type='YouTubeVISMetric', + outfile_prefix=f'{self.tmp_dir.name}/test', + )) + + vis_metric.dataset_meta = dict(classes=['car', 'train']) + data_batch = dict(inputs=None, data_samples=None) + gt_insatnce = InstanceData(**dummy_pred_1) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = gt_insatnce + img_data_sample.set_metainfo( + dict( + img_id=1, + video_id=1, + ori_video_length=2, + ori_shape=(720, 1280), + instances=instances_1)) + gt_insatnce_2 = InstanceData(**dummy_pred_2) + img_data_sample_2 = DetDataSample() + img_data_sample_2.pred_track_instances = gt_insatnce_2 + img_data_sample_2.set_metainfo( + dict( + img_id=2, + video_id=1, + ori_video_length=2, + ori_shape=(720, 1280), + instances=instances_1)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [ + img_data_sample, img_data_sample_2 + ] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + vis_metric.process(data_batch, predictions) + + gt_insatnce = InstanceData(**dummy_pred_3) + img_data_sample = DetDataSample() + img_data_sample.pred_track_instances = gt_insatnce + img_data_sample.set_metainfo( + dict( + img_id=3, + video_id=2, + ori_video_length=1, + ori_shape=(720, 1280), + instances=instances_2)) + track_data_sample = TrackDataSample() + track_data_sample.video_data_samples = [img_data_sample] + predictions = [] + if isinstance(track_data_sample, BaseDataElement): + predictions.append(track_data_sample.to_dict()) + vis_metric.process(data_batch, predictions) + + eval_results = vis_metric.evaluate(size=3) + target = { + 'youtube_vis/segm_mAP': 1.0, + 'youtube_vis/segm_mAP_50': 1.0, + 'youtube_vis/segm_mAP_75': 1.0, + 'youtube_vis/segm_mAP_s': 1.0, + 'youtube_vis/segm_mAP_m': -1.0, + 'youtube_vis/segm_mAP_l': -1.0, + } + self.assertDictEqual(eval_results, target) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/__init__.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb431ba20bd3a89c0750862f7a4874f0ecd55ffb --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .utils import check_norm_state, is_block, is_norm + +__all__ = ['is_block', 'is_norm', 'check_norm_state'] diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_csp_darknet.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_csp_darknet.py new file mode 100644 index 0000000000000000000000000000000000000000..2a2ad41dba941d85ab59781d27731dac9a9dfb72 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_csp_darknet.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.backbones.csp_darknet import CSPDarknet +from .utils import check_norm_state, is_norm + + +def test_csp_darknet_backbone(): + with pytest.raises(ValueError): + # frozen_stages must in range(-1, len(arch_setting) + 1) + CSPDarknet(frozen_stages=6) + + with pytest.raises(AssertionError): + # out_indices in range(len(arch_setting) + 1) + CSPDarknet(out_indices=[6]) + + # Test CSPDarknet with first stage frozen + frozen_stages = 1 + model = CSPDarknet(frozen_stages=frozen_stages) + model.train() + + for mod in model.stem.modules(): + for param in mod.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'stage{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test CSPDarknet with norm_eval=True + model = CSPDarknet(norm_eval=True) + model.train() + + assert check_norm_state(model.modules(), False) + + # Test CSPDarknet-P5 forward with widen_factor=0.5 + model = CSPDarknet(arch='P5', widen_factor=0.25, out_indices=range(0, 5)) + model.train() + + imgs = torch.randn(1, 3, 64, 64) + feat = model(imgs) + assert len(feat) == 5 + assert feat[0].shape == torch.Size((1, 16, 32, 32)) + assert feat[1].shape == torch.Size((1, 32, 16, 16)) + assert feat[2].shape == torch.Size((1, 64, 8, 8)) + assert feat[3].shape == torch.Size((1, 128, 4, 4)) + assert feat[4].shape == torch.Size((1, 256, 2, 2)) + + # Test CSPDarknet-P6 forward with widen_factor=0.5 + model = CSPDarknet( + arch='P6', + widen_factor=0.25, + out_indices=range(0, 6), + spp_kernal_sizes=(3, 5, 7)) + model.train() + + imgs = torch.randn(1, 3, 128, 128) + feat = model(imgs) + assert feat[0].shape == torch.Size((1, 16, 64, 64)) + assert feat[1].shape == torch.Size((1, 32, 32, 32)) + assert feat[2].shape == torch.Size((1, 64, 16, 16)) + assert feat[3].shape == torch.Size((1, 128, 8, 8)) + assert feat[4].shape == torch.Size((1, 192, 4, 4)) + assert feat[5].shape == torch.Size((1, 256, 2, 2)) + + # Test CSPDarknet forward with dict(type='ReLU') + model = CSPDarknet( + widen_factor=0.125, act_cfg=dict(type='ReLU'), out_indices=range(0, 5)) + model.train() + + imgs = torch.randn(1, 3, 64, 64) + feat = model(imgs) + assert len(feat) == 5 + assert feat[0].shape == torch.Size((1, 8, 32, 32)) + assert feat[1].shape == torch.Size((1, 16, 16, 16)) + assert feat[2].shape == torch.Size((1, 32, 8, 8)) + assert feat[3].shape == torch.Size((1, 64, 4, 4)) + assert feat[4].shape == torch.Size((1, 128, 2, 2)) + + # Test CSPDarknet with BatchNorm forward + model = CSPDarknet(widen_factor=0.125, out_indices=range(0, 5)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, _BatchNorm) + model.train() + + imgs = torch.randn(1, 3, 64, 64) + feat = model(imgs) + assert len(feat) == 5 + assert feat[0].shape == torch.Size((1, 8, 32, 32)) + assert feat[1].shape == torch.Size((1, 16, 16, 16)) + assert feat[2].shape == torch.Size((1, 32, 8, 8)) + assert feat[3].shape == torch.Size((1, 64, 4, 4)) + assert feat[4].shape == torch.Size((1, 128, 2, 2)) + + # Test CSPDarknet with custom arch forward + arch_ovewrite = [[32, 56, 3, True, False], [56, 224, 2, True, False], + [224, 512, 1, True, False]] + model = CSPDarknet( + arch_ovewrite=arch_ovewrite, + widen_factor=0.25, + out_indices=(0, 1, 2, 3)) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size((1, 8, 16, 16)) + assert feat[1].shape == torch.Size((1, 14, 8, 8)) + assert feat[2].shape == torch.Size((1, 56, 4, 4)) + assert feat[3].shape == torch.Size((1, 128, 2, 2)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_detectors_resnet.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_detectors_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..69f462a5433592c117ffe4a450bbdd7d60303681 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_detectors_resnet.py @@ -0,0 +1,47 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest + +from mmdet.models.backbones import DetectoRS_ResNet + + +def test_detectorrs_resnet_backbone(): + detectorrs_cfg = dict( + 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', + conv_cfg=dict(type='ConvAWS'), + sac=dict(type='SAC', use_deform=True), + stage_with_sac=(False, True, True, True), + output_img=True) + """Test init_weights config""" + with pytest.raises(AssertionError): + # pretrained and init_cfg cannot be specified at the same time + DetectoRS_ResNet( + **detectorrs_cfg, pretrained='Pretrained', init_cfg='Pretrained') + + with pytest.raises(AssertionError): + # init_cfg must be a dict + DetectoRS_ResNet( + **detectorrs_cfg, pretrained=None, init_cfg=['Pretrained']) + + with pytest.raises(KeyError): + # init_cfg must contain the key `type` + DetectoRS_ResNet( + **detectorrs_cfg, + pretrained=None, + init_cfg=dict(checkpoint='Pretrained')) + + with pytest.raises(AssertionError): + # init_cfg only support initialize pretrained model way + DetectoRS_ResNet( + **detectorrs_cfg, pretrained=None, init_cfg=dict(type='Trained')) + + with pytest.raises(TypeError): + # pretrained mast be a str or None + model = DetectoRS_ResNet( + **detectorrs_cfg, pretrained=['Pretrained'], init_cfg=None) + model.init_weights() diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_efficientnet.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_efficientnet.py new file mode 100644 index 0000000000000000000000000000000000000000..aa21770481986ccc908d2c859e1afddc3b22b5e8 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_efficientnet.py @@ -0,0 +1,25 @@ +import pytest +import torch + +from mmdet.models.backbones import EfficientNet + + +def test_efficientnet_backbone(): + """Test EfficientNet backbone.""" + with pytest.raises(AssertionError): + # EfficientNet arch should be a key in EfficientNet.arch_settings + EfficientNet(arch='c3') + + model = EfficientNet(arch='b0', out_indices=(0, 1, 2, 3, 4, 5, 6)) + model.train() + + imgs = torch.randn(2, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size([2, 32, 16, 16]) + assert feat[1].shape == torch.Size([2, 16, 16, 16]) + assert feat[2].shape == torch.Size([2, 24, 8, 8]) + assert feat[3].shape == torch.Size([2, 40, 4, 4]) + assert feat[4].shape == torch.Size([2, 112, 2, 2]) + assert feat[5].shape == torch.Size([2, 320, 1, 1]) + assert feat[6].shape == torch.Size([2, 1280, 1, 1]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_hourglass.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_hourglass.py new file mode 100644 index 0000000000000000000000000000000000000000..c26f9c05e6987e01e18b135de788ae3113b85de4 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_hourglass.py @@ -0,0 +1,49 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones.hourglass import HourglassNet + + +def test_hourglass_backbone(): + with pytest.raises(AssertionError): + # HourglassNet's num_stacks should larger than 0 + HourglassNet(num_stacks=0) + + with pytest.raises(AssertionError): + # len(stage_channels) should equal len(stage_blocks) + HourglassNet( + stage_channels=[256, 256, 384, 384, 384], + stage_blocks=[2, 2, 2, 2, 2, 4]) + + with pytest.raises(AssertionError): + # len(stage_channels) should lagrer than downsample_times + HourglassNet( + downsample_times=5, + stage_channels=[256, 256, 384, 384, 384], + stage_blocks=[2, 2, 2, 2, 2]) + + # Test HourglassNet-52 + model = HourglassNet( + num_stacks=1, + stage_channels=(64, 64, 96, 96, 96, 128), + feat_channel=64) + model.train() + + imgs = torch.randn(1, 3, 256, 256) + feat = model(imgs) + assert len(feat) == 1 + assert feat[0].shape == torch.Size([1, 64, 64, 64]) + + # Test HourglassNet-104 + model = HourglassNet( + num_stacks=2, + stage_channels=(64, 64, 96, 96, 96, 128), + feat_channel=64) + model.train() + + imgs = torch.randn(1, 3, 256, 256) + feat = model(imgs) + assert len(feat) == 2 + assert feat[0].shape == torch.Size([1, 64, 64, 64]) + assert feat[1].shape == torch.Size([1, 64, 64, 64]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_hrnet.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_hrnet.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae367b4eaf87a34c54841c1b4c4b4b79ca2f2f3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_hrnet.py @@ -0,0 +1,111 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones.hrnet import HRModule, HRNet +from mmdet.models.backbones.resnet import BasicBlock, Bottleneck + + +@pytest.mark.parametrize('block', [BasicBlock, Bottleneck]) +def test_hrmodule(block): + # Test multiscale forward + num_channles = (32, 64) + in_channels = [c * block.expansion for c in num_channles] + hrmodule = HRModule( + num_branches=2, + blocks=block, + in_channels=in_channels, + num_blocks=(4, 4), + num_channels=num_channles, + ) + + feats = [ + torch.randn(1, in_channels[0], 64, 64), + torch.randn(1, in_channels[1], 32, 32) + ] + feats = hrmodule(feats) + + assert len(feats) == 2 + assert feats[0].shape == torch.Size([1, in_channels[0], 64, 64]) + assert feats[1].shape == torch.Size([1, in_channels[1], 32, 32]) + + # Test single scale forward + num_channles = (32, 64) + in_channels = [c * block.expansion for c in num_channles] + hrmodule = HRModule( + num_branches=2, + blocks=block, + in_channels=in_channels, + num_blocks=(4, 4), + num_channels=num_channles, + multiscale_output=False, + ) + + feats = [ + torch.randn(1, in_channels[0], 64, 64), + torch.randn(1, in_channels[1], 32, 32) + ] + feats = hrmodule(feats) + + assert len(feats) == 1 + assert feats[0].shape == torch.Size([1, in_channels[0], 64, 64]) + + +def test_hrnet_backbone(): + # only have 3 stages + extra = dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128))) + + with pytest.raises(AssertionError): + # HRNet now only support 4 stages + HRNet(extra=extra) + extra['stage4'] = dict( + num_modules=3, + num_branches=3, # should be 4 + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256)) + + with pytest.raises(AssertionError): + # len(num_blocks) should equal num_branches + HRNet(extra=extra) + + extra['stage4']['num_branches'] = 4 + + # Test hrnetv2p_w32 + model = HRNet(extra=extra) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 256, 256) + feats = model(imgs) + assert len(feats) == 4 + assert feats[0].shape == torch.Size([1, 32, 64, 64]) + assert feats[3].shape == torch.Size([1, 256, 8, 8]) + + # Test single scale output + model = HRNet(extra=extra, multiscale_output=False) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 256, 256) + feats = model(imgs) + assert len(feats) == 1 + assert feats[0].shape == torch.Size([1, 32, 64, 64]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_mobilenet_v2.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_mobilenet_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..77df7ea50f105f95cdd79a0271e28ece99452b1c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_mobilenet_v2.py @@ -0,0 +1,173 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from torch.nn.modules import GroupNorm +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.backbones.mobilenet_v2 import MobileNetV2 +from .utils import check_norm_state, is_block, is_norm + + +def test_mobilenetv2_backbone(): + with pytest.raises(ValueError): + # frozen_stages must in range(-1, 8) + MobileNetV2(frozen_stages=8) + + with pytest.raises(ValueError): + # out_indices in range(-1, 8) + MobileNetV2(out_indices=[8]) + + # Test MobileNetV2 with first stage frozen + frozen_stages = 1 + model = MobileNetV2(frozen_stages=frozen_stages) + model.train() + + for mod in model.conv1.modules(): + for param in mod.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'layer{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test MobileNetV2 with norm_eval=True + model = MobileNetV2(norm_eval=True) + model.train() + + assert check_norm_state(model.modules(), False) + + # Test MobileNetV2 forward with widen_factor=1.0 + model = MobileNetV2(widen_factor=1.0, out_indices=range(0, 8)) + model.train() + + assert check_norm_state(model.modules(), True) + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 8 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) + assert feat[7].shape == torch.Size((1, 1280, 7, 7)) + + # Test MobileNetV2 forward with widen_factor=0.5 + model = MobileNetV2(widen_factor=0.5, out_indices=range(0, 7)) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 8, 112, 112)) + assert feat[1].shape == torch.Size((1, 16, 56, 56)) + assert feat[2].shape == torch.Size((1, 16, 28, 28)) + assert feat[3].shape == torch.Size((1, 32, 14, 14)) + assert feat[4].shape == torch.Size((1, 48, 14, 14)) + assert feat[5].shape == torch.Size((1, 80, 7, 7)) + assert feat[6].shape == torch.Size((1, 160, 7, 7)) + + # Test MobileNetV2 forward with widen_factor=2.0 + model = MobileNetV2(widen_factor=2.0, out_indices=range(0, 8)) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert feat[0].shape == torch.Size((1, 32, 112, 112)) + assert feat[1].shape == torch.Size((1, 48, 56, 56)) + assert feat[2].shape == torch.Size((1, 64, 28, 28)) + assert feat[3].shape == torch.Size((1, 128, 14, 14)) + assert feat[4].shape == torch.Size((1, 192, 14, 14)) + assert feat[5].shape == torch.Size((1, 320, 7, 7)) + assert feat[6].shape == torch.Size((1, 640, 7, 7)) + assert feat[7].shape == torch.Size((1, 2560, 7, 7)) + + # Test MobileNetV2 forward with dict(type='ReLU') + model = MobileNetV2( + widen_factor=1.0, act_cfg=dict(type='ReLU'), out_indices=range(0, 7)) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) + + # Test MobileNetV2 with BatchNorm forward + model = MobileNetV2(widen_factor=1.0, out_indices=range(0, 7)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, _BatchNorm) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) + + # Test MobileNetV2 with GroupNorm forward + model = MobileNetV2( + widen_factor=1.0, + norm_cfg=dict(type='GN', num_groups=2, requires_grad=True), + out_indices=range(0, 7)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, GroupNorm) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) + + # Test MobileNetV2 with layers 1, 3, 5 out forward + model = MobileNetV2(widen_factor=1.0, out_indices=(0, 2, 4)) + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 32, 28, 28)) + assert feat[2].shape == torch.Size((1, 96, 14, 14)) + + # Test MobileNetV2 with checkpoint forward + model = MobileNetV2( + widen_factor=1.0, with_cp=True, out_indices=range(0, 7)) + for m in model.modules(): + if is_block(m): + assert m.with_cp + model.train() + + imgs = torch.randn(1, 3, 224, 224) + feat = model(imgs) + assert len(feat) == 7 + assert feat[0].shape == torch.Size((1, 16, 112, 112)) + assert feat[1].shape == torch.Size((1, 24, 56, 56)) + assert feat[2].shape == torch.Size((1, 32, 28, 28)) + assert feat[3].shape == torch.Size((1, 64, 14, 14)) + assert feat[4].shape == torch.Size((1, 96, 14, 14)) + assert feat[5].shape == torch.Size((1, 160, 7, 7)) + assert feat[6].shape == torch.Size((1, 320, 7, 7)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_pvt.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_pvt.py new file mode 100644 index 0000000000000000000000000000000000000000..029fdb327803b838001a9121a738e890fbc14780 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_pvt.py @@ -0,0 +1,103 @@ +import pytest +import torch + +from mmdet.models.backbones.pvt import (PVTEncoderLayer, + PyramidVisionTransformer, + PyramidVisionTransformerV2) + + +def test_pvt_block(): + # test PVT structure and forward + block = PVTEncoderLayer( + embed_dims=64, num_heads=4, feedforward_channels=256) + assert block.ffn.embed_dims == 64 + assert block.attn.num_heads == 4 + assert block.ffn.feedforward_channels == 256 + x = torch.randn(1, 56 * 56, 64) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + +def test_pvt(): + """Test PVT backbone.""" + + with pytest.raises(TypeError): + # Pretrained arg must be str or None. + PyramidVisionTransformer(pretrained=123) + + # test pretrained image size + with pytest.raises(AssertionError): + PyramidVisionTransformer(pretrain_img_size=(224, 224, 224)) + + # Test absolute position embedding + temp = torch.randn((1, 3, 224, 224)) + model = PyramidVisionTransformer( + pretrain_img_size=224, use_abs_pos_embed=True) + model.init_weights() + model(temp) + + # Test normal inference + temp = torch.randn((1, 3, 32, 32)) + model = PyramidVisionTransformer() + outs = model(temp) + assert outs[0].shape == (1, 64, 8, 8) + assert outs[1].shape == (1, 128, 4, 4) + assert outs[2].shape == (1, 320, 2, 2) + assert outs[3].shape == (1, 512, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 33, 33)) + model = PyramidVisionTransformer() + outs = model(temp) + assert outs[0].shape == (1, 64, 8, 8) + assert outs[1].shape == (1, 128, 4, 4) + assert outs[2].shape == (1, 320, 2, 2) + assert outs[3].shape == (1, 512, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 112, 137)) + model = PyramidVisionTransformer() + outs = model(temp) + assert outs[0].shape == (1, 64, 28, 34) + assert outs[1].shape == (1, 128, 14, 17) + assert outs[2].shape == (1, 320, 7, 8) + assert outs[3].shape == (1, 512, 3, 4) + + +def test_pvtv2(): + """Test PVTv2 backbone.""" + + with pytest.raises(TypeError): + # Pretrained arg must be str or None. + PyramidVisionTransformerV2(pretrained=123) + + # test pretrained image size + with pytest.raises(AssertionError): + PyramidVisionTransformerV2(pretrain_img_size=(224, 224, 224)) + + # Test normal inference + temp = torch.randn((1, 3, 32, 32)) + model = PyramidVisionTransformerV2() + outs = model(temp) + assert outs[0].shape == (1, 64, 8, 8) + assert outs[1].shape == (1, 128, 4, 4) + assert outs[2].shape == (1, 320, 2, 2) + assert outs[3].shape == (1, 512, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 31, 31)) + model = PyramidVisionTransformerV2() + outs = model(temp) + assert outs[0].shape == (1, 64, 8, 8) + assert outs[1].shape == (1, 128, 4, 4) + assert outs[2].shape == (1, 320, 2, 2) + assert outs[3].shape == (1, 512, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 112, 137)) + model = PyramidVisionTransformerV2() + outs = model(temp) + assert outs[0].shape == (1, 64, 28, 35) + assert outs[1].shape == (1, 128, 14, 18) + assert outs[2].shape == (1, 320, 7, 9) + assert outs[3].shape == (1, 512, 4, 5) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_regnet.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_regnet.py new file mode 100644 index 0000000000000000000000000000000000000000..2f94b1156d5ddd6805a74d41c6211d98d6ec1f0d --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_regnet.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import RegNet + +regnet_test_data = [ + ('regnetx_400mf', + dict(w0=24, wa=24.48, wm=2.54, group_w=16, depth=22, + bot_mul=1.0), [32, 64, 160, 384]), + ('regnetx_800mf', + dict(w0=56, wa=35.73, wm=2.28, group_w=16, depth=16, + bot_mul=1.0), [64, 128, 288, 672]), + ('regnetx_1.6gf', + dict(w0=80, wa=34.01, wm=2.25, group_w=24, depth=18, + bot_mul=1.0), [72, 168, 408, 912]), + ('regnetx_3.2gf', + dict(w0=88, wa=26.31, wm=2.25, group_w=48, depth=25, + bot_mul=1.0), [96, 192, 432, 1008]), + ('regnetx_4.0gf', + dict(w0=96, wa=38.65, wm=2.43, group_w=40, depth=23, + bot_mul=1.0), [80, 240, 560, 1360]), + ('regnetx_6.4gf', + dict(w0=184, wa=60.83, wm=2.07, group_w=56, depth=17, + bot_mul=1.0), [168, 392, 784, 1624]), + ('regnetx_8.0gf', + dict(w0=80, wa=49.56, wm=2.88, group_w=120, depth=23, + bot_mul=1.0), [80, 240, 720, 1920]), + ('regnetx_12gf', + dict(w0=168, wa=73.36, wm=2.37, group_w=112, depth=19, + bot_mul=1.0), [224, 448, 896, 2240]), +] + + +@pytest.mark.parametrize('arch_name,arch,out_channels', regnet_test_data) +def test_regnet_backbone(arch_name, arch, out_channels): + with pytest.raises(AssertionError): + # ResNeXt depth should be in [50, 101, 152] + RegNet(arch_name + '233') + + # Test RegNet with arch_name + model = RegNet(arch_name) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, out_channels[0], 8, 8]) + assert feat[1].shape == torch.Size([1, out_channels[1], 4, 4]) + assert feat[2].shape == torch.Size([1, out_channels[2], 2, 2]) + assert feat[3].shape == torch.Size([1, out_channels[3], 1, 1]) + + # Test RegNet with arch + model = RegNet(arch) + assert feat[0].shape == torch.Size([1, out_channels[0], 8, 8]) + assert feat[1].shape == torch.Size([1, out_channels[1], 4, 4]) + assert feat[2].shape == torch.Size([1, out_channels[2], 2, 2]) + assert feat[3].shape == torch.Size([1, out_channels[3], 1, 1]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_renext.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_renext.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce2ee6137d77084ccb47a32c8f40557e576e74d --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_renext.py @@ -0,0 +1,105 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import ResNeXt +from mmdet.models.backbones.resnext import Bottleneck as BottleneckX +from .utils import is_block + + +def test_renext_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + BottleneckX(64, 64, groups=32, base_width=4, style='tensorflow') + + # Test ResNeXt Bottleneck structure + block = BottleneckX( + 64, 64, groups=32, base_width=4, stride=2, style='pytorch') + assert block.conv2.stride == (2, 2) + assert block.conv2.groups == 32 + assert block.conv2.out_channels == 128 + + # Test ResNeXt Bottleneck with DCN + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + with pytest.raises(AssertionError): + # conv_cfg must be None if dcn is not None + BottleneckX( + 64, + 64, + groups=32, + base_width=4, + dcn=dcn, + conv_cfg=dict(type='Conv')) + BottleneckX(64, 64, dcn=dcn) + + # Test ResNeXt Bottleneck forward + block = BottleneckX(64, 16, groups=32, base_width=4) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test ResNeXt Bottleneck forward with plugins + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + stages=(False, False, True, True), + position='after_conv2') + ] + block = BottleneckX(64, 16, groups=32, base_width=4, plugins=plugins) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnext_backbone(): + with pytest.raises(KeyError): + # ResNeXt depth should be in [50, 101, 152] + ResNeXt(depth=18) + + # Test ResNeXt with group 32, base_width 4 + model = ResNeXt(depth=50, groups=32, base_width=4) + for m in model.modules(): + if is_block(m): + assert m.conv2.groups == 32 + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 256, 8, 8]) + assert feat[1].shape == torch.Size([1, 512, 4, 4]) + assert feat[2].shape == torch.Size([1, 1024, 2, 2]) + assert feat[3].shape == torch.Size([1, 2048, 1, 1]) + + +regnet_test_data = [ + ('regnetx_400mf', + dict(w0=24, wa=24.48, wm=2.54, group_w=16, depth=22, + bot_mul=1.0), [32, 64, 160, 384]), + ('regnetx_800mf', + dict(w0=56, wa=35.73, wm=2.28, group_w=16, depth=16, + bot_mul=1.0), [64, 128, 288, 672]), + ('regnetx_1.6gf', + dict(w0=80, wa=34.01, wm=2.25, group_w=24, depth=18, + bot_mul=1.0), [72, 168, 408, 912]), + ('regnetx_3.2gf', + dict(w0=88, wa=26.31, wm=2.25, group_w=48, depth=25, + bot_mul=1.0), [96, 192, 432, 1008]), + ('regnetx_4.0gf', + dict(w0=96, wa=38.65, wm=2.43, group_w=40, depth=23, + bot_mul=1.0), [80, 240, 560, 1360]), + ('regnetx_6.4gf', + dict(w0=184, wa=60.83, wm=2.07, group_w=56, depth=17, + bot_mul=1.0), [168, 392, 784, 1624]), + ('regnetx_8.0gf', + dict(w0=80, wa=49.56, wm=2.88, group_w=120, depth=23, + bot_mul=1.0), [80, 240, 720, 1920]), + ('regnetx_12gf', + dict(w0=168, wa=73.36, wm=2.37, group_w=112, depth=19, + bot_mul=1.0), [224, 448, 896, 2240]), +] diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_res2net.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_res2net.py new file mode 100644 index 0000000000000000000000000000000000000000..6757869d5a663738bd8c8321e22d491d3a92dbbf --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_res2net.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import Res2Net +from mmdet.models.backbones.res2net import Bottle2neck +from .utils import is_block + + +def test_res2net_bottle2neck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + Bottle2neck(64, 64, base_width=26, scales=4, style='tensorflow') + + with pytest.raises(AssertionError): + # Scale must be larger than 1 + Bottle2neck(64, 64, base_width=26, scales=1, style='pytorch') + + # Test Res2Net Bottle2neck structure + block = Bottle2neck( + 64, 64, base_width=26, stride=2, scales=4, style='pytorch') + assert block.scales == 4 + + # Test Res2Net Bottle2neck with DCN + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + with pytest.raises(AssertionError): + # conv_cfg must be None if dcn is not None + Bottle2neck( + 64, + 64, + base_width=26, + scales=4, + dcn=dcn, + conv_cfg=dict(type='Conv')) + Bottle2neck(64, 64, dcn=dcn) + + # Test Res2Net Bottle2neck forward + block = Bottle2neck(64, 16, base_width=26, scales=4) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_res2net_backbone(): + with pytest.raises(KeyError): + # Res2Net depth should be in [50, 101, 152] + Res2Net(depth=18) + + # Test Res2Net with scales 4, base_width 26 + model = Res2Net(depth=50, scales=4, base_width=26) + for m in model.modules(): + if is_block(m): + assert m.scales == 4 + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 256, 8, 8]) + assert feat[1].shape == torch.Size([1, 512, 4, 4]) + assert feat[2].shape == torch.Size([1, 1024, 2, 2]) + assert feat[3].shape == torch.Size([1, 2048, 1, 1]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_resnest.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_resnest.py new file mode 100644 index 0000000000000000000000000000000000000000..245fdfd3181096afd3bc1c90d790f95186360ace --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_resnest.py @@ -0,0 +1,47 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import ResNeSt +from mmdet.models.backbones.resnest import Bottleneck as BottleneckS + + +def test_resnest_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + BottleneckS(64, 64, radix=2, reduction_factor=4, style='tensorflow') + + # Test ResNeSt Bottleneck structure + block = BottleneckS( + 2, 4, radix=2, reduction_factor=4, stride=2, style='pytorch') + assert block.avd_layer.stride == 2 + assert block.conv2.channels == 4 + + # Test ResNeSt Bottleneck forward + block = BottleneckS(16, 4, radix=2, reduction_factor=4) + x = torch.randn(2, 16, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([2, 16, 56, 56]) + + +def test_resnest_backbone(): + with pytest.raises(KeyError): + # ResNeSt depth should be in [50, 101, 152, 200] + ResNeSt(depth=18) + + # Test ResNeSt with radix 2, reduction_factor 4 + model = ResNeSt( + depth=50, + base_channels=4, + radix=2, + reduction_factor=4, + out_indices=(0, 1, 2, 3)) + model.train() + + imgs = torch.randn(2, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([2, 16, 8, 8]) + assert feat[1].shape == torch.Size([2, 32, 4, 4]) + assert feat[2].shape == torch.Size([2, 64, 2, 2]) + assert feat[3].shape == torch.Size([2, 128, 1, 1]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_resnet.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f648f3b5e00a9191595553fcd75e8c7482a8d2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_resnet.py @@ -0,0 +1,654 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmcv.ops import DeformConv2dPack +from torch.nn.modules import AvgPool2d, GroupNorm +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.backbones import ResNet, ResNetV1d +from mmdet.models.backbones.resnet import BasicBlock, Bottleneck +from mmdet.models.layers import ResLayer, SimplifiedBasicBlock +from .utils import check_norm_state, is_block, is_norm + + +def assert_params_all_zeros(module) -> bool: + """Check if the parameters of the module is all zeros. + + Args: + module (nn.Module): The module to be checked. + + Returns: + bool: Whether the parameters of the module is all zeros. + """ + weight_data = module.weight.data + is_weight_zero = weight_data.allclose( + weight_data.new_zeros(weight_data.size())) + + if hasattr(module, 'bias') and module.bias is not None: + bias_data = module.bias.data + is_bias_zero = bias_data.allclose( + bias_data.new_zeros(bias_data.size())) + else: + is_bias_zero = True + + return is_weight_zero and is_bias_zero + + +def test_resnet_basic_block(): + with pytest.raises(AssertionError): + # Not implemented yet. + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + BasicBlock(64, 64, dcn=dcn) + + with pytest.raises(AssertionError): + # Not implemented yet. + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + BasicBlock(64, 64, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + BasicBlock(64, 64, plugins=plugins) + + # test BasicBlock structure and forward + block = BasicBlock(64, 64) + assert block.conv1.in_channels == 64 + assert block.conv1.out_channels == 64 + assert block.conv1.kernel_size == (3, 3) + assert block.conv2.in_channels == 64 + assert block.conv2.out_channels == 64 + assert block.conv2.kernel_size == (3, 3) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test BasicBlock with checkpoint forward + block = BasicBlock(64, 64, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnet_bottleneck(): + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + Bottleneck(64, 64, style='tensorflow') + + with pytest.raises(AssertionError): + # Allowed positions are 'after_conv1', 'after_conv2', 'after_conv3' + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv4') + ] + Bottleneck(64, 16, plugins=plugins) + + with pytest.raises(AssertionError): + # Need to specify different postfix to avoid duplicate plugin name + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + Bottleneck(64, 16, plugins=plugins) + + with pytest.raises(KeyError): + # Plugin type is not supported + plugins = [dict(cfg=dict(type='WrongPlugin'), position='after_conv3')] + Bottleneck(64, 16, plugins=plugins) + + # Test Bottleneck with checkpoint forward + block = Bottleneck(64, 16, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck style + block = Bottleneck(64, 64, stride=2, style='pytorch') + assert block.conv1.stride == (1, 1) + assert block.conv2.stride == (2, 2) + block = Bottleneck(64, 64, stride=2, style='caffe') + assert block.conv1.stride == (2, 2) + assert block.conv2.stride == (1, 1) + + # Test Bottleneck DCN + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + with pytest.raises(AssertionError): + Bottleneck(64, 64, dcn=dcn, conv_cfg=dict(type='Conv')) + block = Bottleneck(64, 64, dcn=dcn) + assert isinstance(block.conv2, DeformConv2dPack) + + # Test Bottleneck forward + block = Bottleneck(64, 16) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2, 1 NonLocal2D + # after conv2, 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2'), + dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + assert block.nonlocal_block.in_channels == 16 + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv2, 2 ContextBlock after + # conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), + position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=3), + position='after_conv3') + ] + block = Bottleneck(64, 16, plugins=plugins) + assert block.context_block1.in_channels == 16 + assert block.context_block2.in_channels == 64 + assert block.context_block3.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_simplied_basic_block(): + with pytest.raises(AssertionError): + # Not implemented yet. + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + SimplifiedBasicBlock(64, 64, dcn=dcn) + + with pytest.raises(AssertionError): + # Not implemented yet. + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + SimplifiedBasicBlock(64, 64, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + SimplifiedBasicBlock(64, 64, plugins=plugins) + + with pytest.raises(AssertionError): + # Not implemented yet + SimplifiedBasicBlock(64, 64, with_cp=True) + + # test SimplifiedBasicBlock structure and forward + block = SimplifiedBasicBlock(64, 64) + assert block.conv1.in_channels == 64 + assert block.conv1.out_channels == 64 + assert block.conv1.kernel_size == (3, 3) + assert block.conv2.in_channels == 64 + assert block.conv2.out_channels == 64 + assert block.conv2.kernel_size == (3, 3) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # test SimplifiedBasicBlock without norm + block = SimplifiedBasicBlock(64, 64, norm_cfg=None) + assert block.norm1 is None + assert block.norm2 is None + x_out = block(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + +def test_resnet_res_layer(): + # Test ResLayer of 3 Bottleneck w\o downsample + layer = ResLayer(Bottleneck, 64, 16, 3) + assert len(layer) == 3 + assert layer[0].conv1.in_channels == 64 + assert layer[0].conv1.out_channels == 16 + for i in range(1, len(layer)): + assert layer[i].conv1.in_channels == 64 + assert layer[i].conv1.out_channels == 16 + for i in range(len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 64, 56, 56]) + + # Test ResLayer of 3 Bottleneck with downsample + layer = ResLayer(Bottleneck, 64, 64, 3) + assert layer[0].downsample[0].out_channels == 256 + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 56, 56]) + + # Test ResLayer of 3 Bottleneck with stride=2 + layer = ResLayer(Bottleneck, 64, 64, 3, stride=2) + assert layer[0].downsample[0].out_channels == 256 + assert layer[0].downsample[0].stride == (2, 2) + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 28, 28]) + + # Test ResLayer of 3 Bottleneck with stride=2 and average downsample + layer = ResLayer(Bottleneck, 64, 64, 3, stride=2, avg_down=True) + assert isinstance(layer[0].downsample[0], AvgPool2d) + assert layer[0].downsample[1].out_channels == 256 + assert layer[0].downsample[1].stride == (1, 1) + for i in range(1, len(layer)): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 256, 28, 28]) + + # Test ResLayer of 3 BasicBlock with stride=2 and downsample_first=False + layer = ResLayer(BasicBlock, 64, 64, 3, stride=2, downsample_first=False) + assert layer[2].downsample[0].out_channels == 64 + assert layer[2].downsample[0].stride == (2, 2) + for i in range(len(layer) - 1): + assert layer[i].downsample is None + x = torch.randn(1, 64, 56, 56) + x_out = layer(x) + assert x_out.shape == torch.Size([1, 64, 28, 28]) + + +def test_resnest_stem(): + # Test default stem_channels + model = ResNet(50) + assert model.stem_channels == 64 + assert model.conv1.out_channels == 64 + assert model.norm1.num_features == 64 + + # Test default stem_channels, with base_channels=3 + model = ResNet(50, base_channels=3) + assert model.stem_channels == 3 + assert model.conv1.out_channels == 3 + assert model.norm1.num_features == 3 + assert model.layer1[0].conv1.in_channels == 3 + + # Test stem_channels=3 + model = ResNet(50, stem_channels=3) + assert model.stem_channels == 3 + assert model.conv1.out_channels == 3 + assert model.norm1.num_features == 3 + assert model.layer1[0].conv1.in_channels == 3 + + # Test stem_channels=3, with base_channels=2 + model = ResNet(50, stem_channels=3, base_channels=2) + assert model.stem_channels == 3 + assert model.conv1.out_channels == 3 + assert model.norm1.num_features == 3 + assert model.layer1[0].conv1.in_channels == 3 + + # Test V1d stem_channels + model = ResNetV1d(depth=50, stem_channels=6) + model.train() + assert model.stem[0].out_channels == 3 + assert model.stem[1].num_features == 3 + assert model.stem[3].out_channels == 3 + assert model.stem[4].num_features == 3 + assert model.stem[6].out_channels == 6 + assert model.stem[7].num_features == 6 + assert model.layer1[0].conv1.in_channels == 6 + + +def test_resnet_backbone(): + """Test resnet backbone.""" + with pytest.raises(KeyError): + # ResNet depth should be in [18, 34, 50, 101, 152] + ResNet(20) + + with pytest.raises(AssertionError): + # In ResNet: 1 <= num_stages <= 4 + ResNet(50, num_stages=0) + + with pytest.raises(AssertionError): + # len(stage_with_dcn) == num_stages + dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False) + ResNet(50, dcn=dcn, stage_with_dcn=(True, )) + + with pytest.raises(AssertionError): + # len(stage_with_plugin) == num_stages + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + stages=(False, True, True), + position='after_conv3') + ] + ResNet(50, plugins=plugins) + + with pytest.raises(AssertionError): + # In ResNet: 1 <= num_stages <= 4 + ResNet(50, num_stages=5) + + with pytest.raises(AssertionError): + # len(strides) == len(dilations) == num_stages + ResNet(50, strides=(1, ), dilations=(1, 1), num_stages=3) + + with pytest.raises(TypeError): + # pretrained must be a string path + model = ResNet(50, pretrained=0) + + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + ResNet(50, style='tensorflow') + + # Test ResNet50 norm_eval=True + model = ResNet(50, norm_eval=True, base_channels=1) + model.train() + assert check_norm_state(model.modules(), False) + + # Test ResNet50 with torchvision pretrained weight + model = ResNet( + depth=50, norm_eval=True, pretrained='torchvision://resnet50') + model.train() + assert check_norm_state(model.modules(), False) + + # Test ResNet50 with first stage frozen + frozen_stages = 1 + model = ResNet(50, frozen_stages=frozen_stages, base_channels=1) + model.train() + assert model.norm1.training is False + for layer in [model.conv1, model.norm1]: + for param in layer.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'layer{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test ResNet50V1d with first stage frozen + model = ResNetV1d(depth=50, frozen_stages=frozen_stages, base_channels=2) + assert len(model.stem) == 9 + model.train() + assert check_norm_state(model.stem, False) + for param in model.stem.parameters(): + assert param.requires_grad is False + for i in range(1, frozen_stages + 1): + layer = getattr(model, f'layer{i}') + for mod in layer.modules(): + if isinstance(mod, _BatchNorm): + assert mod.training is False + for param in layer.parameters(): + assert param.requires_grad is False + + # Test ResNet18 forward + model = ResNet(18) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 64, 8, 8]) + assert feat[1].shape == torch.Size([1, 128, 4, 4]) + assert feat[2].shape == torch.Size([1, 256, 2, 2]) + assert feat[3].shape == torch.Size([1, 512, 1, 1]) + + # Test ResNet18 with checkpoint forward + model = ResNet(18, with_cp=True) + for m in model.modules(): + if is_block(m): + assert m.with_cp + + # Test ResNet50 with BatchNorm forward + model = ResNet(50, base_channels=1) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, _BatchNorm) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 4, 8, 8]) + assert feat[1].shape == torch.Size([1, 8, 4, 4]) + assert feat[2].shape == torch.Size([1, 16, 2, 2]) + assert feat[3].shape == torch.Size([1, 32, 1, 1]) + + # Test ResNet50 with layers 1, 2, 3 out forward + model = ResNet(50, out_indices=(0, 1, 2), base_channels=1) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 3 + assert feat[0].shape == torch.Size([1, 4, 8, 8]) + assert feat[1].shape == torch.Size([1, 8, 4, 4]) + assert feat[2].shape == torch.Size([1, 16, 2, 2]) + + # Test ResNet50 with checkpoint forward + model = ResNet(50, with_cp=True, base_channels=1) + for m in model.modules(): + if is_block(m): + assert m.with_cp + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 4, 8, 8]) + assert feat[1].shape == torch.Size([1, 8, 4, 4]) + assert feat[2].shape == torch.Size([1, 16, 2, 2]) + assert feat[3].shape == torch.Size([1, 32, 1, 1]) + + # Test ResNet50 with GroupNorm forward + model = ResNet( + 50, + base_channels=4, + norm_cfg=dict(type='GN', num_groups=2, requires_grad=True)) + for m in model.modules(): + if is_norm(m): + assert isinstance(m, GroupNorm) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 16, 8, 8]) + assert feat[1].shape == torch.Size([1, 32, 4, 4]) + assert feat[2].shape == torch.Size([1, 64, 2, 2]) + assert feat[3].shape == torch.Size([1, 128, 1, 1]) + + # Test ResNet50 with 1 GeneralizedAttention after conv2, 1 NonLocal2D + # after conv2, 1 ContextBlock after conv3 in layers 2, 3, 4 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + stages=(False, True, True, True), + position='after_conv2'), + dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + stages=(False, True, True, False), + position='after_conv3') + ] + model = ResNet(50, plugins=plugins, base_channels=8) + for m in model.layer1.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'gen_attention_block') + assert m.nonlocal_block.in_channels == 8 + for m in model.layer2.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 16 + assert m.gen_attention_block.in_channels == 16 + assert m.context_block.in_channels == 64 + + for m in model.layer3.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 32 + assert m.gen_attention_block.in_channels == 32 + assert m.context_block.in_channels == 128 + + for m in model.layer4.modules(): + if is_block(m): + assert m.nonlocal_block.in_channels == 64 + assert m.gen_attention_block.in_channels == 64 + assert not hasattr(m, 'context_block') + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 32, 8, 8]) + assert feat[1].shape == torch.Size([1, 64, 4, 4]) + assert feat[2].shape == torch.Size([1, 128, 2, 2]) + assert feat[3].shape == torch.Size([1, 256, 1, 1]) + + # Test ResNet50 with 1 ContextBlock after conv2, 1 ContextBlock after + # conv3 in layers 2, 3, 4 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), + stages=(False, True, True, False), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), + stages=(False, True, True, False), + position='after_conv3') + ] + + model = ResNet(50, plugins=plugins, base_channels=8) + for m in model.layer1.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'context_block1') + assert not hasattr(m, 'context_block2') + for m in model.layer2.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert m.context_block1.in_channels == 64 + assert m.context_block2.in_channels == 64 + + for m in model.layer3.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert m.context_block1.in_channels == 128 + assert m.context_block2.in_channels == 128 + + for m in model.layer4.modules(): + if is_block(m): + assert not hasattr(m, 'context_block') + assert not hasattr(m, 'context_block1') + assert not hasattr(m, 'context_block2') + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 32, 8, 8]) + assert feat[1].shape == torch.Size([1, 64, 4, 4]) + assert feat[2].shape == torch.Size([1, 128, 2, 2]) + assert feat[3].shape == torch.Size([1, 256, 1, 1]) + + # Test ResNet50 zero initialization of residual + model = ResNet(50, zero_init_residual=True, base_channels=1) + model.init_weights() + for m in model.modules(): + if isinstance(m, Bottleneck): + assert assert_params_all_zeros(m.norm3) + elif isinstance(m, BasicBlock): + assert assert_params_all_zeros(m.norm2) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 4, 8, 8]) + assert feat[1].shape == torch.Size([1, 8, 4, 4]) + assert feat[2].shape == torch.Size([1, 16, 2, 2]) + assert feat[3].shape == torch.Size([1, 32, 1, 1]) + + # Test ResNetV1d forward + model = ResNetV1d(depth=50, base_channels=2) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 8, 8, 8]) + assert feat[1].shape == torch.Size([1, 16, 4, 4]) + assert feat[2].shape == torch.Size([1, 32, 2, 2]) + assert feat[3].shape == torch.Size([1, 64, 1, 1]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_swin.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_swin.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6420cf8e3f67f9f0c47cc48f6197d1b7302283 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_swin.py @@ -0,0 +1,82 @@ +import pytest +import torch + +from mmdet.models.backbones.swin import SwinBlock, SwinTransformer + + +def test_swin_block(): + # test SwinBlock structure and forward + block = SwinBlock(embed_dims=64, num_heads=4, feedforward_channels=256) + assert block.ffn.embed_dims == 64 + assert block.attn.w_msa.num_heads == 4 + assert block.ffn.feedforward_channels == 256 + x = torch.randn(1, 56 * 56, 64) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + # Test BasicBlock with checkpoint forward + block = SwinBlock( + embed_dims=64, num_heads=4, feedforward_channels=256, with_cp=True) + assert block.with_cp + x = torch.randn(1, 56 * 56, 64) + x_out = block(x, (56, 56)) + assert x_out.shape == torch.Size([1, 56 * 56, 64]) + + +def test_swin_transformer(): + """Test Swin Transformer backbone.""" + + with pytest.raises(TypeError): + # Pretrained arg must be str or None. + SwinTransformer(pretrained=123) + + with pytest.raises(AssertionError): + # Because swin uses non-overlapping patch embed, so the stride of patch + # embed must be equal to patch size. + SwinTransformer(strides=(2, 2, 2, 2), patch_size=4) + + # test pretrained image size + with pytest.raises(AssertionError): + SwinTransformer(pretrain_img_size=(224, 224, 224)) + + # Test absolute position embedding + temp = torch.randn((1, 3, 224, 224)) + model = SwinTransformer(pretrain_img_size=224, use_abs_pos_embed=True) + model.init_weights() + model(temp) + + # Test patch norm + model = SwinTransformer(patch_norm=False) + model(temp) + + # Test normal inference + temp = torch.randn((1, 3, 32, 32)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 8, 8) + assert outs[1].shape == (1, 192, 4, 4) + assert outs[2].shape == (1, 384, 2, 2) + assert outs[3].shape == (1, 768, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 31, 31)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 8, 8) + assert outs[1].shape == (1, 192, 4, 4) + assert outs[2].shape == (1, 384, 2, 2) + assert outs[3].shape == (1, 768, 1, 1) + + # Test abnormal inference size + temp = torch.randn((1, 3, 112, 137)) + model = SwinTransformer() + outs = model(temp) + assert outs[0].shape == (1, 96, 28, 35) + assert outs[1].shape == (1, 192, 14, 18) + assert outs[2].shape == (1, 384, 7, 9) + assert outs[3].shape == (1, 768, 4, 5) + + model = SwinTransformer(frozen_stages=4) + model.train() + for p in model.parameters(): + assert not p.requires_grad diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/test_trident_resnet.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_trident_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..a79b97e1d1560663013c4b60ccde6ba47b7fc72c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/test_trident_resnet.py @@ -0,0 +1,180 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.backbones import TridentResNet +from mmdet.models.backbones.trident_resnet import TridentBottleneck + + +def test_trident_resnet_bottleneck(): + trident_dilations = (1, 2, 3) + test_branch_idx = 1 + concat_output = True + trident_build_config = (trident_dilations, test_branch_idx, concat_output) + + with pytest.raises(AssertionError): + # Style must be in ['pytorch', 'caffe'] + TridentBottleneck( + *trident_build_config, inplanes=64, planes=64, style='tensorflow') + + with pytest.raises(AssertionError): + # Allowed positions are 'after_conv1', 'after_conv2', 'after_conv3' + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv4') + ] + TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + + with pytest.raises(AssertionError): + # Need to specify different postfix to avoid duplicate plugin name + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + + with pytest.raises(KeyError): + # Plugin type is not supported + plugins = [dict(cfg=dict(type='WrongPlugin'), position='after_conv3')] + TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + + # Test Bottleneck with checkpoint forward + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, with_cp=True) + assert block.with_cp + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck style + block = TridentBottleneck( + *trident_build_config, + inplanes=64, + planes=64, + stride=2, + style='pytorch') + assert block.conv1.stride == (1, 1) + assert block.conv2.stride == (2, 2) + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=64, stride=2, style='caffe') + assert block.conv1.stride == (2, 2) + assert block.conv2.stride == (1, 1) + + # Test Bottleneck forward + block = TridentBottleneck(*trident_build_config, inplanes=64, planes=16) + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2') + ] + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck with 1 GeneralizedAttention after conv2, 1 NonLocal2D + # after conv2, 1 ContextBlock after conv3 + plugins = [ + dict( + cfg=dict( + type='GeneralizedAttention', + spatial_range=-1, + num_heads=8, + attention_type='0010', + kv_stride=2), + position='after_conv2'), + dict(cfg=dict(type='NonLocal2d'), position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16), + position='after_conv3') + ] + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + assert block.gen_attention_block.in_channels == 16 + assert block.nonlocal_block.in_channels == 16 + assert block.context_block.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + # Test Bottleneck with 1 ContextBlock after conv2, 2 ContextBlock after + # conv3 + plugins = [ + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1), + position='after_conv2'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2), + position='after_conv3'), + dict( + cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=3), + position='after_conv3') + ] + block = TridentBottleneck( + *trident_build_config, inplanes=64, planes=16, plugins=plugins) + assert block.context_block1.in_channels == 16 + assert block.context_block2.in_channels == 64 + assert block.context_block3.in_channels == 64 + x = torch.randn(1, 64, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size([block.num_branch, 64, 56, 56]) + + +def test_trident_resnet_backbone(): + tridentresnet_config = dict( + num_branch=3, + test_branch_idx=1, + strides=(1, 2, 2), + dilations=(1, 1, 1), + trident_dilations=(1, 2, 3), + out_indices=(2, ), + ) + """Test tridentresnet backbone.""" + with pytest.raises(AssertionError): + # TridentResNet depth should be in [50, 101, 152] + TridentResNet(18, **tridentresnet_config) + + with pytest.raises(AssertionError): + # In TridentResNet: num_stages == 3 + TridentResNet(50, num_stages=4, **tridentresnet_config) + + model = TridentResNet(50, num_stages=3, **tridentresnet_config) + model.train() + + imgs = torch.randn(1, 3, 32, 32) + feat = model(imgs) + assert len(feat) == 1 + assert feat[0].shape == torch.Size([3, 1024, 2, 2]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_backbones/utils.py b/mmdet_code/mmdetection/tests/test_models/test_backbones/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0f69a9e339e2a4e082dd0ffc7ede68cd834a4a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_backbones/utils.py @@ -0,0 +1,32 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from torch.nn.modules import GroupNorm +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.backbones.res2net import Bottle2neck +from mmdet.models.backbones.resnet import BasicBlock, Bottleneck +from mmdet.models.backbones.resnext import Bottleneck as BottleneckX +from mmdet.models.layers import SimplifiedBasicBlock + + +def is_block(modules): + """Check if is ResNet building block.""" + if isinstance(modules, (BasicBlock, Bottleneck, BottleneckX, Bottle2neck, + SimplifiedBasicBlock)): + return True + return False + + +def is_norm(modules): + """Check if is one of the norms.""" + if isinstance(modules, (GroupNorm, _BatchNorm)): + return True + return False + + +def check_norm_state(modules, train_state): + """Check if norm layer is in correct train state.""" + for mod in modules: + if isinstance(mod, _BatchNorm): + if mod.training != train_state: + return False + return True diff --git a/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_batch_resize.py b/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_batch_resize.py new file mode 100644 index 0000000000000000000000000000000000000000..9278d4957800319ca32a24a8fc7878f44bc0652f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_batch_resize.py @@ -0,0 +1,27 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +from mmdet.models.data_preprocessors import BatchResize, DetDataPreprocessor +from mmdet.testing import demo_mm_inputs + + +class TestDetDataPreprocessor(TestCase): + + def test_batch_resize(self): + + processor = DetDataPreprocessor( + mean=[103.53, 116.28, 123.675], + std=[57.375, 57.12, 58.395], + bgr_to_rgb=False, + batch_augments=[ + dict(type='BatchResize', scale=(32, 32), pad_size_divisor=32) + ]) + self.assertTrue(isinstance(processor.batch_augments[0], BatchResize)) + + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], use_box_type=True) + data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = data['inputs'], data['data_samples'] + self.assertEqual(batch_inputs.shape[-2:], (32, 32)) + self.assertEqual(batch_data_samples[0].scale_factor, + batch_data_samples[1].scale_factor) diff --git a/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_boxinst_preprocessor.py b/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_boxinst_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..57038fe80dd54c0853edf530e2fc6160fb49dd1e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_boxinst_preprocessor.py @@ -0,0 +1,59 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models.data_preprocessors import BoxInstDataPreprocessor +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs + + +class TestBoxInstDataPreprocessor(TestCase): + + def test_forward(self): + processor = BoxInstDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + + data = { + 'inputs': [torch.randint(0, 256, (3, 256, 256))], + 'data_samples': [DetDataSample()] + } + + # Test evaluation mode + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + + self.assertEqual(batch_inputs.shape, (1, 3, 256, 256)) + self.assertEqual(len(batch_data_samples), 1) + + # Test traning mode without gt bboxes + packed_inputs = demo_mm_inputs( + 2, [[3, 256, 256], [3, 128, 128]], num_items=[0, 0]) + out_data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + + self.assertEqual(batch_inputs.shape, (2, 3, 256, 256)) + self.assertEqual(len(batch_data_samples), 2) + self.assertEqual(len(batch_data_samples[0].gt_instances.masks), 0) + self.assertEqual( + len(batch_data_samples[0].gt_instances.pairwise_masks), 0) + self.assertEqual(len(batch_data_samples[1].gt_instances.masks), 0) + self.assertEqual( + len(batch_data_samples[1].gt_instances.pairwise_masks), 0) + + # Test traning mode with gt bboxes + packed_inputs = demo_mm_inputs( + 2, [[3, 256, 256], [3, 128, 128]], num_items=[2, 1]) + out_data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + + self.assertEqual(batch_inputs.shape, (2, 3, 256, 256)) + self.assertEqual(len(batch_data_samples), 2) + self.assertEqual(len(batch_data_samples[0].gt_instances.masks), 2) + self.assertEqual( + len(batch_data_samples[0].gt_instances.pairwise_masks), 2) + self.assertEqual(len(batch_data_samples[1].gt_instances.masks), 1) + self.assertEqual( + len(batch_data_samples[1].gt_instances.pairwise_masks), 1) diff --git a/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_data_preprocessor.py b/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_data_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..fce9dd7d35de3a0dffa6b7298c14f14d0cc23ab6 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_data_preprocessor.py @@ -0,0 +1,380 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub + +from mmdet.models.data_preprocessors import (BatchFixedSizePad, + BatchSyncRandomResize, + DetDataPreprocessor, + MultiBranchDataPreprocessor) +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs + + +class TestDetDataPreprocessor(TestCase): + + def test_init(self): + # test mean is None + processor = DetDataPreprocessor() + self.assertTrue(not hasattr(processor, 'mean')) + self.assertTrue(processor._enable_normalize is False) + + # test mean is not None + processor = DetDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + self.assertTrue(hasattr(processor, 'mean')) + self.assertTrue(hasattr(processor, 'std')) + self.assertTrue(processor._enable_normalize) + + # please specify both mean and std + with self.assertRaises(AssertionError): + DetDataPreprocessor(mean=[0, 0, 0]) + + # bgr2rgb and rgb2bgr cannot be set to True at the same time + with self.assertRaises(AssertionError): + DetDataPreprocessor(bgr_to_rgb=True, rgb_to_bgr=True) + + def test_pad_shape(self): + processor = DetDataPreprocessor() + data = dict(inputs=torch.randint(0, 256, (2, 3, 10, 15))) + batch_pad_shape = processor._get_pad_shape(data) + self.assertEqual(batch_pad_shape, [(10, 15), (10, 15)]) + + data = dict(inputs=[torch.randint(0, 256, (3, 11, 10))]) + self.assertEqual(processor._get_pad_shape(data), [(11, 10)]) + + # batch with different image sizes + data = dict(inputs=[ + torch.randint(0, 256, (3, 10, 16)), + torch.randint(0, 256, (3, 15, 20)) + ]) + + self.assertEqual(processor._get_pad_shape(data), [(10, 16), (15, 20)]) + + # test with pad divisor + processor = DetDataPreprocessor(pad_size_divisor=10) + data = dict(inputs=torch.randint(0, 256, (2, 3, 52, 65))) + self.assertAlmostEqual( + processor._get_pad_shape(data), [(60, 70), (60, 70)]) + + def test_forward(self): + processor = DetDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + + data = { + 'inputs': [torch.randint(0, 256, (3, 11, 10))], + 'data_samples': [DetDataSample()] + } + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + + self.assertEqual(batch_inputs.shape, (1, 3, 11, 10)) + self.assertEqual(len(batch_data_samples), 1) + + # test channel_conversion + processor = DetDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], bgr_to_rgb=True) + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + self.assertEqual(batch_inputs.shape, (1, 3, 11, 10)) + self.assertEqual(len(batch_data_samples), 1) + + # test padding + data = { + 'inputs': [ + torch.randint(0, 256, (3, 10, 11)), + torch.randint(0, 256, (3, 9, 14)) + ] + } + processor = DetDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], bgr_to_rgb=True) + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + self.assertEqual(batch_inputs.shape, (2, 3, 10, 14)) + self.assertIsNone(batch_data_samples) + + # test pad_size_divisor + data = { + 'inputs': [ + torch.randint(0, 256, (3, 10, 11)), + torch.randint(0, 256, (3, 9, 24)) + ], + 'data_samples': [DetDataSample()] * 2 + } + processor = DetDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], pad_size_divisor=5) + out_data = processor(data) + batch_inputs, batch_data_samples = out_data['inputs'], out_data[ + 'data_samples'] + self.assertEqual(batch_inputs.shape, (2, 3, 10, 25)) + self.assertEqual(len(batch_data_samples), 2) + for data_samples, expected_shape in zip(batch_data_samples, + [(10, 15), (10, 25)]): + self.assertEqual(data_samples.pad_shape, expected_shape) + + # test pad_mask=True and pad_seg=True + processor = DetDataPreprocessor( + pad_mask=True, mask_pad_value=0, pad_seg=True, seg_pad_value=0) + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], + with_mask=True, + with_semantic=True, + use_box_type=True) + packed_inputs['data_samples'][0].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 10, 11)) + packed_inputs['data_samples'][1].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 9, 24)) + mask_pad_sums = [ + x.gt_instances.masks.masks.sum() + for x in packed_inputs['data_samples'] + ] + seg_pad_sums = [ + x.gt_sem_seg.sem_seg.sum() for x in packed_inputs['data_samples'] + ] + batch_data_samples = processor( + packed_inputs, training=True)['data_samples'] + for data_samples, expected_shape, mask_pad_sum, seg_pad_sum in zip( + batch_data_samples, [(10, 24), (10, 24)], mask_pad_sums, + seg_pad_sums): + self.assertEqual(data_samples.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_instances.masks.masks.sum(), + mask_pad_sum) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.sum(), + seg_pad_sum) + + def test_batch_sync_random_resize(self): + processor = DetDataPreprocessor(batch_augments=[ + dict( + type='BatchSyncRandomResize', + random_size_range=(320, 320), + size_divisor=32, + interval=1) + ]) + self.assertTrue( + isinstance(processor.batch_augments[0], BatchSyncRandomResize)) + message_hub = MessageHub.get_instance('test_batch_sync_random_resize') + message_hub.update_info('iter', 0) + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 128, 128]], use_box_type=True) + batch_inputs = processor(packed_inputs, training=True)['inputs'] + self.assertEqual(batch_inputs.shape, (2, 3, 128, 128)) + + # resize after one iter + message_hub.update_info('iter', 1) + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 128, 128]], use_box_type=True) + batch_inputs = processor(packed_inputs, training=True)['inputs'] + self.assertEqual(batch_inputs.shape, (2, 3, 320, 320)) + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 128, 128]], use_box_type=True) + batch_inputs = processor(packed_inputs, training=False)['inputs'] + self.assertEqual(batch_inputs.shape, (2, 3, 128, 128)) + + def test_batch_fixed_size_pad(self): + # test pad_mask=False and pad_seg=False + processor = DetDataPreprocessor( + pad_mask=False, + pad_seg=False, + batch_augments=[ + dict( + type='BatchFixedSizePad', + size=(32, 32), + img_pad_value=0, + pad_mask=True, + mask_pad_value=0, + pad_seg=True, + seg_pad_value=0) + ]) + self.assertTrue( + isinstance(processor.batch_augments[0], BatchFixedSizePad)) + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], + with_mask=True, + with_semantic=True, + use_box_type=True) + packed_inputs['data_samples'][0].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 10, 11)) + packed_inputs['data_samples'][1].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 9, 24)) + mask_pad_sums = [ + x.gt_instances.masks.masks.sum() + for x in packed_inputs['data_samples'] + ] + seg_pad_sums = [ + x.gt_sem_seg.sem_seg.sum() for x in packed_inputs['data_samples'] + ] + data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = data['inputs'], data['data_samples'] + self.assertEqual(batch_inputs.shape[-2:], (32, 32)) + for data_samples, expected_shape, mask_pad_sum, seg_pad_sum in zip( + batch_data_samples, [(32, 32), (32, 32)], mask_pad_sums, + seg_pad_sums): + self.assertEqual(data_samples.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_instances.masks.masks.sum(), + mask_pad_sum) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.sum(), + seg_pad_sum) + + # test pad_mask=True and pad_seg=True + processor = DetDataPreprocessor( + pad_mask=True, + pad_seg=True, + seg_pad_value=0, + mask_pad_value=0, + batch_augments=[ + dict( + type='BatchFixedSizePad', + size=(32, 32), + img_pad_value=0, + pad_mask=True, + mask_pad_value=0, + pad_seg=True, + seg_pad_value=0) + ]) + self.assertTrue( + isinstance(processor.batch_augments[0], BatchFixedSizePad)) + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], + with_mask=True, + with_semantic=True, + use_box_type=True) + packed_inputs['data_samples'][0].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 10, 11)) + packed_inputs['data_samples'][1].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 9, 24)) + mask_pad_sums = [ + x.gt_instances.masks.masks.sum() + for x in packed_inputs['data_samples'] + ] + seg_pad_sums = [ + x.gt_sem_seg.sem_seg.sum() for x in packed_inputs['data_samples'] + ] + data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = data['inputs'], data['data_samples'] + self.assertEqual(batch_inputs.shape[-2:], (32, 32)) + for data_samples, expected_shape, mask_pad_sum, seg_pad_sum in zip( + batch_data_samples, [(32, 32), (32, 32)], mask_pad_sums, + seg_pad_sums): + self.assertEqual(data_samples.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_instances.masks.masks.sum(), + mask_pad_sum) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.sum(), + seg_pad_sum) + + # test negative pad/no pad + processor = DetDataPreprocessor( + pad_mask=True, + pad_seg=True, + seg_pad_value=0, + mask_pad_value=0, + batch_augments=[ + dict( + type='BatchFixedSizePad', + size=(5, 5), + img_pad_value=0, + pad_mask=True, + mask_pad_value=1, + pad_seg=True, + seg_pad_value=1) + ]) + self.assertTrue( + isinstance(processor.batch_augments[0], BatchFixedSizePad)) + packed_inputs = demo_mm_inputs( + 2, [[3, 10, 11], [3, 9, 24]], + with_mask=True, + with_semantic=True, + use_box_type=True) + packed_inputs['data_samples'][0].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 10, 11)) + packed_inputs['data_samples'][1].gt_sem_seg.sem_seg = torch.randint( + 0, 256, (1, 9, 24)) + mask_pad_sums = [ + x.gt_instances.masks.masks.sum() + for x in packed_inputs['data_samples'] + ] + seg_pad_sums = [ + x.gt_sem_seg.sem_seg.sum() for x in packed_inputs['data_samples'] + ] + data = processor(packed_inputs, training=True) + batch_inputs, batch_data_samples = data['inputs'], data['data_samples'] + self.assertEqual(batch_inputs.shape[-2:], (10, 24)) + for data_samples, expected_shape, mask_pad_sum, seg_pad_sum in zip( + batch_data_samples, [(10, 24), (10, 24)], mask_pad_sums, + seg_pad_sums): + self.assertEqual(data_samples.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.shape[-2:], + expected_shape) + self.assertEqual(data_samples.gt_instances.masks.masks.sum(), + mask_pad_sum) + self.assertEqual(data_samples.gt_sem_seg.sem_seg.sum(), + seg_pad_sum) + + +class TestMultiBranchDataPreprocessor(TestCase): + + def setUp(self): + """Setup the model and optimizer which are used in every test method. + + TestCase calls functions in this order: setUp() -> testMethod() -> + tearDown() -> cleanUp() + """ + self.data_preprocessor = dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_size_divisor=32) + self.multi_data = { + 'inputs': { + 'sup': [torch.randint(0, 256, (3, 224, 224))], + 'unsup_teacher': [ + torch.randint(0, 256, (3, 400, 600)), + torch.randint(0, 256, (3, 600, 400)) + ], + 'unsup_student': [ + torch.randint(0, 256, (3, 700, 500)), + torch.randint(0, 256, (3, 500, 700)) + ] + }, + 'data_samples': { + 'sup': [DetDataSample()], + 'unsup_teacher': [DetDataSample(), + DetDataSample()], + 'unsup_student': [DetDataSample(), + DetDataSample()], + } + } + self.data = { + 'inputs': [torch.randint(0, 256, (3, 224, 224))], + 'data_samples': [DetDataSample()] + } + + def test_multi_data_preprocessor(self): + processor = MultiBranchDataPreprocessor(self.data_preprocessor) + # test processing multi_data when training + multi_data = processor(self.multi_data, training=True) + self.assertEqual(multi_data['inputs']['sup'].shape, (1, 3, 224, 224)) + self.assertEqual(multi_data['inputs']['unsup_teacher'].shape, + (2, 3, 608, 608)) + self.assertEqual(multi_data['inputs']['unsup_student'].shape, + (2, 3, 704, 704)) + self.assertEqual(len(multi_data['data_samples']['sup']), 1) + self.assertEqual(len(multi_data['data_samples']['unsup_teacher']), 2) + self.assertEqual(len(multi_data['data_samples']['unsup_student']), 2) + # test processing data when testing + data = processor(self.data) + self.assertEqual(data['inputs'].shape, (1, 3, 224, 224)) + self.assertEqual(len(data['data_samples']), 1) diff --git a/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_track_data_preprocessor.py b/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_track_data_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..d5810167e61f01e1021ebdf698f69169aaaefe0c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_data_preprocessors/test_track_data_preprocessor.py @@ -0,0 +1,102 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +from mmdet.models.data_preprocessors import TrackDataPreprocessor +from mmdet.testing import demo_track_inputs + + +class TestTrackDataPreprocessor(TestCase): + + def test_init(self): + # test mean is None + processor = TrackDataPreprocessor() + self.assertTrue(not hasattr(processor, 'mean')) + self.assertTrue(processor._enable_normalize is False) + + # test mean is not None + processor = TrackDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + self.assertTrue(hasattr(processor, 'mean')) + self.assertTrue(hasattr(processor, 'std')) + self.assertTrue(processor._enable_normalize) + + # please specify both mean and std + with self.assertRaises(AssertionError): + TrackDataPreprocessor(mean=[0, 0, 0]) + + # bgr2rgb and rgb2bgr cannot be set to True at the same time + with self.assertRaises(AssertionError): + TrackDataPreprocessor(bgr_to_rgb=True, rgb_to_bgr=True) + + def test_forward(self): + processor = TrackDataPreprocessor(mean=[0, 0, 0], std=[1, 1, 1]) + + data = demo_track_inputs( + batch_size=1, + num_frames=1, + image_shapes=(3, 11, 10), + num_items=[1]) + out_data = processor(data) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + self.assertEqual(inputs.shape, (1, 1, 3, 11, 10)) + self.assertEqual(len(data_samples), 1) + + # test channel_conversion + processor = TrackDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], bgr_to_rgb=True) + out_data = processor(data) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + self.assertEqual(len(data_samples), 1) + + # test padding + data = demo_track_inputs( + batch_size=2, + num_frames=2, + image_shapes=[(3, 10, 11), (3, 9, 14)], + num_items=[1, 1]) + out_data = processor(data) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + self.assertEqual(inputs.shape, (2, 2, 3, 10, 14)) + + # test pad_size_divisor + data = demo_track_inputs( + batch_size=2, + num_frames=2, + image_shapes=[(3, 10, 11), (3, 9, 24)], + num_items=[1, 1]) + processor = TrackDataPreprocessor( + mean=[0., 0., 0.], std=[1., 1., 1.], pad_size_divisor=5) + out_data = processor(data) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + self.assertEqual(inputs.shape, (2, 2, 3, 10, 25)) + self.assertEqual(len(data_samples), 2) + for track_data_sample, expected_shape in zip(data_samples, [(10, 15), + (10, 25)]): + for det_data_sample in track_data_sample.video_data_samples: + self.assertEqual(det_data_sample.pad_shape, expected_shape) + + # test pad_mask=True + data = demo_track_inputs( + batch_size=2, + num_frames=2, + image_shapes=[(3, 10, 11), (3, 9, 24)], + num_items=[1, 1], + with_mask=True) + processor = TrackDataPreprocessor(pad_mask=True, mask_pad_value=0) + mask_pad_sums = [] + for track_data_sample in data['data_samples']: + pad_sum_per_sample = [] + for x in track_data_sample.video_data_samples: + pad_sum_per_sample.append(x.gt_instances.masks.masks.sum()) + mask_pad_sums.append(pad_sum_per_sample) + out_data = processor(data, training=True) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + for track_data_sample, expected_shape, mask_pad_sum in zip( + data_samples, [(10, 24), (10, 24)], mask_pad_sums): + for i, det_data_sample in enumerate( + track_data_sample.video_data_samples): + self.assertEqual( + det_data_sample.gt_instances.masks.masks.shape[-2:], + expected_shape) + self.assertEqual( + det_data_sample.gt_instances.masks.masks.sum(), + mask_pad_sum[i]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/__pycache__/test_dala_heads.cpython-313.pyc b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/__pycache__/test_dala_heads.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..203be0442aede9c11784f832886761f93e1d9220 Binary files /dev/null and b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/__pycache__/test_dala_heads.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_anchor_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_anchor_head.py new file mode 100644 index 0000000000000000000000000000000000000000..80781f8ddaaa0eebefa235b3a0967d4f885bc9d6 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_anchor_head.py @@ -0,0 +1,77 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import AnchorHead + + +class TestAnchorHead(TestCase): + + def test_anchor_head_loss(self): + """Tests anchor head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + cfg = Config( + 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=0, + pos_weight=-1, + debug=False)) + anchor_head = AnchorHead(num_classes=4, in_channels=1, train_cfg=cfg) + + # Anchor head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(len(anchor_head.prior_generator.strides))) + cls_scores, bbox_preds = anchor_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + assert empty_cls_loss.item() > 0, 'cls loss should be non-zero' + assert empty_box_loss.item() == 0, ( + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero' + assert onegt_box_loss.item() > 0, 'box loss should be non-zero' diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_atss_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_atss_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e85154bbb8b0ecfc1460393438ebea07ef5547c1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_atss_head.py @@ -0,0 +1,94 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import ATSSHead + + +class TestATSSHead(TestCase): + + def test_atss_head_loss(self): + """Tests atss head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False)) + atss_head = ATSSHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=1, + norm_cfg=None, + train_cfg=cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [8, 16, 32, 64, 128] + ] + cls_scores, bbox_preds, centernesses = atss_head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + empty_centerness_loss = sum(empty_gt_losses['loss_centerness']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_centerness_loss.item(), 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + onegt_centerness_loss = sum(one_gt_losses['loss_centerness']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_centerness_loss.item(), 0, + 'centerness loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_autoassign_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_autoassign_head.py new file mode 100644 index 0000000000000000000000000000000000000000..8328edee7ab79bed500955daeb0e83e3098a7690 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_autoassign_head.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import AutoAssignHead + + +class TestAutoAssignHead(TestCase): + + def test_autoassign_head_loss(self): + """Tests autoassign head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + autoassign_head = AutoAssignHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=1, + strides=[8, 16, 32, 64, 128], + loss_bbox=dict(type='GIoULoss', loss_weight=5.0), + norm_cfg=None) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in autoassign_head.prior_generator.strides) + cls_scores, bbox_preds, centernesses = autoassign_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = autoassign_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, + [gt_instances], + img_metas) + # When there is no truth, the neg loss should be nonzero but + # pos loss and center loss should be zero + empty_pos_loss = empty_gt_losses['loss_pos'].item() + empty_neg_loss = empty_gt_losses['loss_neg'].item() + empty_ctr_loss = empty_gt_losses['loss_center'].item() + self.assertGreater(empty_neg_loss, 0, 'neg loss should be non-zero') + self.assertEqual( + empty_pos_loss, 0, + 'there should be no pos loss when there are no true boxes') + self.assertEqual( + empty_ctr_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all pos, neg loss and center loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = autoassign_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, + [gt_instances], img_metas) + onegt_pos_loss = one_gt_losses['loss_pos'].item() + onegt_neg_loss = one_gt_losses['loss_neg'].item() + onegt_ctr_loss = one_gt_losses['loss_center'].item() + self.assertGreater(onegt_pos_loss, 0, 'pos loss should be non-zero') + self.assertGreater(onegt_neg_loss, 0, 'neg loss should be non-zero') + self.assertGreater(onegt_ctr_loss, 0, 'center loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_boxinst_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_boxinst_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d677a1d2047fe91d9f9485e8891ca7e9a9c73b8e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_boxinst_head.py @@ -0,0 +1,125 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine import MessageHub +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import BoxInstBboxHead, BoxInstMaskHead +from mmdet.structures.mask import BitmapMasks + + +def _rand_masks(num_items, bboxes, img_w, img_h): + rng = np.random.RandomState(0) + masks = np.zeros((num_items, img_h, img_w), dtype=np.float32) + for i, bbox in enumerate(bboxes): + bbox = bbox.astype(np.int32) + mask = (rng.rand(1, bbox[3] - bbox[1], bbox[2] - bbox[0]) > + 0.3).astype(np.int64) + masks[i:i + 1, bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask + return BitmapMasks(masks, height=img_h, width=img_w) + + +def _fake_mask_feature_head(): + mask_feature_head = ConfigDict( + in_channels=1, + feat_channels=1, + start_level=0, + end_level=2, + out_channels=8, + mask_stride=8, + num_stacked_convs=4, + norm_cfg=dict(type='BN', requires_grad=True)) + return mask_feature_head + + +class TestBoxInstHead(TestCase): + + def test_boxinst_maskhead_loss(self): + """Tests boxinst maskhead loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + boxinst_bboxhead = BoxInstBboxHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + mask_feature_head = _fake_mask_feature_head() + boxinst_maskhead = BoxInstMaskHead( + mask_feature_head=mask_feature_head, + loss_mask=dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + eps=5e-6, + loss_weight=1.0)) + + # Fcos head expects a multiple levels of features per image + feats = [] + for i in range(len(boxinst_bboxhead.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 3)), s // (2**(i + 3)))) + feats = tuple(feats) + cls_scores, bbox_preds, centernesses, param_preds =\ + boxinst_bboxhead.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + gt_instances.pairwise_masks = _rand_masks( + 0, gt_instances.bboxes.numpy(), s // 4, s // 4).to_tensor( + dtype=torch.float32, + device='cpu').unsqueeze(1).repeat(1, 8, 1, 1) + message_hub = MessageHub.get_instance('runtime_info') + message_hub.update_info('iter', 1) + _ = boxinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, centernesses, + param_preds, [gt_instances], + img_metas) + # When truth is empty then all mask loss + # should be zero for random inputs + positive_infos = boxinst_bboxhead.get_positive_infos() + mask_outs = boxinst_maskhead.forward(feats, positive_infos) + empty_gt_mask_losses = boxinst_maskhead.loss_by_feat( + *mask_outs, [gt_instances], img_metas, positive_infos) + loss_mask_project = empty_gt_mask_losses['loss_mask_project'] + loss_mask_pairwise = empty_gt_mask_losses['loss_mask_pairwise'] + self.assertEqual(loss_mask_project, 0, + 'mask project loss should be zero') + self.assertEqual(loss_mask_pairwise, 0, + 'mask pairwise loss should be zero') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor([[0.111, 0.222, 25.6667, 29.8757]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + gt_instances.pairwise_masks = _rand_masks( + 1, gt_instances.bboxes.numpy(), s // 4, s // 4).to_tensor( + dtype=torch.float32, + device='cpu').unsqueeze(1).repeat(1, 8, 1, 1) + + _ = boxinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, centernesses, + param_preds, [gt_instances], + img_metas) + positive_infos = boxinst_bboxhead.get_positive_infos() + mask_outs = boxinst_maskhead.forward(feats, positive_infos) + one_gt_mask_losses = boxinst_maskhead.loss_by_feat( + *mask_outs, [gt_instances], img_metas, positive_infos) + loss_mask_project = one_gt_mask_losses['loss_mask_project'] + loss_mask_pairwise = one_gt_mask_losses['loss_mask_pairwise'] + self.assertGreater(loss_mask_project, 0, + 'mask project loss should be nonzero') + self.assertGreater(loss_mask_pairwise, 0, + 'mask pairwise loss should be nonzero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_cascade_rpn_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_cascade_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c1058c51341628f907e31fdf0a962fae99486265 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_cascade_rpn_head.py @@ -0,0 +1,179 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CascadeRPNHead +from mmdet.structures import DetDataSample + +rpn_weight = 0.7 +cascade_rpn_config = ConfigDict( + dict( + num_stages=2, + num_classes=1, + stages=[ + dict( + type='StageCascadeRPNHead', + in_channels=1, + feat_channels=1, + anchor_generator=dict( + type='AnchorGenerator', + scales=[8], + ratios=[1.0], + strides=[4, 8, 16, 32, 64]), + adapt_cfg=dict(type='dilation', dilation=3), + bridged_feature=True, + with_cls=False, + reg_decoded_bbox=True, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=(.0, .0, .0, .0), + target_stds=(0.1, 0.1, 0.5, 0.5)), + loss_bbox=dict( + type='IoULoss', linear=True, + loss_weight=10.0 * rpn_weight)), + dict( + type='StageCascadeRPNHead', + in_channels=1, + feat_channels=1, + adapt_cfg=dict(type='offset'), + bridged_feature=False, + with_cls=True, + reg_decoded_bbox=True, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=(.0, .0, .0, .0), + target_stds=(0.05, 0.05, 0.1, 0.1)), + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=True, + loss_weight=1.0 * rpn_weight), + loss_bbox=dict( + type='IoULoss', linear=True, + loss_weight=10.0 * rpn_weight)) + ], + train_cfg=[ + dict( + assigner=dict( + type='RegionAssigner', center_ratio=0.2, ignore_ratio=0.5), + allowed_border=-1, + pos_weight=-1, + debug=False), + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.7, + min_pos_iou=0.3, + 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) + ], + test_cfg=dict(max_per_img=300, nms=dict(iou_threshold=0.8)))) + + +class TestStageCascadeRPNHead(TestCase): + + def test_cascade_rpn_head_loss(self): + """Tests cascade rpn head loss when truth is empty and non-empty.""" + cascade_rpn_head = CascadeRPNHead(**cascade_rpn_config) + + s = 256 + feats = [ + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in cascade_rpn_head.stages[0].prior_generator.strides + ] + img_metas = { + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + } + sample = DetDataSample() + sample.set_metainfo(img_metas) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + sample.gt_instances = gt_instances + + empty_gt_losses = cascade_rpn_head.loss(feats, [sample]) + for key, loss in empty_gt_losses.items(): + loss = sum(loss) + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'reg' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no reg loss when no ground true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([0]) + sample.gt_instances = gt_instances + + one_gt_losses = cascade_rpn_head.loss(feats, [sample]) + for loss in one_gt_losses.values(): + loss = sum(loss) + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + def test_cascade_rpn_head_loss_and_predict(self): + """Tests cascade rpn head loss and predict function.""" + cascade_rpn_head = CascadeRPNHead(**cascade_rpn_config) + + s = 256 + feats = [ + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in cascade_rpn_head.stages[0].prior_generator.strides + ] + img_metas = { + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + } + sample = DetDataSample() + sample.set_metainfo(img_metas) + + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + sample.gt_instances = gt_instances + proposal_cfg = ConfigDict( + dict(max_per_img=300, nms=dict(iou_threshold=0.8))) + + cascade_rpn_head.loss_and_predict(feats, [sample], proposal_cfg) + + def test_cascade_rpn_head_predict(self): + """Tests cascade rpn head predict function.""" + cascade_rpn_head = CascadeRPNHead(**cascade_rpn_config) + + s = 256 + feats = [ + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in cascade_rpn_head.stages[0].prior_generator.strides + ] + img_metas = { + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + } + sample = DetDataSample() + sample.set_metainfo(img_metas) + + cascade_rpn_head.predict(feats, [sample]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centernet_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centernet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5c474d8a904467139e3a285d485f834acd7c41d4 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centernet_head.py @@ -0,0 +1,158 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CenterNetHead + + +class TestCenterNetHead(TestCase): + + def test_center_head_loss(self): + """Tests center head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{'batch_input_shape': (s, s, 3)}] + test_cfg = dict(topK=100, max_per_img=100) + centernet_head = CenterNetHead( + num_classes=4, in_channels=1, feat_channels=4, test_cfg=test_cfg) + + feat = [torch.rand(1, 1, s, s)] + center_out, wh_out, offset_out = centernet_head.forward(feat) + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = centernet_head.loss_by_feat(center_out, wh_out, + offset_out, + [gt_instances], + img_metas) + loss_center = empty_gt_losses['loss_center_heatmap'] + loss_wh = empty_gt_losses['loss_wh'] + loss_offset = empty_gt_losses['loss_offset'] + assert loss_center.item() > 0, 'loss_center should be non-zero' + assert loss_wh.item() == 0, ( + 'there should be no loss_wh when there are no true boxes') + assert loss_offset.item() == 0, ( + 'there should be no loss_offset when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = centernet_head.loss_by_feat(center_out, wh_out, + offset_out, [gt_instances], + img_metas) + loss_center = one_gt_losses['loss_center_heatmap'] + loss_wh = one_gt_losses['loss_wh'] + loss_offset = one_gt_losses['loss_offset'] + assert loss_center.item() > 0, 'loss_center should be non-zero' + assert loss_wh.item() > 0, 'loss_wh should be non-zero' + assert loss_offset.item() > 0, 'loss_offset should be non-zero' + + def test_centernet_head_get_targets(self): + """Tests center head generating and decoding the heatmap.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'batch_input_shape': (s, s), + }] + test_cfg = ConfigDict( + dict(topk=100, local_maximum_kernel=3, max_per_img=100)) + gt_bboxes = [ + torch.Tensor([[10, 20, 200, 240], [40, 50, 100, 200], + [10, 20, 100, 240]]) + ] + gt_labels = [torch.LongTensor([1, 1, 2])] + + centernet_head = CenterNetHead( + num_classes=4, in_channels=1, feat_channels=4, test_cfg=test_cfg) + self.feat_shape = (1, 1, s // 4, s // 4) + targets, _ = centernet_head.get_targets(gt_bboxes, gt_labels, + self.feat_shape, + img_metas[0]['img_shape']) + center_target = targets['center_heatmap_target'] + wh_target = targets['wh_target'] + offset_target = targets['offset_target'] + # make sure assign target right + for i in range(len(gt_bboxes[0])): + bbox, label = gt_bboxes[0][i] / 4, gt_labels[0][i] + ctx, cty = sum(bbox[0::2]) / 2, sum(bbox[1::2]) / 2 + int_ctx, int_cty = int(sum(bbox[0::2]) / 2), int( + sum(bbox[1::2]) / 2) + w, h = bbox[2] - bbox[0], bbox[3] - bbox[1] + x_off = ctx - int(ctx) + y_off = cty - int(cty) + assert center_target[0, label, int_cty, int_ctx] == 1 + assert wh_target[0, 0, int_cty, int_ctx] == w + assert wh_target[0, 1, int_cty, int_ctx] == h + assert offset_target[0, 0, int_cty, int_ctx] == x_off + assert offset_target[0, 1, int_cty, int_ctx] == y_off + + def test_centernet_head_get_results(self): + """Tests center head generating and decoding the heatmap.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'batch_input_shape': (s, s), + 'border': (0, 0, 0, 0), + }] + test_cfg = ConfigDict( + dict( + topk=100, + local_maximum_kernel=3, + max_per_img=100, + nms=dict(type='nms', iou_threshold=0.5))) + gt_bboxes = [ + torch.Tensor([[10, 20, 200, 240], [40, 50, 100, 200], + [10, 20, 100, 240]]) + ] + gt_labels = [torch.LongTensor([1, 1, 2])] + + centernet_head = CenterNetHead( + num_classes=4, in_channels=1, feat_channels=4, test_cfg=test_cfg) + self.feat_shape = (1, 1, s // 4, s // 4) + targets, _ = centernet_head.get_targets(gt_bboxes, gt_labels, + self.feat_shape, + img_metas[0]['img_shape']) + center_target = targets['center_heatmap_target'] + wh_target = targets['wh_target'] + offset_target = targets['offset_target'] + # make sure get_bboxes is right + detections = centernet_head.predict_by_feat([center_target], + [wh_target], + [offset_target], + img_metas, + rescale=True, + with_nms=False) + + pred_instances = detections[0] + out_bboxes = pred_instances.bboxes[:3] + out_clses = pred_instances.labels[:3] + for bbox, cls in zip(out_bboxes, out_clses): + flag = False + for gt_bbox, gt_cls in zip(gt_bboxes[0], gt_labels[0]): + if (bbox[:4] == gt_bbox[:4]).all(): + flag = True + assert flag, 'get_bboxes is wrong' + + detections = centernet_head.predict_by_feat([center_target], + [wh_target], + [offset_target], + img_metas, + rescale=True, + with_nms=True) + + pred_instances = detections[0] + out_bboxes = pred_instances.bboxes[:3] + out_clses = pred_instances.labels[:3] + for bbox, cls in zip(out_bboxes, out_clses): + flag = False + for gt_bbox, gt_cls in zip(gt_bboxes[0], gt_labels[0]): + if (bbox[:4] == gt_bbox[:4]).all(): + flag = True + assert flag, 'get_bboxes is wrong' diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centernet_update_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centernet_update_head.py new file mode 100644 index 0000000000000000000000000000000000000000..325ce7e6cd9bda4e0a4ec807e11c54636f45fe2a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centernet_update_head.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CenterNetUpdateHead + + +class TestCenterNetUpdateHead(TestCase): + + def test_centernet_update_head_loss(self): + """Tests fcos head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + centernet_head = CenterNetUpdateHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in centernet_head.prior_generator.strides) + cls_scores, bbox_preds = centernet_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = centernet_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = empty_gt_losses['loss_cls'].item() + empty_box_loss = empty_gt_losses['loss_bbox'].item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = centernet_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].item() + onegt_box_loss = one_gt_losses['loss_bbox'].item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centripetal_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centripetal_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6811ef7699ab70fc63e33a07103d3c6d4e16970c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_centripetal_head.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CentripetalHead + + +class TestCentripetalHead(TestCase): + + def test_centripetal_head_loss(self): + """Tests corner head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + }] + + centripetal_head = CentripetalHead( + num_classes=4, in_channels=1, corner_emb_channels=0) + + # Corner head expects a multiple levels of features per image + feat = [ + torch.rand(1, 1, s // 4, s // 4) + for _ in range(centripetal_head.num_feat_levels) + ] + forward_outputs = centripetal_head.forward(feat) + + # Test that empty ground truth encourages the network + # to predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + + empty_gt_losses = centripetal_head.loss_by_feat( + *forward_outputs, [gt_instances], img_metas, gt_bboxes_ignore) + empty_det_loss = sum(empty_gt_losses['det_loss']) + empty_guiding_loss = sum(empty_gt_losses['guiding_loss']) + empty_centripetal_loss = sum(empty_gt_losses['centripetal_loss']) + empty_off_loss = sum(empty_gt_losses['off_loss']) + self.assertTrue(empty_det_loss.item() > 0, + 'det loss should be non-zero') + self.assertTrue( + empty_guiding_loss.item() == 0, + 'there should be no guiding loss when there are no true boxes') + self.assertTrue( + empty_centripetal_loss.item() == 0, + 'there should be no centripetal loss when there are no true boxes') + self.assertTrue( + empty_off_loss.item() == 0, + 'there should be no box loss when there are no true boxes') + + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874], + [123.6667, 123.8757, 138.6326, 251.8874]]) + gt_instances.labels = torch.LongTensor([2, 3]) + + two_gt_losses = centripetal_head.loss_by_feat(*forward_outputs, + [gt_instances], + img_metas, + gt_bboxes_ignore) + twogt_det_loss = sum(two_gt_losses['det_loss']) + twogt_guiding_loss = sum(two_gt_losses['guiding_loss']) + twogt_centripetal_loss = sum(two_gt_losses['centripetal_loss']) + twogt_off_loss = sum(two_gt_losses['off_loss']) + assert twogt_det_loss.item() > 0, 'det loss should be non-zero' + assert twogt_guiding_loss.item() > 0, 'push loss should be non-zero' + assert twogt_centripetal_loss.item( + ) > 0, 'pull loss should be non-zero' + assert twogt_off_loss.item() > 0, 'off loss should be non-zero' diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_condinst_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_condinst_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b2938f86cbb36df03dfd50e36a2ff9b261c7dc5b --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_condinst_head.py @@ -0,0 +1,200 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import CondInstBboxHead, CondInstMaskHead +from mmdet.structures.mask import BitmapMasks + + +def _rand_masks(num_items, bboxes, img_w, img_h): + rng = np.random.RandomState(0) + masks = np.zeros((num_items, img_h, img_w), dtype=np.float32) + for i, bbox in enumerate(bboxes): + bbox = bbox.astype(np.int32) + mask = (rng.rand(1, bbox[3] - bbox[1], bbox[2] - bbox[0]) > + 0.3).astype(np.int64) + masks[i:i + 1, bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask + return BitmapMasks(masks, height=img_h, width=img_w) + + +def _fake_mask_feature_head(): + mask_feature_head = ConfigDict( + in_channels=1, + feat_channels=1, + start_level=0, + end_level=2, + out_channels=8, + mask_stride=8, + num_stacked_convs=4, + norm_cfg=dict(type='BN', requires_grad=True)) + return mask_feature_head + + +class TestCondInstHead(TestCase): + + def test_condinst_bboxhead_loss(self): + """Tests condinst bboxhead loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + condinst_bboxhead = CondInstBboxHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in condinst_bboxhead.prior_generator.strides) + cls_scores, bbox_preds, centernesses, param_preds =\ + condinst_bboxhead.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + + empty_gt_losses = condinst_bboxhead.loss_by_feat( + cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = empty_gt_losses['loss_cls'].item() + empty_box_loss = empty_gt_losses['loss_bbox'].item() + empty_ctr_loss = empty_gt_losses['loss_centerness'].item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_ctr_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + + one_gt_losses = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, + centernesses, + param_preds, + [gt_instances], + img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].item() + onegt_box_loss = one_gt_losses['loss_bbox'].item() + onegt_ctr_loss = one_gt_losses['loss_centerness'].item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_ctr_loss, 0, + 'centerness loss should be non-zero') + + # Test the `center_sampling` works fine. + condinst_bboxhead.center_sampling = True + ctrsamp_losses = condinst_bboxhead.loss_by_feat( + cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], + img_metas) + ctrsamp_cls_loss = ctrsamp_losses['loss_cls'].item() + ctrsamp_box_loss = ctrsamp_losses['loss_bbox'].item() + ctrsamp_ctr_loss = ctrsamp_losses['loss_centerness'].item() + self.assertGreater(ctrsamp_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(ctrsamp_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(ctrsamp_ctr_loss, 0, + 'centerness loss should be non-zero') + + # Test the `norm_on_bbox` works fine. + condinst_bboxhead.norm_on_bbox = True + normbox_losses = condinst_bboxhead.loss_by_feat( + cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], + img_metas) + normbox_cls_loss = normbox_losses['loss_cls'].item() + normbox_box_loss = normbox_losses['loss_bbox'].item() + normbox_ctr_loss = normbox_losses['loss_centerness'].item() + self.assertGreater(normbox_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(normbox_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(normbox_ctr_loss, 0, + 'centerness loss should be non-zero') + + def test_condinst_maskhead_loss(self): + """Tests condinst maskhead loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + condinst_bboxhead = CondInstBboxHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + mask_feature_head = _fake_mask_feature_head() + condinst_maskhead = CondInstMaskHead( + mask_feature_head=mask_feature_head, + loss_mask=dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + eps=5e-6, + loss_weight=1.0)) + + # Fcos head expects a multiple levels of features per image + feats = [] + for i in range(len(condinst_bboxhead.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 3)), s // (2**(i + 3)))) + feats = tuple(feats) + cls_scores, bbox_preds, centernesses, param_preds =\ + condinst_bboxhead.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + + _ = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, + centernesses, param_preds, + [gt_instances], img_metas) + # When truth is empty then all mask loss + # should be zero for random inputs + positive_infos = condinst_bboxhead.get_positive_infos() + mask_outs = condinst_maskhead.forward(feats, positive_infos) + empty_gt_mask_losses = condinst_maskhead.loss_by_feat( + *mask_outs, [gt_instances], img_metas, positive_infos) + loss_mask = empty_gt_mask_losses['loss_mask'] + self.assertEqual(loss_mask, 0, 'mask loss should be zero') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + + _ = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, + centernesses, param_preds, + [gt_instances], img_metas) + positive_infos = condinst_bboxhead.get_positive_infos() + mask_outs = condinst_maskhead.forward(feats, positive_infos) + one_gt_mask_losses = condinst_maskhead.loss_by_feat( + *mask_outs, [gt_instances], img_metas, positive_infos) + loss_mask = one_gt_mask_losses['loss_mask'] + self.assertGreater(loss_mask, 0, 'mask loss should be nonzero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_corner_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_corner_head.py new file mode 100644 index 0000000000000000000000000000000000000000..8bd92f5731e9916ac46e82cc81776f2fe22d980f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_corner_head.py @@ -0,0 +1,178 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.evaluation import bbox_overlaps +from mmdet.models.dense_heads import CornerHead + + +class TestCornerHead(TestCase): + + def test_corner_head_loss(self): + """Tests corner head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + }] + + corner_head = CornerHead(num_classes=4, in_channels=1) + + # Corner head expects a multiple levels of features per image + feat = [ + torch.rand(1, 1, s // 4, s // 4) + for _ in range(corner_head.num_feat_levels) + ] + forward_outputs = corner_head.forward(feat) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + + empty_gt_losses = corner_head.loss_by_feat(*forward_outputs, + [gt_instances], img_metas, + gt_bboxes_ignore) + empty_det_loss = sum(empty_gt_losses['det_loss']) + empty_push_loss = sum(empty_gt_losses['push_loss']) + empty_pull_loss = sum(empty_gt_losses['pull_loss']) + empty_off_loss = sum(empty_gt_losses['off_loss']) + self.assertTrue(empty_det_loss.item() > 0, + 'det loss should be non-zero') + self.assertTrue( + empty_push_loss.item() == 0, + 'there should be no push loss when there are no true boxes') + self.assertTrue( + empty_pull_loss.item() == 0, + 'there should be no pull loss when there are no true boxes') + self.assertTrue( + empty_off_loss.item() == 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = corner_head.loss_by_feat(*forward_outputs, + [gt_instances], img_metas, + gt_bboxes_ignore) + onegt_det_loss = sum(one_gt_losses['det_loss']) + onegt_push_loss = sum(one_gt_losses['push_loss']) + onegt_pull_loss = sum(one_gt_losses['pull_loss']) + onegt_off_loss = sum(one_gt_losses['off_loss']) + self.assertTrue(onegt_det_loss.item() > 0, + 'det loss should be non-zero') + self.assertTrue( + onegt_push_loss.item() == 0, + 'there should be no push loss when there are only one true box') + self.assertTrue(onegt_pull_loss.item() > 0, + 'pull loss should be non-zero') + self.assertTrue(onegt_off_loss.item() > 0, + 'off loss should be non-zero') + + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874], + [123.6667, 123.8757, 138.6326, 251.8874]]) + gt_instances.labels = torch.LongTensor([2, 3]) + + two_gt_losses = corner_head.loss_by_feat(*forward_outputs, + [gt_instances], img_metas, + gt_bboxes_ignore) + twogt_det_loss = sum(two_gt_losses['det_loss']) + twogt_push_loss = sum(two_gt_losses['push_loss']) + twogt_pull_loss = sum(two_gt_losses['pull_loss']) + twogt_off_loss = sum(two_gt_losses['off_loss']) + self.assertTrue(twogt_det_loss.item() > 0, + 'det loss should be non-zero') + # F.relu limits push loss larger than or equal to 0. + self.assertTrue(twogt_push_loss.item() >= 0, + 'push loss should be non-zero') + self.assertTrue(twogt_pull_loss.item() > 0, + 'pull loss should be non-zero') + self.assertTrue(twogt_off_loss.item() > 0, + 'off loss should be non-zero') + + def test_corner_head_encode_and_decode_heatmap(self): + """Tests corner head generating and decoding the heatmap.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3), + 'border': (0, 0, 0, 0) + }] + + gt_bboxes = [ + torch.Tensor([[10, 20, 200, 240], [40, 50, 100, 200], + [10, 20, 200, 240]]) + ] + gt_labels = [torch.LongTensor([1, 1, 2])] + + corner_head = CornerHead( + num_classes=4, in_channels=1, corner_emb_channels=1) + + feat = [ + torch.rand(1, 1, s // 4, s // 4) + for _ in range(corner_head.num_feat_levels) + ] + + targets = corner_head.get_targets( + gt_bboxes, + gt_labels, + feat[0].shape, + img_metas[0]['batch_input_shape'], + with_corner_emb=corner_head.with_corner_emb) + + gt_tl_heatmap = targets['topleft_heatmap'] + gt_br_heatmap = targets['bottomright_heatmap'] + gt_tl_offset = targets['topleft_offset'] + gt_br_offset = targets['bottomright_offset'] + embedding = targets['corner_embedding'] + [top, left], [bottom, right] = embedding[0][0] + gt_tl_embedding_heatmap = torch.zeros([1, 1, s // 4, s // 4]) + gt_br_embedding_heatmap = torch.zeros([1, 1, s // 4, s // 4]) + gt_tl_embedding_heatmap[0, 0, top, left] = 1 + gt_br_embedding_heatmap[0, 0, bottom, right] = 1 + + batch_bboxes, batch_scores, batch_clses = corner_head._decode_heatmap( + tl_heat=gt_tl_heatmap, + br_heat=gt_br_heatmap, + tl_off=gt_tl_offset, + br_off=gt_br_offset, + tl_emb=gt_tl_embedding_heatmap, + br_emb=gt_br_embedding_heatmap, + img_meta=img_metas[0], + k=100, + kernel=3, + distance_threshold=0.5) + + bboxes = batch_bboxes.view(-1, 4) + scores = batch_scores.view(-1, 1) + clses = batch_clses.view(-1, 1) + + idx = scores.argsort(dim=0, descending=True) + bboxes = bboxes[idx].view(-1, 4) + scores = scores[idx].view(-1) + clses = clses[idx].view(-1) + + valid_bboxes = bboxes[torch.where(scores > 0.05)] + valid_labels = clses[torch.where(scores > 0.05)] + max_coordinate = valid_bboxes.max() + offsets = valid_labels.to(valid_bboxes) * (max_coordinate + 1) + gt_offsets = gt_labels[0].to(gt_bboxes[0]) * (max_coordinate + 1) + + offset_bboxes = valid_bboxes + offsets[:, None] + offset_gtbboxes = gt_bboxes[0] + gt_offsets[:, None] + + iou_matrix = bbox_overlaps(offset_bboxes.numpy(), + offset_gtbboxes.numpy()) + self.assertEqual((iou_matrix == 1).sum(), 3) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_dala_heads.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_dala_heads.py new file mode 100644 index 0000000000000000000000000000000000000000..34a3b098fd4664719c68be4fd3c4a931a6f5e069 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_dala_heads.py @@ -0,0 +1,43 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import DalaFCOSHead + + +def test_dala_fcos_point_assignment_and_dwl(): + head = DalaFCOSHead( + num_classes=1, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None, + sync_stats=False) + points = torch.tensor([[2., 2.], [4., 4.], [12., 12.]]) + gt_instances = InstanceData( + bboxes=torch.tensor([[0., 0., 8., 8.]]), labels=torch.tensor([0])) + + labels, targets, label_weights, bbox_weights = head._get_targets_single( + gt_instances, points) + assert torch.equal(labels, torch.tensor([1, 0, 1])) + assert torch.allclose(targets[1], torch.tensor([4., 4., 4., 4.])) + assert torch.allclose(label_weights, torch.ones(3)) + assert torch.allclose(bbox_weights, torch.tensor([0., 1., 0.])) + + +def test_dala_fcos_empty_ground_truth(): + head = DalaFCOSHead( + num_classes=1, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None, + sync_stats=False) + gt_instances = InstanceData( + bboxes=torch.empty((0, 4)), + labels=torch.empty((0, ), dtype=torch.long)) + labels, _, label_weights, bbox_weights = head._get_targets_single( + gt_instances, torch.tensor([[2., 2.]])) + assert torch.equal(labels, torch.tensor([1])) + assert torch.equal(label_weights, torch.ones(1)) + assert torch.equal(bbox_weights, torch.zeros(1)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ddod_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ddod_head.py new file mode 100644 index 0000000000000000000000000000000000000000..753bb3ae46f1a5eca537889dc461723ee9a18724 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ddod_head.py @@ -0,0 +1,98 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import DDODHead + + +class TestDDODHead(TestCase): + + def test_ddod_head_loss(self): + """Tests ddod head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9, alpha=0.8), + reg_assigner=dict(type='ATSSAssigner', topk=9, alpha=0.5), + allowed_border=-1, + pos_weight=-1, + debug=False)) + atss_head = DDODHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=1, + use_dcn=False, + norm_cfg=None, + train_cfg=cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + loss_iou=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [8, 16, 32, 64, 128] + ] + cls_scores, bbox_preds, centernesses = atss_head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + empty_centerness_loss = sum(empty_gt_losses['loss_iou']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_centerness_loss.item(), 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + onegt_centerness_loss = sum(one_gt_losses['loss_iou']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_centerness_loss.item(), 0, + 'centerness loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ddq_detr_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ddq_detr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..cbede07214de975f958d3f353c027f4c10ba3759 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ddq_detr_head.py @@ -0,0 +1,171 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import json +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import DDQDETRHead +from mmdet.structures import DetDataSample + + +class TestDDQDETRHead(TestCase): + + def test_ddq_detr_head_loss(self): + """Tests DDQDETRHead loss when truth is empty and non-empty.""" + num_classes = 2 + num_dn_queries = 10 + num_distinct_queries = 10 + dense_topk_ratio = 1.0 + num_decoder_layers = 2 + embed_dims = 256 + num_attention_heads = 8 + + batch_data_samples = self.get_batch_data_samples() + batch_size = len(batch_data_samples) + + batch_gt_instances = [] + batch_img_metas = [] + + for data_sample in batch_data_samples: + batch_img_metas.append(data_sample.metainfo) + batch_gt_instances.append(data_sample.gt_instances) + + max_num_target = max( + len(data_sample.gt_instances) + for data_sample in batch_data_samples) + + num_denoising_groups = max(num_dn_queries // max_num_target, 1) + num_denoising_queries = num_denoising_groups * 2 * max_num_target + + num_dense_queries = int(num_distinct_queries * dense_topk_ratio) + + num_total_queries = ( + num_denoising_queries + num_distinct_queries + num_dense_queries) + + dn_meta = { + 'num_denoising_queries': num_denoising_queries, + 'num_denoising_groups': num_denoising_groups, + 'num_dense_queries': num_dense_queries + } + + train_cfg = Config( + dict( + assigner=dict( + type='HungarianAssigner', + match_costs=[ + dict(type='FocalLossCost', weight=2.0), + dict(type='BBoxL1Cost', weight=5.0, box_format='xywh'), + dict(type='IoUCost', iou_mode='giou', weight=2.0) + ]))) + + bbox_head = DDQDETRHead( + num_classes=num_classes, + sync_cls_avg_factor=True, + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='L1Loss', loss_weight=5.0), + loss_iou=dict(type='GIoULoss', loss_weight=2.0), + share_pred_layer=False, + num_pred_layer=1 + num_decoder_layers, + as_two_stage=True, + train_cfg=train_cfg, + test_cfg=dict(max_per_img=300)) + + bbox_head.cache_dict = dict( + distinct_query_mask=list( + torch.rand([ + num_decoder_layers - 1, batch_size * num_attention_heads, + num_distinct_queries, num_distinct_queries + ]) < 0.5), + num_heads=num_attention_heads, + num_dense_queries=num_dense_queries) + + # query + hidden_states = torch.randn( + [num_decoder_layers, batch_size, num_total_queries, embed_dims]) + # normalized cx, cy, w, h + references = list( + torch.rand( + [1 + num_decoder_layers, batch_size, num_total_queries, 4])) + all_layers_outputs_classes, all_layers_outputs_coords = \ + bbox_head.forward(hidden_states, references) + + # logits + enc_outputs_class = torch.randn( + [batch_size, num_distinct_queries, num_classes]) + + # normalized cx, cy, w, h + enc_outputs_coord = torch.rand([batch_size, num_distinct_queries, 4]) + + # Test that empty ground truth encourages the network to predict + # background + empty_batch_gt_instances = [] + + for _ in range(batch_size): + gt_instances = InstanceData() + gt_instances.labels = torch.LongTensor([]) + gt_instances.bboxes = torch.empty((0, 4)) + empty_batch_gt_instances.append(gt_instances) + + empty_gt_losses = bbox_head.loss_by_feat(all_layers_outputs_classes, + all_layers_outputs_coords, + enc_outputs_class, + enc_outputs_coord, + empty_batch_gt_instances, + batch_img_metas, dn_meta) + + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + losses = bbox_head.loss_by_feat(all_layers_outputs_classes, + all_layers_outputs_coords, + enc_outputs_class, enc_outputs_coord, + batch_gt_instances, batch_img_metas, + dn_meta) + + cls_loss = losses['loss_cls'] + box_loss = losses['loss_bbox'] + self.assertGreater(cls_loss.item(), 0, 'cls loss should be non-zero') + self.assertGreater(box_loss.item(), 0, 'box loss should be non-zero') + + def get_batch_data_samples(self): + """Generate batch data samples including model inputs and gt labels.""" + data_sample_file_path = 'tests/data/coco_batched_sample.json' + + with open(data_sample_file_path, 'r') as file_stream: + data_sample_infos = json.load(file_stream) + + batch_data_samples = [] + + for data_sample_info in data_sample_infos: + data_sample = DetDataSample() + + metainfo = data_sample_info['metainfo'] + labels = data_sample_info['labels'] + bboxes = data_sample_info['bboxes'] + + data_sample.set_metainfo(metainfo) + + gt_instances = InstanceData() + gt_instances.labels = torch.LongTensor(labels) + gt_instances.bboxes = torch.Tensor(bboxes) + data_sample.gt_instances = gt_instances + + batch_data_samples.append(data_sample) + + return batch_data_samples diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_embedding_rpn_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_embedding_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f713da586d7cb7303d50fcbecd9eaa9ce8ec4f84 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_embedding_rpn_head.py @@ -0,0 +1,55 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import pytest +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import EmbeddingRPNHead +from mmdet.structures import DetDataSample + + +class TestEmbeddingRPNHead(TestCase): + + def test_init(self): + """Test init rpn head.""" + rpn_head = EmbeddingRPNHead( + num_proposals=100, proposal_feature_channel=256) + rpn_head.init_weights() + self.assertTrue(rpn_head.init_proposal_bboxes) + self.assertTrue(rpn_head.init_proposal_features) + + def test_loss_and_predict(self): + s = 256 + img_meta = { + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + } + rpn_head = EmbeddingRPNHead( + num_proposals=100, proposal_feature_channel=256) + + feats = [ + torch.rand(2, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(5) + ] + + data_sample = DetDataSample() + data_sample.set_metainfo(img_meta) + + # test predict + result_list = rpn_head.predict(feats, [data_sample]) + self.assertTrue(isinstance(result_list, list)) + self.assertTrue(isinstance(result_list[0], InstanceData)) + + # test loss_and_predict + result_list = rpn_head.loss_and_predict(feats, [data_sample]) + self.assertTrue(isinstance(result_list, tuple)) + self.assertTrue(isinstance(result_list[0], dict)) + self.assertEqual(len(result_list[0]), 0) + self.assertTrue(isinstance(result_list[1], list)) + self.assertTrue(isinstance(result_list[1][0], InstanceData)) + + # test loss + with pytest.raises(NotImplementedError): + rpn_head.loss(feats, [data_sample]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fcos_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fcos_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ba0f9dadac83a07cdf3f26f8006405fef2d5f27a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fcos_head.py @@ -0,0 +1,97 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import FCOSHead + + +class TestFCOSHead(TestCase): + + def test_fcos_head_loss(self): + """Tests fcos head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + fcos_head = FCOSHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + norm_cfg=None) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in fcos_head.prior_generator.strides) + cls_scores, bbox_preds, centernesses = fcos_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = fcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = empty_gt_losses['loss_cls'].item() + empty_box_loss = empty_gt_losses['loss_bbox'].item() + empty_ctr_loss = empty_gt_losses['loss_centerness'].item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_ctr_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = fcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].item() + onegt_box_loss = one_gt_losses['loss_bbox'].item() + onegt_ctr_loss = one_gt_losses['loss_centerness'].item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_ctr_loss, 0, + 'centerness loss should be non-zero') + + # Test the `center_sampling` works fine. + fcos_head.center_sampling = True + ctrsamp_losses = fcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + ctrsamp_cls_loss = ctrsamp_losses['loss_cls'].item() + ctrsamp_box_loss = ctrsamp_losses['loss_bbox'].item() + ctrsamp_ctr_loss = ctrsamp_losses['loss_centerness'].item() + self.assertGreater(ctrsamp_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(ctrsamp_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(ctrsamp_ctr_loss, 0, + 'centerness loss should be non-zero') + + # Test the `norm_on_bbox` works fine. + fcos_head.norm_on_bbox = True + normbox_losses = fcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + normbox_cls_loss = normbox_losses['loss_cls'].item() + normbox_box_loss = normbox_losses['loss_bbox'].item() + normbox_ctr_loss = normbox_losses['loss_centerness'].item() + self.assertGreater(normbox_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(normbox_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(normbox_ctr_loss, 0, + 'centerness loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fovea_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fovea_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c00f980354e5fed36f1b734132ff965c24ab2b17 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fovea_head.py @@ -0,0 +1,61 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import FoveaHead + + +class TestFOVEAHead(TestCase): + + def test_fovea_head_loss(self): + """Tests anchor head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + fovea_head = FoveaHead(num_classes=4, in_channels=1) + + # Anchor head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(len(fovea_head.prior_generator.strides))) + cls_scores, bbox_preds = fovea_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = fovea_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = fovea_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_free_anchor_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_free_anchor_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d2698bc225f3dee06893c33f5c2860bf05662a7c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_free_anchor_head.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import FreeAnchorRetinaHead + + +class TestFreeAnchorRetinaHead(TestCase): + + def test_free_anchor_head_loss(self): + """Tests rpn head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + anchor_head = FreeAnchorRetinaHead(num_classes=1, in_channels=1) + + # Anchor head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(len(anchor_head.prior_generator.strides))) + cls_scores, bbox_preds = anchor_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + positive_bag_loss = empty_gt_losses['positive_bag_loss'] + negative_bag_loss = empty_gt_losses['negative_bag_loss'] + self.assertGreater(negative_bag_loss.item(), 0, + 'negative_bag loss should be non-zero') + self.assertEqual( + positive_bag_loss.item(), 0, + 'there should be no positive_bag loss when there are no true boxes' + ) + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([0]) + + one_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['positive_bag_loss'] + onegt_box_loss = one_gt_losses['negative_bag_loss'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'positive bag loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'negative bag loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fsaf_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fsaf_head.py new file mode 100644 index 0000000000000000000000000000000000000000..155af5fd5264b245c918e314289996d3f0471b3e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_fsaf_head.py @@ -0,0 +1,93 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from math import ceil +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import FSAFHead + + +class TestFSAFHead(TestCase): + + def test_fsaf_head_loss(self): + """Tests fsaf head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + }] + cfg = Config( + dict( + assigner=dict( + type='CenterRegionAssigner', + pos_scale=0.2, + neg_scale=0.2, + min_pos_iof=0.01), + allowed_border=-1, + pos_weight=-1, + debug=False)) + fsaf_head = FSAFHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=1, + reg_decoded_bbox=True, + anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=1, + scales_per_octave=1, + ratios=[1.0], + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict(type='TBLRBBoxCoder', normalizer=4.0), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0, + reduction='none'), + loss_bbox=dict( + type='IoULoss', eps=1e-6, loss_weight=1.0, reduction='none'), + train_cfg=cfg) + + # FSAF head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, ceil(s / stride[0]), ceil(s / stride[0])) + for stride in fsaf_head.prior_generator.strides) + cls_scores, bbox_preds = fsaf_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = fsaf_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss should be zero + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = fsaf_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ga_retina_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ga_retina_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e129ec419f9625769ca2a940bcdc3005122f9e25 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ga_retina_head.py @@ -0,0 +1,97 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict + +from mmdet.models.dense_heads import GARetinaHead + +ga_retina_head_config = ConfigDict( + dict( + num_classes=4, + in_channels=4, + feat_channels=4, + stacked_convs=1, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[4], + strides=[8, 16, 32, 64, 128]), + anchor_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + loc_filter_thr=0.01, + loss_loc=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_shape=dict(type='BoundedIoULoss', beta=0.2, loss_weight=1.0), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=0.04, loss_weight=1.0), + train_cfg=dict( + ga_assigner=dict( + type='ApproxMaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0.4, + ignore_iof_thr=-1), + ga_sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + center_ratio=0.2, + ignore_ratio=0.5, + debug=False), + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100))) + + +class TestGARetinaHead(TestCase): + + def test_ga_retina_head_init_and_forward(self): + """The GARetinaHead inherit loss and prediction function from + GuidedAchorHead. + + Here, we only test GARetinaHet initialization and forward. + """ + # Test initializaion + ga_retina_head = GARetinaHead(**ga_retina_head_config) + + # Test forward + s = 256 + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in ga_retina_head.square_anchor_generator.strides) + ga_retina_head(feats) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ga_rpn_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ga_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b0fc555586a46066485dc62633588c8fdfc02cb2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ga_rpn_head.py @@ -0,0 +1,143 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import GARPNHead + +ga_rpn_config = ConfigDict( + dict( + num_classes=1, + in_channels=4, + feat_channels=4, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=8, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[4, 8, 16, 32, 64]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[8], + strides=[4, 8, 16, 32, 64]), + anchor_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[0.07, 0.07, 0.14, 0.14]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[0.07, 0.07, 0.11, 0.11]), + loc_filter_thr=0.01, + loss_loc=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_shape=dict(type='BoundedIoULoss', beta=0.2, loss_weight=1.0), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0), + train_cfg=dict( + ga_assigner=dict( + type='ApproxMaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.3, + min_pos_iou=0.3, + ignore_iof_thr=-1), + ga_sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + 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, + center_ratio=0.2, + ignore_ratio=0.5, + pos_weight=-1, + debug=False), + test_cfg=dict( + nms_pre=1000, + ms_post=1000, + max_per_img=300, + nms=dict(type='nms', iou_threshold=0.7), + min_bbox_size=0))) + + +class TestGARPNHead(TestCase): + + def test_ga_rpn_head_loss(self): + """Tests ga rpn head loss.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': (1, 1) + }] + ga_rpn_head = GARPNHead(**ga_rpn_config) + + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in ga_rpn_head.square_anchor_generator.strides) + outs = ga_rpn_head(feats) + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([0]) + + one_gt_losses = ga_rpn_head.loss_by_feat(*outs, [gt_instances], + img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_rpn_cls']).item() + onegt_box_loss = sum(one_gt_losses['loss_rpn_bbox']).item() + onegt_shape_loss = sum(one_gt_losses['loss_anchor_shape']).item() + onegt_loc_loss = sum(one_gt_losses['loss_anchor_loc']).item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_shape_loss, 0, + 'shape loss should be non-zero') + self.assertGreater(onegt_loc_loss, 0, + 'location loss should be non-zero') + + def test_ga_rpn_head_predict_by_feat(self): + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': (1, 1) + }] + ga_rpn_head = GARPNHead(**ga_rpn_config) + + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in ga_rpn_head.square_anchor_generator.strides) + outs = ga_rpn_head(feats) + + cfg = ConfigDict( + dict( + nms_pre=2000, + nms_post=1000, + max_per_img=300, + nms=dict(type='nms', iou_threshold=0.7), + min_bbox_size=0)) + ga_rpn_head.predict_by_feat( + *outs, batch_img_metas=img_metas, cfg=cfg, rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_gfl_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_gfl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..247627c05d09047db1faec2ce667cb83e75a19a5 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_gfl_head.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import GFLHead + + +class TestGFLHead(TestCase): + + def test_gfl_head_loss(self): + """Tests gfl head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + train_cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False)) + gfl_head = GFLHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + loss_cls=dict( + type='QualityFocalLoss', + use_sigmoid=True, + beta=2.0, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + cls_scores, bbox_preds = gfl_head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = gfl_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + empty_dfl_loss = sum(empty_gt_losses['loss_dfl']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_dfl_loss.item(), 0, + 'there should be no dfl loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = gfl_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + onegt_dfl_loss = sum(one_gt_losses['loss_dfl']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_dfl_loss.item(), 0, + 'dfl loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_guided_anchor_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_guided_anchor_head.py new file mode 100644 index 0000000000000000000000000000000000000000..410f4eebd39a7c6e55729fde639b67f25f456e7f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_guided_anchor_head.py @@ -0,0 +1,157 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import GuidedAnchorHead + +guided_anchor_head_config = ConfigDict( + dict( + num_classes=4, + in_channels=4, + feat_channels=4, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[4], + strides=[8, 16, 32, 64, 128]), + anchor_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + loc_filter_thr=0.01, + loss_loc=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_shape=dict(type='BoundedIoULoss', beta=0.2, loss_weight=1.0), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=0.04, loss_weight=1.0), + train_cfg=dict( + ga_assigner=dict( + type='ApproxMaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0.4, + ignore_iof_thr=-1), + ga_sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + center_ratio=0.2, + ignore_ratio=0.5, + debug=False), + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100))) + + +class TestGuidedAnchorHead(TestCase): + + def test_guided_anchor_head_loss(self): + """Tests guided anchor loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': (1, 1) + }] + guided_anchor_head = GuidedAnchorHead(**guided_anchor_head_config) + + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in guided_anchor_head.square_anchor_generator.strides) + outs = guided_anchor_head(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = guided_anchor_head.loss_by_feat( + *outs, [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # box shape and location loss should be zero + empty_cls_loss = sum(empty_gt_losses['loss_cls']).item() + empty_box_loss = sum(empty_gt_losses['loss_bbox']).item() + empty_shape_loss = sum(empty_gt_losses['loss_shape']).item() + empty_loc_loss = sum(empty_gt_losses['loss_loc']).item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(empty_loc_loss, 0, + 'location loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_shape_loss, 0, + 'there should be no shape loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = guided_anchor_head.loss_by_feat( + *outs, [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']).item() + onegt_box_loss = sum(one_gt_losses['loss_bbox']).item() + onegt_shape_loss = sum(one_gt_losses['loss_shape']).item() + onegt_loc_loss = sum(one_gt_losses['loss_loc']).item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_shape_loss, 0, + 'shape loss should be non-zero') + self.assertGreater(onegt_loc_loss, 0, + 'location loss should be non-zero') + + def test_guided_anchor_head_predict_by_feat(self): + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': (1, 1) + }] + guided_anchor_head = GuidedAnchorHead(**guided_anchor_head_config) + + feats = ( + torch.rand(1, 4, s // stride[1], s // stride[0]) + for stride in guided_anchor_head.square_anchor_generator.strides) + outs = guided_anchor_head(feats) + + guided_anchor_head.predict_by_feat( + *outs, batch_img_metas=img_metas, rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_lad_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_lad_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0dfd17d5864d2c10ac315b541eeebf7cdb18e92f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_lad_head.py @@ -0,0 +1,168 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import LADHead, lad_head +from mmdet.models.dense_heads.lad_head import levels_to_images + + +class TestLADHead(TestCase): + + def test_lad_head_loss(self): + """Tests lad head loss when truth is empty and non-empty.""" + + class mock_skm: + + def GaussianMixture(self, *args, **kwargs): + return self + + def fit(self, loss): + pass + + def predict(self, loss): + components = np.zeros_like(loss, dtype=np.long) + return components.reshape(-1) + + def score_samples(self, loss): + scores = np.random.random(len(loss)) + return scores + + lad_head.skm = mock_skm() + + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + train_cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.1, + neg_iou_thr=0.1, + min_pos_iou=0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + debug=False)) + # since Focal Loss is not supported on CPU + # since Focal Loss is not supported on CPU + lad = LADHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + teacher_model = LADHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + lad.init_weights() + teacher_model.init_weights() + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + batch_gt_instances_ignore = None + + outs_teacher = teacher_model(feat) + label_assignment_results = teacher_model.get_label_assignment( + *outs_teacher, [gt_instances], img_metas, + batch_gt_instances_ignore) + + outs = teacher_model(feat) + empty_gt_losses = lad.loss_by_feat(*outs, [gt_instances], img_metas, + batch_gt_instances_ignore, + label_assignment_results) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + empty_iou_loss = empty_gt_losses['loss_iou'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_iou_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + batch_gt_instances_ignore = None + + label_assignment_results = teacher_model.get_label_assignment( + *outs_teacher, [gt_instances], img_metas, + batch_gt_instances_ignore) + one_gt_losses = lad.loss_by_feat(*outs, [gt_instances], img_metas, + batch_gt_instances_ignore, + label_assignment_results) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + onegt_iou_loss = one_gt_losses['loss_iou'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_iou_loss.item(), 0, + 'box loss should be non-zero') + n, c, h, w = 10, 4, 20, 20 + mlvl_tensor = [torch.ones(n, c, h, w) for i in range(5)] + results = levels_to_images(mlvl_tensor) + self.assertEqual(len(results), n) + self.assertEqual(results[0].size(), (h * w * 5, c)) + self.assertTrue(lad.with_score_voting) + + lad = LADHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8]), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + cls_scores = [torch.ones(2, 4, 5, 5)] + bbox_preds = [torch.ones(2, 4, 5, 5)] + iou_preds = [torch.ones(2, 1, 5, 5)] + cfg = Config( + dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + rescale = False + lad.predict_by_feat( + cls_scores, bbox_preds, iou_preds, img_metas, cfg, rescale=rescale) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ld_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ld_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ce49b5385677aa1fdc9cc2a815cec40ea06b7a0c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ld_head.py @@ -0,0 +1,149 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import GFLHead, LDHead + + +class TestLDHead(TestCase): + + def test_ld_head_loss(self): + """Tests ld head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + train_cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9, ignore_iof_thr=0.1), + allowed_border=-1, + pos_weight=-1, + debug=False)) + + ld_head = LDHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_ld=dict( + type='KnowledgeDistillationKLDivLoss', loss_weight=1.0), + loss_cls=dict( + type='QualityFocalLoss', + use_sigmoid=True, + beta=2.0, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128])) + + teacher_model = GFLHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_cls=dict( + type='QualityFocalLoss', + use_sigmoid=True, + beta=2.0, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128])) + + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + cls_scores, bbox_preds = ld_head.forward(feat) + rand_soft_target = teacher_model.forward(feat)[1] + + # Test that empty ground truth encourages the network to predict + # background + + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + batch_gt_instances_ignore = None + + empty_gt_losses = ld_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + rand_soft_target, + batch_gt_instances_ignore) + + # When there is no truth, the cls loss should be nonzero, ld loss + # should be non-negative but there should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + empty_ld_loss = sum(empty_gt_losses['loss_ld']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertGreaterEqual(empty_ld_loss.item(), 0, + 'ld loss should be non-negative') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + batch_gt_instances_ignore = None + + one_gt_losses = ld_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + rand_soft_target, + batch_gt_instances_ignore) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + + batch_gt_instances_ignore = gt_instances + + # When truth is non-empty but ignored then the cls loss should be + # nonzero, but there should be no box loss. + ignore_gt_losses = ld_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + rand_soft_target, + batch_gt_instances_ignore) + ignore_cls_loss = sum(ignore_gt_losses['loss_cls']) + ignore_box_loss = sum(ignore_gt_losses['loss_bbox']) + + self.assertGreater(ignore_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual(ignore_box_loss.item(), 0, + 'gt bbox ignored loss should be zero') + + # When truth is non-empty and not ignored then both cls and box loss + # should be nonzero for random inputs + batch_gt_instances_ignore = InstanceData() + batch_gt_instances_ignore.bboxes = torch.randn(1, 4) + + not_ignore_gt_losses = ld_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + rand_soft_target, + batch_gt_instances_ignore) + not_ignore_cls_loss = sum(not_ignore_gt_losses['loss_cls']) + not_ignore_box_loss = sum(not_ignore_gt_losses['loss_bbox']) + + self.assertGreater(not_ignore_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreaterEqual(not_ignore_box_loss.item(), 0, + 'gt bbox not ignored loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_nasfcos_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_nasfcos_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1194e5c5fbca5d872b034e1c9b668eae4b930305 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_nasfcos_head.py @@ -0,0 +1,70 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import NASFCOSHead + + +class TestNASFCOSHead(TestCase): + + def test_nasfcos_head_loss(self): + """Tests nasfcos head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + nasfcos_head = NASFCOSHead( + num_classes=4, + in_channels=2, # the same as `deform_groups` in dconv3x3_config + feat_channels=2, + norm_cfg=None) + + # Nasfcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 2, s // stride[1], s // stride[0]).float() + for stride in nasfcos_head.prior_generator.strides) + cls_scores, bbox_preds, centernesses = nasfcos_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = nasfcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = empty_gt_losses['loss_cls'].item() + empty_box_loss = empty_gt_losses['loss_bbox'].item() + empty_ctr_loss = empty_gt_losses['loss_centerness'].item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_ctr_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = nasfcos_head.loss_by_feat(cls_scores, bbox_preds, + centernesses, [gt_instances], + img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].item() + onegt_box_loss = one_gt_losses['loss_bbox'].item() + onegt_ctr_loss = one_gt_losses['loss_centerness'].item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero') + self.assertGreater(onegt_ctr_loss, 0, + 'centerness loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_paa_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_paa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..137b2c55e17390612771b0844629cde28876aa68 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_paa_head.py @@ -0,0 +1,148 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import PAAHead, paa_head +from mmdet.models.utils import levels_to_images + + +class TestPAAHead(TestCase): + + def test_paa_head_loss(self): + """Tests paa head loss when truth is empty and non-empty.""" + + class mock_skm: + + def GaussianMixture(self, *args, **kwargs): + return self + + def fit(self, loss): + pass + + def predict(self, loss): + components = np.zeros_like(loss, dtype=np.long) + return components.reshape(-1) + + def score_samples(self, loss): + scores = np.random.random(len(loss)) + return scores + + paa_head.skm = mock_skm() + + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + train_cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.1, + neg_iou_thr=0.1, + min_pos_iou=0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + debug=False)) + # since Focal Loss is not supported on CPU + paa = PAAHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + paa.init_weights() + cls_scores, bbox_preds, iou_preds = paa(feat) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = paa.loss_by_feat(cls_scores, bbox_preds, iou_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + empty_iou_loss = empty_gt_losses['loss_iou'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_iou_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = paa.loss_by_feat(cls_scores, bbox_preds, iou_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + onegt_iou_loss = one_gt_losses['loss_iou'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_iou_loss.item(), 0, + 'box loss should be non-zero') + n, c, h, w = 10, 4, 20, 20 + mlvl_tensor = [torch.ones(n, c, h, w) for i in range(5)] + results = levels_to_images(mlvl_tensor) + self.assertEqual(len(results), n) + self.assertEqual(results[0].size(), (h * w * 5, c)) + self.assertTrue(paa.with_score_voting) + + paa = PAAHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8]), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.3), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5)) + cls_scores = [torch.ones(2, 4, 5, 5)] + bbox_preds = [torch.ones(2, 4, 5, 5)] + iou_preds = [torch.ones(2, 1, 5, 5)] + cfg = Config( + dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + rescale = False + paa.predict_by_feat( + cls_scores, bbox_preds, iou_preds, img_metas, cfg, rescale=rescale) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_pisa_retinanet_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_pisa_retinanet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf94404cfdab1a97a5960e9338aad15a2916626 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_pisa_retinanet_head.py @@ -0,0 +1,105 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from math import ceil +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import PISARetinaHead + + +class TestPISARetinaHead(TestCase): + + def test_pisa_reitnanet_head_loss(self): + """Tests pisa retinanet head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': 1, + }] + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0, + ignore_iof_thr=-1), + isr=dict(k=2., bias=0.), + carl=dict(k=1., bias=0.2), + sampler=dict(type='PseudoSampler'), + allowed_border=-1, + pos_weight=-1, + debug=False)) + pisa_retinanet_head = PISARetinaHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + feat_channels=256, + anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0]), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0), + train_cfg=cfg) + + # pisa retina head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, ceil(s / stride[0]), ceil(s / stride[0])) + for stride in pisa_retinanet_head.prior_generator.strides) + cls_scores, bbox_preds = pisa_retinanet_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = pisa_retinanet_head.loss_by_feat( + cls_scores, bbox_preds, [gt_instances], img_metas) + # When there is no truth, cls_loss and box_loss should all be zero. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + empty_carl_loss = empty_gt_losses['loss_carl'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_carl_loss.item(), 0, + 'there should be no carl loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = pisa_retinanet_head.loss_by_feat( + cls_scores, bbox_preds, [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + onegt_carl_loss = one_gt_losses['loss_carl'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_carl_loss.item(), 0, + 'carl loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_pisa_ssd_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_pisa_ssd_head.py new file mode 100644 index 0000000000000000000000000000000000000000..cfdc0c79862c127eea2b751e9bb11f5bab0ce731 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_pisa_ssd_head.py @@ -0,0 +1,127 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from math import ceil +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import PISASSDHead + + +class TestPISASSDHead(TestCase): + + def test_pisa_ssd_head_loss(self): + """Tests pisa ssd head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0., + ignore_iof_thr=-1, + gt_max_assign_all=False), + sampler=dict(type='PseudoSampler'), + smoothl1_beta=1., + allowed_border=-1, + pos_weight=-1, + neg_pos_ratio=3, + debug=False)) + pisa_ssd_head = PISASSDHead( + num_classes=4, + in_channels=(1, 1, 1, 1, 1, 1), + anchor_generator=dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=s, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]), + train_cfg=cfg) + + # PISA SSD head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, ceil(s / stride[0]), ceil(s / stride[0])) + for stride in pisa_ssd_head.prior_generator.strides) + cls_scores, bbox_preds = pisa_ssd_head.forward(feats) + + # test without isr and carl + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = pisa_ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, cls_loss and box_loss should all be zero. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = pisa_ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + + pisa_ssd_head.train_cfg.update( + dict(isr=dict(k=2., bias=0.), carl=dict(k=1., bias=0.2))) + + # test with isr and carl + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = pisa_ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, cls_loss and box_loss should all be zero. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = pisa_ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_reppoints_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_reppoints_head.py new file mode 100644 index 0000000000000000000000000000000000000000..96ec3caf496fc30c0c366458e095b9f36aad54ee --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_reppoints_head.py @@ -0,0 +1,143 @@ +import unittest + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet.models.dense_heads import RepPointsHead +from mmdet.structures import DetDataSample + + +class TestRepPointsHead(unittest.TestCase): + + @parameterized.expand(['moment', 'minmax', 'partial_minmax']) + def test_head_loss(self, transform_method='moment'): + cfg = ConfigDict( + dict( + num_classes=2, + in_channels=32, + point_feat_channels=10, + num_points=9, + gradient_mul=0.1, + point_strides=[8, 16, 32, 64, 128], + point_base_scale=4, + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox_init=dict( + type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=0.5), + loss_bbox_refine=dict( + type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0), + use_grid_points=False, + center_init=True, + transform_method=transform_method, + moment_mul=0.01, + init_cfg=dict( + type='Normal', + layer='Conv2d', + std=0.01, + override=dict( + type='Normal', + name='reppoints_cls_out', + std=0.01, + bias_prob=0.01)), + train_cfg=dict( + init=dict( + assigner=dict( + type='PointAssigner', scale=4, pos_num=1), + allowed_border=-1, + pos_weight=-1, + debug=False), + refine=dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + debug=False)), + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100))) + reppoints_head = RepPointsHead(**cfg) + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + }] + x = [ + torch.rand(1, 32, s // 2**(i + 2), s // 2**(i + 2)) + for i in range(5) + ] + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + + reppoints_head.train() + forward_outputs = reppoints_head.forward(x) + empty_gt_losses = reppoints_head.loss_by_feat(*forward_outputs, + [gt_instances], + img_metas, + gt_bboxes_ignore) + # When there is no truth, the cls loss should be nonzero but there + # should be no pts loss. + for key, losses in empty_gt_losses.items(): + for loss in losses: + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'pts' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no reg loss when no ground true boxes' + ) + + # When truth is non-empty then both cls and pts loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = reppoints_head.loss_by_feat(*forward_outputs, + [gt_instances], img_metas, + gt_bboxes_ignore) + # loss_cls should all be non-zero + self.assertTrue( + all([loss.item() > 0 for loss in one_gt_losses['loss_cls']])) + # only one level loss_pts_init is non-zero + cnt_non_zero = 0 + for loss in one_gt_losses['loss_pts_init']: + if loss.item() != 0: + cnt_non_zero += 1 + self.assertEqual(cnt_non_zero, 1) + + # only one level loss_pts_refine is non-zero + cnt_non_zero = 0 + for loss in one_gt_losses['loss_pts_init']: + if loss.item() != 0: + cnt_non_zero += 1 + self.assertEqual(cnt_non_zero, 1) + + # test loss + samples = DetDataSample() + samples.set_metainfo(img_metas[0]) + samples.gt_instances = gt_instances + reppoints_head.loss(x, [samples]) + # test only predict + reppoints_head.eval() + reppoints_head.predict(x, [samples], rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_retina_sepBN_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_retina_sepBN_head.py new file mode 100644 index 0000000000000000000000000000000000000000..95a18f64827290c1339ab5eba9d5bc9ce1a488ec --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_retina_sepBN_head.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import RetinaSepBNHead + + +class TestRetinaSepBNHead(TestCase): + + def test_init(self): + """Test init RetinaSepBN head.""" + anchor_head = RetinaSepBNHead(num_classes=1, num_ins=1, in_channels=1) + anchor_head.init_weights() + self.assertTrue(anchor_head.cls_convs) + self.assertTrue(anchor_head.reg_convs) + self.assertTrue(anchor_head.retina_cls) + self.assertTrue(anchor_head.retina_reg) + + def test_retina_sepbn_head_loss(self): + """Tests RetinaSepBN head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0, + ignore_iof_thr=-1), + sampler=dict(type='PseudoSampler' + ), # Focal loss should use PseudoSampler + allowed_border=-1, + pos_weight=-1, + debug=False)) + anchor_head = RetinaSepBNHead( + num_classes=4, num_ins=5, in_channels=1, train_cfg=cfg) + + # Anchor head expects a multiple levels of features per image + feats = [] + for i in range(len(anchor_head.prior_generator.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2)))) + + cls_scores, bbox_preds = anchor_head.forward(tuple(feats)) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = anchor_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_rpn_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_rpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1309d01d9917a82b48c91c520171eb6462626d94 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_rpn_head.py @@ -0,0 +1,124 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import pytest +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import RPNHead + + +class TestRPNHead(TestCase): + + def test_init(self): + """Test init rpn head.""" + rpn_head = RPNHead(num_classes=1, in_channels=1) + self.assertTrue(rpn_head.rpn_conv) + self.assertTrue(rpn_head.rpn_cls) + self.assertTrue(rpn_head.rpn_reg) + + # rpn_head.num_convs > 1 + rpn_head = RPNHead(num_classes=1, in_channels=1, num_convs=2) + self.assertTrue(rpn_head.rpn_conv) + self.assertTrue(rpn_head.rpn_cls) + self.assertTrue(rpn_head.rpn_reg) + + def test_rpn_head_loss(self): + """Tests rpn head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.3, + min_pos_iou=0.3, + 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=0, + pos_weight=-1, + debug=False)) + rpn_head = RPNHead(num_classes=1, in_channels=1, train_cfg=cfg) + + # Anchor head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2))) + for i in range(len(rpn_head.prior_generator.strides))) + cls_scores, bbox_preds = rpn_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = rpn_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = sum(empty_gt_losses['loss_rpn_cls']) + empty_box_loss = sum(empty_gt_losses['loss_rpn_bbox']) + self.assertGreater(empty_cls_loss.item(), 0, + 'rpn cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([0]) + + one_gt_losses = rpn_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_rpn_cls']) + onegt_box_loss = sum(one_gt_losses['loss_rpn_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'rpn cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'rpn box loss should be non-zero') + + # When there is no valid anchor, the loss will be None, + # and this will raise a ValueError. + img_metas = [{ + 'img_shape': (8, 8, 3), + 'pad_shape': (8, 8, 3), + 'scale_factor': 1, + }] + with pytest.raises(ValueError): + rpn_head.loss_by_feat(cls_scores, bbox_preds, [gt_instances], + img_metas) + + def test_bbox_post_process(self): + """Test the length of detection instance results is 0.""" + from mmengine.config import ConfigDict + cfg = ConfigDict( + nms_pre=1000, + max_per_img=1000, + nms=dict(type='nms', iou_threshold=0.7), + min_bbox_size=0) + + rpn_head = RPNHead(num_classes=1, in_channels=1) + results = InstanceData(metainfo=dict()) + results.bboxes = torch.zeros((0, 4)) + results.scores = torch.zeros(0) + results = rpn_head._bbox_post_process(results, cfg, img_meta=dict()) + self.assertEqual(len(results), 0) + self.assertEqual(results.bboxes.size(), (0, 4)) + self.assertEqual(results.scores.size(), (0, )) + self.assertEqual(results.labels.size(), (0, )) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_sabl_retina_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_sabl_retina_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2f6638ff857717bd18e1f1d257c13277c7ea6be5 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_sabl_retina_head.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import SABLRetinaHead + + +class TestSABLRetinaHead(TestCase): + + def test_sabl_retina_head(self): + """Tests sabl retina head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s), + 'pad_shape': (s, s), + 'scale_factor': [1, 1], + }] + train_cfg = ConfigDict( + dict( + assigner=dict( + type='ApproxMaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.4, + min_pos_iou=0.0, + ignore_iof_thr=-1), + allowed_border=-1, + pos_weight=-1, + debug=False)) + sabl_retina_head = SABLRetinaHead( + num_classes=4, + in_channels=1, + feat_channels=1, + stacked_convs=1, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[4], + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='BucketingBBoxCoder', num_buckets=14, scale_factor=3.0), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.5), + loss_bbox_reg=dict( + type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.5), + train_cfg=train_cfg) + + # Fcos head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in sabl_retina_head.square_anchor_generator.strides) + outs = sabl_retina_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = sabl_retina_head.loss_by_feat( + *outs, [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but + # box loss and centerness loss should be zero + empty_cls_loss = sum(empty_gt_losses['loss_cls']).item() + empty_box_cls_loss = sum(empty_gt_losses['loss_bbox_cls']).item() + empty_box_reg_loss = sum(empty_gt_losses['loss_bbox_reg']).item() + self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero') + self.assertEqual( + empty_box_cls_loss, 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_box_reg_loss, 0, + 'there should be no centerness loss when there are no true boxes') + + # When truth is non-empty then all cls, box loss and centerness loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = sabl_retina_head.loss_by_feat(*outs, [gt_instances], + img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']).item() + onegt_box_cls_loss = sum(one_gt_losses['loss_bbox_cls']).item() + onegt_box_reg_loss = sum(one_gt_losses['loss_bbox_reg']).item() + self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(onegt_box_cls_loss, 0, + 'box loss should be non-zero') + self.assertGreater(onegt_box_reg_loss, 0, + 'centerness loss should be non-zero') + + test_cfg = ConfigDict( + dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100)) + # test predict_by_feat + sabl_retina_head.predict_by_feat( + *outs, batch_img_metas=img_metas, cfg=test_cfg, rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_solo_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_solo_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1182d85b6f75da272a0c77cb18eae487778e86a6 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_solo_head.py @@ -0,0 +1,144 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet import * # noqa +from mmdet.models.dense_heads import (DecoupledSOLOHead, + DecoupledSOLOLightHead, SOLOHead) +from mmdet.structures.mask import BitmapMasks + + +def _rand_masks(num_items, bboxes, img_w, img_h): + rng = np.random.RandomState(0) + masks = np.zeros((num_items, img_h, img_w)) + for i, bbox in enumerate(bboxes): + bbox = bbox.astype(np.int32) + mask = (rng.rand(1, bbox[3] - bbox[1], bbox[2] - bbox[0]) > + 0.3).astype(np.int64) + masks[i:i + 1, bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask + return BitmapMasks(masks, height=img_h, width=img_w) + + +class TestSOLOHead(TestCase): + + @parameterized.expand([(SOLOHead, ), (DecoupledSOLOHead, ), + (DecoupledSOLOLightHead, )]) + def test_mask_head_loss(self, MaskHead): + """Tests mask head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + }] + + mask_head = MaskHead(num_classes=4, in_channels=1) + + # SOLO head expects a multiple levels of features per image + feats = [] + for i in range(len(mask_head.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2)))) + feats = tuple(feats) + + mask_outs = mask_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty(0, 4) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + + empty_gt_losses = mask_head.loss_by_feat( + *mask_outs, + batch_gt_instances=[gt_instances], + batch_img_metas=img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_mask_loss = empty_gt_losses['loss_mask'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_mask_loss.item(), 0, + 'there should be no mask loss when there are no true mask') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + + one_gt_losses = mask_head.loss_by_feat( + *mask_outs, + batch_gt_instances=[gt_instances], + batch_img_metas=img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_mask_loss = one_gt_losses['loss_mask'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_mask_loss.item(), 0, + 'mask loss should be non-zero') + + def test_solo_head_empty_result(self): + s = 256 + img_metas = { + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + } + + mask_head = SOLOHead(num_classes=4, in_channels=1) + + cls_scores = torch.empty(0, 80) + mask_preds = torch.empty(0, 16, 16) + test_cfg = ConfigDict( + score_thr=0.1, + mask_thr=0.5, + ) + results = mask_head._predict_by_feat_single( + cls_scores=cls_scores, + mask_preds=mask_preds, + img_meta=img_metas, + cfg=test_cfg) + + self.assertIsInstance(results, InstanceData) + self.assertEqual(len(results), 0) + + def test_decoupled_solo_head_empty_result(self): + s = 256 + img_metas = { + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + } + + mask_head = DecoupledSOLOHead(num_classes=4, in_channels=1) + + cls_scores = torch.empty(0, 80) + mask_preds_x = torch.empty(0, 16, 16) + mask_preds_y = torch.empty(0, 16, 16) + test_cfg = ConfigDict( + score_thr=0.1, + mask_thr=0.5, + ) + results = mask_head._predict_by_feat_single( + cls_scores=cls_scores, + mask_preds_x=mask_preds_x, + mask_preds_y=mask_preds_y, + img_meta=img_metas, + cfg=test_cfg) + + self.assertIsInstance(results, InstanceData) + self.assertEqual(len(results), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_solov2_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_solov2_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6abf91664dcf6d22850fdc971596b24a894cd487 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_solov2_head.py @@ -0,0 +1,130 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import SOLOV2Head +from mmdet.structures.mask import BitmapMasks + + +def _rand_masks(num_items, bboxes, img_w, img_h): + rng = np.random.RandomState(0) + masks = np.zeros((num_items, img_h, img_w)) + for i, bbox in enumerate(bboxes): + bbox = bbox.astype(np.int32) + mask = (rng.rand(1, bbox[3] - bbox[1], bbox[2] - bbox[0]) > + 0.3).astype(np.int64) + masks[i:i + 1, bbox[1]:bbox[3], bbox[0]:bbox[2]] = mask + return BitmapMasks(masks, height=img_h, width=img_w) + + +def _fake_mask_feature_head(): + mask_feature_head = ConfigDict( + feat_channels=128, + start_level=0, + end_level=3, + out_channels=256, + mask_stride=4, + norm_cfg=dict(type='GN', num_groups=32, requires_grad=True)) + return mask_feature_head + + +class TestSOLOv2Head(TestCase): + + def test_solov2_head_loss(self): + """Tests mask head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + }] + + mask_feature_head = _fake_mask_feature_head() + + mask_head = SOLOV2Head( + num_classes=4, in_channels=1, mask_feature_head=mask_feature_head) + + # SOLO head expects a multiple levels of features per image + feats = [] + for i in range(len(mask_head.strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), s // (2**(i + 2)))) + feats = tuple(feats) + + mask_outs = mask_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty(0, 4) + gt_instances.labels = torch.LongTensor([]) + gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) + + empty_gt_losses = mask_head.loss_by_feat( + *mask_outs, + batch_gt_instances=[gt_instances], + batch_img_metas=img_metas) + # When there is no truth, the cls loss should be nonzero but + # there should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_mask_loss = empty_gt_losses['loss_mask'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_mask_loss.item(), 0, + 'there should be no mask loss when there are no true mask') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) + + one_gt_losses = mask_head.loss_by_feat( + *mask_outs, + batch_gt_instances=[gt_instances], + batch_img_metas=img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_mask_loss = one_gt_losses['loss_mask'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_mask_loss.item(), 0, + 'mask loss should be non-zero') + + def test_solov2_head_empty_result(self): + s = 256 + img_metas = { + 'img_shape': (s, s, 3), + 'ori_shape': (s, s, 3), + 'scale_factor': 1, + 'batch_input_shape': (s, s, 3) + } + + mask_feature_head = _fake_mask_feature_head() + mask_head = SOLOV2Head( + num_classes=4, in_channels=1, mask_feature_head=mask_feature_head) + + kernel_preds = torch.empty(0, 128) + cls_scores = torch.empty(0, 80) + mask_feats = torch.empty(0, 16, 16) + test_cfg = ConfigDict( + score_thr=0.1, + mask_thr=0.5, + ) + results = mask_head._predict_by_feat_single( + kernel_preds=kernel_preds, + cls_scores=cls_scores, + mask_feats=mask_feats, + img_meta=img_metas, + cfg=test_cfg) + + self.assertIsInstance(results, InstanceData) + self.assertEqual(len(results), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ssd_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ssd_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c76a5e2584783c21974c7796edeea604827886 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_ssd_head.py @@ -0,0 +1,91 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from math import ceil +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import SSDHead + + +class TestSSDHead(TestCase): + + def test_ssd_head_loss(self): + """Tests ssd head loss when truth is empty and non-empty.""" + s = 300 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1, + }] + cfg = Config( + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0., + ignore_iof_thr=-1, + gt_max_assign_all=False), + sampler=dict(type='PseudoSampler'), + smoothl1_beta=1., + allowed_border=-1, + pos_weight=-1, + neg_pos_ratio=3, + debug=False)) + ssd_head = SSDHead( + num_classes=4, + in_channels=(1, 1, 1, 1, 1, 1), + stacked_convs=1, + feat_channels=1, + use_depthwise=True, + anchor_generator=dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=s, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]), + train_cfg=cfg) + + # SSD head expects a multiple levels of features per image + feats = ( + torch.rand(1, 1, ceil(s / stride[0]), ceil(s / stride[0])) + for stride in ssd_head.prior_generator.strides) + cls_scores, bbox_preds = ssd_head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, cls_loss and box_loss should all be zero. + empty_cls_loss = sum(empty_gt_losses['loss_cls']) + empty_box_loss = sum(empty_gt_losses['loss_bbox']) + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = ssd_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = sum(one_gt_losses['loss_cls']) + onegt_box_loss = sum(one_gt_losses['loss_bbox']) + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_tood_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_tood_head.py new file mode 100644 index 0000000000000000000000000000000000000000..346085553d637426fd2e60735163d83030882bf1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_tood_head.py @@ -0,0 +1,193 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config, MessageHub +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import TOODHead + + +def _tood_head(anchor_type): + """Set type of tood head.""" + train_cfg = Config( + dict( + initial_epoch=4, + initial_assigner=dict(type='ATSSAssigner', topk=9), + assigner=dict(type='TaskAlignedAssigner', topk=13), + alpha=1, + beta=6, + allowed_border=-1, + pos_weight=-1, + debug=False)) + test_cfg = Config( + dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + + tood_head = TOODHead( + num_classes=80, + in_channels=1, + stacked_convs=1, + feat_channels=8, # the same as `la_down_rate` in TaskDecomposition + norm_cfg=None, + anchor_type=anchor_type, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[0.1, 0.1, 0.2, 0.2]), + initial_loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + activated=True, # use probability instead of logit as input + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_cls=dict( + type='QualityFocalLoss', + use_sigmoid=True, + activated=True, # use probability instead of logit as input + beta=2.0, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + train_cfg=train_cfg, + test_cfg=test_cfg) + return tood_head + + +class TestTOODHead(TestCase): + + def test_tood_head_anchor_free_loss(self): + """Tests tood head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + tood_head = _tood_head('anchor_free') + tood_head.init_weights() + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [8, 16, 32, 64, 128] + ] + cls_scores, bbox_preds = tood_head(feat) + + message_hub = MessageHub.get_instance('runtime_info') + message_hub.update_info('epoch', 0) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + empty_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater( + sum(empty_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertEqual( + sum(empty_box_loss).item(), 0, + 'there should be no box loss when there are no true boxes') + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_bboxes_ignore = None + one_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater( + sum(onegt_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertGreater( + sum(onegt_box_loss).item(), 0, 'box loss should be non-zero') + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + empty_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater( + sum(empty_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertEqual( + sum(empty_box_loss).item(), 0, + 'there should be no box loss when there are no true boxes') + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + gt_bboxes_ignore = None + one_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater( + sum(onegt_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertGreater( + sum(onegt_box_loss).item(), 0, 'box loss should be non-zero') + + def test_tood_head_anchor_based_loss(self): + """Tests tood head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'pad_shape': (s, s, 3), + 'scale_factor': 1 + }] + tood_head = _tood_head('anchor_based') + tood_head.init_weights() + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [8, 16, 32, 64, 128] + ] + cls_scores, bbox_preds = tood_head(feat) + + message_hub = MessageHub.get_instance('runtime_info') + message_hub.update_info('epoch', 0) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + gt_bboxes_ignore = None + empty_gt_losses = tood_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas, + gt_bboxes_ignore) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater( + sum(empty_cls_loss).item(), 0, 'cls loss should be non-zero') + self.assertEqual( + sum(empty_box_loss).item(), 0, + 'there should be no box loss when there are no true boxes') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_vfnet_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_vfnet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..26f63c77079c23801b8ab527be7205eb7c1487b2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_vfnet_head.py @@ -0,0 +1,135 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import VFNetHead + + +class TestVFNetHead(TestCase): + + def test_vfnet_head_loss(self): + """Tests vfnet head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'pad_shape': (s, s, 3) + }] + train_cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False)) + # since VarFocal Loss is not supported on CPU + vfnet_head = VFNetHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + loss_cls=dict( + type='VarifocalLoss', use_sigmoid=True, loss_weight=1.0)) + + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + cls_scores, bbox_preds, bbox_preds_refine = vfnet_head.forward(feat) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = vfnet_head.loss_by_feat(cls_scores, bbox_preds, + bbox_preds_refine, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = vfnet_head.loss_by_feat(cls_scores, bbox_preds, + bbox_preds_refine, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + + def test_vfnet_head_loss_without_atss(self): + """Tests vfnet head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'pad_shape': (s, s, 3) + }] + train_cfg = Config( + dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False)) + # since VarFocal Loss is not supported on CPU + vfnet_head = VFNetHead( + num_classes=4, + in_channels=1, + train_cfg=train_cfg, + use_atss=False, + loss_cls=dict( + type='VarifocalLoss', use_sigmoid=True, loss_weight=1.0)) + + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16, 32, 64] + ] + cls_scores, bbox_preds, bbox_preds_refine = vfnet_head.forward(feat) + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = vfnet_head.loss_by_feat(cls_scores, bbox_preds, + bbox_preds_refine, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = vfnet_head.loss_by_feat(cls_scores, bbox_preds, + bbox_preds_refine, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolo_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolo_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2c48170dbf7054da32e28c7eee9fd736c772caf4 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolo_head.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import Config +from mmengine.structures import InstanceData + +from mmdet.models.dense_heads import YOLOV3Head + + +class TestYOLOV3Head(TestCase): + + def test_yolo_head_loss(self): + """Tests YOLO head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + head = YOLOV3Head( + num_classes=4, + in_channels=[1, 1, 1], + out_channels=[1, 1, 1], + train_cfg=Config( + dict( + assigner=dict( + type='GridAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0)))) + head.init_weights() + + # YOLO head expects a multiple levels of features per image + feats = [ + torch.rand(1, 1, s // stride[1], s // stride[0]) + for stride in head.prior_generator.strides + ] + predmaps, = head.forward(feats) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + + empty_gt_losses = head.loss_by_feat(predmaps, [gt_instances], + img_metas) + # When there is no truth, the conf loss should be nonzero but + # cls loss and xy&wh loss should be zero + empty_cls_loss = sum(empty_gt_losses['loss_cls']).item() + empty_conf_loss = sum(empty_gt_losses['loss_conf']).item() + empty_xy_loss = sum(empty_gt_losses['loss_xy']).item() + empty_wh_loss = sum(empty_gt_losses['loss_wh']).item() + self.assertGreater(empty_conf_loss, 0, 'conf loss should be non-zero') + self.assertEqual( + empty_cls_loss, 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_xy_loss, 0, + 'there should be no xy loss when there are no true boxes') + self.assertEqual( + empty_wh_loss, 0, + 'there should be no wh loss when there are no true boxes') + + # When truth is non-empty then all conf, cls loss and xywh loss + # should be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + + one_gt_losses = head.loss_by_feat(predmaps, [gt_instances], img_metas) + one_gt_cls_loss = sum(one_gt_losses['loss_cls']).item() + one_gt_conf_loss = sum(one_gt_losses['loss_conf']).item() + one_gt_xy_loss = sum(one_gt_losses['loss_xy']).item() + one_gt_wh_loss = sum(one_gt_losses['loss_wh']).item() + self.assertGreater(one_gt_conf_loss, 0, 'conf loss should be non-zero') + self.assertGreater(one_gt_cls_loss, 0, 'cls loss should be non-zero') + self.assertGreater(one_gt_xy_loss, 0, 'xy loss should be non-zero') + self.assertGreater(one_gt_wh_loss, 0, 'wh loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolof_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolof_head.py new file mode 100644 index 0000000000000000000000000000000000000000..29375d19914d1ae950328adc90d7479d596fe4a1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolof_head.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config +from mmengine.structures import InstanceData + +from mmdet import * # noqa +from mmdet.models.dense_heads import YOLOFHead + + +class TestYOLOFHead(TestCase): + + def test_yolof_head_loss(self): + """Tests yolof head loss when truth is empty and non-empty.""" + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + 'pad_shape': (s, s, 3) + }] + train_cfg = Config( + dict( + assigner=dict( + type='UniformAssigner', + pos_ignore_thr=0.15, + neg_ignore_thr=0.7), + allowed_border=-1, + pos_weight=-1, + debug=False)) + yolof_head = YOLOFHead( + num_classes=4, + in_channels=1, + feat_channels=1, + reg_decoded_bbox=True, + train_cfg=train_cfg, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[1, 2, 4, 8, 16], + strides=[32]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1., 1., 1., 1.], + add_ctr_clamp=True, + ctr_clamp=32), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.0)) + feat = [torch.rand(1, 1, s // 32, s // 32)] + cls_scores, bbox_preds = yolof_head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + empty_gt_losses = yolof_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'] + empty_box_loss = empty_gt_losses['loss_bbox'] + self.assertGreater(empty_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + one_gt_losses = yolof_head.loss_by_feat(cls_scores, bbox_preds, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'] + onegt_box_loss = one_gt_losses['loss_bbox'] + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolox_head.py b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1c830f58016fe508e950c79c222a0951ef0e988e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_dense_heads/test_yolox_head.py @@ -0,0 +1,164 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule +from mmengine.config import Config +from mmengine.model import bias_init_with_prob +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.dense_heads import YOLOXHead + + +class TestYOLOXHead(TestCase): + + def test_init_weights(self): + head = YOLOXHead( + num_classes=4, in_channels=1, stacked_convs=1, use_depthwise=False) + head.init_weights() + bias_init = bias_init_with_prob(0.01) + for conv_cls, conv_obj in zip(head.multi_level_conv_cls, + head.multi_level_conv_obj): + assert_allclose(conv_cls.bias.data, + torch.ones_like(conv_cls.bias.data) * bias_init) + assert_allclose(conv_obj.bias.data, + torch.ones_like(conv_obj.bias.data) * bias_init) + + def test_predict_by_feat(self): + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': (1.0, 1.0), + }] + test_cfg = Config( + dict(score_thr=0.01, nms=dict(type='nms', iou_threshold=0.65))) + head = YOLOXHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + use_depthwise=False, + test_cfg=test_cfg) + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16] + ] + cls_scores, bbox_preds, objectnesses = head.forward(feat) + head.predict_by_feat( + cls_scores, + bbox_preds, + objectnesses, + img_metas, + cfg=test_cfg, + rescale=True, + with_nms=True) + head.predict_by_feat( + cls_scores, + bbox_preds, + objectnesses, + img_metas, + cfg=test_cfg, + rescale=False, + with_nms=False) + + def test_loss_by_feat(self): + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + train_cfg = Config( + dict( + assigner=dict( + type='SimOTAAssigner', + center_radius=2.5, + candidate_topk=10, + iou_weight=3.0, + cls_weight=1.0))) + head = YOLOXHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + use_depthwise=False, + train_cfg=train_cfg) + assert not head.use_l1 + assert isinstance(head.multi_level_cls_convs[0][0], ConvModule) + + feat = [ + torch.rand(1, 1, s // feat_size, s // feat_size) + for feat_size in [4, 8, 16] + ] + cls_scores, bbox_preds, objectnesses = head.forward(feat) + + # Test that empty ground truth encourages the network to predict + # background + gt_instances = InstanceData( + bboxes=torch.empty((0, 4)), labels=torch.LongTensor([])) + + empty_gt_losses = head.loss_by_feat(cls_scores, bbox_preds, + objectnesses, [gt_instances], + img_metas) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + empty_cls_loss = empty_gt_losses['loss_cls'].sum() + empty_box_loss = empty_gt_losses['loss_bbox'].sum() + empty_obj_loss = empty_gt_losses['loss_obj'].sum() + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when there are no true boxes') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when there are no true boxes') + self.assertGreater(empty_obj_loss.item(), 0, + 'objectness loss should be non-zero') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + head = YOLOXHead( + num_classes=4, + in_channels=1, + stacked_convs=1, + use_depthwise=True, + train_cfg=train_cfg) + assert isinstance(head.multi_level_cls_convs[0][0], + DepthwiseSeparableConvModule) + head.use_l1 = True + gt_instances = InstanceData( + bboxes=torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]]), + labels=torch.LongTensor([2])) + + one_gt_losses = head.loss_by_feat(cls_scores, bbox_preds, objectnesses, + [gt_instances], img_metas) + onegt_cls_loss = one_gt_losses['loss_cls'].sum() + onegt_box_loss = one_gt_losses['loss_bbox'].sum() + onegt_obj_loss = one_gt_losses['loss_obj'].sum() + onegt_l1_loss = one_gt_losses['loss_l1'].sum() + self.assertGreater(onegt_cls_loss.item(), 0, + 'cls loss should be non-zero') + self.assertGreater(onegt_box_loss.item(), 0, + 'box loss should be non-zero') + self.assertGreater(onegt_obj_loss.item(), 0, + 'obj loss should be non-zero') + self.assertGreater(onegt_l1_loss.item(), 0, + 'l1 loss should be non-zero') + + # Test groud truth out of bound + gt_instances = InstanceData( + bboxes=torch.Tensor([[s * 4, s * 4, s * 4 + 10, s * 4 + 10]]), + labels=torch.LongTensor([2])) + empty_gt_losses = head.loss_by_feat(cls_scores, bbox_preds, + objectnesses, [gt_instances], + img_metas) + # When gt_bboxes out of bound, the assign results should be empty, + # so the cls and bbox loss should be zero. + empty_cls_loss = empty_gt_losses['loss_cls'].sum() + empty_box_loss = empty_gt_losses['loss_bbox'].sum() + empty_obj_loss = empty_gt_losses['loss_obj'].sum() + self.assertEqual( + empty_cls_loss.item(), 0, + 'there should be no cls loss when gt_bboxes out of bound') + self.assertEqual( + empty_box_loss.item(), 0, + 'there should be no box loss when gt_bboxes out of bound') + self.assertGreater(empty_obj_loss.item(), 0, + 'objectness loss should be non-zero') diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_conditional_detr.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_conditional_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..f907f6face1395bc56472b7c109b22448a7597b1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_conditional_detr.py @@ -0,0 +1,85 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestConditionalDETR(TestCase): + + def setUp(self) -> None: + register_all_modules() + + def test_conditional_detr_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + img_metas = DetDataSample() + img_metas.set_metainfo(metainfo) + batch_data_samples = [] + batch_data_samples.append(img_metas) + + config = get_detector_cfg( + 'conditional_detr/conditional-detr_r50_8xb2-50e_coco.py') + + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + img_metas.gt_instances = gt_instances + batch_data_samples1 = [] + batch_data_samples1.append(img_metas) + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'bbox' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no box loss when no ground true boxes') + elif 'iou' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no iou loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + img_metas.gt_instances = gt_instances + batch_data_samples2 = [] + batch_data_samples2.append(img_metas) + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward(random_image, batch_data_samples=batch_data_samples2) + # test only predict + model.predict( + random_image, batch_data_samples=batch_data_samples2, rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_cornernet.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_cornernet.py new file mode 100644 index 0000000000000000000000000000000000000000..10bc62649f699b9f6c38a9369091c38cd18c2c6c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_cornernet.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestCornerNet(TestCase): + + def setUp(self) -> None: + register_all_modules() + model_cfg = get_detector_cfg( + 'cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py') + + backbone = dict( + type='ResNet', + depth=18, + num_stages=4, + out_indices=(3, ), + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=True, + style='pytorch') + + neck = dict( + type='FPN', + in_channels=[512], + out_channels=256, + start_level=0, + add_extra_convs='on_input', + num_outs=1) + + model_cfg.backbone = ConfigDict(**backbone) + model_cfg.neck = ConfigDict(**neck) + model_cfg.bbox_head.num_feat_levels = 1 + self.model_cfg = model_cfg + + def test_init(self): + model = get_detector_cfg( + 'cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py') + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.bbox_head is not None) + self.assertTrue(detector.backbone is not None) + self.assertTrue(not hasattr(detector, 'neck')) + + @unittest.skipIf(not torch.cuda.is_available(), + 'test requires GPU and torch+cuda') + def test_cornernet_forward_loss_mode(self): + from mmdet.registry import MODELS + detector = MODELS.build(self.model_cfg) + detector.init_weights() + + packed_inputs = demo_mm_inputs(2, [[3, 511, 511], [3, 511, 511]]) + data = detector.data_preprocessor(packed_inputs, True) + losses = detector.forward(**data, mode='loss') + assert isinstance(losses, dict) + + @unittest.skipIf(not torch.cuda.is_available(), + 'test requires GPU and torch+cuda') + def test_cornernet_forward_predict_mode(self): + from mmdet.registry import MODELS + detector = MODELS.build(self.model_cfg) + detector.init_weights() + + packed_inputs = demo_mm_inputs(2, [[3, 512, 512], [3, 512, 512]]) + data = detector.data_preprocessor(packed_inputs, False) + + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + assert len(batch_results) == 2 + assert isinstance(batch_results[0], DetDataSample) + + @unittest.skipIf(not torch.cuda.is_available(), + 'test requires GPU and torch+cuda') + def test_cornernet_forward_tensor_mode(self): + from mmdet.registry import MODELS + detector = MODELS.build(self.model_cfg) + detector.init_weights() + + packed_inputs = demo_mm_inputs(2, [[3, 512, 512], [3, 512, 512]]) + data = detector.data_preprocessor(packed_inputs, False) + batch_results = detector.forward(**data, mode='tensor') + assert isinstance(batch_results, tuple) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_dab_detr.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_dab_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..37cc042c83441b24b71faa433e2b53e877cbddb9 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_dab_detr.py @@ -0,0 +1,84 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDABDETR(TestCase): + + def setUp(self) -> None: + register_all_modules() + + def test_dab_detr_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + img_metas = DetDataSample() + img_metas.set_metainfo(metainfo) + batch_data_samples = [] + batch_data_samples.append(img_metas) + + config = get_detector_cfg('dab_detr/dab-detr_r50_8xb2-50e_coco.py') + + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + img_metas.gt_instances = gt_instances + batch_data_samples1 = [] + batch_data_samples1.append(img_metas) + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'bbox' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no box loss when no ground true boxes') + elif 'iou' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no iou loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + img_metas.gt_instances = gt_instances + batch_data_samples2 = [] + batch_data_samples2.append(img_metas) + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward(random_image, batch_data_samples=batch_data_samples2) + # test only predict + model.predict( + random_image, batch_data_samples=batch_data_samples2, rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_ddq_detr.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_ddq_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3c5ca1e456d6785505c242ede716ccf6fc49e3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_ddq_detr.py @@ -0,0 +1,152 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import json +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDDQDETR(TestCase): + + def setUp(self): + register_all_modules() + + def test_ddq_detr_head_loss(self): + """Tests DDQ DETR head loss when truth is empty and non-empty.""" + configs = [ + get_detector_cfg('ddq/ddq-detr-4scale_r50_8xb2-12e_coco.py') + ] # noqa E501 + + for config in configs: + config.backbone.depth = 18 + config.backbone.init_cfg = None + config.neck.in_channels = [128, 256, 512] + config.encoder.num_layers = 1 + # `num_layers` >= 2, because attention masks of the last + # `num_layers` - 1 layers are used for distinct query selection + config.decoder.num_layers = 2 + config.bbox_head.num_classes = 2 + config.num_queries = 10 + config.dense_topk_ratio = 1.0 + config.dn_cfg.group_cfg.num_dn_queries = 10 + config.test_cfg.max_per_img = 2 + model = MODELS.build(config) + model.init_weights() + + batch_data_samples = self.get_batch_data_samples() + batch_input_shape = batch_data_samples[0].metainfo[ + 'batch_input_shape'] + random_images = torch.rand([1, 3, *batch_input_shape]) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + data_sample = DetDataSample() + data_sample.set_metainfo(batch_data_samples[0].metainfo) + data_sample.gt_instances = gt_instances + + batch_data_samples_1 = [data_sample] + empty_gt_losses = model.loss( + random_images, batch_data_samples=batch_data_samples_1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box or aux loss. + zero_loss_keywords = ['bbox', 'iou', 'dn'] + + for key, loss in empty_gt_losses.items(): + if 'aux' in key: + self.assertEqual( + len(loss), len(batch_data_samples_1), + (r'Actual aux loss count for {} is {},' + + r'it should be {}').format(key, len(loss), + len(batch_data_samples_1))) + + for image_loss in loss: + _image_loss = image_loss.item() + self.assertEqual( + _image_loss, 0, + f'there should be no {key}({_image_loss}) ' + f'when no ground true boxes') + + continue + + _loss = loss.item() + + if any(zero_loss_keyword in key + for zero_loss_keyword in zero_loss_keywords): + self.assertEqual( + _loss, 0, f'there should be no {key}({_loss}) ' + f'when no ground true boxes') + elif 'cls' in key: + self.assertGreater(_loss, 0, + f'{key}({_loss}) should be non-zero') + + # When truth is non-empty then both cls and box loss should + # be nonzero for random inputs. + random_images = torch.rand( + [len(batch_data_samples), 3, *batch_input_shape]) + batch_data_samples_2 = batch_data_samples + gt_losses = model.loss( + random_images, batch_data_samples=batch_data_samples_2) + for key, loss in gt_losses.items(): + if 'aux' in key: + self.assertEqual( + len(loss), len(batch_data_samples_2), + (r'Actual aux loss count for {} is {},' + + r'it should be {}').format(key, len(loss), + len(batch_data_samples_2))) + + for image_loss in loss: + self.assertGreater( + image_loss.item(), 0, + 'cls loss, or box loss, or iou loss should be' + + ' non-zero') + + continue + + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward( + random_images, batch_data_samples=batch_data_samples_2) + # test only predict + model.predict( + random_images, + batch_data_samples=batch_data_samples_2, + rescale=True) + + def get_batch_data_samples(self): + """Generate batch data samples including model inputs and gt labels.""" + data_sample_file_path = 'tests/data/coco_batched_sample.json' + + with open(data_sample_file_path, 'r') as file_stream: + data_sample_infos = json.load(file_stream) + + batch_data_samples = [] + + for data_sample_info in data_sample_infos: + data_sample = DetDataSample() + + metainfo = data_sample_info['metainfo'] + labels = data_sample_info['labels'] + bboxes = data_sample_info['bboxes'] + + data_sample.set_metainfo(metainfo) + + gt_instances = InstanceData() + gt_instances.labels = torch.LongTensor(labels) + gt_instances.bboxes = torch.Tensor(bboxes) + data_sample.gt_instances = gt_instances + + batch_data_samples.append(data_sample) + + return batch_data_samples diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_deformable_detr.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_deformable_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..45be51db74457a794d6ed08bcc4ccc72aee17f3a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_deformable_detr.py @@ -0,0 +1,99 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDeformableDETR(TestCase): + + def setUp(self): + register_all_modules() + + def test_deformable_detr_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + img_metas = DetDataSample() + img_metas.set_metainfo(metainfo) + batch_data_samples = [] + batch_data_samples.append(img_metas) + + configs = [ + get_detector_cfg( + 'deformable_detr/deformable-detr_r50_16xb2-50e_coco.py'), + get_detector_cfg( + 'deformable_detr/deformable-detr-refine_r50_16xb2-50e_coco.py' # noqa + ), + get_detector_cfg( + 'deformable_detr/deformable-detr-refine-twostage_r50_16xb2-50e_coco.py' # noqa + ) + ] + + for config in configs: + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + img_metas.gt_instances = gt_instances + batch_data_samples1 = [] + batch_data_samples1.append(img_metas) + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'bbox' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no box loss when no ground true boxes' + ) + elif 'iou' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no iou loss when no ground true boxes' + ) + + # When truth is non-empty then both cls and box loss should + # be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + img_metas.gt_instances = gt_instances + batch_data_samples2 = [] + batch_data_samples2.append(img_metas) + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward( + random_image, batch_data_samples=batch_data_samples2) + # test only predict + model.predict( + random_image, + batch_data_samples=batch_data_samples2, + rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_detr.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_detr.py new file mode 100644 index 0000000000000000000000000000000000000000..8af26da2eb4258eac02f3c3645da577b2fe20558 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_detr.py @@ -0,0 +1,84 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDETR(TestCase): + + def setUp(self) -> None: + register_all_modules() + + def test_detr_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + img_metas = DetDataSample() + img_metas.set_metainfo(metainfo) + batch_data_samples = [] + batch_data_samples.append(img_metas) + + config = get_detector_cfg('detr/detr_r50_8xb2-150e_coco.py') + + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + img_metas.gt_instances = gt_instances + batch_data_samples1 = [] + batch_data_samples1.append(img_metas) + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + if 'cls' in key: + self.assertGreater(loss.item(), 0, + 'cls loss should be non-zero') + elif 'bbox' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no box loss when no ground true boxes') + elif 'iou' in key: + self.assertEqual( + loss.item(), 0, + 'there should be no iou loss when there are no true boxes') + + # When truth is non-empty then both cls and box loss should be nonzero + # for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + img_metas.gt_instances = gt_instances + batch_data_samples2 = [] + batch_data_samples2.append(img_metas) + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward(random_image, batch_data_samples=batch_data_samples2) + # test only predict + model.predict( + random_image, batch_data_samples=batch_data_samples2, rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_dino.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_dino.py new file mode 100644 index 0000000000000000000000000000000000000000..99885c1dfee9c57ee044c410844aead51b8cfbd3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_dino.py @@ -0,0 +1,81 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDINO(TestCase): + + def setUp(self): + register_all_modules() + + def test_dino_head_loss(self): + """Tests transformer head loss when truth is empty and non-empty.""" + s = 256 + metainfo = { + 'img_shape': (s, s), + 'scale_factor': (1, 1), + 'pad_shape': (s, s), + 'batch_input_shape': (s, s) + } + data_sample = DetDataSample() + data_sample.set_metainfo(metainfo) + + configs = [get_detector_cfg('dino/dino-4scale_r50_8xb2-12e_coco.py')] + + for config in configs: + model = MODELS.build(config) + model.init_weights() + random_image = torch.rand(1, 3, s, s) + + # Test that empty ground truth encourages the network to + # predict background + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)) + gt_instances.labels = torch.LongTensor([]) + data_sample.gt_instances = gt_instances + batch_data_samples_1 = [data_sample] + empty_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples_1) + # When there is no truth, the cls loss should be nonzero but there + # should be no box loss. + for key, loss in empty_gt_losses.items(): + _loss = loss.item() + if 'bbox' in key or 'iou' in key or 'dn' in key: + self.assertEqual( + _loss, 0, f'there should be no {key}({_loss}) ' + f'when no ground true boxes') + elif 'cls' in key: + self.assertGreater(_loss, 0, + f'{key}({_loss}) should be non-zero') + + # When truth is non-empty then both cls and box loss should + # be nonzero for random inputs + gt_instances = InstanceData() + gt_instances.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instances.labels = torch.LongTensor([2]) + data_sample.gt_instances = gt_instances + batch_data_samples_2 = [data_sample] + one_gt_losses = model.loss( + random_image, batch_data_samples=batch_data_samples_2) + for loss in one_gt_losses.values(): + self.assertGreater( + loss.item(), 0, + 'cls loss, or box loss, or iou loss should be non-zero') + + model.eval() + # test _forward + model._forward( + random_image, batch_data_samples=batch_data_samples_2) + # test only predict + model.predict( + random_image, + batch_data_samples=batch_data_samples_2, + rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_glip.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_glip.py new file mode 100644 index 0000000000000000000000000000000000000000..dc38d3142d261c2fc766eba7f345155138f9a0fc --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_glip.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestGLIP(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand( + ['glip/glip_atss_swin-t_a_fpn_dyhead_pretrain_obj365.py']) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.language_model) + self.assertTrue(detector.neck) + self.assertTrue(detector.bbox_head) + + @parameterized.expand([ + ('glip/glip_atss_swin-t_a_fpn_dyhead_pretrain_obj365.py', ('cpu', + 'cuda')) + ]) + def test_glip_forward_predict_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + # test custom_entities is True + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + texts=['a', 'b'], + custom_entities=True) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + # test custom_entities is False + # packed_inputs = demo_mm_inputs( + # 2, [[3, 128, 128], [3, 125, 130]], + # texts=['a', 'b'], + # custom_entities=False) + # data = detector.data_preprocessor(packed_inputs, False) + # # Test forward test + # detector.eval() + # with torch.no_grad(): + # batch_results = detector.forward(**data, mode='predict') + # self.assertEqual(len(batch_results), 2) + # self.assertIsInstance(batch_results[0], DetDataSample) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_kd_single_stage.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_kd_single_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..93d886263a87c6472ac83135e792f3ced6a5dd30 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_kd_single_stage.py @@ -0,0 +1,78 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet import * # noqa +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestKDSingleStageDetector(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand(['ld/ld_r18-gflv1-r101_fpn_1x_coco.py']) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.bbox_head) + + @parameterized.expand([('ld/ld_r18-gflv1-r101_fpn_1x_coco.py', ('cpu', + 'cuda'))]) + def test_single_stage_forward_train(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, True) + # Test forward train + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([('ld/ld_r18-gflv1-r101_fpn_1x_coco.py', ('cpu', + 'cuda'))]) + def test_single_stage_forward_test(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_maskformer.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_maskformer.py new file mode 100644 index 0000000000000000000000000000000000000000..3eeb04bfd55fcebaeaf0cc403880951c2123bcb3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_maskformer.py @@ -0,0 +1,236 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing._utils import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestMaskFormer(unittest.TestCase): + + def setUp(self): + register_all_modules() + + def _create_model_cfg(self): + cfg_path = 'maskformer/maskformer_r50_ms-16xb1-75e_coco.py' + model_cfg = get_detector_cfg(cfg_path) + base_channels = 32 + model_cfg.backbone.depth = 18 + model_cfg.backbone.init_cfg = None + model_cfg.backbone.base_channels = base_channels + model_cfg.panoptic_head.in_channels = [ + base_channels * 2**i for i in range(4) + ] + model_cfg.panoptic_head.feat_channels = base_channels + model_cfg.panoptic_head.out_channels = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.self_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.ffn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.ffn_cfg.feedforward_channels = base_channels * 8 + model_cfg.panoptic_head.pixel_decoder.\ + positional_encoding.num_feats = base_channels // 2 + model_cfg.panoptic_head.positional_encoding.\ + num_feats = base_channels // 2 + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.self_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder. \ + layer_cfg.cross_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.ffn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.ffn_cfg.feedforward_channels = base_channels * 8 + return model_cfg + + def test_init(self): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + detector.init_weights() + assert detector.backbone + assert detector.panoptic_head + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_loss_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_predict_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_tensor_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, False) + out = detector.forward(**data, mode='tensor') + self.assertIsInstance(out, tuple) + + +class TestMask2Former(unittest.TestCase): + + def setUp(self): + register_all_modules() + + def _create_model_cfg(self, cfg_path): + model_cfg = get_detector_cfg(cfg_path) + base_channels = 32 + model_cfg.backbone.depth = 18 + model_cfg.backbone.init_cfg = None + model_cfg.backbone.base_channels = base_channels + model_cfg.panoptic_head.in_channels = [ + base_channels * 2**i for i in range(4) + ] + model_cfg.panoptic_head.feat_channels = base_channels + model_cfg.panoptic_head.out_channels = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.self_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.ffn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.pixel_decoder.encoder.\ + layer_cfg.ffn_cfg.feedforward_channels = base_channels * 4 + model_cfg.panoptic_head.pixel_decoder.\ + positional_encoding.num_feats = base_channels // 2 + model_cfg.panoptic_head.positional_encoding.\ + num_feats = base_channels // 2 + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.self_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder. \ + layer_cfg.cross_attn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.ffn_cfg.embed_dims = base_channels + model_cfg.panoptic_head.transformer_decoder.\ + layer_cfg.ffn_cfg.feedforward_channels = base_channels * 8 + + return model_cfg + + def test_init(self): + model_cfg = self._create_model_cfg( + 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py') + detector = MODELS.build(model_cfg) + detector.init_weights() + assert detector.backbone + assert detector.panoptic_head + + @parameterized.expand([ + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py') + ]) + def test_forward_loss_mode(self, device, cfg_path): + print(device, cfg_path) + with_semantic = 'panoptic' in cfg_path + model_cfg = self._create_model_cfg(cfg_path) + detector = MODELS.build(model_cfg) + + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=with_semantic) + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py') + ]) + def test_forward_predict_mode(self, device, cfg_path): + with_semantic = 'panoptic' in cfg_path + model_cfg = self._create_model_cfg(cfg_path) + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=with_semantic) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([ + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cpu', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco-panoptic.py'), + ('cuda', 'mask2former/mask2former_r50_8xb2-lsj-50e_coco.py') + ]) + def test_forward_tensor_mode(self, device, cfg_path): + with_semantic = 'panoptic' in cfg_path + model_cfg = self._create_model_cfg(cfg_path) + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=with_semantic) + data = detector.data_preprocessor(packed_inputs, False) + out = detector.forward(**data, mode='tensor') + self.assertIsInstance(out, tuple) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_panoptic_two_stage_segmentor.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_panoptic_two_stage_segmentor.py new file mode 100644 index 0000000000000000000000000000000000000000..9234554f7b31f3c8d567b7396211a3589a2c0918 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_panoptic_two_stage_segmentor.py @@ -0,0 +1,93 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing._utils import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestTwoStagePanopticSegmentor(unittest.TestCase): + + def setUp(self): + register_all_modules() + + def _create_model_cfg(self): + cfg_file = 'panoptic_fpn/panoptic-fpn_r50_fpn_1x_coco.py' + model_cfg = get_detector_cfg(cfg_file) + model_cfg.backbone.depth = 18 + model_cfg.neck.in_channels = [64, 128, 256, 512] + model_cfg.backbone.init_cfg = None + return model_cfg + + def test_init(self): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + assert detector.backbone + assert detector.neck + assert detector.rpn_head + assert detector.roi_head + assert detector.roi_head.mask_head + assert detector.with_semantic_head + assert detector.with_panoptic_fusion_head + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_loss_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_predict_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + packed_inputs = demo_mm_inputs( + 2, + image_shapes=[(3, 128, 127), (3, 91, 92)], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([('cpu', ), ('cuda', )]) + def test_forward_tensor_mode(self, device): + model_cfg = self._create_model_cfg() + detector = MODELS.build(model_cfg) + if device == 'cuda' and not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.to(device) + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], + sem_seg_output_strides=1, + with_mask=True, + with_semantic=True) + data = detector.data_preprocessor(packed_inputs, False) + out = detector.forward(**data, mode='tensor') + self.assertIsInstance(out, tuple) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_rpn.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_rpn.py new file mode 100644 index 0000000000000000000000000000000000000000..60f7492a96b8a0380ec7fe3e31f2e4c72f2d1237 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_rpn.py @@ -0,0 +1,112 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestRPN(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand(['rpn/rpn_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.bbox_head) + + # if rpn.num_classes > 1, force set rpn.num_classes = 1 + model.rpn_head.num_classes = 2 + detector = MODELS.build(model) + self.assertEqual(detector.bbox_head.num_classes, 1) + + @parameterized.expand([('rpn/rpn_r50_fpn_1x_coco.py', ('cpu', 'cuda'))]) + def test_rpn_forward_loss_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, True) + # Test forward train + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([('rpn/rpn_r50_fpn_1x_coco.py', ('cpu', 'cuda'))]) + def test_rpn_forward_predict_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([('rpn/rpn_r50_fpn_1x_coco.py', ('cpu', 'cuda'))]) + def test_rpn_forward_tensor_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + batch_results = detector.forward(**data, mode='tensor') + self.assertIsInstance(batch_results, tuple) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_semi_base.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_semi_base.py new file mode 100644 index 0000000000000000000000000000000000000000..7980fa6c32dfb022c0bb59ce280ee97646b55fff --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_semi_base.py @@ -0,0 +1,34 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +from mmengine.registry import MODELS +from parameterized import parameterized + +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + +register_all_modules() + + +class TestSemiBase(TestCase): + + @parameterized.expand([ + 'soft_teacher/' + 'soft-teacher_faster-rcnn_r50-caffe_fpn_180k_semi-0.1-coco.py', + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.detector.backbone.depth = 18 + model.detector.neck.in_channels = [64, 128, 256, 512] + model.detector.backbone.init_cfg = None + + model = MODELS.build(model) + self.assertTrue(model.teacher.backbone) + self.assertTrue(model.teacher.neck) + self.assertTrue(model.teacher.rpn_head) + self.assertTrue(model.teacher.roi_head) + self.assertTrue(model.student.backbone) + self.assertTrue(model.student.neck) + self.assertTrue(model.student.rpn_head) + self.assertTrue(model.student.roi_head) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_single_stage.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_single_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..22dbd1a98cb96c1b8edf9f1c2c34e131a8c9d4da --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_single_stage.py @@ -0,0 +1,126 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestSingleStageDetector(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand([ + 'retinanet/retinanet_r18_fpn_1x_coco.py', + 'centernet/centernet_r18_8xb16-crop512-140e_coco.py', + 'fsaf/fsaf_r50_fpn_1x_coco.py', + 'yolox/yolox_tiny_8xb8-300e_coco.py', + 'yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', + 'reppoints/reppoints-minmax_r50_fpn-gn_head-gn_1x_coco.py', + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.bbox_head) + + @parameterized.expand([ + ('retinanet/retinanet_r18_fpn_1x_coco.py', ('cpu', 'cuda')), + ('centernet/centernet_r18_8xb16-crop512-140e_coco.py', ('cpu', + 'cuda')), + ('yolox/yolox_tiny_8xb8-300e_coco.py', ('cpu', 'cuda')), + ('yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_single_stage_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + detector.init_weights() + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, True) + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + ('retinanet/retinanet_r18_fpn_1x_coco.py', ('cpu', 'cuda')), + ('centernet/centernet_r18_8xb16-crop512-140e_coco.py', ('cpu', + 'cuda')), + ('yolox/yolox_tiny_8xb8-300e_coco.py', ('cpu', 'cuda')), + ('yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_predict_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([ + ('retinanet/retinanet_r18_fpn_1x_coco.py', ('cpu', 'cuda')), + ('centernet/centernet_r18_8xb16-crop512-140e_coco.py', ('cpu', + 'cuda')), + ('yolox/yolox_tiny_8xb8-300e_coco.py', ('cpu', 'cuda')), + ('yolo/yolov3_mobilenetv2_8xb24-320-300e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_tensor_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + batch_results = detector.forward(**data, mode='tensor') + self.assertIsInstance(batch_results, tuple) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_single_stage_instance_seg.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_single_stage_instance_seg.py new file mode 100644 index 0000000000000000000000000000000000000000..515303412412256802452906aed87e306947a891 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_single_stage_instance_seg.py @@ -0,0 +1,120 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestSingleStageInstanceSegmentor(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand([ + 'solo/solo_r50_fpn_1x_coco.py', + 'solov2/solov2_r50_fpn_1x_coco.py', + 'yolact/yolact_r50_1xb8-55e_coco.py', + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.mask_head) + if detector.with_bbox: + self.assertTrue(detector.bbox_head) + + @parameterized.expand([ + ('solo/solo_r50_fpn_1x_coco.py', ('cpu', 'cuda')), + ('solov2/solov2-light_r18_fpn_ms-3x_coco.py', ('cpu', 'cuda')), + ('yolact/yolact_r50_1xb8-55e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_loss_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + detector.init_weights() + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], with_mask=True) + data = detector.data_preprocessor(packed_inputs, True) + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + ('solo/decoupled-solo-light_r50_fpn_3x_coco.py', ('cpu', 'cuda')), + ('yolact/yolact_r50_1xb8-55e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_predict_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], with_mask=True) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + @parameterized.expand([ + ('solo/solo_r50_fpn_1x_coco.py', ('cpu', 'cuda')), + ('solov2/solov2_r50_fpn_1x_coco.py', ('cpu', 'cuda')), + ('yolact/yolact_r50_1xb8-55e_coco.py', ('cpu', 'cuda')), + ]) + def test_single_stage_forward_tensor_mode(self, cfg_file, devices): + model = get_detector_cfg(cfg_file) + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + detector = MODELS.build(model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + batch_results = detector.forward(**data, mode='tensor') + self.assertIsInstance(batch_results, tuple) diff --git a/mmdet_code/mmdetection/tests/test_models/test_detectors/test_two_stage.py b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_two_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..5609c0821dcff4ae1e9b33a00d24cc61b59ebc36 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_detectors/test_two_stage.py @@ -0,0 +1,236 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.structures import DetDataSample +from mmdet.testing import demo_mm_inputs, get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestTwoStageBBox(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand([ + 'faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py', + 'sparse_rcnn/sparse-rcnn_r50_fpn_1x_coco.py', + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.rpn_head) + self.assertTrue(detector.roi_head) + + # if rpn.num_classes > 1, force set rpn.num_classes = 1 + if hasattr(model.rpn_head, 'num_classes'): + model.rpn_head.num_classes = 2 + detector = MODELS.build(model) + self.assertEqual(detector.rpn_head.num_classes, 1) + + @parameterized.expand([ + 'faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py', + 'sparse_rcnn/sparse-rcnn_r50_fpn_1x_coco.py', + ]) + def test_two_stage_forward_loss_mode(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + 'faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py', + 'sparse_rcnn/sparse-rcnn_r50_fpn_1x_coco.py', + ]) + def test_two_stage_forward_predict_mode(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + # TODO: Awaiting refactoring + # @parameterized.expand([ + # 'faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', + # 'cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py', + # 'sparse_rcnn/sparse-rcnn_r50_fpn_1x_coco.py', + # ]) + # def test_two_stage_forward_tensor_mode(self, cfg_file): + # model = get_detector_cfg(cfg_file) + # # backbone convert to ResNet18 + # model.backbone.depth = 18 + # model.neck.in_channels = [64, 128, 256, 512] + # model.backbone.init_cfg = None + # + # from mmdet.models import build_detector + # detector = build_detector(model) + # + # if not torch.cuda.is_available(): + # return unittest.skip('test requires GPU and torch+cuda') + # detector = detector.cuda() + # + # packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + + # data = detector.data_preprocessor(packed_inputs, False) + + # out = detector.forward(**data, mode='tensor') + # self.assertIsInstance(out, tuple) + + +class TestTwoStageMask(TestCase): + + def setUp(self): + register_all_modules() + + @parameterized.expand([ + 'mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py', + 'queryinst/queryinst_r50_fpn_1x_coco.py' + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + self.assertTrue(detector.backbone) + self.assertTrue(detector.neck) + self.assertTrue(detector.rpn_head) + self.assertTrue(detector.roi_head) + self.assertTrue(detector.roi_head.mask_head) + + # if rpn.num_classes > 1, force set rpn.num_classes = 1 + if hasattr(model.rpn_head, 'num_classes'): + model.rpn_head.num_classes = 2 + detector = MODELS.build(model) + self.assertEqual(detector.rpn_head.num_classes, 1) + + @parameterized.expand([ + 'mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py', + 'queryinst/queryinst_r50_fpn_1x_coco.py' + ]) + def test_two_stage_forward_loss_mode(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs( + 2, [[3, 128, 128], [3, 125, 130]], with_mask=True) + data = detector.data_preprocessor(packed_inputs, True) + # Test loss mode + losses = detector.forward(**data, mode='loss') + self.assertIsInstance(losses, dict) + + @parameterized.expand([ + 'mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py', + 'cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py', + 'queryinst/queryinst_r50_fpn_1x_coco.py' + ]) + def test_two_stage_forward_predict_mode(self, cfg_file): + model = get_detector_cfg(cfg_file) + # backbone convert to ResNet18 + model.backbone.depth = 18 + model.neck.in_channels = [64, 128, 256, 512] + model.backbone.init_cfg = None + + from mmdet.registry import MODELS + detector = MODELS.build(model) + + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + detector = detector.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 256, 256], [3, 255, 260]]) + data = detector.data_preprocessor(packed_inputs, False) + # Test forward test + detector.eval() + with torch.no_grad(): + batch_results = detector.forward(**data, mode='predict') + self.assertEqual(len(batch_results), 2) + self.assertIsInstance(batch_results[0], DetDataSample) + + # TODO: Awaiting refactoring + # @parameterized.expand([ + # 'mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py', + # 'cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py', + # 'queryinst/queryinst_r50_fpn_1x_coco.py' + # ]) + # def test_two_stage_forward_tensor_mode(self, cfg_file): + # model = get_detector_cfg(cfg_file) + # # backbone convert to ResNet18 + # model.backbone.depth = 18 + # model.neck.in_channels = [64, 128, 256, 512] + # model.backbone.init_cfg = None + # + # from mmdet.models import build_detector + # detector = build_detector(model) + # + # if not torch.cuda.is_available(): + # return unittest.skip('test requires GPU and torch+cuda') + # detector = detector.cuda() + # + # packed_inputs = demo_mm_inputs( + # 2, [[3, 128, 128], [3, 125, 130]], with_mask=True) + # data = detector.data_preprocessor(packed_inputs, False) + # + # # out = detector.forward(**data, mode='tensor') + # # self.assertIsInstance(out, tuple) diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/__init__.py b/mmdet_code/mmdetection/tests/test_models/test_layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/test_brick_wrappers.py b/mmdet_code/mmdetection/tests/test_models/test_layers/test_brick_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..3c59fcf79ba1d02ba377ab8ef3f8ef26ecd61ec4 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_layers/test_brick_wrappers.py @@ -0,0 +1,93 @@ +from unittest.mock import patch + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from mmdet.models.layers import AdaptiveAvgPool2d, adaptive_avg_pool2d + +if torch.__version__ != 'parrots': + torch_version = '1.7' +else: + torch_version = 'parrots' + + +@patch('torch.__version__', torch_version) +def test_adaptive_avg_pool2d(): + # Test the empty batch dimension + # Test the two input conditions + x_empty = torch.randn(0, 3, 4, 5) + # 1. tuple[int, int] + wrapper_out = adaptive_avg_pool2d(x_empty, (2, 2)) + assert wrapper_out.shape == (0, 3, 2, 2) + # 2. int + wrapper_out = adaptive_avg_pool2d(x_empty, 2) + assert wrapper_out.shape == (0, 3, 2, 2) + + # wrapper op with 3-dim input + x_normal = torch.randn(3, 3, 4, 5) + wrapper_out = adaptive_avg_pool2d(x_normal, (2, 2)) + ref_out = F.adaptive_avg_pool2d(x_normal, (2, 2)) + assert wrapper_out.shape == (3, 3, 2, 2) + assert torch.equal(wrapper_out, ref_out) + + wrapper_out = adaptive_avg_pool2d(x_normal, 2) + ref_out = F.adaptive_avg_pool2d(x_normal, 2) + assert wrapper_out.shape == (3, 3, 2, 2) + assert torch.equal(wrapper_out, ref_out) + + +@patch('torch.__version__', torch_version) +def test_AdaptiveAvgPool2d(): + # Test the empty batch dimension + x_empty = torch.randn(0, 3, 4, 5) + # Test the four input conditions + # 1. tuple[int, int] + wrapper = AdaptiveAvgPool2d((2, 2)) + wrapper_out = wrapper(x_empty) + assert wrapper_out.shape == (0, 3, 2, 2) + + # 2. int + wrapper = AdaptiveAvgPool2d(2) + wrapper_out = wrapper(x_empty) + assert wrapper_out.shape == (0, 3, 2, 2) + + # 3. tuple[None, int] + wrapper = AdaptiveAvgPool2d((None, 2)) + wrapper_out = wrapper(x_empty) + assert wrapper_out.shape == (0, 3, 4, 2) + + # 3. tuple[int, None] + wrapper = AdaptiveAvgPool2d((2, None)) + wrapper_out = wrapper(x_empty) + assert wrapper_out.shape == (0, 3, 2, 5) + + # Test the normal batch dimension + x_normal = torch.randn(3, 3, 4, 5) + wrapper = AdaptiveAvgPool2d((2, 2)) + ref = nn.AdaptiveAvgPool2d((2, 2)) + wrapper_out = wrapper(x_normal) + ref_out = ref(x_normal) + assert wrapper_out.shape == (3, 3, 2, 2) + assert torch.equal(wrapper_out, ref_out) + + wrapper = AdaptiveAvgPool2d(2) + ref = nn.AdaptiveAvgPool2d(2) + wrapper_out = wrapper(x_normal) + ref_out = ref(x_normal) + assert wrapper_out.shape == (3, 3, 2, 2) + assert torch.equal(wrapper_out, ref_out) + + wrapper = AdaptiveAvgPool2d((None, 2)) + ref = nn.AdaptiveAvgPool2d((None, 2)) + wrapper_out = wrapper(x_normal) + ref_out = ref(x_normal) + assert wrapper_out.shape == (3, 3, 4, 2) + assert torch.equal(wrapper_out, ref_out) + + wrapper = AdaptiveAvgPool2d((2, None)) + ref = nn.AdaptiveAvgPool2d((2, None)) + wrapper_out = wrapper(x_normal) + ref_out = ref(x_normal) + assert wrapper_out.shape == (3, 3, 2, 5) + assert torch.equal(wrapper_out, ref_out) diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/test_conv_upsample.py b/mmdet_code/mmdetection/tests/test_models/test_layers/test_conv_upsample.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc64d032a36731aad2c9870e565085cc46e7020 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_layers/test_conv_upsample.py @@ -0,0 +1,24 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.layers import ConvUpsample + + +@pytest.mark.parametrize('num_layers', [0, 1, 2]) +def test_conv_upsample(num_layers): + num_upsample = num_layers if num_layers > 0 else 0 + num_layers = num_layers if num_layers > 0 else 1 + layer = ConvUpsample( + 10, + 5, + num_layers=num_layers, + num_upsample=num_upsample, + conv_cfg=None, + norm_cfg=None) + + size = 5 + x = torch.randn((1, 10, size, size)) + size = size * pow(2, num_upsample) + x = layer(x) + assert x.shape[-2:] == (size, size) diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/test_ema.py b/mmdet_code/mmdetection/tests/test_models/test_layers/test_ema.py new file mode 100644 index 0000000000000000000000000000000000000000..5acf5460ce0a3f8273628db6a7755c0f73dc7c7f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_layers/test_ema.py @@ -0,0 +1,94 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import itertools +import math +from unittest import TestCase + +import torch +import torch.nn as nn +from mmengine.testing import assert_allclose + +from mmdet.models.layers import ExpMomentumEMA + + +class TestEMA(TestCase): + + def test_exp_momentum_ema(self): + model = nn.Sequential(nn.Conv2d(1, 5, kernel_size=3), nn.Linear(5, 10)) + # Test invalid gamma + with self.assertRaisesRegex(AssertionError, + 'gamma must be greater than 0'): + ExpMomentumEMA(model, gamma=-1) + + # Test EMA + model = torch.nn.Sequential( + torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.Linear(5, 10)) + momentum = 0.1 + gamma = 4 + + ema_model = ExpMomentumEMA(model, momentum=momentum, gamma=gamma) + averaged_params = [ + torch.zeros_like(param) for param in model.parameters() + ] + n_updates = 10 + for i in range(n_updates): + updated_averaged_params = [] + for p, p_avg in zip(model.parameters(), averaged_params): + p.detach().add_(torch.randn_like(p)) + if i == 0: + updated_averaged_params.append(p.clone()) + else: + m = (1 - momentum) * math.exp(-(1 + i) / gamma) + momentum + updated_averaged_params.append( + (p_avg * (1 - m) + p * m).clone()) + ema_model.update_parameters(model) + averaged_params = updated_averaged_params + + for p_target, p_ema in zip(averaged_params, ema_model.parameters()): + assert_allclose(p_target, p_ema) + + def test_exp_momentum_ema_update_buffer(self): + model = nn.Sequential( + nn.Conv2d(1, 5, kernel_size=3), nn.BatchNorm2d(5, momentum=0.3), + nn.Linear(5, 10)) + # Test invalid gamma + with self.assertRaisesRegex(AssertionError, + 'gamma must be greater than 0'): + ExpMomentumEMA(model, gamma=-1) + + # Test EMA with momentum annealing. + momentum = 0.1 + gamma = 4 + + ema_model = ExpMomentumEMA( + model, gamma=gamma, momentum=momentum, update_buffers=True) + averaged_params = [ + torch.zeros_like(param) + for param in itertools.chain(model.parameters(), model.buffers()) + if param.size() != torch.Size([]) + ] + n_updates = 10 + for i in range(n_updates): + updated_averaged_params = [] + params = [ + param for param in itertools.chain(model.parameters(), + model.buffers()) + if param.size() != torch.Size([]) + ] + for p, p_avg in zip(params, averaged_params): + p.detach().add_(torch.randn_like(p)) + if i == 0: + updated_averaged_params.append(p.clone()) + else: + m = (1 - momentum) * math.exp(-(1 + i) / gamma) + momentum + updated_averaged_params.append( + (p_avg * (1 - m) + p * m).clone()) + ema_model.update_parameters(model) + averaged_params = updated_averaged_params + + ema_params = [ + param for param in itertools.chain(ema_model.module.parameters(), + ema_model.module.buffers()) + if param.size() != torch.Size([]) + ] + for p_target, p_ema in zip(averaged_params, ema_params): + assert_allclose(p_target, p_ema) diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/test_inverted_residual.py b/mmdet_code/mmdetection/tests/test_models/test_layers/test_inverted_residual.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e9d6988a37aa5d5fa2333c9d5a6047baa5aa2f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_layers/test_inverted_residual.py @@ -0,0 +1,76 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmcv.cnn import is_norm +from torch.nn.modules import GroupNorm + +from mmdet.models.layers import InvertedResidual, SELayer + + +def test_inverted_residual(): + + with pytest.raises(AssertionError): + # stride must be in [1, 2] + InvertedResidual(16, 16, 32, stride=3) + + with pytest.raises(AssertionError): + # se_cfg must be None or dict + InvertedResidual(16, 16, 32, se_cfg=list()) + + with pytest.raises(AssertionError): + # in_channeld and mid_channels must be the same if + # with_expand_conv is False + InvertedResidual(16, 16, 32, with_expand_conv=False) + + # Test InvertedResidual forward, stride=1 + block = InvertedResidual(16, 16, 32, stride=1) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert getattr(block, 'se', None) is None + assert block.with_res_shortcut + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward, stride=2 + block = InvertedResidual(16, 16, 32, stride=2) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert not block.with_res_shortcut + assert x_out.shape == torch.Size((1, 16, 28, 28)) + + # Test InvertedResidual forward with se layer + se_cfg = dict(channels=32) + block = InvertedResidual(16, 16, 32, stride=1, se_cfg=se_cfg) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert isinstance(block.se, SELayer) + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward, with_expand_conv=False + block = InvertedResidual(32, 16, 32, with_expand_conv=False) + x = torch.randn(1, 32, 56, 56) + x_out = block(x) + assert getattr(block, 'expand_conv', None) is None + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward with GroupNorm + block = InvertedResidual( + 16, 16, 32, norm_cfg=dict(type='GN', num_groups=2)) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + for m in block.modules(): + if is_norm(m): + assert isinstance(m, GroupNorm) + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward with HSigmoid + block = InvertedResidual(16, 16, 32, act_cfg=dict(type='HSigmoid')) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert x_out.shape == torch.Size((1, 16, 56, 56)) + + # Test InvertedResidual forward with checkpoint + block = InvertedResidual(16, 16, 32, with_cp=True) + x = torch.randn(1, 16, 56, 56) + x_out = block(x) + assert block.with_cp + assert x_out.shape == torch.Size((1, 16, 56, 56)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/test_plugins.py b/mmdet_code/mmdetection/tests/test_models/test_layers/test_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..023ebe6d7fe9e566071a4238934da8ffbf30442d --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_layers/test_plugins.py @@ -0,0 +1,171 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import pytest +import torch +from mmengine.config import ConfigDict + +from mmdet.models.layers import DropBlock +from mmdet.registry import MODELS +from mmdet.utils import register_all_modules + +register_all_modules() + + +def test_dropblock(): + feat = torch.rand(1, 1, 11, 11) + drop_prob = 1.0 + dropblock = DropBlock(drop_prob, block_size=11, warmup_iters=0) + out_feat = dropblock(feat) + assert (out_feat == 0).all() and out_feat.shape == feat.shape + drop_prob = 0.5 + dropblock = DropBlock(drop_prob, block_size=5, warmup_iters=0) + out_feat = dropblock(feat) + assert out_feat.shape == feat.shape + + # drop_prob must be (0,1] + with pytest.raises(AssertionError): + DropBlock(1.5, 3) + + # block_size cannot be an even number + with pytest.raises(AssertionError): + DropBlock(0.5, 2) + + # warmup_iters cannot be less than 0 + with pytest.raises(AssertionError): + DropBlock(0.5, 3, -1) + + +class TestPixelDecoder(unittest.TestCase): + + def test_forward(self): + base_channels = 64 + pixel_decoder_cfg = ConfigDict( + dict( + type='PixelDecoder', + in_channels=[base_channels * 2**i for i in range(4)], + feat_channels=base_channels, + out_channels=base_channels, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'))) + self = MODELS.build(pixel_decoder_cfg) + self.init_weights() + img_metas = [{}, {}] + feats = [ + torch.rand( + (2, base_channels * 2**i, 4 * 2**(3 - i), 5 * 2**(3 - i))) + for i in range(4) + ] + mask_feature, memory = self(feats, img_metas) + + assert (memory == feats[-1]).all() + assert mask_feature.shape == feats[0].shape + + +class TestTransformerEncoderPixelDecoder(unittest.TestCase): + + def test_forward(self): + base_channels = 64 + pixel_decoder_cfg = ConfigDict( + dict( + type='TransformerEncoderPixelDecoder', + in_channels=[base_channels * 2**i for i in range(4)], + feat_channels=base_channels, + out_channels=base_channels, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'), + encoder=dict( # DetrTransformerEncoder + num_layers=6, + layer_cfg=dict( # DetrTransformerEncoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=base_channels, + num_heads=8, + attn_drop=0.1, + proj_drop=0.1, + dropout_layer=None, + batch_first=True), + ffn_cfg=dict( + embed_dims=base_channels, + feedforward_channels=base_channels * 8, + num_fcs=2, + act_cfg=dict(type='ReLU', inplace=True), + ffn_drop=0.1, + dropout_layer=None, + add_identity=True), + norm_cfg=dict(type='LN'), + init_cfg=None), + init_cfg=None), + positional_encoding=dict( + num_feats=base_channels // 2, normalize=True))) + self = MODELS.build(pixel_decoder_cfg) + self.init_weights() + img_metas = [{ + 'batch_input_shape': (128, 160), + 'img_shape': (120, 160), + }, { + 'batch_input_shape': (128, 160), + 'img_shape': (125, 160), + }] + feats = [ + torch.rand( + (2, base_channels * 2**i, 4 * 2**(3 - i), 5 * 2**(3 - i))) + for i in range(4) + ] + mask_feature, memory = self(feats, img_metas) + + assert memory.shape[-2:] == feats[-1].shape[-2:] + assert mask_feature.shape == feats[0].shape + + +class TestMSDeformAttnPixelDecoder(unittest.TestCase): + + def test_forward(self): + base_channels = 64 + pixel_decoder_cfg = ConfigDict( + dict( + type='MSDeformAttnPixelDecoder', + in_channels=[base_channels * 2**i for i in range(4)], + strides=[4, 8, 16, 32], + feat_channels=base_channels, + out_channels=base_channels, + num_outs=3, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'), + encoder=dict( # DeformableDetrTransformerEncoder + num_layers=6, + layer_cfg=dict( # DeformableDetrTransformerEncoderLayer + self_attn_cfg=dict( # MultiScaleDeformableAttention + embed_dims=base_channels, + num_heads=8, + num_levels=3, + num_points=4, + im2col_step=64, + dropout=0.0, + batch_first=True, + norm_cfg=None, + init_cfg=None), + ffn_cfg=dict( + embed_dims=base_channels, + feedforward_channels=base_channels * 4, + num_fcs=2, + ffn_drop=0.0, + act_cfg=dict(type='ReLU', inplace=True))), + init_cfg=None), + positional_encoding=dict( + num_feats=base_channels // 2, normalize=True), + init_cfg=None)) + self = MODELS.build(pixel_decoder_cfg) + self.init_weights() + feats = [ + torch.rand( + (2, base_channels * 2**i, 4 * 2**(3 - i), 5 * 2**(3 - i))) + for i in range(4) + ] + mask_feature, multi_scale_features = self(feats) + + assert mask_feature.shape == feats[0].shape + assert len(multi_scale_features) == 3 + multi_scale_features = multi_scale_features[::-1] + for i in range(3): + assert multi_scale_features[i].shape[-2:] == feats[i + + 1].shape[-2:] diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/test_position_encoding.py b/mmdet_code/mmdetection/tests/test_models/test_layers/test_position_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..0d47287da7f0e1a5feddfcb7d0fbfbc2b9200136 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_layers/test_position_encoding.py @@ -0,0 +1,39 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.layers import (LearnedPositionalEncoding, + SinePositionalEncoding) + + +def test_sine_positional_encoding(num_feats=16, batch_size=2): + # test invalid type of scale + with pytest.raises(AssertionError): + module = SinePositionalEncoding( + num_feats, scale=(3., ), normalize=True) + + module = SinePositionalEncoding(num_feats) + h, w = 10, 6 + mask = (torch.rand(batch_size, h, w) > 0.5).to(torch.int) + assert not module.normalize + out = module(mask) + assert out.shape == (batch_size, num_feats * 2, h, w) + + # set normalize + module = SinePositionalEncoding(num_feats, normalize=True) + assert module.normalize + out = module(mask) + assert out.shape == (batch_size, num_feats * 2, h, w) + + +def test_learned_positional_encoding(num_feats=16, + row_num_embed=10, + col_num_embed=10, + batch_size=2): + module = LearnedPositionalEncoding(num_feats, row_num_embed, col_num_embed) + assert module.row_embed.weight.shape == (row_num_embed, num_feats) + assert module.col_embed.weight.shape == (col_num_embed, num_feats) + h, w = 10, 6 + mask = torch.rand(batch_size, h, w) > 0.5 + out = module(mask) + assert out.shape == (batch_size, num_feats * 2, h, w) diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/test_se_layer.py b/mmdet_code/mmdetection/tests/test_models/test_layers/test_se_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..2a19d4c3ae933868e58d776d0137eb0cc9016fc1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_layers/test_se_layer.py @@ -0,0 +1,54 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +import torch.nn.functional as F +from mmengine.model import constant_init + +from mmdet.models.layers import DyReLU, SELayer + + +def test_se_layer(): + with pytest.raises(AssertionError): + # act_cfg sequence length must equal to 2 + SELayer(channels=32, act_cfg=(dict(type='ReLU'), )) + + with pytest.raises(AssertionError): + # act_cfg sequence must be a tuple of dict + SELayer(channels=32, act_cfg=[dict(type='ReLU'), dict(type='ReLU')]) + + # Test SELayer forward + layer = SELayer(channels=32) + layer.init_weights() + layer.train() + + x = torch.randn((1, 32, 10, 10)) + x_out = layer(x) + assert x_out.shape == torch.Size((1, 32, 10, 10)) + + +def test_dyrelu(): + with pytest.raises(AssertionError): + # act_cfg sequence length must equal to 2 + DyReLU(channels=32, act_cfg=(dict(type='ReLU'), )) + + with pytest.raises(AssertionError): + # act_cfg sequence must be a tuple of dict + DyReLU(channels=32, act_cfg=[dict(type='ReLU'), dict(type='ReLU')]) + + # Test DyReLU forward + layer = DyReLU(channels=32) + layer.init_weights() + layer.train() + x = torch.randn((1, 32, 10, 10)) + x_out = layer(x) + assert x_out.shape == torch.Size((1, 32, 10, 10)) + + # DyReLU should act as standard (static) ReLU + # when eliminating the effect of SE-like module + layer = DyReLU(channels=32) + constant_init(layer.conv2.conv, 0) + layer.train() + x = torch.randn((1, 32, 10, 10)) + x_out = layer(x) + relu_out = F.relu(x) + assert torch.equal(x_out, relu_out) diff --git a/mmdet_code/mmdetection/tests/test_models/test_layers/test_transformer.py b/mmdet_code/mmdetection/tests/test_models/test_layers/test_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..3d95b8ae84b4eddd68ee1ab47e44a92bdf2cd4a3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_layers/test_transformer.py @@ -0,0 +1,524 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from mmengine.config import ConfigDict + +from mmdet.models.layers.transformer import (AdaptivePadding, + DDQTransformerDecoder, + DetrTransformerDecoder, + DetrTransformerEncoder, + PatchEmbed, PatchMerging) + + +def test_adaptive_padding(): + + for padding in ('same', 'corner'): + kernel_size = 16 + stride = 16 + dilation = 1 + input = torch.rand(1, 1, 15, 17) + pool = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + out = pool(input) + # padding to divisible by 16 + assert (out.shape[2], out.shape[3]) == (16, 32) + input = torch.rand(1, 1, 16, 17) + out = pool(input) + # padding to divisible by 16 + assert (out.shape[2], out.shape[3]) == (16, 32) + + kernel_size = (2, 2) + stride = (2, 2) + dilation = (1, 1) + + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 11, 13) + out = adap_pad(input) + # padding to divisible by 2 + assert (out.shape[2], out.shape[3]) == (12, 14) + + kernel_size = (2, 2) + stride = (10, 10) + dilation = (1, 1) + + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 10, 13) + out = adap_pad(input) + # no padding + assert (out.shape[2], out.shape[3]) == (10, 13) + + kernel_size = (11, 11) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + input = torch.rand(1, 1, 11, 13) + out = adap_pad(input) + # all padding + assert (out.shape[2], out.shape[3]) == (21, 21) + + # test padding as kernel is (7,9) + input = torch.rand(1, 1, 11, 13) + stride = (3, 4) + kernel_size = (4, 5) + dilation = (2, 2) + # actually (7, 9) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + dilation_out = adap_pad(input) + assert (dilation_out.shape[2], dilation_out.shape[3]) == (16, 21) + kernel_size = (7, 9) + dilation = (1, 1) + adap_pad = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + kernel79_out = adap_pad(input) + assert (kernel79_out.shape[2], kernel79_out.shape[3]) == (16, 21) + assert kernel79_out.shape == dilation_out.shape + + # assert only support "same" "corner" + with pytest.raises(AssertionError): + AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=1) + + +def test_patch_embed(): + B = 2 + H = 3 + W = 4 + C = 3 + embed_dims = 10 + kernel_size = 3 + stride = 1 + dummy_input = torch.rand(B, C, H, W) + patch_merge_1 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=1, + norm_cfg=None) + + x1, shape = patch_merge_1(dummy_input) + # test out shape + assert x1.shape == (2, 2, 10) + # test outsize is correct + assert shape == (1, 2) + # test L = out_h * out_w + assert shape[0] * shape[1] == x1.shape[1] + + B = 2 + H = 10 + W = 10 + C = 3 + embed_dims = 10 + kernel_size = 5 + stride = 2 + dummy_input = torch.rand(B, C, H, W) + # test dilation + patch_merge_2 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=None, + ) + + x2, shape = patch_merge_2(dummy_input) + # test out shape + assert x2.shape == (2, 1, 10) + # test outsize is correct + assert shape == (1, 1) + # test L = out_h * out_w + assert shape[0] * shape[1] == x2.shape[1] + + stride = 2 + input_size = (10, 10) + + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + x3, shape = patch_merge_3(dummy_input) + # test out shape + assert x3.shape == (2, 1, 10) + # test outsize is correct + assert shape == (1, 1) + # test L = out_h * out_w + assert shape[0] * shape[1] == x3.shape[1] + + # test the init_out_size with nn.Unfold + assert patch_merge_3.init_out_size[1] == (input_size[0] - 2 * 4 - + 1) // 2 + 1 + assert patch_merge_3.init_out_size[0] == (input_size[0] - 2 * 4 - + 1) // 2 + 1 + H = 11 + W = 12 + input_size = (H, W) + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + _, shape = patch_merge_3(dummy_input) + # when input_size equal to real input + # the out_size should be equal to `init_out_size` + assert shape == patch_merge_3.init_out_size + + input_size = (H, W) + dummy_input = torch.rand(B, C, H, W) + # test stride and norm + patch_merge_3 = PatchEmbed( + in_channels=C, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=0, + dilation=2, + norm_cfg=dict(type='LN'), + input_size=input_size) + + _, shape = patch_merge_3(dummy_input) + # when input_size equal to real input + # the out_size should be equal to `init_out_size` + assert shape == patch_merge_3.init_out_size + + # test adap padding + for padding in ('same', 'corner'): + in_c = 2 + embed_dims = 3 + B = 2 + + # test stride is 1 + input_size = (5, 5) + kernel_size = (5, 5) + stride = (1, 1) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 25, 3) + assert out_size == (5, 5) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (5, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 1, 3) + assert out_size == (1, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (6, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 2, 3) + assert out_size == (2, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test different kernel_size with different stride + input_size = (6, 5) + kernel_size = (6, 2) + stride = (6, 2) + dilation = 1 + bias = False + + x = torch.rand(B, in_c, *input_size) + patch_embed = PatchEmbed( + in_channels=in_c, + embed_dims=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_embed(x) + assert x_out.size() == (B, 3, 3) + assert out_size == (1, 3) + assert x_out.size(1) == out_size[0] * out_size[1] + + +def test_patch_merging(): + + # Test the model with int padding + in_c = 3 + out_c = 4 + kernel_size = 3 + stride = 3 + padding = 1 + dilation = 1 + bias = False + # test the case `pad_to_stride` is False + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + B, L, C = 1, 100, 3 + input_size = (10, 10) + x = torch.rand(B, L, C) + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (1, 16, 4) + assert out_size == (4, 4) + # assert out size is consistent with real output + assert x_out.size(1) == out_size[0] * out_size[1] + in_c = 4 + out_c = 5 + kernel_size = 6 + stride = 3 + padding = 2 + dilation = 2 + bias = False + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + B, L, C = 1, 100, 4 + input_size = (10, 10) + x = torch.rand(B, L, C) + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (1, 4, 5) + assert out_size == (2, 2) + # assert out size is consistent with real output + assert x_out.size(1) == out_size[0] * out_size[1] + + # Test with adaptive padding + for padding in ('same', 'corner'): + in_c = 2 + out_c = 3 + B = 2 + + # test stride is 1 + input_size = (5, 5) + kernel_size = (5, 5) + stride = (1, 1) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 25, 3) + assert out_size == (5, 5) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (5, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 1, 3) + assert out_size == (1, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test kernel_size == stride + input_size = (6, 5) + kernel_size = (5, 5) + stride = (5, 5) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 2, 3) + assert out_size == (2, 1) + assert x_out.size(1) == out_size[0] * out_size[1] + + # test different kernel_size with different stride + input_size = (6, 5) + kernel_size = (6, 2) + stride = (6, 2) + dilation = 1 + bias = False + L = input_size[0] * input_size[1] + + x = torch.rand(B, L, in_c) + patch_merge = PatchMerging( + in_channels=in_c, + out_channels=out_c, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + x_out, out_size = patch_merge(x, input_size) + assert x_out.size() == (B, 3, 3) + assert out_size == (1, 3) + assert x_out.size(1) == out_size[0] * out_size[1] + + +def test_detr_transformer_encoder_decoder(): + config = ConfigDict( + num_layers=6, + layer_cfg=dict( # DetrTransformerDecoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.1), + cross_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.1), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + ffn_drop=0.1, + act_cfg=dict(type='ReLU', inplace=True)))) + assert len(DetrTransformerDecoder(**config).layers) == 6 + assert DetrTransformerDecoder(**config) + + config = ConfigDict( + dict( + num_layers=6, + layer_cfg=dict( # DetrTransformerEncoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.1), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + ffn_drop=0.1, + act_cfg=dict(type='ReLU', inplace=True))))) + assert len(DetrTransformerEncoder(**config).layers) == 6 + assert DetrTransformerEncoder(**config) + + +def test_ddq_transformer_decoder(): + num_layers = 2 + config = ConfigDict( + num_layers=num_layers, + return_intermediate=True, + layer_cfg=dict( + self_attn_cfg=dict(embed_dims=256, num_heads=8, + dropout=0.0), # 0.1 for DeformDETR + cross_attn_cfg=dict(embed_dims=256, num_levels=4, + dropout=0.0), # 0.1 for DeformDETR + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, # 1024 for DeformDETR + ffn_drop=0.0)), # 0.1 for DeformDETR + post_norm_cfg=None) + assert len(DDQTransformerDecoder(**config).layers) == num_layers + assert DDQTransformerDecoder(**config) diff --git a/mmdet_code/mmdetection/tests/test_models/test_losses/test_gaussian_focal_loss.py b/mmdet_code/mmdetection/tests/test_models/test_losses/test_gaussian_focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..5f26d6479076ec50f5514a4f4f256044131b91b2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_losses/test_gaussian_focal_loss.py @@ -0,0 +1,38 @@ +import unittest + +import torch + +from mmdet.models.losses import GaussianFocalLoss + + +class TestGaussianFocalLoss(unittest.TestCase): + + def test_forward(self): + pred = torch.rand((10, 4)) + target = torch.rand((10, 4)) + gaussian_focal_loss = GaussianFocalLoss() + loss1 = gaussian_focal_loss(pred, target) + self.assertIsInstance(loss1, torch.Tensor) + + loss2 = gaussian_focal_loss(pred, target, avg_factor=0.5) + self.assertIsInstance(loss2, torch.Tensor) + + # test reduction + gaussian_focal_loss = GaussianFocalLoss(reduction='none') + loss = gaussian_focal_loss(pred, target) + self.assertTrue(loss.shape == (10, 4)) + + # test reduction_override + loss = gaussian_focal_loss(pred, target, reduction_override='mean') + self.assertTrue(loss.ndim == 0) + + # Only supports None, 'none', 'mean', 'sum' + with self.assertRaises(AssertionError): + gaussian_focal_loss(pred, target, reduction_override='max') + + # test pos_inds + pos_inds = (torch.rand(5) * 8).long() + pos_labels = (torch.rand(5) * 2).long() + gaussian_focal_loss = GaussianFocalLoss() + loss = gaussian_focal_loss(pred, target, pos_inds, pos_labels) + self.assertIsInstance(loss, torch.Tensor) diff --git a/mmdet_code/mmdetection/tests/test_models/test_losses/test_l2_loss.py b/mmdet_code/mmdetection/tests/test_models/test_losses/test_l2_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..2aa3e536c7b2477177b70045181f6f27635d96f8 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_losses/test_l2_loss.py @@ -0,0 +1,21 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models import L2Loss + + +class TestL2Loss(TestCase): + + def test_l2_loss(self): + pred = torch.Tensor([[1, 1, 0, 0, 0, 0, 1]]) + target = torch.Tensor([[1, 1, 0, 0, 0, 0, 0]]) + + loss = L2Loss( + neg_pos_ub=2, + pos_margin=0, + neg_margin=0.1, + hard_mining=True, + loss_weight=1.0) + assert torch.allclose(loss(pred, target), torch.tensor(0.1350)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_losses/test_loss.py b/mmdet_code/mmdetection/tests/test_models/test_losses/test_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a634e2c6b4410cd272d93dac327b44c275f22ebe --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_losses/test_loss.py @@ -0,0 +1,346 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import json + +import pytest +import torch +import torch.nn.functional as F +from mmengine.utils import digit_version + +from mmdet.models.losses import (BalancedL1Loss, CrossEntropyLoss, DDQAuxLoss, + DiceLoss, DistributionFocalLoss, EQLV2Loss, + FocalLoss, GaussianFocalLoss, + KnowledgeDistillationKLDivLoss, L1Loss, + MarginL2Loss, MSELoss, QualityFocalLoss, + SeesawLoss, SmoothL1Loss, VarifocalLoss) +from mmdet.models.losses.ghm_loss import GHMC, GHMR +from mmdet.models.losses.iou_loss import (BoundedIoULoss, CIoULoss, DIoULoss, + EIoULoss, GIoULoss, IoULoss, + SIoULoss) + + +@pytest.mark.parametrize('loss_class', [ + IoULoss, BoundedIoULoss, GIoULoss, DIoULoss, CIoULoss, EIoULoss, SIoULoss +]) +def test_iou_type_loss_zeros_weight(loss_class): + pred = torch.rand((10, 4)) + target = torch.rand((10, 4)) + weight = torch.zeros(10) + + loss = loss_class()(pred, target, weight) + assert loss == 0. + + +@pytest.mark.parametrize('loss_class', [ + BalancedL1Loss, BoundedIoULoss, CIoULoss, CrossEntropyLoss, DIoULoss, + EIoULoss, SIoULoss, FocalLoss, DistributionFocalLoss, MSELoss, SeesawLoss, + GaussianFocalLoss, GIoULoss, QualityFocalLoss, IoULoss, L1Loss, + VarifocalLoss, GHMR, GHMC, SmoothL1Loss, KnowledgeDistillationKLDivLoss, + DiceLoss +]) +def test_loss_with_reduction_override(loss_class): + pred = torch.rand((10, 4)) + target = torch.rand((10, 4)), + weight = None + + with pytest.raises(AssertionError): + # only reduction_override from [None, 'none', 'mean', 'sum'] + # is not allowed + reduction_override = True + loss_class()( + pred, target, weight, reduction_override=reduction_override) + + +@pytest.mark.parametrize('loss_class', [QualityFocalLoss]) +@pytest.mark.parametrize('activated', [False, True]) +def test_QualityFocalLoss_Loss(loss_class, activated): + input_shape = (4, 5) + pred = torch.rand(input_shape) + label = torch.Tensor([0, 1, 2, 0]).long() + quality_label = torch.rand(input_shape[0]) + + original_loss = loss_class(activated=activated)(pred, + (label, quality_label)) + assert isinstance(original_loss, torch.Tensor) + + target = torch.nn.functional.one_hot(label, 5) + target = target * quality_label.reshape(input_shape[0], 1) + + new_loss = loss_class(activated=activated)(pred, target) + assert isinstance(new_loss, torch.Tensor) + assert new_loss == original_loss + + +@pytest.mark.parametrize('loss_class', [ + IoULoss, BoundedIoULoss, GIoULoss, DIoULoss, CIoULoss, EIoULoss, SIoULoss, + MSELoss, L1Loss, SmoothL1Loss, BalancedL1Loss, MarginL2Loss +]) +@pytest.mark.parametrize('input_shape', [(10, 4), (0, 4)]) +def test_regression_losses(loss_class, input_shape): + pred = torch.rand(input_shape) + target = torch.rand(input_shape) + weight = torch.rand(input_shape) + + # Test loss forward + loss = loss_class()(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with weight + loss = loss_class()(pred, target, weight) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class()(pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class()(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('loss_class', [CrossEntropyLoss]) +@pytest.mark.parametrize('input_shape', [(10, 5), (0, 5)]) +def test_classification_losses(loss_class, input_shape): + if input_shape[0] == 0 and digit_version( + torch.__version__) < digit_version('1.5.0'): + pytest.skip( + f'CELoss in PyTorch {torch.__version__} does not support empty' + f'tensor.') + + pred = torch.rand(input_shape) + target = torch.randint(0, 5, (input_shape[0], )) + + # Test loss forward + loss = loss_class()(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class()(pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class()(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('loss_class', [FocalLoss]) +@pytest.mark.parametrize('input_shape', [(10, 5), (3, 5, 40, 40)]) +def test_FocalLoss_loss(loss_class, input_shape): + pred = torch.rand(input_shape) + target = torch.randint(0, 5, (input_shape[0], )) + if len(input_shape) == 4: + B, N, W, H = input_shape + target = F.one_hot(torch.randint(0, 5, (B * W * H, )), + 5).reshape(B, W, H, N).permute(0, 3, 1, 2) + + # Test loss forward + loss = loss_class()(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class()(pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class()(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class()( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('loss_class', [GHMR]) +@pytest.mark.parametrize('input_shape', [(10, 4), (0, 4)]) +def test_GHMR_loss(loss_class, input_shape): + pred = torch.rand(input_shape) + target = torch.rand(input_shape) + weight = torch.rand(input_shape) + + # Test loss forward + loss = loss_class()(pred, target, weight) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('use_sigmoid', [True, False]) +@pytest.mark.parametrize('reduction', ['sum', 'mean', None]) +@pytest.mark.parametrize('avg_non_ignore', [True, False]) +def test_loss_with_ignore_index(use_sigmoid, reduction, avg_non_ignore): + # Test cross_entropy loss + loss_class = CrossEntropyLoss( + use_sigmoid=use_sigmoid, + use_mask=False, + ignore_index=255, + avg_non_ignore=avg_non_ignore) + pred = torch.rand((10, 5)) + target = torch.randint(0, 5, (10, )) + + ignored_indices = torch.randint(0, 10, (2, ), dtype=torch.long) + target[ignored_indices] = 255 + + # Test loss forward with default ignore + loss_with_ignore = loss_class(pred, target, reduction_override=reduction) + assert isinstance(loss_with_ignore, torch.Tensor) + + # Test loss forward with forward ignore + target[ignored_indices] = 255 + loss_with_forward_ignore = loss_class( + pred, target, ignore_index=255, reduction_override=reduction) + assert isinstance(loss_with_forward_ignore, torch.Tensor) + + # Verify correctness + if avg_non_ignore: + # manually remove the ignored elements + not_ignored_indices = (target != 255) + pred = pred[not_ignored_indices] + target = target[not_ignored_indices] + loss = loss_class(pred, target, reduction_override=reduction) + + assert torch.allclose(loss, loss_with_ignore) + assert torch.allclose(loss, loss_with_forward_ignore) + + # test ignore all target + pred = torch.rand((10, 5)) + target = torch.ones((10, ), dtype=torch.long) * 255 + loss = loss_class(pred, target, reduction_override=reduction) + assert loss == 0 + + +@pytest.mark.parametrize('naive_dice', [True, False]) +def test_dice_loss(naive_dice): + loss_class = DiceLoss + pred = torch.rand((10, 4, 4)) + target = torch.rand((10, 4, 4)) + weight = torch.rand((10)) + + # Test loss forward + loss = loss_class(naive_dice=naive_dice)(pred, target) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with weight + loss = loss_class(naive_dice=naive_dice)(pred, target, weight) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with reduction_override + loss = loss_class(naive_dice=naive_dice)( + pred, target, reduction_override='mean') + assert isinstance(loss, torch.Tensor) + + # Test loss forward with avg_factor + loss = loss_class(naive_dice=naive_dice)(pred, target, avg_factor=10) + assert isinstance(loss, torch.Tensor) + + with pytest.raises(ValueError): + # loss can evaluate with avg_factor only if + # reduction is None, 'none' or 'mean'. + reduction_override = 'sum' + loss_class(naive_dice=naive_dice)( + pred, target, avg_factor=10, reduction_override=reduction_override) + + # Test loss forward with avg_factor and reduction + for reduction_override in [None, 'none', 'mean']: + loss_class(naive_dice=naive_dice)( + pred, target, avg_factor=10, reduction_override=reduction_override) + assert isinstance(loss, torch.Tensor) + + # Test loss forward with has_acted=False and use_sigmoid=False + with pytest.raises(NotImplementedError): + loss_class( + use_sigmoid=False, activate=True, naive_dice=naive_dice)(pred, + target) + + # Test loss forward with weight.ndim != loss.ndim + with pytest.raises(AssertionError): + weight = torch.rand((2, 8)) + loss_class(naive_dice=naive_dice)(pred, target, weight) + + # Test loss forward with len(weight) != len(pred) + with pytest.raises(AssertionError): + weight = torch.rand((8)) + loss_class(naive_dice=naive_dice)(pred, target, weight) + + +@pytest.mark.parametrize('loss_class', [EQLV2Loss]) +@pytest.mark.parametrize('reduction', ['mean']) +def test_eqlv2_loss(loss_class, reduction): + cls_score = torch.randn((1204, 1204)) + label = torch.randint(0, 2, (1204, )) + weight = None + + loss = loss_class()(cls_score, label, weight) + assert isinstance(loss, torch.Tensor) + + +@pytest.mark.parametrize('loss_class', [DDQAuxLoss]) +def test_ddq_aux_loss(loss_class): + data_sample_file_path = 'tests/data/coco_batched_sample.json' + num_classes = 80 + num_pred = 1350 + + with open(data_sample_file_path, 'r') as file_stream: + data_sample_infos = json.load(file_stream) + + gt_bboxes = [] + img_metas = [] + gt_labels = [] + + for data_sample_info in data_sample_infos: + metainfo = data_sample_info['metainfo'] + labels = torch.LongTensor(data_sample_info['labels']) + bboxes = torch.Tensor(data_sample_info['bboxes']) + + img_metas.append(metainfo) + gt_labels.append(labels) + gt_bboxes.append(bboxes) + + batch_size = len(data_sample_infos) + pred_classes = torch.rand([batch_size, num_pred, num_classes]) + pred_bboxes = torch.rand([batch_size, num_pred, 4]) + + aux_loss_for_dense = loss_class( + train_cfg=dict(assigner=dict(type='TopkHungarianAssigner', topk=4))) + + aux_loss = aux_loss_for_dense.loss(pred_classes, pred_bboxes, gt_bboxes, + gt_labels, img_metas) + + assert isinstance(aux_loss, dict) + + for loss_name, batch_losses in aux_loss.items(): + assert isinstance(batch_losses, list) + + for loss in batch_losses: + assert isinstance(loss, torch.Tensor) diff --git a/mmdet_code/mmdetection/tests/test_models/test_losses/test_multi_pos_cross_entropy_loss.py b/mmdet_code/mmdetection/tests/test_models/test_losses/test_multi_pos_cross_entropy_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f17c67ee6521d9d1260dfda24b5e4dd93f3c75 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_losses/test_multi_pos_cross_entropy_loss.py @@ -0,0 +1,20 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models.losses import MultiPosCrossEntropyLoss + + +class TestMultiPosCrossEntropyLoss(TestCase): + + def test_mpce_loss(self): + costs = torch.tensor([[1, 0], [0, 1]]) + labels = torch.tensor([[1, 1], [0, 0]]) + + loss = MultiPosCrossEntropyLoss(reduction='mean', loss_weight=1.0) + assert torch.allclose(loss(costs, labels), torch.tensor(0.)) + + labels = torch.Tensor([[1, 0], [0, 1]]) + loss(costs, labels) + assert torch.allclose(loss(costs, labels), torch.tensor(0.31326)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_losses/test_triplet_loss.py b/mmdet_code/mmdetection/tests/test_models/test_losses/test_triplet_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..034419ab38f9eda0890d1abcc222e433fcb0db19 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_losses/test_triplet_loss.py @@ -0,0 +1,19 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models import TripletLoss + + +class TestTripletLoss(TestCase): + + def test_triplet_loss(self): + feature = torch.Tensor([[1, 1], [1, 1], [0, 0], [0, 0]]) + label = torch.Tensor([1, 1, 0, 0]) + + loss = TripletLoss(margin=0.3, loss_weight=1.0) + assert torch.allclose(loss(feature, label), torch.tensor(0.)) + + label = torch.Tensor([1, 0, 1, 0]) + assert torch.allclose(loss(feature, label), torch.tensor(1.7142)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_mot/test_byte_track.py b/mmdet_code/mmdetection/tests/test_models/test_mot/test_byte_track.py new file mode 100644 index 0000000000000000000000000000000000000000..a48548c7510adf3d8c1e36090f28b8dfbd461b7b --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_mot/test_byte_track.py @@ -0,0 +1,100 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_track_inputs, get_detector_cfg + + +class TestByteTrack(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain' + '_test-mot17halfval.py', + ]) + def test_bytetrack_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.detector.neck.out_channels = 1 + model.detector.neck.num_csp_blocks = 1 + model.detector.bbox_head.in_channels = 1 + model.detector.bbox_head.feat_channels = 1 + model = MODELS.build(model) + assert model.detector + + @parameterized.expand([ + ('bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_bytetrack_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.num_classes = 10 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = model.data_preprocessor(packed_inputs, True) + losses = model.forward(**data, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ('bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_bytetrack_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/mmdetection/tests/test_models/test_mot/test_deep_sort.py b/mmdet_code/mmdetection/tests/test_models/test_mot/test_deep_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..72dfeb43510a54ac337a0fcb840a36682b23c593 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_mot/test_deep_sort.py @@ -0,0 +1,64 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestDeepSORT(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'deepsort/deepsort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model = MODELS.build(model) + assert model.detector + assert model.reid + assert model.tracker + + @parameterized.expand([ + ('deepsort/deepsort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_deepsort_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_deepsort_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/mmdetection/tests/test_models/test_mot/test_oc_sort.py b/mmdet_code/mmdetection/tests/test_models/test_mot/test_oc_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf29513e00cb5756199b20d98c46fc3ab9bc89f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_mot/test_oc_sort.py @@ -0,0 +1,100 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_track_inputs, get_detector_cfg + + +class TestByteTrack(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'ocsort/ocsort_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain' + '_test-mot17halfval.py', + ]) + def test_bytetrack_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.detector.neck.out_channels = 1 + model.detector.neck.num_csp_blocks = 1 + model.detector.bbox_head.in_channels = 1 + model.detector.bbox_head.feat_channels = 1 + model = MODELS.build(model) + assert model.detector + + @parameterized.expand([ + ('ocsort/ocsort_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_bytetrack_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.num_classes = 10 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_mm_inputs(2, [[3, 128, 128], [3, 125, 130]]) + data = model.data_preprocessor(packed_inputs, True) + losses = model.forward(**data, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ('ocsort/ocsort_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_bytetrack_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/mmdetection/tests/test_models/test_mot/test_qdtrack.py b/mmdet_code/mmdetection/tests/test_models/test_mot/test_qdtrack.py new file mode 100644 index 0000000000000000000000000000000000000000..714e022fdec71ecda49b662fcb0626ff1092eaff --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_mot/test_qdtrack.py @@ -0,0 +1,94 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestQDTrack(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17halftrain_' + 'test-mot17halfval.py', + ]) + def test_qdtrack_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + + model = MODELS.build(model) + assert model.detector + assert model.track_head + + @parameterized.expand([ + ('qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17' + 'halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_qdtrack_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_qdtrack_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=(3, 128, 128), + num_items=None) + out_data = model.data_preprocessor(packed_inputs, True) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + # Test forward + losses = model.forward(inputs, data_samples, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ('qdtrack/qdtrack_faster-rcnn_r50_fpn_8xb2-4e_mot17' + 'halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_qdtrack_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_bytetrack_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, num_frames=1, image_shapes=(3, 128, 128)) + out_data = model.data_preprocessor(packed_inputs, False) + + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/mmdetection/tests/test_models/test_mot/test_sort.py b/mmdet_code/mmdetection/tests/test_models/test_mot/test_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..ec15a6bdde25c0b756c86df0ec36cada9762f58a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_mot/test_sort.py @@ -0,0 +1,63 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestDeepSORT(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'sort/sort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model = MODELS.build(model) + assert model.detector + assert model.tracker + + @parameterized.expand([ + ('sort/sort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_deepsort_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_deepsort_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/mmdetection/tests/test_models/test_mot/test_strong_sort.py b/mmdet_code/mmdetection/tests/test_models/test_mot/test_strong_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d48a1dbf2f8040937b6efbf155ca7aae8d0ac9 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_mot/test_strong_sort.py @@ -0,0 +1,83 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestDeepSORT(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'strongsort/strongsort_yolox_x_8xb4-80e_crowdhuman' + '-mot17halftrain_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + model.detector.neck.out_channels = 1 + model.detector.neck.num_csp_blocks = 1 + model.detector.bbox_head.in_channels = 1 + model.detector.bbox_head.feat_channels = 1 + model.reid.backbone.depth = 18 + model.reid.head.fc_channels = 1 + model.reid.head.out_channels = 1 + model.reid.head.num_classes = 2 + model.cmc = None + model = MODELS.build(model) + assert model.detector + assert model.reid + assert model.tracker + + @parameterized.expand([ + ('strongsort/strongsort_yolox_x_8xb4-80e_crowdhuman' + '-mot17halftrain_test-mot17halfval.py', ('cpu', 'cuda')), + ]) + def test_strongsort_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_strongsort_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + _model.detector.neck.out_channels = 1 + _model.detector.neck.num_csp_blocks = 1 + _model.detector.bbox_head.in_channels = 1 + _model.detector.bbox_head.feat_channels = 1 + _model.reid.backbone.depth = 18 + _model.reid.head.in_channels = 512 + _model.reid.head.fc_channels = 1 + _model.reid.head.out_channels = 1 + _model.reid.head.num_classes = 2 + _model.cmc = None + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + image_shapes=[(3, 256, 256)], + num_classes=1) + out_data = model.data_preprocessor(packed_inputs, False) + + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/mmdetection/tests/test_models/test_necks/test_ct_resnet_neck.py b/mmdet_code/mmdetection/tests/test_models/test_necks/test_ct_resnet_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..acc5258f0d2beb07442fbc9c25af8814ad80229b --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_necks/test_ct_resnet_neck.py @@ -0,0 +1,53 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch + +from mmdet.models.necks import CTResNetNeck + + +class TestCTResNetNeck(unittest.TestCase): + + def test_init(self): + # num_filters/num_kernels must be same length + with self.assertRaises(AssertionError): + CTResNetNeck( + in_channels=10, + num_deconv_filters=(10, 10), + num_deconv_kernels=(4, )) + + ct_resnet_neck = CTResNetNeck( + in_channels=16, + num_deconv_filters=(8, 8), + num_deconv_kernels=(4, 4), + use_dcn=False) + ct_resnet_neck.init_weights() + + def test_forward(self): + in_channels = 16 + num_filters = (8, 8) + num_kernels = (4, 4) + feat = torch.rand(1, 16, 4, 4) + ct_resnet_neck = CTResNetNeck( + in_channels=in_channels, + num_deconv_filters=num_filters, + num_deconv_kernels=num_kernels, + use_dcn=False) + + # feat must be list or tuple + with self.assertRaises(AssertionError): + ct_resnet_neck(feat) + + out_feat = ct_resnet_neck([feat])[0] + self.assertEqual(out_feat.shape, (1, num_filters[-1], 16, 16)) + + if torch.cuda.is_available(): + # test dcn + ct_resnet_neck = CTResNetNeck( + in_channels=in_channels, + num_deconv_filters=num_filters, + num_deconv_kernels=num_kernels) + ct_resnet_neck = ct_resnet_neck.cuda() + feat = feat.cuda() + out_feat = ct_resnet_neck([feat])[0] + self.assertEqual(out_feat.shape, (1, num_filters[-1], 16, 16)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_necks/test_necks.py b/mmdet_code/mmdetection/tests/test_models/test_necks/test_necks.py new file mode 100644 index 0000000000000000000000000000000000000000..92a86c13a1a46b369574cf27cee90c4ca0e3b7d3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_necks/test_necks.py @@ -0,0 +1,761 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch +from torch.nn.modules.batchnorm import _BatchNorm + +from mmdet.models.necks import (FPG, FPN, FPN_CARAFE, NASFCOS_FPN, NASFPN, SSH, + YOLOXPAFPN, ChannelMapper, DilatedEncoder, + DyHead, FeatureAugmentNeck, + MorphologicalEnhancement, SSDNeck, YOLOV3Neck) + + +def test_fpn(): + """Tests fpn.""" + s = 64 + in_channels = [8, 16, 32, 64] + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + out_channels = 8 + + # end_level=-1 is equal to end_level=3 + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=0, + end_level=-1, + num_outs=5) + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=0, + end_level=3, + num_outs=5) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + end_level=2, + num_outs=3) + + # `num_outs` is not equal to len(in_channels) - start_level + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + num_outs=2) + + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + end_level=4, + num_outs=2) + + # `num_outs` is not equal to end_level - start_level + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + end_level=3, + num_outs=1) + + # Invalid `add_extra_convs` option + with pytest.raises(AssertionError): + FPN(in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs='on_xxx', + num_outs=5) + + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=True, + num_outs=5) + + # FPN expects a multiple levels of features per image + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels)) + ] + outs = fpn_model(feats) + assert fpn_model.add_extra_convs == 'on_input' + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + +def test_feature_augment_neck(): + feats = ( + torch.rand(2, 8, 32, 32, requires_grad=True), + torch.rand(2, 16, 16, 16, requires_grad=True), + torch.rand(2, 32, 8, 8, requires_grad=True), + torch.rand(2, 64, 4, 4, requires_grad=True), + ) + imgs = torch.rand(2, 3, 128, 128) + neck = FeatureAugmentNeck( + base_neck=dict( + type='FPN', + in_channels=[8, 16, 32, 64], + out_channels=8, + num_outs=4), + out_channels=8, + levels=(0, ), + dgfe=dict(type='FeatureDGFE'), + api=dict(type='AdversarialPerturbationInjection')) + + neck.eval() + eval_outs = neck(feats, batch_inputs=imgs) + assert len(eval_outs) == 4 + assert eval_outs[0].shape == (2, 8, 32, 32) + + neck.train() + neck.capture_api() + outs = neck(feats, batch_inputs=imgs) + api = neck.api_modules[0] + assert api.captured is not None + target = torch.zeros(2, 1, 32, 32) + loss = api.auxiliary_loss(target) + outs[0].sum() + grad = torch.autograd.grad(loss, api.captured, retain_graph=True)[0] + assert api.set_perturbation_from_grad(grad) + neck.perturb_api() + perturbed_outs = neck(feats, batch_inputs=imgs) + assert perturbed_outs[0].shape == outs[0].shape + + +def test_fpn_remaining_cases(): + s = 64 + in_channels = [8, 16, 32, 64] + out_channels = 8 + feats = [ + torch.rand(1, channels, s // 2**i, s // 2**i) + for i, channels in enumerate(in_channels) + ] + + # Tests for fpn with no extra convs (pooling is used instead) + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=False, + num_outs=5) + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + assert not fpn_model.add_extra_convs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Tests for fpn with lateral bns + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=True, + no_norm_on_lateral=False, + norm_cfg=dict(type='BN', requires_grad=True), + num_outs=5) + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + assert fpn_model.add_extra_convs == 'on_input' + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + bn_exist = False + for m in fpn_model.modules(): + if isinstance(m, _BatchNorm): + bn_exist = True + assert bn_exist + + # Bilinear upsample + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=True, + upsample_cfg=dict(mode='bilinear', align_corners=True), + num_outs=5) + fpn_model(feats) + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + assert fpn_model.add_extra_convs == 'on_input' + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Scale factor instead of fixed upsample size upsample + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + start_level=1, + add_extra_convs=True, + upsample_cfg=dict(scale_factor=2), + num_outs=5) + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Extra convs source is 'inputs' + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + add_extra_convs='on_input', + start_level=1, + num_outs=5) + assert fpn_model.add_extra_convs == 'on_input' + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Extra convs source is 'laterals' + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + add_extra_convs='on_lateral', + start_level=1, + num_outs=5) + assert fpn_model.add_extra_convs == 'on_lateral' + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # Extra convs source is 'outputs' + fpn_model = FPN( + in_channels=in_channels, + out_channels=out_channels, + add_extra_convs='on_output', + start_level=1, + num_outs=5) + assert fpn_model.add_extra_convs == 'on_output' + outs = fpn_model(feats) + assert len(outs) == fpn_model.num_outs + for i in range(fpn_model.num_outs): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + +def test_channel_mapper(): + """Tests ChannelMapper.""" + s = 64 + in_channels = [8, 16, 32, 64] + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + out_channels = 8 + kernel_size = 3 + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels)) + ] + + # in_channels must be a list + with pytest.raises(AssertionError): + channel_mapper = ChannelMapper( + in_channels=10, out_channels=out_channels, kernel_size=kernel_size) + # the length of channel_mapper's inputs must be equal to the length of + # in_channels + with pytest.raises(AssertionError): + channel_mapper = ChannelMapper( + in_channels=in_channels[:-1], + out_channels=out_channels, + kernel_size=kernel_size) + channel_mapper(feats) + + channel_mapper = ChannelMapper( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size) + + outs = channel_mapper(feats) + assert len(outs) == len(feats) + for i in range(len(feats)): + outs[i].shape[1] == out_channels + outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + +def test_dilated_encoder(): + in_channels = 16 + out_channels = 32 + out_shape = 34 + dilated_encoder = DilatedEncoder(in_channels, out_channels, 16, 2, + [2, 4, 6, 8]) + feat = [torch.rand(1, in_channels, 34, 34)] + out_feat = dilated_encoder(feat)[0] + assert out_feat.shape == (1, out_channels, out_shape, out_shape) + + +def test_yolov3_neck(): + # num_scales, in_channels, out_channels must be same length + with pytest.raises(AssertionError): + YOLOV3Neck(num_scales=3, in_channels=[16, 8, 4], out_channels=[8, 4]) + + # len(feats) must equal to num_scales + with pytest.raises(AssertionError): + neck = YOLOV3Neck( + num_scales=3, in_channels=[16, 8, 4], out_channels=[8, 4, 2]) + feats = (torch.rand(1, 4, 16, 16), torch.rand(1, 8, 16, 16)) + neck(feats) + + # test normal channels + s = 32 + in_channels = [16, 8, 4] + out_channels = [8, 4, 2] + feat_sizes = [s // 2**i for i in range(len(in_channels) - 1, -1, -1)] + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels) - 1, -1, -1) + ] + neck = YOLOV3Neck( + num_scales=3, in_channels=in_channels, out_channels=out_channels) + outs = neck(feats) + + assert len(outs) == len(feats) + for i in range(len(outs)): + assert outs[i].shape == \ + (1, out_channels[i], feat_sizes[i], feat_sizes[i]) + + # test more flexible setting + s = 32 + in_channels = [32, 8, 16] + out_channels = [19, 21, 5] + feat_sizes = [s // 2**i for i in range(len(in_channels) - 1, -1, -1)] + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels) - 1, -1, -1) + ] + neck = YOLOV3Neck( + num_scales=3, in_channels=in_channels, out_channels=out_channels) + outs = neck(feats) + + assert len(outs) == len(feats) + for i in range(len(outs)): + assert outs[i].shape == \ + (1, out_channels[i], feat_sizes[i], feat_sizes[i]) + + +def test_ssd_neck(): + # level_strides/level_paddings must be same length + with pytest.raises(AssertionError): + SSDNeck( + in_channels=[8, 16], + out_channels=[8, 16, 32], + level_strides=[2], + level_paddings=[2, 1]) + + # length of out_channels must larger than in_channels + with pytest.raises(AssertionError): + SSDNeck( + in_channels=[8, 16], + out_channels=[8], + level_strides=[2], + level_paddings=[2]) + + # len(out_channels) - len(in_channels) must equal to len(level_strides) + with pytest.raises(AssertionError): + SSDNeck( + in_channels=[8, 16], + out_channels=[4, 16, 64], + level_strides=[2, 2], + level_paddings=[2, 2]) + + # in_channels must be same with out_channels[:len(in_channels)] + with pytest.raises(AssertionError): + SSDNeck( + in_channels=[8, 16], + out_channels=[4, 16, 64], + level_strides=[2], + level_paddings=[2]) + + ssd_neck = SSDNeck( + in_channels=[4], + out_channels=[4, 8, 16], + level_strides=[2, 1], + level_paddings=[1, 0]) + feats = (torch.rand(1, 4, 16, 16), ) + outs = ssd_neck(feats) + assert outs[0].shape == (1, 4, 16, 16) + assert outs[1].shape == (1, 8, 8, 8) + assert outs[2].shape == (1, 16, 6, 6) + + # test SSD-Lite Neck + ssd_neck = SSDNeck( + in_channels=[4, 8], + out_channels=[4, 8, 16], + level_strides=[1], + level_paddings=[1], + l2_norm_scale=None, + use_depthwise=True, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU6')) + assert not hasattr(ssd_neck, 'l2_norm') + + from mmcv.cnn.bricks import DepthwiseSeparableConvModule + assert isinstance(ssd_neck.extra_layers[0][-1], + DepthwiseSeparableConvModule) + + feats = (torch.rand(1, 4, 8, 8), torch.rand(1, 8, 8, 8)) + outs = ssd_neck(feats) + assert outs[0].shape == (1, 4, 8, 8) + assert outs[1].shape == (1, 8, 8, 8) + assert outs[2].shape == (1, 16, 8, 8) + + +def test_yolox_pafpn(): + s = 64 + in_channels = [8, 16, 32, 64] + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + out_channels = 24 + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels)) + ] + neck = YOLOXPAFPN(in_channels=in_channels, out_channels=out_channels) + outs = neck(feats) + assert len(outs) == len(feats) + for i in range(len(feats)): + assert outs[i].shape[1] == out_channels + assert outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + # test depth-wise + neck = YOLOXPAFPN( + in_channels=in_channels, out_channels=out_channels, use_depthwise=True) + + from mmcv.cnn.bricks import DepthwiseSeparableConvModule + assert isinstance(neck.downsamples[0], DepthwiseSeparableConvModule) + + outs = neck(feats) + assert len(outs) == len(feats) + for i in range(len(feats)): + assert outs[i].shape[1] == out_channels + assert outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + +def test_dyhead(): + s = 64 + in_channels = 8 + out_channels = 16 + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + feats = [ + torch.rand(1, in_channels, feat_sizes[i], feat_sizes[i]) + for i in range(len(feat_sizes)) + ] + neck = DyHead( + in_channels=in_channels, out_channels=out_channels, num_blocks=3) + outs = neck(feats) + assert len(outs) == len(feats) + for i in range(len(outs)): + assert outs[i].shape[1] == out_channels + assert outs[i].shape[2] == outs[i].shape[3] == s // (2**i) + + feat = torch.rand(1, 8, 4, 4) + # input feat must be tuple or list + with pytest.raises(AssertionError): + neck(feat) + + +def test_fpg(): + # end_level=-1 is equal to end_level=3 + norm_cfg = dict(type='BN', requires_grad=True) + FPG(in_channels=[8, 16, 32, 64], + out_channels=8, + inter_channels=8, + num_outs=5, + add_extra_convs=True, + start_level=1, + end_level=-1, + stack_times=9, + paths=['bu'] * 9, + same_down_trans=None, + same_up_trans=dict( + type='conv', + kernel_size=3, + stride=2, + padding=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + across_lateral_trans=dict( + type='conv', + kernel_size=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + across_down_trans=dict( + type='interpolation_conv', + mode='nearest', + kernel_size=3, + norm_cfg=norm_cfg, + order=('act', 'conv', 'norm'), + inplace=False), + across_up_trans=None, + across_skip_trans=dict( + type='conv', + kernel_size=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + output_trans=dict( + type='last_conv', + kernel_size=3, + order=('act', 'conv', 'norm'), + inplace=False), + norm_cfg=norm_cfg, + skip_inds=[(0, 1, 2, 3), (0, 1, 2), (0, 1), (0, ), ()]) + FPG(in_channels=[8, 16, 32, 64], + out_channels=8, + inter_channels=8, + num_outs=5, + add_extra_convs=True, + start_level=1, + end_level=3, + stack_times=9, + paths=['bu'] * 9, + same_down_trans=None, + same_up_trans=dict( + type='conv', + kernel_size=3, + stride=2, + padding=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + across_lateral_trans=dict( + type='conv', + kernel_size=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + across_down_trans=dict( + type='interpolation_conv', + mode='nearest', + kernel_size=3, + norm_cfg=norm_cfg, + order=('act', 'conv', 'norm'), + inplace=False), + across_up_trans=None, + across_skip_trans=dict( + type='conv', + kernel_size=1, + norm_cfg=norm_cfg, + inplace=False, + order=('act', 'conv', 'norm')), + output_trans=dict( + type='last_conv', + kernel_size=3, + order=('act', 'conv', 'norm'), + inplace=False), + norm_cfg=norm_cfg, + skip_inds=[(0, 1, 2, 3), (0, 1, 2), (0, 1), (0, ), ()]) + + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + FPG(in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + paths=['bu'] * 9, + start_level=1, + end_level=4, + num_outs=2, + skip_inds=[(0, 1, 2, 3), (0, 1, 2), (0, 1), (0, ), ()]) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + FPG(in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + paths=['bu'] * 9, + start_level=1, + end_level=2, + num_outs=3, + skip_inds=[(0, 1, 2, 3), (0, 1, 2), (0, 1), (0, ), ()]) + + +def test_fpn_carafe(): + # end_level=-1 is equal to end_level=3 + FPN_CARAFE( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=0, + end_level=3, + num_outs=4) + FPN_CARAFE( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=0, + end_level=-1, + num_outs=4) + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + FPN_CARAFE( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=1, + end_level=4, + num_outs=2) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + FPN_CARAFE( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=1, + end_level=2, + num_outs=3) + + +def test_nas_fpn(): + # end_level=-1 is equal to end_level=3 + NASFPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + start_level=0, + end_level=3, + num_outs=4) + NASFPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + start_level=0, + end_level=-1, + num_outs=4) + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + NASFPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + start_level=1, + end_level=4, + num_outs=2) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + NASFPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + stack_times=9, + start_level=1, + end_level=2, + num_outs=3) + + +def test_nasfcos_fpn(): + # end_level=-1 is equal to end_level=3 + NASFCOS_FPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=0, + end_level=3, + num_outs=4) + NASFCOS_FPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=0, + end_level=-1, + num_outs=4) + + # `end_level` is larger than len(in_channels) - 1 + with pytest.raises(AssertionError): + NASFCOS_FPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=1, + end_level=4, + num_outs=2) + + # `num_outs` is not equal to end_level - start_level + 1 + with pytest.raises(AssertionError): + NASFCOS_FPN( + in_channels=[8, 16, 32, 64], + out_channels=8, + start_level=1, + end_level=2, + num_outs=3) + + +def test_ssh_neck(): + """Tests ssh.""" + s = 64 + in_channels = [8, 16, 32, 64] + feat_sizes = [s // 2**i for i in range(4)] # [64, 32, 16, 8] + out_channels = [16, 32, 64, 128] + ssh_model = SSH( + num_scales=4, in_channels=in_channels, out_channels=out_channels) + + feats = [ + torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) + for i in range(len(in_channels)) + ] + outs = ssh_model(feats) + assert len(outs) == len(feats) + for i in range(len(outs)): + assert outs[i].shape == \ + (1, out_channels[i], feat_sizes[i], feat_sizes[i]) + + +def test_morphological_enhancement(): + modules = [ + MorphologicalEnhancement(2, mode=mode) + for mode in ('positive', 'raw') + ] + for module in modules: + assert module.mixer.bias is None + assert torch.count_nonzero(module.mixer.weight) == 0 + x = torch.zeros(1, 2, 7, 7, requires_grad=True) + x.data[..., 3, 3] = 1 + out = module(x) + assert torch.equal(out, x) + assert out.shape == x.shape + assert out.dtype == x.dtype + out.sum().backward() + assert module.mixer.weight.grad is not None + assert torch.isfinite(module.mixer.weight.grad).all() + assert torch.count_nonzero(module.mixer.weight.grad) > 0 + assert sum(p.numel() for p in modules[0].parameters()) == sum( + p.numel() for p in modules[1].parameters()) + + positive = MorphologicalEnhancement(1, mode='positive') + positive.mixer.weight.data.fill_(1) + peak = torch.zeros(1, 1, 7, 7) + peak[..., 3, 3] = 1 + assert positive(peak)[..., 3, 3].item() > peak[..., 3, 3].item() + flat = torch.ones(1, 1, 7, 7) + assert torch.equal(positive(flat), flat) + + with pytest.raises(ValueError): + MorphologicalEnhancement(1, kernel_size=2) + with pytest.raises(ValueError): + MorphologicalEnhancement(1, mode='unknown') + + +def test_feature_augment_neck_morphology_only_changes_p3(): + feats = tuple( + torch.rand(1, channels, size, size) + for channels, size in zip((8, 16, 32, 64), (32, 16, 8, 4))) + base = FPN( + in_channels=[8, 16, 32, 64], out_channels=8, num_outs=4) + expected = base(feats) + neck = FeatureAugmentNeck( + base_neck=dict( + type='FPN', + in_channels=[8, 16, 32, 64], + out_channels=8, + num_outs=4), + out_channels=8, + levels=(0, ), + morphology=dict(mode='positive')) + neck.base_neck.load_state_dict(base.state_dict()) + optimizer = torch.optim.SGD(neck.morphology_modules['0'].parameters(), 1) + neck(feats)[0].sum().backward() + optimizer.step() + actual = neck(feats) + assert not torch.equal(actual[0], expected[0]) + for level in range(1, 4): + assert torch.equal(actual[level], expected[level]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_reid/test_base_reid.py b/mmdet_code/mmdetection/tests/test_models/test_reid/test_base_reid.py new file mode 100644 index 0000000000000000000000000000000000000000..120cd402dbc68da83ef6721da94b90c9868cb2ec --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_reid/test_base_reid.py @@ -0,0 +1,46 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.structures import ReIDDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestBaseReID(TestCase): + + @classmethod + def setUpClass(cls) -> None: + register_all_modules() + + @parameterized.expand([ + 'reid/reid_r50_8xb32-6e_mot17train80_test-mot17val20.py', + ]) + def test_forward(self, cfg_file): + model_cfg = get_detector_cfg(cfg_file) + model = MODELS.build(model_cfg) + inputs = torch.rand(1, 4, 3, 256, 128) + data_samples = [ + ReIDDataSample().set_gt_label(label) for label in (0, 0, 1, 1) + ] + + # test mode='tensor' + feats = model(inputs, mode='tensor') + assert feats.shape == (4, 128) + + # test mode='loss' + losses = model(inputs, data_samples, mode='loss') + assert losses.keys() == {'triplet_loss', 'ce_loss', 'accuracy_top-1'} + assert losses['ce_loss'].item() > 0 + assert losses['triplet_loss'].item() > 0 + + # test mode='predict' + predictions = model(inputs, data_samples, mode='predict') + for pred in predictions: + assert isinstance(pred, ReIDDataSample) + assert isinstance(pred.pred_feature, torch.Tensor) + assert isinstance(pred.gt_label.label, torch.Tensor) + assert pred.pred_feature.shape == (128, ) diff --git a/mmdet_code/mmdetection/tests/test_models/test_reid/test_fc_module.py b/mmdet_code/mmdetection/tests/test_models/test_reid/test_fc_module.py new file mode 100644 index 0000000000000000000000000000000000000000..1f998b76362f06170597c2d334df7166a3b11137 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_reid/test_fc_module.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models import FcModule + + +class TestFcModule(TestCase): + + def test_forward(self): + inputs = torch.rand(32, 128) + + # test + fc = FcModule( + in_channels=128, + out_channels=32, + ) + fc.init_weights() + outputs = fc(inputs) + assert outputs.shape == (32, 32) + + # test with norm + fc = FcModule( + in_channels=128, + out_channels=32, + norm_cfg=dict(type='BN1d'), + ) + outputs = fc(inputs) + assert outputs.shape == (32, 32) + + # test with norm and act + fc = FcModule( + in_channels=128, + out_channels=32, + norm_cfg=dict(type='BN1d'), + act_cfg=dict(type='ReLU'), + ) + outputs = fc(inputs) + assert outputs.shape == (32, 32) diff --git a/mmdet_code/mmdetection/tests/test_models/test_reid/test_gap.py b/mmdet_code/mmdetection/tests/test_models/test_reid/test_gap.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b546b94b73c49c0407212583f2066fea2e0191 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_reid/test_gap.py @@ -0,0 +1,27 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.models import GlobalAveragePooling + + +class TestGlobalAveragePooling(TestCase): + + def test_forward(self): + inputs = torch.rand(32, 128, 14, 14) + + # test AdaptiveAvgPool2d + neck = GlobalAveragePooling() + outputs = neck(inputs) + assert outputs.shape == (32, 128) + + # test kernel_size + neck = GlobalAveragePooling(kernel_size=7) + outputs = neck(inputs) + assert outputs.shape == (32, 128 * 2 * 2) + + # test kenel_size and stride + neck = GlobalAveragePooling(kernel_size=7, stride=2) + outputs = neck(inputs) + assert outputs.shape == (32, 128 * 4 * 4) diff --git a/mmdet_code/mmdetection/tests/test_models/test_reid/test_linear_reid_head.py b/mmdet_code/mmdetection/tests/test_models/test_reid/test_linear_reid_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe582756873991f462f85070b4c38fa9ede8dab --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_reid/test_linear_reid_head.py @@ -0,0 +1,49 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS +from mmdet.structures import ReIDDataSample +from mmdet.utils import register_all_modules + + +class TestLinearReIDHead(TestCase): + + @classmethod + def setUpClass(cls) -> None: + register_all_modules() + head_cfg = dict( + type='LinearReIDHead', + num_fcs=1, + in_channels=128, + fc_channels=64, + out_channels=32, + num_classes=2, + loss_cls=dict(type='mmpretrain.CrossEntropyLoss', loss_weight=1.0), + loss_triplet=dict(type='TripletLoss', margin=0.3, loss_weight=1.0), + norm_cfg=dict(type='BN1d'), + act_cfg=dict(type='ReLU')) + cls.head = MODELS.build(head_cfg) + cls.inputs = (torch.rand(4, 128), torch.rand(4, 128)) + cls.data_samples = [ + ReIDDataSample().set_gt_label(label) for label in (0, 0, 1, 1) + ] + + def test_forward(self): + outputs = self.head(self.inputs) + assert outputs.shape == (4, 32) + + def test_loss(self): + losses = self.head.loss(self.inputs, self.data_samples) + assert losses.keys() == {'triplet_loss', 'ce_loss', 'accuracy_top-1'} + assert losses['ce_loss'].item() >= 0 + assert losses['triplet_loss'].item() >= 0 + + def test_predict(self): + predictions = self.head.predict(self.inputs, self.data_samples) + for pred in predictions: + assert isinstance(pred, ReIDDataSample) + assert isinstance(pred.pred_feature, torch.Tensor) + assert isinstance(pred.gt_label.label, torch.Tensor) + assert pred.pred_feature.shape == (32, ) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_bbox_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7003b0be348237be5fbc30c99ca3344e982e90d0 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_bbox_head.py @@ -0,0 +1,140 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.roi_heads.bbox_heads import (BBoxHead, Shared2FCBBoxHead, + Shared4Conv1FCBBoxHead) +from mmdet.models.task_modules.samplers import SamplingResult + + +class TestBboxHead(TestCase): + + def test_init(self): + # Shared2FCBBoxHead + bbox_head = Shared2FCBBoxHead( + in_channels=1, fc_out_channels=1, num_classes=4) + self.assertTrue(bbox_head.fc_cls) + self.assertTrue(bbox_head.fc_reg) + self.assertEqual(len(bbox_head.shared_fcs), 2) + + # Shared4Conv1FCBBoxHead + bbox_head = Shared4Conv1FCBBoxHead( + in_channels=1, fc_out_channels=1, num_classes=4) + self.assertTrue(bbox_head.fc_cls) + self.assertTrue(bbox_head.fc_reg) + self.assertEqual(len(bbox_head.shared_convs), 4) + self.assertEqual(len(bbox_head.shared_fcs), 1) + + def test_bbox_head_get_results(self): + num_classes = 6 + bbox_head = BBoxHead(reg_class_agnostic=True, num_classes=num_classes) + s = 128 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + + num_samples = 2 + rois = [torch.rand((num_samples, 5))] + cls_scores = [torch.rand((num_samples, num_classes + 1))] + bbox_preds = [torch.rand((num_samples, 4))] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertLessEqual(len(result_list[0]), num_samples * num_classes) + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + self.assertEqual(len(result_list[0].scores.shape), 1) + self.assertEqual(len(result_list[0].labels.shape), 1) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].bboxes.shape, bbox_preds[0].shape) + self.assertEqual(result_list[0].scores.shape, cls_scores[0].shape) + self.assertIsNone(result_list[0].get('label', None)) + + # num_samples is 0 + num_samples = 0 + rois = [torch.rand((num_samples, 5))] + cls_scores = [torch.rand((num_samples, num_classes + 1))] + bbox_preds = [torch.rand((num_samples, 4))] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertEqual(result_list[0].bboxes.shape, bbox_preds[0].shape) + self.assertIsNone(result_list[0].get('label', None)) + + def test_bbox_head_refine_bboxes(self): + num_classes = 6 + bbox_head = BBoxHead(reg_class_agnostic=True, num_classes=num_classes) + s = 128 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + sampling_results = [SamplingResult.random()] + num_samples = 20 + rois = torch.rand((num_samples, 4)) + roi_img_ids = torch.zeros(num_samples, 1) + rois = torch.cat((roi_img_ids, rois), dim=1) + cls_scores = torch.rand((num_samples, num_classes + 1)) + bbox_preds = torch.rand((num_samples, 4)) + labels = torch.randint(0, num_classes + 1, (num_samples, )).long() + bbox_targets = (labels, None, None, None) + bbox_results = dict( + rois=rois, + bbox_pred=bbox_preds, + cls_score=cls_scores, + bbox_targets=bbox_targets) + + bbox_list = bbox_head.refine_bboxes( + sampling_results=sampling_results, + bbox_results=bbox_results, + batch_img_metas=img_metas) + + self.assertGreaterEqual(num_samples, len(bbox_list[0])) + self.assertIsInstance(bbox_list[0], InstanceData) + self.assertEqual(bbox_list[0].bboxes.shape[1], 4) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_double_bbox_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_double_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..95aa02ee6bdc2bc2b5caeba40928fcab0dc6052f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_double_bbox_head.py @@ -0,0 +1,29 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads.bbox_heads import DoubleConvFCBBoxHead + + +class TestDoubleBboxHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + double_bbox_head = DoubleConvFCBBoxHead( + num_convs=4, + num_fcs=2, + in_channels=1, + conv_out_channels=4, + fc_out_channels=4) + double_bbox_head = double_bbox_head.to(device=device) + + num_samples = 4 + feats = torch.rand((num_samples, 1, 7, 7)).to(device) + double_bbox_head(x_cls=feats, x_reg=feats) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_multi_instance_bbox_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_multi_instance_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..04202a0732dd63a2203d15b3ea2f34d5f1c7bedc --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_multi_instance_bbox_head.py @@ -0,0 +1,118 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.roi_heads.bbox_heads import MultiInstanceBBoxHead + + +class TestMultiInstanceBBoxHead(TestCase): + + def test_init(self): + bbox_head = MultiInstanceBBoxHead( + num_instance=2, + with_refine=True, + num_shared_fcs=2, + in_channels=1, + fc_out_channels=1, + num_classes=4) + self.assertTrue(bbox_head.shared_fcs_ref) + self.assertTrue(bbox_head.fc_reg) + self.assertTrue(bbox_head.fc_cls) + self.assertEqual(len(bbox_head.shared_fcs), 2) + self.assertEqual(len(bbox_head.fc_reg), 2) + self.assertEqual(len(bbox_head.fc_cls), 2) + + def test_bbox_head_get_results(self): + num_classes = 1 + num_instance = 2 + bbox_head = MultiInstanceBBoxHead( + num_instance=num_instance, + num_shared_fcs=2, + reg_class_agnostic=True, + num_classes=num_classes) + s = 128 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + + num_samples = 2 + rois = [torch.rand((num_samples, 5))] + cls_scores = [] + bbox_preds = [] + for k in range(num_instance): + cls_scores.append(torch.rand((num_samples, num_classes + 1))) + bbox_preds.append(torch.rand((num_samples, 4))) + cls_scores = [torch.cat(cls_scores, dim=1)] + bbox_preds = [torch.cat(bbox_preds, dim=1)] + + # with nms + rcnn_test_cfg = ConfigDict( + nms=dict(type='nms', iou_threshold=0.5), + score_thr=0.01, + max_per_img=500) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertLessEqual( + len(result_list[0]), num_samples * num_instance * num_classes) + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + self.assertEqual(len(result_list[0].scores.shape), 1) + self.assertEqual(len(result_list[0].labels.shape), 1) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples * num_instance) + self.assertIsNone(result_list[0].get('label', None)) + + # num_samples is 0 + num_samples = 0 + rois = [torch.rand((num_samples, 5))] + cls_scores = [] + bbox_preds = [] + for k in range(num_instance): + cls_scores.append(torch.rand((num_samples, num_classes + 1))) + bbox_preds.append(torch.rand((num_samples, 4))) + cls_scores = [torch.cat(cls_scores, dim=1)] + bbox_preds = [torch.cat(bbox_preds, dim=1)] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0 * num_instance) + self.assertIsNone(result_list[0].get('label', None)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_sabl_bbox_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_sabl_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b796108c446d57353b639d000655eea98133abd1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_sabl_bbox_head.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.roi_heads.bbox_heads import SABLHead +from mmdet.models.task_modules.samplers import SamplingResult + + +class TestSABLBboxHead(TestCase): + + def test_init(self): + bbox_head = SABLHead( + cls_in_channels=1, + cls_out_channels=1, + reg_in_channels=1, + reg_offset_out_channels=1, + reg_cls_out_channels=1, + num_classes=4) + self.assertTrue(bbox_head.fc_cls) + self.assertTrue(hasattr(bbox_head, 'reg_cls_fcs')) + self.assertTrue(hasattr(bbox_head, 'reg_offset_fcs')) + self.assertFalse(hasattr(bbox_head, 'fc_reg')) + + def test_bbox_head_get_results(self): + num_classes = 6 + bbox_head = SABLHead(reg_class_agnostic=True, num_classes=num_classes) + s = 128 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + + num_samples = 2 + rois = [torch.rand((num_samples, 5))] + cls_scores = [torch.rand((num_samples, num_classes + 1))] + bbox_preds = [(torch.rand( + (num_samples, 28)), torch.rand((num_samples, 28)))] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertLessEqual(len(result_list[0]), num_samples * num_classes) + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + self.assertEqual(len(result_list[0].scores.shape), 1) + self.assertEqual(len(result_list[0].labels.shape), 1) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].scores.shape, cls_scores[0].shape) + self.assertIsNone(result_list[0].get('label', None)) + + # num_samples is 0 + num_samples = 0 + rois = [torch.rand((num_samples, 5))] + cls_scores = [torch.rand((num_samples, num_classes + 1))] + bbox_preds = [(torch.rand( + (num_samples, 28)), torch.rand((num_samples, 28)))] + + # with nms + rcnn_test_cfg = ConfigDict( + score_thr=0., + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100) + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas, + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertEqual(result_list[0].bboxes.shape[1], 4) + + # without nms + result_list = bbox_head.predict_by_feat( + rois=tuple(rois), + cls_scores=tuple(cls_scores), + bbox_preds=tuple(bbox_preds), + batch_img_metas=img_metas) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), 0) + self.assertIsNone(result_list[0].get('label', None)) + + def test_bbox_head_refine_bboxes(self): + num_classes = 8 + bbox_head = SABLHead(reg_class_agnostic=True, num_classes=num_classes) + s = 20 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + sampling_results = [SamplingResult.random()] + num_samples = 20 + rois = torch.rand((num_samples, 4)) + roi_img_ids = torch.zeros(num_samples, 1) + rois = torch.cat((roi_img_ids, rois), dim=1) + cls_scores = torch.rand((num_samples, num_classes + 1)) + cls_preds = torch.rand((num_samples, 28)) + offset_preds = torch.rand((num_samples, 28)) + labels = torch.randint(0, num_classes + 1, (num_samples, )).long() + bbox_targets = (labels, None, None, None) + bbox_results = dict( + rois=rois, + bbox_pred=(cls_preds, offset_preds), + cls_score=cls_scores, + bbox_targets=bbox_targets) + + bbox_list = bbox_head.refine_bboxes( + sampling_results=sampling_results, + bbox_results=bbox_results, + batch_img_metas=img_metas) + + self.assertGreaterEqual(num_samples, len(bbox_list[0])) + self.assertIsInstance(bbox_list[0], InstanceData) + self.assertEqual(bbox_list[0].bboxes.shape[1], 4) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_scnet_bbox_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_scnet_bbox_head.py new file mode 100644 index 0000000000000000000000000000000000000000..eb74ab5770571e95c45bc5308528ed4b63f8e325 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_bbox_heads/test_scnet_bbox_head.py @@ -0,0 +1,22 @@ +import unittest + +import torch + +from mmdet.models.roi_heads.bbox_heads import SCNetBBoxHead + + +class TestSCNetBBoxHead(unittest.TestCase): + + def test_forward(self): + x = torch.rand((2, 1, 16, 16)) + bbox_head = SCNetBBoxHead( + num_shared_fcs=2, + in_channels=1, + roi_feat_size=16, + conv_out_channels=1, + fc_out_channels=256, + ) + results = bbox_head(x, return_shared_feat=False) + self.assertEqual(len(results), 2) + results = bbox_head(x, return_shared_feat=True) + self.assertEqual(len(results), 3) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_cascade_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_cascade_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5918b0067f1d540fce61edc59e15abcf2b90a4eb --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_cascade_roi_head.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads import StandardRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestCascadeRoIHead(TestCase): + + @parameterized.expand( + ['cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + """Test init standard RoI head.""" + # Normal Cascade Mask R-CNN RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + assert roi_head.with_bbox + assert roi_head.with_mask + + @parameterized.expand( + ['cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py']) + def test_cascade_roi_head_loss(self, cfg_file): + """Tests standard roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss_cls' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + elif 'loss_bbox' in name or 'loss_mask' in name: + self.assertEqual(value.sum(), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_dynamic_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_dynamic_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4b44de6991003890fe0d5dd24a42b02ae5f9f3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_dynamic_roi_head.py @@ -0,0 +1,71 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestDynamicRoIHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'dynamic_rcnn/dynamic-rcnn_r50_fpn_1x_coco.py') + + def test_init(self): + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + + @parameterized.expand(['cpu', 'cuda']) + def test_dynamic_roi_head_loss(self, device): + """Tests trident roi head predict.""" + if not torch.cuda.is_available() and device == 'cuda': + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_bbox = out['loss_bbox'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_bbox.sum(), 0, 'box loss should be non-zero') + + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + empty_bbox_loss = out['loss_bbox'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_bbox_loss.sum(), 0, + 'there should be no box loss when there are no true boxes') diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_grid_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_grid_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fc2988760c87247a49328578412d451b32e44527 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_grid_roi_head.py @@ -0,0 +1,121 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestGridRoIHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'grid_rcnn/grid-rcnn_r50_fpn_gn-head_2x_coco.py') + + def test_init(self): + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + + @parameterized.expand(['cpu', 'cuda']) + def test_grid_roi_head_loss(self, device): + """Tests trident roi head predict.""" + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_grid = out['loss_grid'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_grid.sum(), 0, 'grid loss should be non-zero') + + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertNotIn( + 'loss_grid', out, + 'grid loss should be passed when there are no true boxes') + + @parameterized.expand(['cpu', 'cuda']) + def test_grid_roi_head_predict(self, device): + """Tests trident roi head predict.""" + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + roi_head.predict(feats, proposals_list, batch_data_samples) + + @parameterized.expand(['cpu', 'cuda']) + def test_grid_roi_head_forward(self, device): + """Tests trident roi head forward.""" + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + roi_head.forward(feats, proposals_list) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_htc_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_htc_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..37bb92f5787d598571aa0189f2a7adbbc05e6963 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_htc_roi_head.py @@ -0,0 +1,114 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads import HybridTaskCascadeRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestHTCRoIHead(TestCase): + + @parameterized.expand(['htc/htc_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + """Test init htc RoI head.""" + # Normal HTC RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + assert roi_head.with_bbox + assert roi_head.with_mask + assert roi_head.with_semantic + + @parameterized.expand(['htc/htc_r50_fpn_1x_coco.py']) + def test_htc_roi_head_loss(self, cfg_file): + """Tests htc roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + with_semantic=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + with_semantic=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss_cls' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + elif 'loss_bbox' in name or 'loss_mask' in name: + self.assertEqual(value.sum(), 0) + + @parameterized.expand(['htc/htc_r50_fpn_1x_coco.py']) + def test_htc_roi_head_predict(self, cfg_file): + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + results = roi_head.predict( + feats, proposal_list, batch_data_samples, rescale=True) + self.assertEqual(results[0].masks.shape[-2:], (s, s)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_coarse_mask_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_coarse_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ffadc19ff2bb88007ad6be01ead0760dd7ee234f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_coarse_mask_head.py @@ -0,0 +1,41 @@ +import unittest + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads.mask_heads import CoarseMaskHead + + +class TestCoarseMaskHead(unittest.TestCase): + + def test_init(self): + with self.assertRaises(AssertionError): + CoarseMaskHead(num_fcs=0) + + with self.assertRaises(AssertionError): + CoarseMaskHead(downsample_factor=0.5) + + @parameterized.expand(['cpu', 'cuda']) + def test_forward(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + x = torch.rand((1, 32, 7, 7)).to(device) + mask_head = CoarseMaskHead( + downsample_factor=2, + in_channels=32, + conv_out_channels=32, + roi_feat_size=7).to(device) + mask_head.init_weights() + res = mask_head(x) + self.assertEqual(res.shape[-2:], (3, 3)) + + mask_head = CoarseMaskHead( + downsample_factor=1, + in_channels=32, + conv_out_channels=32, + roi_feat_size=7).to(device) + mask_head.init_weights() + res = mask_head(x) + self.assertEqual(res.shape[-2:], (7, 7)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_fcn_mask_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_fcn_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b4ee9362b1c588c705afa1a816d5da9fde2df6 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_fcn_mask_head.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet.models.roi_heads.mask_heads import FCNMaskHead + + +class TestFCNMaskHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_get_seg_masks(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + num_classes = 6 + mask_head = FCNMaskHead( + num_convs=1, + in_channels=1, + conv_out_channels=1, + num_classes=num_classes) + rcnn_test_cfg = ConfigDict( + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100, + mask_thr_binary=0.5) + s = 128 + img_metas = { + 'img_shape': (s, s, 3), + 'scale_factor': (1, 1), + 'ori_shape': (s, s, 3) + } + result = InstanceData(metainfo=img_metas) + + num_samples = 2 + mask_pred = [torch.rand((num_samples, num_classes, 14, 14)).to(device)] + result.bboxes = torch.rand((num_samples, 4)).to(device) + result.labels = torch.randint( + num_classes, (num_samples, ), dtype=torch.long).to(device) + mask_head.to(device=device) + result_list = mask_head.predict_by_feat( + mask_preds=tuple(mask_pred), + results_list=[result], + batch_img_metas=[img_metas], + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].masks.shape, (num_samples, s, s)) + + # test with activate_map, `mask_pred` has been activated before + num_samples = 2 + mask_pred = [torch.rand((num_samples, num_classes, 14, 14)).to(device)] + mask_pred = [m.sigmoid().detach() for m in mask_pred] + result.bboxes = torch.rand((num_samples, 4)).to(device) + result.labels = torch.randint( + num_classes, (num_samples, ), dtype=torch.long).to(device) + mask_head.to(device=device) + result_list = mask_head.predict_by_feat( + mask_preds=tuple(mask_pred), + results_list=[result], + batch_img_metas=[img_metas], + rcnn_test_cfg=rcnn_test_cfg, + activate_map=True) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].masks.shape, (num_samples, s, s)) + + # num_samples is 0 + num_samples = 0 + result = InstanceData(metainfo=img_metas) + mask_pred = [torch.rand((num_samples, num_classes, 14, 14)).to(device)] + result.bboxes = torch.zeros((num_samples, 4)).to(device) + result.labels = torch.zeros((num_samples, )).to(device) + result_list = mask_head.predict_by_feat( + mask_preds=tuple(mask_pred), + results_list=[result], + batch_img_metas=[img_metas], + rcnn_test_cfg=rcnn_test_cfg) + + self.assertIsInstance(result_list[0], InstanceData) + self.assertEqual(len(result_list[0]), num_samples) + self.assertEqual(result_list[0].masks.shape, (num_samples, s, s)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_feature_relay_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_feature_relay_head.py new file mode 100644 index 0000000000000000000000000000000000000000..4a182b842d9a4b84e7e064a2b2ace80d87d6661f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_feature_relay_head.py @@ -0,0 +1,26 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import FeatureRelayHead + + +class TestFeatureRelayHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + mask_head = FeatureRelayHead(in_channels=10, out_conv_channels=10) + + x = torch.rand((1, 10)) + results = mask_head(x) + self.assertIsInstance(results, Tensor) + x = torch.empty((0, 10)) + results = mask_head(x) + self.assertEqual(results, None) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_fused_semantic_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_fused_semantic_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7f912d797ebc7f8e8c8b85f058ddd2202d4f3d48 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_fused_semantic_head.py @@ -0,0 +1,33 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import FusedSemanticHead + + +class TestFusedSemanticHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + semantic_head = FusedSemanticHead( + num_ins=5, + fusion_level=1, + in_channels=4, + conv_out_channels=4, + num_classes=6) + feats = [ + torch.rand((1, 4, 32 // 2**(i + 1), 32 // 2**(i + 1))) + for i in range(5) + ] + mask_pred, x = semantic_head(feats) + labels = torch.randint(0, 6, (1, 1, 64, 64)) + loss = semantic_head.loss(mask_pred, labels) + self.assertIsInstance(loss, Tensor) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_global_context_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_global_context_head.py new file mode 100644 index 0000000000000000000000000000000000000000..32e850935011b1791ca9bdfb8e27c1b2afe34d6a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_global_context_head.py @@ -0,0 +1,30 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import GlobalContextHead + + +class TestGlobalContextHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + head = GlobalContextHead( + num_convs=1, in_channels=4, conv_out_channels=4, num_classes=10) + feats = [ + torch.rand((1, 4, 64 // 2**(i + 1), 64 // 2**(i + 1))) + for i in range(5) + ] + mc_pred, x = head(feats) + + labels = [torch.randint(0, 10, (10, ))] + loss = head.loss(mc_pred, labels) + self.assertIsInstance(loss, Tensor) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_grid_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_grid_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7a583cd4e61221ebf02ed9c1bf962851b7f31b08 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_grid_head.py @@ -0,0 +1,85 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet.models.roi_heads.mask_heads import GridHead +from mmdet.models.utils import unpack_gt_instances +from mmdet.testing import (demo_mm_inputs, demo_mm_proposals, + demo_mm_sampling_results) + + +class TestGridHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_grid_head_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + grid_head = GridHead() + grid_head.to(device=device) + + s = 256 + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + + train_cfg = ConfigDict(dict(pos_radius=1)) + + # prepare ground truth + (batch_gt_instances, batch_gt_instances_ignore, + _) = unpack_gt_instances(batch_data_samples) + sampling_results = demo_mm_sampling_results( + proposals_list=proposals_list, + batch_gt_instances=batch_gt_instances, + batch_gt_instances_ignore=batch_gt_instances_ignore) + + # prepare grid feats + pos_bboxes = torch.cat([res.pos_bboxes for res in sampling_results]) + grid_feats = torch.rand((pos_bboxes.size(0), 256, 14, 14)).to(device) + sample_idx = torch.arange(0, pos_bboxes.size(0)) + grid_pred = grid_head(grid_feats) + + grid_head.loss(grid_pred, sample_idx, sampling_results, train_cfg) + + @parameterized.expand(['cpu', 'cuda']) + def test_mask_iou_head_predict_by_feat(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + grid_head = GridHead() + grid_head.to(device=device) + + s = 128 + num_samples = 2 + num_classes = 4 + img_metas = { + 'img_shape': (s, s, 3), + 'scale_factor': (1, 1), + 'ori_shape': (s, s, 3) + } + results = InstanceData(metainfo=img_metas) + results.bboxes = torch.rand((num_samples, 4)).to(device) + results.scores = torch.rand((num_samples, )).to(device) + results.labels = torch.randint( + num_classes, (num_samples, ), dtype=torch.long).to(device) + + grid_feats = torch.rand((num_samples, 256, 14, 14)).to(device) + grid_preds = grid_head(grid_feats) + grid_head.predict_by_feat( + grid_preds=grid_preds, + results_list=[results], + batch_img_metas=[img_metas]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_htc_mask_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_htc_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6927e618da4a42451a355f44d8cbeaceae91329f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_htc_mask_head.py @@ -0,0 +1,46 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import HTCMaskHead + + +class TestHTCMaskHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + num_classes = 6 + mask_head = HTCMaskHead( + with_conv_res=True, + num_convs=1, + in_channels=1, + conv_out_channels=1, + num_classes=num_classes) + + x = torch.rand((1, 1, 10, 10)) + res_feat = torch.rand((1, 1, 10, 10)) + + with self.assertRaises(AssertionError): + mask_head(x, return_logits=False, return_feat=False) + + results = mask_head(x) + self.assertEqual(len(results), 2) + results = mask_head(x, res_feat=res_feat) + self.assertEqual(len(results), 2) + + results = mask_head(x, return_logits=False) + self.assertIsInstance(results, Tensor) + results = mask_head(x, return_feat=False) + self.assertIsInstance(results, Tensor) + + results = mask_head(x, res_feat=res_feat, return_logits=False) + self.assertIsInstance(results, Tensor) + results = mask_head(x, res_feat=res_feat, return_feat=False) + self.assertIsInstance(results, Tensor) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_maskiou_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_maskiou_head.py new file mode 100644 index 0000000000000000000000000000000000000000..548147861d5af5a1213629be462189cccf473de3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_maskiou_head.py @@ -0,0 +1,100 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData +from parameterized import parameterized + +from mmdet.models.roi_heads.mask_heads import MaskIoUHead +from mmdet.models.utils import unpack_gt_instances +from mmdet.structures.mask import mask_target +from mmdet.testing import (demo_mm_inputs, demo_mm_proposals, + demo_mm_sampling_results) + + +class TestMaskIoUHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_mask_iou_head_loss_and_target(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + mask_iou_head = MaskIoUHead(num_classes=4) + mask_iou_head.to(device=device) + + s = 256 + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + train_cfg = ConfigDict(dict(mask_size=28, mask_thr_binary=0.5)) + + # prepare ground truth + (batch_gt_instances, batch_gt_instances_ignore, + _) = unpack_gt_instances(batch_data_samples) + sampling_results = demo_mm_sampling_results( + proposals_list=proposals_list, + batch_gt_instances=batch_gt_instances, + batch_gt_instances_ignore=batch_gt_instances_ignore) + + # prepare mask feats, pred and target + pos_proposals = [res.pos_priors for res in sampling_results] + pos_assigned_gt_inds = [ + res.pos_assigned_gt_inds for res in sampling_results + ] + gt_masks = [res.masks for res in batch_gt_instances] + mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, + gt_masks, train_cfg) + mask_feats = torch.rand((mask_targets.size(0), 256, 14, 14)).to(device) + mask_preds = torch.rand((mask_targets.size(0), 4, 28, 28)).to(device) + + pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results]) + pos_mask_pred = mask_preds[range(mask_preds.size(0)), pos_labels] + mask_iou_pred = mask_iou_head(mask_feats, pos_mask_pred) + pos_mask_iou_pred = mask_iou_pred[range(mask_iou_pred.size(0)), + pos_labels] + + mask_iou_head.loss_and_target(pos_mask_iou_pred, pos_mask_pred, + mask_targets, sampling_results, + batch_gt_instances, train_cfg) + + @parameterized.expand(['cpu', 'cuda']) + def test_mask_iou_head_predict_by_feat(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + mask_iou_head = MaskIoUHead(num_classes=4) + mask_iou_head.to(device=device) + + s = 128 + num_samples = 2 + num_classes = 4 + img_metas = { + 'img_shape': (s, s, 3), + 'scale_factor': (1, 1), + 'ori_shape': (s, s, 3) + } + results = InstanceData(metainfo=img_metas) + results.bboxes = torch.rand((num_samples, 4)).to(device) + results.scores = torch.rand((num_samples, )).to(device) + results.labels = torch.randint( + num_classes, (num_samples, ), dtype=torch.long).to(device) + + mask_feats = torch.rand((num_samples, 256, 14, 14)).to(device) + mask_preds = torch.rand((num_samples, num_classes, 28, 28)).to(device) + mask_iou_preds = mask_iou_head( + mask_feats, mask_preds[range(results.labels.size(0)), + results.labels]) + + mask_iou_head.predict_by_feat( + mask_iou_preds=[mask_iou_preds], results_list=[results]) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_mask_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..4df9dc59e9b3dd0db81d3926643e1f270b3780a2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_mask_head.py @@ -0,0 +1,29 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import SCNetMaskHead + + +class TestSCNetMaskHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + num_classes = 6 + mask_head = SCNetMaskHead( + conv_to_res=True, + num_convs=1, + in_channels=1, + conv_out_channels=1, + num_classes=num_classes) + + x = torch.rand((1, 1, 10, 10)) + results = mask_head(x) + self.assertIsInstance(results, Tensor) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_semantic_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_semantic_head.py new file mode 100644 index 0000000000000000000000000000000000000000..84f787bb7f4d62f87053bf97dfc1141ed11d344a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_heads/test_scnet_semantic_head.py @@ -0,0 +1,33 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized +from torch import Tensor + +from mmdet.models.roi_heads.mask_heads import SCNetSemanticHead + + +class TestSCNetSemanticHead(TestCase): + + @parameterized.expand(['cpu', 'cuda']) + def test_forward_loss(self, device): + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + + semantic_head = SCNetSemanticHead( + num_ins=5, + fusion_level=1, + in_channels=4, + conv_out_channels=4, + num_classes=6) + feats = [ + torch.rand((1, 4, 32 // 2**(i + 1), 32 // 2**(i + 1))) + for i in range(5) + ] + mask_pred, x = semantic_head(feats) + labels = torch.randint(0, 6, (1, 1, 64, 64)) + loss = semantic_head.loss(mask_pred, labels) + self.assertIsInstance(loss, Tensor) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_scoring_roI_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_scoring_roI_head.py new file mode 100644 index 0000000000000000000000000000000000000000..458eb302b00ab20d65052dd89bf57536b62015e9 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_mask_scoring_roI_head.py @@ -0,0 +1,124 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestMaskScoringRoiHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'ms_rcnn/ms-rcnn_r50_fpn_1x_coco.py') + + def test_init(self): + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + self.assertTrue(roi_head.with_mask) + self.assertTrue(roi_head.mask_iou_head) + + def test_mask_scoring_roi_head_loss(self): + """Tests trident roi head predict.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.cuda() + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_bbox = out['loss_bbox'] + loss_mask = out['loss_mask'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_bbox.sum(), 0, 'box loss should be non-zero') + self.assertGreater(loss_mask.sum(), 0, 'mask loss should be non-zero') + + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + empty_bbox_loss = out['loss_bbox'] + empty_mask_loss = out['loss_mask'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_bbox_loss.sum(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_mask_loss.sum(), 0, + 'there should be no mask loss when there are no true boxes') + + def test_mask_scoring_roi_head_predict(self): + """Tests trident roi head predict.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.cuda() + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + roi_head.predict(feats, proposals_list, batch_data_samples) + + def test_mask_scoring_roi_head_forward(self): + """Tests trident roi head forward.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.cuda() + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + + image_shapes = [(3, s, s)] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + roi_head.forward(feats, proposals_list) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_multi_instance_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_multi_instance_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..df7734c5a952cf99853dba21baa84d010b423446 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_multi_instance_roi_head.py @@ -0,0 +1,129 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import Config + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals +from mmdet.utils import register_all_modules + +register_all_modules() + + +def _fake_roi_head(): + """Set a fake roi head config.""" + + roi_head = Config( + dict( + type='MultiInstanceRoIHead', + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', + output_size=7, + sampling_ratio=-1, + aligned=True, + use_torchvision=True), + out_channels=256, + featmap_strides=[4, 8, 16, 32]), + bbox_head=dict( + type='MultiInstanceBBoxHead', + with_refine=False, + num_shared_fcs=2, + 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.], + target_stds=[0.1, 0.1, 0.2, 0.2]), + reg_class_agnostic=False, + loss_cls=dict( + type='CrossEntropyLoss', + loss_weight=1.0, + use_sigmoid=False, + reduction='none'), + loss_bbox=dict( + type='SmoothL1Loss', loss_weight=1.0, reduction='none')), + train_cfg=dict( + assigner=dict( + type='MultiInstanceAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.3, + match_low_quality=False, + ignore_iof_thr=-1), + sampler=dict( + type='MultiInsRandomSampler', + num=512, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + pos_weight=-1, + debug=False), + test_cfg=dict( + nms=dict(iou_threshold=0.5), score_thr=0.01, max_per_img=500))) + + return roi_head + + +class TestMultiInstanceRoIHead(TestCase): + + def test_init(self): + """Test init multi instance RoI head.""" + roi_head_cfg = _fake_roi_head() + roi_head = MODELS.build(roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + + def test_standard_roi_head_loss(self): + """Tests multi instance roi head loss when truth is empty and non- + empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + roi_head_cfg = _fake_roi_head() + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then emd loss should be nonzero for + # random inputs + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=False, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss = out['loss_rcnn_emd'] + self.assertGreater(loss.sum(), 0, 'loss should be non-zero') + + # When there is no truth, the emd loss should be zero. + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_loss = out['loss_rcnn_emd'] + self.assertEqual( + empty_loss.sum(), 0, + 'there should be no emd loss when there are no true boxes') diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_pisa_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_pisa_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5820c3977c82207ee9f47cc5947b132281251f1c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_pisa_roi_head.py @@ -0,0 +1,71 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestPISARoIHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'pisa/faster-rcnn_r50_fpn_pisa_1x_coco.py') + + def test_init(self): + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + + @parameterized.expand(['cpu', 'cuda']) + def test_pisa_roi_head(self, device): + """Tests trident roi head predict.""" + if not torch.cuda.is_available() and device == 'cuda': + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + roi_head = MODELS.build(self.roi_head_cfg) + roi_head = roi_head.to(device=device) + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device=device)) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_bbox = out['loss_bbox'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_bbox.sum(), 0, 'box loss should be non-zero') + + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device=device)['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device=device) + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + empty_bbox_loss = out['loss_bbox'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_bbox_loss.sum(), 0, + 'there should be no box loss when there are no true boxes') diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_point_rend_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_point_rend_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..dce8bf498eaf7d7fd4bae7b618973446c6b502c4 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_point_rend_roi_head.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads import PointRendRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestHTCRoIHead(TestCase): + + @parameterized.expand( + ['point_rend/point-rend_r50-caffe_fpn_ms-1x_coco.py']) + def test_init(self, cfg_file): + """Test init Point rend RoI head.""" + # Normal HTC RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + assert roi_head.with_bbox + assert roi_head.with_mask + + @parameterized.expand( + ['point_rend/point-rend_r50-caffe_fpn_ms-1x_coco.py']) + def test_point_rend_roi_head_loss(self, cfg_file): + """Tests htc roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [img_meta['img_shape'] for img_meta in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # Positive rois must not be empty + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + with self.assertRaises(AssertionError): + out = roi_head.loss(feats, proposal_list, batch_data_samples) + + @parameterized.expand( + ['point_rend/point-rend_r50-caffe_fpn_ms-1x_coco.py']) + def test_point_rend_roi_head_predict(self, cfg_file): + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + img_shape_list = [img_meta['img_shape'] for img_meta in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + results = roi_head.predict( + feats, proposal_list, batch_data_samples, rescale=True) + self.assertEqual(results[0].masks.shape[-2:], (s, s)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_roi_extractors/test_generic_roi_extractor.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_roi_extractors/test_generic_roi_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..c5637a4d8c93210b74b5febc1278a26d9a61a7bc --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_roi_extractors/test_generic_roi_extractor.py @@ -0,0 +1,101 @@ +import unittest + +import torch + +from mmdet.models.roi_heads.roi_extractors import GenericRoIExtractor + + +class TestGenericRoIExtractor(unittest.TestCase): + + def test_init(self): + with self.assertRaises(AssertionError): + GenericRoIExtractor( + aggregation='other', + roi_layer=dict( + type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16, + featmap_strides=[4, 8, 16, 32]) + + roi_extractor = GenericRoIExtractor( + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16, + featmap_strides=[4, 8, 16, 32]) + self.assertFalse(roi_extractor.with_pre) + self.assertFalse(roi_extractor.with_post) + + def test_forward(self): + # test with pre/post + cfg = dict( + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16, + featmap_strides=[4, 8, 16, 32], + pre_cfg=dict( + type='ConvModule', + in_channels=16, + out_channels=16, + kernel_size=5, + padding=2, + inplace=False), + post_cfg=dict( + type='ConvModule', + in_channels=16, + out_channels=16, + kernel_size=5, + padding=2, + inplace=False)) + roi_extractor = GenericRoIExtractor(**cfg) + + # empty rois + feats = ( + torch.rand((1, 16, 200, 336)), + torch.rand((1, 16, 100, 168)), + ) + rois = torch.empty((0, 5), dtype=torch.float32) + res = roi_extractor(feats, rois) + self.assertEqual(len(res), 0) + + # single scale feature + rois = torch.tensor([[0.0000, 587.8285, 52.1405, 886.2484, 341.5644]]) + feats = (torch.rand((1, 16, 200, 336)), ) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 16, 7, 7)) + + # multi-scale features + feats = ( + torch.rand((1, 16, 200, 336)), + torch.rand((1, 16, 100, 168)), + torch.rand((1, 16, 50, 84)), + torch.rand((1, 16, 25, 42)), + ) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 16, 7, 7)) + + # test w.o. pre/post concat + cfg = dict( + aggregation='concat', + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16 * 4, + featmap_strides=[4, 8, 16, 32]) + + roi_extractor = GenericRoIExtractor(**cfg) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 64, 7, 7)) + + # test concat channels number + cfg = dict( + aggregation='concat', + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=256 * 5, # 256*5 != 256*4 + featmap_strides=[4, 8, 16, 32]) + + roi_extractor = GenericRoIExtractor(**cfg) + + feats = ( + torch.rand((1, 256, 200, 336)), + torch.rand((1, 256, 100, 168)), + torch.rand((1, 256, 50, 84)), + torch.rand((1, 256, 25, 42)), + ) + # out_channels does not sum of feat channels + with self.assertRaises(AssertionError): + roi_extractor(feats, rois) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_roi_extractors/test_single_level_roi_extractor.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_roi_extractors/test_single_level_roi_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..a401197f107546b9b31982d2f01577b542934df0 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_roi_extractors/test_single_level_roi_extractor.py @@ -0,0 +1,39 @@ +import unittest + +import torch + +from mmdet.models.roi_heads.roi_extractors import SingleRoIExtractor + + +class TestSingleRoIExtractor(unittest.TestCase): + + def test_forward(self): + cfg = dict( + roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), + out_channels=16, + featmap_strides=[4, 8, 16, 32]) + roi_extractor = SingleRoIExtractor(**cfg) + + # empty rois + feats = (torch.rand((1, 16, 200, 336)), ) + rois = torch.empty((0, 5), dtype=torch.float32) + res = roi_extractor(feats, rois) + self.assertEqual(len(res), 0) + + # single scale feature + rois = torch.tensor([[0.0000, 587.8285, 52.1405, 886.2484, 341.5644]]) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 16, 7, 7)) + + # multi-scale features + feats = ( + torch.rand((1, 16, 200, 336)), + torch.rand((1, 16, 100, 168)), + torch.rand((1, 16, 50, 84)), + torch.rand((1, 16, 25, 42)), + ) + res = roi_extractor(feats, rois) + self.assertEqual(res.shape, (1, 16, 7, 7)) + + res = roi_extractor(feats, rois, roi_scale_factor=2.0) + self.assertEqual(res.shape, (1, 16, 7, 7)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_scnet_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_scnet_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9f14530ba7be05ae1cf3903402ff98055a25eb5a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_scnet_roi_head.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from parameterized import parameterized + +from mmdet.models.roi_heads import SCNetRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestSCNetRoIHead(TestCase): + + @parameterized.expand(['scnet/scnet_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + """Test init scnet RoI head.""" + # Normal Cascade Mask R-CNN RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + assert roi_head.with_bbox + assert roi_head.with_mask + assert roi_head.with_semantic + assert roi_head.with_feat_relay + assert roi_head.with_glbctx + + @parameterized.expand(['scnet/scnet_r50_fpn_1x_coco.py']) + def test_scnet_roi_head_loss(self, cfg_file): + """Tests htc roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + with_semantic=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + with_semantic=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss_cls' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + elif 'loss_bbox' in name or 'loss_mask' in name: + self.assertEqual(value.sum(), 0) + + @parameterized.expand(['scnet/scnet_r50_fpn_1x_coco.py']) + def test_scnet_roi_head_predict(self, cfg_file): + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + results = roi_head.predict( + feats, proposal_list, batch_data_samples, rescale=True) + self.assertEqual(results[0].masks.shape[-2:], (s, s)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_sparse_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_sparse_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1182786c0e0da52ac8e5efb294a8478be42dd470 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_sparse_roi_head.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +import torch.nn as nn +from parameterized import parameterized + +from mmdet.models.roi_heads import StandardRoIHead # noqa +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg + + +class TestCascadeRoIHead(TestCase): + + @parameterized.expand(['queryinst/queryinst_r50_fpn_1x_coco.py']) + def test_init(self, cfg_file): + """Test init standard RoI head.""" + # Normal Cascade Mask R-CNN RoI head + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head.init_weights() + assert roi_head.with_bbox + assert roi_head.with_mask + + @parameterized.expand(['queryinst/queryinst_r50_fpn_1x_coco.py']) + def test_cascade_roi_head_loss(self, cfg_file): + """Tests standard roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + img_metas = [{ + 'img_shape': (s, s, 3), + 'scale_factor': 1, + }] + roi_head_cfg = get_roi_head_cfg(cfg_file) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head_cfg.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + img_shape_list = [(3, s, s) for _ in img_metas] + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + # add import elements into proposal + init_proposal_features = nn.Embedding(100, 256).cuda().weight.clone() + for proposal in proposal_list: + proposal.features = init_proposal_features + proposal.imgs_whwh = feats[0].new_tensor([[s, s, s, + s]]).repeat(100, 1) + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + proposal_list = demo_mm_proposals(img_shape_list, 100, device='cuda') + # add import elements into proposal + init_proposal_features = nn.Embedding(100, 256).cuda().weight.clone() + for proposal in proposal_list: + proposal.features = init_proposal_features + proposal.imgs_whwh = feats[0].new_tensor([[s, s, s, + s]]).repeat(100, 1) + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=[(3, s, s)], + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + out = roi_head.loss(feats, proposal_list, batch_data_samples) + for name, value in out.items(): + if 'loss_cls' in name: + self.assertGreaterEqual( + value.sum(), 0, msg='loss should be non-zero') + elif 'loss_bbox' in name or 'loss_mask' in name: + self.assertEqual(value.sum(), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_standard_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_standard_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae95e284406bcf2f26b47d1b6b034c685395d7a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_standard_roi_head.py @@ -0,0 +1,206 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest +from unittest import TestCase + +import torch +from mmengine.config import Config +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals +from mmdet.utils import register_all_modules + +register_all_modules() + + +def _fake_roi_head(with_shared_head=False): + """Set a fake roi head config.""" + if not with_shared_head: + roi_head = Config( + dict( + type='StandardRoIHead', + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', output_size=7, sampling_ratio=0), + out_channels=1, + featmap_strides=[4, 8, 16, 32]), + bbox_head=dict( + type='Shared2FCBBoxHead', + in_channels=1, + fc_out_channels=1, + num_classes=4), + mask_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', output_size=14, sampling_ratio=0), + out_channels=1, + featmap_strides=[4, 8, 16, 32]), + mask_head=dict( + type='FCNMaskHead', + num_convs=1, + in_channels=1, + conv_out_channels=1, + num_classes=4), + train_cfg=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( + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100, + mask_thr_binary=0.5))) + else: + roi_head = Config( + dict( + type='StandardRoIHead', + shared_head=dict( + type='ResLayer', + depth=50, + stage=3, + stride=2, + dilation=1, + style='caffe', + norm_cfg=dict(type='BN', requires_grad=False), + norm_eval=True), + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', output_size=14, sampling_ratio=0), + out_channels=1, + featmap_strides=[16]), + bbox_head=dict( + type='BBoxHead', + with_avg_pool=True, + in_channels=2048, + roi_feat_size=7, + num_classes=4), + mask_roi_extractor=None, + mask_head=dict( + type='FCNMaskHead', + num_convs=0, + in_channels=2048, + conv_out_channels=1, + num_classes=4), + train_cfg=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), + mask_size=14, + pos_weight=-1, + debug=False), + test_cfg=dict( + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.5), + max_per_img=100, + mask_thr_binary=0.5))) + return roi_head + + +class TestStandardRoIHead(TestCase): + + def test_init(self): + """Test init standard RoI head.""" + # Normal Mask R-CNN RoI head + roi_head_cfg = _fake_roi_head() + roi_head = MODELS.build(roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + self.assertTrue(roi_head.with_mask) + + # Mask R-CNN RoI head with shared_head + roi_head_cfg = _fake_roi_head(with_shared_head=True) + roi_head = MODELS.build(roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + self.assertTrue(roi_head.with_mask) + self.assertTrue(roi_head.with_shared_head) + + @parameterized.expand([(False, ), (True, )]) + def test_standard_roi_head_loss(self, with_shared_head): + """Tests standard roi head loss when truth is empty and non-empty.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + s = 256 + roi_head_cfg = _fake_roi_head(with_shared_head=with_shared_head) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + if not with_shared_head: + feats.append( + torch.rand(1, 1, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + else: + feats.append( + torch.rand(1, 1024, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + feats = tuple(feats) + + # When truth is non-empty then both cls, box, and mask loss + # should be nonzero for random inputs + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[1], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + + out = roi_head.loss(feats, proposals_list, batch_data_samples) + loss_cls = out['loss_cls'] + loss_bbox = out['loss_bbox'] + loss_mask = out['loss_mask'] + self.assertGreater(loss_cls.sum(), 0, 'cls loss should be non-zero') + self.assertGreater(loss_bbox.sum(), 0, 'box loss should be non-zero') + self.assertGreater(loss_mask.sum(), 0, 'mask loss should be non-zero') + + # When there is no truth, the cls loss should be nonzero but + # there should be no box and mask loss. + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + out = roi_head.loss(feats, proposals_list, batch_data_samples) + empty_cls_loss = out['loss_cls'] + empty_bbox_loss = out['loss_bbox'] + empty_mask_loss = out['loss_mask'] + self.assertGreater(empty_cls_loss.sum(), 0, + 'cls loss should be non-zero') + self.assertEqual( + empty_bbox_loss.sum(), 0, + 'there should be no box loss when there are no true boxes') + self.assertEqual( + empty_mask_loss.sum(), 0, + 'there should be no mask loss when there are no true boxes') diff --git a/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_trident_roi_head.py b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_trident_roi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a173b01066cedf0b8915ce17ae22921d8b136827 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_roi_heads/test_trident_roi_head.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import copy +import unittest +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS +from mmdet.testing import demo_mm_inputs, demo_mm_proposals, get_roi_head_cfg +from mmdet.utils import register_all_modules + + +class TestTridentRoIHead(TestCase): + + def setUp(self): + register_all_modules() + self.roi_head_cfg = get_roi_head_cfg( + 'tridentnet/tridentnet_r50-caffe_1x_coco.py') + + def test_init(self): + + roi_head = MODELS.build(self.roi_head_cfg) + self.assertTrue(roi_head.with_bbox) + self.assertTrue(roi_head.with_shared_head) + + def test_trident_roi_head_predict(self): + """Tests trident roi head predict.""" + if not torch.cuda.is_available(): + # RoI pooling only support in GPU + return unittest.skip('test requires GPU and torch+cuda') + + roi_head_cfg = copy.deepcopy(self.roi_head_cfg) + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + s = 256 + feats = [] + for i in range(len(roi_head.bbox_roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 1024, s // (2**(i + 2)), + s // (2**(i + 2))).to(device='cuda')) + + image_shapes = [(3, s, s)] + batch_data_samples = demo_mm_inputs( + batch_size=1, + image_shapes=image_shapes, + num_items=[0], + num_classes=4, + with_mask=True, + device='cuda')['data_samples'] + proposals_list = demo_mm_proposals( + image_shapes=image_shapes, num_proposals=100, device='cuda') + # When `test_branch_idx == 1` + roi_head.predict(feats, proposals_list, batch_data_samples) + # When `test_branch_idx == -1` + roi_head_cfg.test_branch_idx = -1 + roi_head = MODELS.build(roi_head_cfg) + roi_head = roi_head.cuda() + roi_head.predict(feats, proposals_list, batch_data_samples) diff --git a/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_heuristic_fusion_head.py b/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_heuristic_fusion_head.py new file mode 100644 index 0000000000000000000000000000000000000000..89f3168c61f1437e9e173c447322a247b397ded8 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_heuristic_fusion_head.py @@ -0,0 +1,59 @@ +import unittest + +import torch +from mmengine.config import Config +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.evaluation import INSTANCE_OFFSET +from mmdet.models.seg_heads.panoptic_fusion_heads import HeuristicFusionHead + + +class TestHeuristicFusionHead(unittest.TestCase): + + def test_loss(self): + head = HeuristicFusionHead(num_things_classes=2, num_stuff_classes=2) + result = head.loss() + self.assertTrue(not head.with_loss) + self.assertDictEqual(result, dict()) + + def test_predict(self): + test_cfg = Config(dict(mask_overlap=0.5, stuff_area_limit=1)) + head = HeuristicFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + mask_results = InstanceData() + mask_results.bboxes = torch.tensor([[0, 0, 1, 1], [1, 1, 2, 2]]) + mask_results.labels = torch.tensor([0, 1]) + mask_results.scores = torch.tensor([0.8, 0.7]) + mask_results.masks = torch.tensor([[[1, 0], [0, 0]], [[0, 0], + [0, 1]]]).bool() + + seg_preds_list = [ + torch.tensor([[[0.2, 0.7], [0.3, 0.1]], [[0.2, 0.2], [0.6, 0.1]], + [[0.6, 0.1], [0.1, 0.8]]]) + ] + target_list = [ + torch.tensor([[0 + 1 * INSTANCE_OFFSET, 2], + [3, 1 + 2 * INSTANCE_OFFSET]]) + ] + results_list = head.predict([mask_results], seg_preds_list) + for target, result in zip(target_list, results_list): + assert_allclose(result.sem_seg[0], target) + + # test with no thing + head = HeuristicFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + mask_results = InstanceData() + mask_results.bboxes = torch.zeros((0, 4)) + mask_results.labels = torch.zeros((0, )).long() + mask_results.scores = torch.zeros((0, )) + mask_results.masks = torch.zeros((0, 2, 2), dtype=torch.bool) + seg_preds_list = [ + torch.tensor([[[0.2, 0.7], [0.3, 0.1]], [[0.2, 0.2], [0.6, 0.1]], + [[0.6, 0.1], [0.1, 0.8]]]) + ] + target_list = [torch.tensor([[4, 2], [3, 4]])] + + results_list = head.predict([mask_results], seg_preds_list) + for target, result in zip(target_list, results_list): + assert_allclose(result.sem_seg[0], target) diff --git a/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_maskformer_fusion_head.py b/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_maskformer_fusion_head.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0be936de61e36f6c28ae8b8c47770da5c1be1a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_maskformer_fusion_head.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch +from mmengine.config import Config + +from mmdet.models.seg_heads.panoptic_fusion_heads import MaskFormerFusionHead +from mmdet.structures import DetDataSample + + +class TestMaskFormerFusionHead(unittest.TestCase): + + def test_loss(self): + head = MaskFormerFusionHead(num_things_classes=2, num_stuff_classes=2) + result = head.loss() + self.assertTrue(not head.with_loss) + self.assertDictEqual(result, dict()) + + def test_predict(self): + mask_cls_results = torch.rand((2, 10, 5)) + mask_pred_results = torch.rand((2, 10, 32, 32)) + batch_data_samples = [ + DetDataSample( + metainfo={ + 'batch_input_shape': (32, 32), + 'img_shape': (32, 30), + 'ori_shape': (30, 30) + }), + DetDataSample( + metainfo={ + 'batch_input_shape': (32, 32), + 'img_shape': (32, 30), + 'ori_shape': (29, 30) + }) + ] + + # get panoptic and instance segmentation results + test_cfg = Config( + dict( + panoptic_on=True, + semantic_on=False, + instance_on=True, + max_per_image=10, + object_mask_thr=0.3, + iou_thr=0.3, + filter_low_score=False)) + head = MaskFormerFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + results = head.predict( + mask_cls_results, + mask_pred_results, + batch_data_samples, + rescale=False) + for i in range(len(results)): + self.assertEqual(results[i]['pan_results'].sem_seg.shape[-2:], + batch_data_samples[i].img_shape) + self.assertEqual(results[i]['ins_results'].masks.shape[-2:], + batch_data_samples[i].img_shape) + + results = head.predict( + mask_cls_results, + mask_pred_results, + batch_data_samples, + rescale=True) + for i in range(len(results)): + self.assertEqual(results[i]['pan_results'].sem_seg.shape[-2:], + batch_data_samples[i].ori_shape) + self.assertEqual(results[i]['ins_results'].masks.shape[-2:], + batch_data_samples[i].ori_shape) + + # get empty results + test_cfg = Config( + dict( + panoptic_on=False, + semantic_on=False, + instance_on=False, + max_per_image=10, + object_mask_thr=0.3, + iou_thr=0.3, + filter_low_score=False)) + head = MaskFormerFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + results = head.predict( + mask_cls_results, + mask_pred_results, + batch_data_samples, + rescale=True) + for i in range(len(results)): + self.assertEqual(results[i], dict()) + + # semantic segmentation is not supported + test_cfg = Config( + dict( + panoptic_on=False, + semantic_on=True, + instance_on=False, + max_per_image=10, + object_mask_thr=0.3, + iou_thr=0.3, + filter_low_score=False)) + head = MaskFormerFusionHead( + num_things_classes=2, num_stuff_classes=2, test_cfg=test_cfg) + with self.assertRaises(AssertionError): + results = head.predict( + mask_cls_results, + mask_pred_results, + batch_data_samples, + rescale=True) diff --git a/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_panoptic_fpn_head.py b/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_panoptic_fpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f7471f246ea4cdaa7c5ccf949a2d3a9ab01fa49b --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_seg_heads/test_panoptic_fpn_head.py @@ -0,0 +1,70 @@ +import unittest + +import torch +from mmengine.structures import PixelData +from mmengine.testing import assert_allclose + +from mmdet.models.seg_heads import PanopticFPNHead +from mmdet.structures import DetDataSample + + +class TestPanopticFPNHead(unittest.TestCase): + + def test_init_weights(self): + head = PanopticFPNHead( + num_things_classes=2, + num_stuff_classes=2, + in_channels=32, + inner_channels=32) + head.init_weights() + assert_allclose(head.conv_logits.bias.data, + torch.zeros_like(head.conv_logits.bias.data)) + + def test_loss(self): + head = PanopticFPNHead( + num_things_classes=2, + num_stuff_classes=2, + in_channels=32, + inner_channels=32, + start_level=0, + end_level=1) + x = [torch.rand((2, 32, 8, 8)), torch.rand((2, 32, 4, 4))] + data_sample1 = DetDataSample() + data_sample1.gt_sem_seg = PixelData( + sem_seg=torch.randint(0, 4, (1, 7, 8))) + data_sample2 = DetDataSample() + data_sample2.gt_sem_seg = PixelData( + sem_seg=torch.randint(0, 4, (1, 7, 8))) + batch_data_samples = [data_sample1, data_sample2] + results = head.loss(x, batch_data_samples) + self.assertIsInstance(results, dict) + + def test_predict(self): + head = PanopticFPNHead( + num_things_classes=2, + num_stuff_classes=2, + in_channels=32, + inner_channels=32, + start_level=0, + end_level=1) + x = [torch.rand((2, 32, 8, 8)), torch.rand((2, 32, 4, 4))] + img_meta1 = { + 'batch_input_shape': (16, 16), + 'img_shape': (14, 14), + 'ori_shape': (12, 12), + } + img_meta2 = { + 'batch_input_shape': (16, 16), + 'img_shape': (16, 16), + 'ori_shape': (16, 16), + } + batch_img_metas = [img_meta1, img_meta2] + head.eval() + with torch.no_grad(): + seg_preds = head.predict(x, batch_img_metas, rescale=False) + self.assertTupleEqual(seg_preds[0].shape[-2:], (16, 16)) + self.assertTupleEqual(seg_preds[1].shape[-2:], (16, 16)) + + seg_preds = head.predict(x, batch_img_metas, rescale=True) + self.assertTupleEqual(seg_preds[0].shape[-2:], (12, 12)) + self.assertTupleEqual(seg_preds[1].shape[-2:], (16, 16)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/__init__.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-313.pyc b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..452882e23417768598c2c21573122446752b2d07 Binary files /dev/null and b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-313.pyc differ diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-314.pyc b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36bb91644d9cb273c06553cf6633631f3574e6ee Binary files /dev/null and b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-314.pyc differ diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_approx_max_iou_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_approx_max_iou_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9975b91d063dedf77273f7bd4b9acf8c8f517a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_approx_max_iou_assigner.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import ApproxMaxIoUAssigner + + +class TestApproxIoUAssigner(TestCase): + + def test_approx_iou_assigner(self): + assigner = ApproxMaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + bboxes = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData() + pred_instances.priors = bboxes + pred_instances.approxs = bboxes[:, None, :] + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([1, 0, 2, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_approx_iou_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + assigner = ApproxMaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + bboxes = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([]) + gt_labels = torch.LongTensor([]) + + pred_instances = InstanceData() + pred_instances.priors = bboxes + pred_instances.approxs = bboxes[:, None, :] + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_approx_iou_assigner_with_empty_boxes(self): + """Test corner case where an network might predict no boxes.""" + assigner = ApproxMaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + bboxes = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData() + pred_instances.priors = bboxes + pred_instances.approxs = bboxes[:, None, :] + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + self.assertEqual(len(assign_result.gt_inds), 0) + + def test_approx_iou_assigner_with_empty_boxes_and_gt(self): + """Test corner case where an network might predict no boxes and no + gt.""" + assigner = ApproxMaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + bboxes = torch.empty((0, 4)) + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.LongTensor([]) + + pred_instances = InstanceData() + pred_instances.priors = bboxes + pred_instances.approxs = bboxes[:, None, :] + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_atss_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_atss_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..8cce7e3bfc03c71182ecc6225396c4f167b60cd8 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_atss_assigner.py @@ -0,0 +1,147 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import ATSSAssigner + + +class TestATSSAssigner(TestCase): + + def test_atss_assigner(self): + atss_assigner = ATSSAssigner(topk=9) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_bboxes = [4] + + assign_result = atss_assigner.assign(pred_instances, num_level_bboxes, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + expected_gt_inds = torch.LongTensor([1, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_atss_assigner_with_ignore(self): + atss_assigner = ATSSAssigner(topk=9) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [30, 32, 40, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + num_level_bboxes = [4] + assign_result = atss_assigner.assign( + pred_instances, + num_level_bboxes, + gt_instances, + gt_instances_ignore=gt_instances_ignore) + + expected_gt_inds = torch.LongTensor([1, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_atss_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + atss_assigner = ATSSAssigner(topk=9) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_bboxes = [4] + assign_result = atss_assigner.assign(pred_instances, num_level_bboxes, + gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_atss_assigner_with_empty_boxes(self): + """Test corner case where a network might predict no boxes.""" + atss_assigner = ATSSAssigner(topk=9) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_bboxes = [0] + assign_result = atss_assigner.assign(pred_instances, num_level_bboxes, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_atss_assigner_with_empty_boxes_and_ignore(self): + """Test corner case where a network might predict no boxes and + ignore_iof_thr is on.""" + atss_assigner = ATSSAssigner(topk=9) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + num_level_bboxes = [0] + + assign_result = atss_assigner.assign( + pred_instances, + num_level_bboxes, + gt_instances, + gt_instances_ignore=gt_instances_ignore) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_atss_assigner_with_empty_boxes_and_gt(self): + """Test corner case where a network might predict no boxes and no + gt.""" + atss_assigner = ATSSAssigner(topk=9) + priors = torch.empty((0, 4)) + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.empty(0) + num_level_bboxes = [0] + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = atss_assigner.assign(pred_instances, num_level_bboxes, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_center_region_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_center_region_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..b98768fb3929e40f91d68410062f6888ad355251 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_center_region_assigner.py @@ -0,0 +1,149 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import CenterRegionAssigner + + +class TestCenterRegionAssigner(TestCase): + + def test_center_region_assigner(self): + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + + assign_result = center_region_assigner.assign(pred_instances, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + expected_gt_inds = torch.LongTensor([1, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + expected_shadowed_labels = torch.LongTensor([[2, 3]]) + shadowed_labels = assign_result.get_extra_property('shadowed_labels') + self.assertTrue(torch.all(shadowed_labels == expected_shadowed_labels)) + + def test_center_region_assigner_with_ignore(self): + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [30, 32, 40, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + assign_result = center_region_assigner.assign( + pred_instances, + gt_instances, + gt_instances_ignore=gt_instances_ignore) + + expected_gt_inds = torch.LongTensor([1, 0, 0, -1]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_center_region_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = center_region_assigner.assign(pred_instances, + gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_center_region_assigner_with_empty_boxes(self): + """Test corner case where a network might predict no boxes.""" + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = center_region_assigner.assign(pred_instances, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_center_region_assigner_with_empty_boxes_and_ignore(self): + """Test corner case where a network might predict no boxes and + ignore_iof_thr is on.""" + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + + assign_result = center_region_assigner.assign( + pred_instances, + gt_instances, + gt_instances_ignore=gt_instances_ignore) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_center_region_assigner_with_empty_boxes_and_gt(self): + """Test corner case where a network might predict no boxes and no + gt.""" + center_region_assigner = CenterRegionAssigner( + pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01) + priors = torch.empty((0, 4)) + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = center_region_assigner.assign(pred_instances, + gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_dala_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_dala_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..f42817f67deefa30f1065ec4c24e303da48c568c --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_dala_assigner.py @@ -0,0 +1,115 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import (DalaAssigner, + DalaPositiveQuota, + bbox_similarity_distance, + geometry_balanced_similarity, + level_aware_similarity, + normalized_wasserstein_similarity) + + +def test_dala_similarity_distance(): + boxes = torch.tensor([[0., 0., 10., 10.]]) + anchors = torch.tensor([[0., 0., 10., 10.], [10., 0., 20., 10.]]) + similarities = bbox_similarity_distance(anchors, boxes) + assert similarities.shape == (2, 1) + assert torch.allclose(similarities[0], torch.ones(1)) + assert 0 < similarities[1, 0] < similarities[0, 0] + + +def test_s1_normalized_wasserstein_similarity(): + boxes = torch.tensor([[0., 0., 10., 10.]]) + anchors = torch.tensor([[0., 0., 10., 10.], [2., 0., 12., 10.]]) + similarities = normalized_wasserstein_similarity( + anchors, boxes, normalizer=32.) + assert torch.allclose(similarities[0], torch.ones(1)) + assert 0 < similarities[1, 0] < similarities[0, 0] + + +def test_s2_geometry_balanced_similarity(): + boxes = torch.tensor([[0., 0., 10., 10.]]) + equal_size = torch.tensor([[2., 0., 12., 10.]]) + mismatched_size = torch.tensor([[2., 0., 22., 20.]]) + + # S2 exactly recovers S0 when anchor and GT sizes are equal. + assert torch.allclose( + geometry_balanced_similarity(equal_size, boxes), + bbox_similarity_distance(equal_size, boxes)) + # For a size-mismatched and off-centre anchor, the geometric denominator + # removes the artificial location tolerance of the larger anchor. + assert torch.all( + geometry_balanced_similarity(mismatched_size, boxes) < + bbox_similarity_distance(mismatched_size, boxes)) + + +def test_s3_level_aware_similarity(): + boxes = torch.tensor([[0., 0., 10., 10.]]) + anchors = torch.tensor([[0., 0., 10., 10.], [0., 0., 20., 20.]]) + level_ids = torch.tensor([0, 1]) + base = bbox_similarity_distance(anchors, boxes) + similarities = level_aware_similarity( + anchors, boxes, level_ids, level_lambda=1.) + + assert torch.allclose(similarities[0], base[0]) + assert torch.allclose(similarities[1] / base[1], + torch.exp(torch.tensor([-1.]))) + assert torch.allclose( + level_aware_similarity( + anchors, boxes, level_ids, level_lambda=0.), base) + + +def test_s3_assigner_requires_level_ids(): + assigner = DalaAssigner(similarity_mode='s3', sync_stats=False) + pred_instances = InstanceData( + priors=torch.tensor([[0., 0., 10., 10.]])) + gt_instances = InstanceData( + bboxes=torch.tensor([[0., 0., 10., 10.]]), labels=torch.tensor([0])) + try: + assigner.assign(pred_instances, gt_instances) + except ValueError as error: + assert 'level_ids' in str(error) + else: + raise AssertionError('S3 must reject priors without FPN level IDs') + + +def test_dala_positive_quota_is_checkpointable(): + tracker = DalaPositiveQuota(sync_stats=False) + quotas = tracker(torch.tensor([2., 8.])) + assert torch.equal(quotas, torch.tensor([1, 1])) + assert tracker.density_sum.item() == 10 + assert tracker.density_count.item() == 2 + + restored = DalaPositiveQuota(sync_stats=False) + restored.load_state_dict(tracker.state_dict()) + assert restored.density_sum.item() == 10 + assert restored.density_count.item() == 2 + + +def test_dala_assigner_positive_ignore_and_negative(): + assigner = DalaAssigner(sync_stats=False) + pred_instances = InstanceData( + priors=torch.tensor([ + [0., 0., 10., 10.], + [1., 1., 9., 9.], + [20., 20., 30., 30.], + ])) + gt_instances = InstanceData( + bboxes=torch.tensor([[0., 0., 10., 10.]]), labels=torch.tensor([3])) + + result = assigner.assign(pred_instances, gt_instances) + # Density is two and Equation (4) selects one: exact match is positive, + # the other inside anchor is ignored, and the outside anchor is negative. + assert torch.equal(result.gt_inds, torch.tensor([1, -1, 0])) + assert torch.equal(result.labels, torch.tensor([3, -1, -1])) + + +def test_dala_assigner_empty_ground_truth(): + assigner = DalaAssigner(sync_stats=False) + pred_instances = InstanceData(priors=torch.tensor([[0., 0., 10., 10.]])) + gt_instances = InstanceData( + bboxes=torch.empty((0, 4)), + labels=torch.empty((0, ), dtype=torch.long)) + result = assigner.assign(pred_instances, gt_instances) + assert torch.equal(result.gt_inds, torch.tensor([0])) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_dynamic_soft_label_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_dynamic_soft_label_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..233f6a1bc1d060e5281ca9f213193bc53110e28d --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_dynamic_soft_label_assigner.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import DynamicSoftLabelAssigner +from mmdet.structures.bbox import HorizontalBoxes + + +class TestDynamicSoftLabelAssigner(TestCase): + + def test_assign(self): + assigner = DynamicSoftLabelAssigner( + soft_center_radius=3.0, topk=1, iou_weight=3.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43], [4, 5, 6, 7]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43]]), + labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_no_valid_bboxes(self): + assigner = DynamicSoftLabelAssigner( + soft_center_radius=3.0, topk=1, iou_weight=3.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[123, 123, 143, 143], [114, 151, 161, 171]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [55, 55, 8, 8]])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[0, 0, 1, 1]]), labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_empty_gt(self): + assigner = DynamicSoftLabelAssigner( + soft_center_radius=3.0, topk=1, iou_weight=3.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[[30, 40, 50, 60]], [[4, 5, 6, 7]]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[0, 12, 23, 34], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=torch.empty(0, 4), labels=torch.empty(0)) + + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_box_type_input(self): + assigner = DynamicSoftLabelAssigner( + soft_center_radius=3.0, topk=1, iou_weight=3.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43], [4, 5, 6, 7]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=HorizontalBoxes(torch.Tensor([[23, 23, 43, 43]])), + labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_grid_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_grid_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4b1374be2e196315c051abd9904de6f995170e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_grid_assigner.py @@ -0,0 +1,81 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import GridAssigner + + +class TestGridAssigner(TestCase): + + def test_assign(self): + assigner = GridAssigner(pos_iou_thr=0.5, neg_iou_thr=0.3) + pred_instances = InstanceData( + priors=torch.Tensor([[23, 23, 43, 43], [4, 5, 6, 7]]), + responsible_flags=torch.BoolTensor([1, 1])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43]]), + labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + # invalid neg_iou_thr + with self.assertRaises(AssertionError): + assigner = GridAssigner( + pos_iou_thr=0.5, neg_iou_thr=[0.3, 0.1, 0.4]) + assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + # multi-neg_iou_thr + assigner = GridAssigner(pos_iou_thr=0.5, neg_iou_thr=(0.1, 0.3)) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([1, -1]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + # gt_max_assign_all=False + assigner = GridAssigner( + pos_iou_thr=0.5, neg_iou_thr=0.3, gt_max_assign_all=False) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + # large min_pos_iou + assigner = GridAssigner( + pos_iou_thr=0.5, neg_iou_thr=0.3, min_pos_iou=1) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_empty_gt(self): + assigner = GridAssigner(pos_iou_thr=0.5, neg_iou_thr=0.3) + pred_instances = InstanceData( + priors=torch.Tensor([[0, 12, 23, 34], [4, 5, 6, 7]]), + responsible_flags=torch.BoolTensor([1, 1])) + gt_instances = InstanceData( + bboxes=torch.empty(0, 4), labels=torch.empty(0)) + + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_empty_priors(self): + assigner = GridAssigner(pos_iou_thr=0.5, neg_iou_thr=0.3) + pred_instances = InstanceData( + priors=torch.Tensor(torch.empty(0, 4)), + responsible_flags=torch.empty(0)) + gt_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43]]), + labels=torch.LongTensor([0])) + + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_hungarian_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_hungarian_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..923d3b79f1a88cb2b217b47e3f46b1b5671be435 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_hungarian_assigner.py @@ -0,0 +1,148 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import HungarianAssigner + + +class TestHungarianAssigner(TestCase): + + def test_init(self): + with self.assertRaises(AssertionError): + HungarianAssigner([]) + + def test_hungarian_match_assigner(self): + assigner = HungarianAssigner([ + dict(type='ClassificationCost', weight=1.), + dict(type='BBoxL1Cost', weight=5.0), + dict(type='IoUCost', iou_mode='giou', weight=2.0) + ]) + + # test no gt bboxes + gt_instances = InstanceData() + gt_instances.bboxes = torch.empty((0, 4)).float() + gt_instances.labels = torch.empty((0, )).long() + pred_instances = InstanceData() + pred_instances.scores = torch.rand((10, 81)) + pred_instances.bboxes = torch.rand((10, 4)) + img_meta = dict(img_shape=(10, 8)) + + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds == 0)) + self.assertTrue(torch.all(assign_result.labels == -1)) + + # test with gt bboxes + gt_instances.bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_instances.labels = torch.LongTensor([1, 20]) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + def test_bbox_match_cost(self): + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_instances.labels = torch.LongTensor([1, 20]) + pred_instances = InstanceData() + pred_instances.scores = torch.rand((10, 81)) + pred_instances.bboxes = torch.rand((10, 4)) + img_meta = dict(img_shape=(10, 8)) + + # test IoUCost + assigner = HungarianAssigner( + ConfigDict(dict(type='IoUCost', iou_mode='iou'))) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + # test BBoxL1Cost + assigner = HungarianAssigner(ConfigDict(dict(type='BBoxL1Cost'))) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + def test_cls_match_cost(self): + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_instances.labels = torch.LongTensor([1, 20]) + pred_instances = InstanceData() + pred_instances.scores = torch.rand((10, 81)) + pred_instances.bboxes = torch.rand((10, 4)) + img_meta = dict(img_shape=(10, 8)) + + # test FocalLossCost + assigner = HungarianAssigner(dict(type='FocalLossCost')) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + # test ClassificationCost + assigner = HungarianAssigner(dict(type='ClassificationCost')) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.bboxes.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.bboxes.size(0)) + + def test_mask_match_cost(self): + gt_instances = InstanceData() + gt_instances.masks = torch.randint(0, 2, (2, 10, 10)).long() + gt_instances.labels = torch.LongTensor([1, 20]) + + pred_instances = InstanceData() + pred_instances.masks = torch.rand((4, 10, 10)) + pred_instances.scores = torch.rand((4, 25)) + img_meta = dict(img_shape=(10, 10)) + + # test DiceCost + assigner = HungarianAssigner(dict(type='DiceCost')) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.masks.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.masks.size(0)) + + # test CrossEntropyLossCost + assigner = HungarianAssigner(dict(type='CrossEntropyLossCost')) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.masks.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.masks.size(0)) + + # test FocalLossCost + assigner = HungarianAssigner( + dict(type='FocalLossCost', binary_input=True)) + assign_result = assigner.assign( + pred_instances, gt_instances, img_meta=img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_instances.masks.size(0)) + self.assertEqual((assign_result.labels > -1).sum(), + gt_instances.masks.size(0)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_max_iou_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_max_iou_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..958933a784835116e495208ea5d0514bc3b58546 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_max_iou_assigner.py @@ -0,0 +1,162 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Tests the Assigner objects. + +CommandLine: + pytest tests/test_core/test_bbox/test_assigners/test_max_iou_assigner.py + xdoctest tests/test_core/test_bbox/test_assigners/test_max_iou_assigner.py zero +""" # noqa +import pytest +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import MaxIoUAssigner + + +@pytest.mark.parametrize('neg_iou_thr', [0.5, (0, 0.5)]) +def test_max_iou_assigner(neg_iou_thr): + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=neg_iou_thr, + ) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + + assign_result = self.assign(pred_instances, gt_instances) + assert len(assign_result.gt_inds) == 4 + assert len(assign_result.labels) == 4 + + expected_gt_inds = torch.LongTensor([1, 0, 2, 0]) + assert torch.all(assign_result.gt_inds == expected_gt_inds) + + +def test_max_iou_assigner_with_ignore(): + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ignore_iof_thr=0.5, + ignore_wrt_candidates=False, + ) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [30, 32, 40, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + assign_result = self.assign( + pred_instances, gt_instances, gt_instances_ignore=gt_instances_ignore) + + expected_gt_inds = torch.LongTensor([1, 0, 2, -1]) + assert torch.all(assign_result.gt_inds == expected_gt_inds) + + +def test_max_iou_assigner_with_empty_gt(): + """Test corner case where an image might have no true detections.""" + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = self.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + assert torch.all(assign_result.gt_inds == expected_gt_inds) + + +def test_max_iou_assigner_with_empty_priors(): + """Test corner case where a network might predict no boxes.""" + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + # Test with gt_labels + assign_result = self.assign(pred_instances, gt_instances) + assert len(assign_result.gt_inds) == 0 + assert tuple(assign_result.labels.shape) == (0, ) + + +def test_max_iou_assigner_with_empty_boxes_and_ignore(): + """Test corner case where a network might predict no boxes and + ignore_iof_thr is on.""" + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ignore_iof_thr=0.5, + ) + priors = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + + # Test with gt_labels + assign_result = self.assign( + pred_instances, gt_instances, gt_instances_ignore=gt_instances_ignore) + assert len(assign_result.gt_inds) == 0 + assert tuple(assign_result.labels.shape) == (0, ) + + +def test_max_iou_assigner_with_empty_priors_and_gt(): + """Test corner case where a network might predict no boxes and no gt.""" + self = MaxIoUAssigner( + pos_iou_thr=0.5, + neg_iou_thr=0.5, + ) + priors = torch.empty(0, 4) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = self.assign(pred_instances, gt_instances) + assert len(assign_result.gt_inds) == 0 diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_point_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_point_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1e38cf14c298ec17f038e00e7af9e36b4029bf --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_point_assigner.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import unittest + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import PointAssigner + + +class TestPointAssigner(unittest.TestCase): + + def test_point_assigner(self): + assigner = PointAssigner() + pred_instances = InstanceData() + pred_instances.priors = torch.FloatTensor([ + # [x, y, stride] + [0, 0, 1], + [10, 10, 1], + [5, 5, 1], + [32, 32, 1], + ]) + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_instances.labels = torch.LongTensor([0, 1]) + assign_result = assigner.assign(pred_instances, gt_instances) + expected_gt_inds = torch.LongTensor([1, 2, 1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_point_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + assigner = PointAssigner() + pred_instances = InstanceData() + pred_instances.priors = torch.FloatTensor([ + # [x, y, stride] + [0, 0, 1], + [10, 10, 1], + [5, 5, 1], + [32, 32, 1], + ]) + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([]) + gt_instances.labels = torch.LongTensor([]) + assign_result = assigner.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_point_assigner_with_empty_boxes_and_gt(self): + """Test corner case where an image might predict no points and no + gt.""" + assigner = PointAssigner() + pred_instances = InstanceData() + pred_instances.priors = torch.FloatTensor([]) + gt_instances = InstanceData() + gt_instances.bboxes = torch.FloatTensor([]) + gt_instances.labels = torch.LongTensor([]) + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_region_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_region_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..6a73b680333654a487a19cbfdd29b17ec0a24300 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_region_assigner.py @@ -0,0 +1,138 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.config import ConfigDict +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import RegionAssigner + + +class TestRegionAssigner(TestCase): + + def setUp(self): + self.img_meta = ConfigDict(dict(img_shape=(256, 256))) + self.featmap_sizes = [(64, 64)] + self.anchor_scale = 10 + self.anchor_strides = [1] + + def test_region_assigner(self): + region_assigner = RegionAssigner(center_ratio=0.5, ignore_ratio=0.8) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + valid_flags = torch.BoolTensor([1, 1, 1, 1]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_anchors = [4] + + assign_result = region_assigner.assign( + pred_instances, gt_instances, self.img_meta, self.featmap_sizes, + num_level_anchors, self.anchor_scale, self.anchor_strides) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + expected_gt_inds = torch.LongTensor([1, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_region_assigner_with_ignore(self): + region_assigner = RegionAssigner(center_ratio=0.5) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [30, 32, 40, 42], + ]) + valid_flags = torch.BoolTensor([1, 1, 1, 1]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + gt_bboxes_ignore = torch.Tensor([ + [30, 30, 40, 40], + ]) + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + gt_instances_ignore = InstanceData(bboxes=gt_bboxes_ignore) + num_level_anchors = [4] + with self.assertRaises(NotImplementedError): + region_assigner.assign( + pred_instances, + gt_instances, + self.img_meta, + self.featmap_sizes, + num_level_anchors, + self.anchor_scale, + self.anchor_strides, + gt_instances_ignore=gt_instances_ignore) + + def test_region_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + region_assigner = RegionAssigner(center_ratio=0.5) + priors = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + valid_flags = torch.BoolTensor([1, 1, 1, 1]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_anchors = [4] + assign_result = region_assigner.assign( + pred_instances, gt_instances, self.img_meta, self.featmap_sizes, + num_level_anchors, self.anchor_scale, self.anchor_strides) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) + + def test_atss_assigner_with_empty_boxes(self): + """Test corner case where a network might predict no boxes.""" + region_assigner = RegionAssigner(center_ratio=0.5) + priors = torch.empty((0, 4)) + valid_flags = torch.BoolTensor([]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + num_level_anchors = [0] + assign_result = region_assigner.assign( + pred_instances, gt_instances, self.img_meta, self.featmap_sizes, + num_level_anchors, self.anchor_scale, self.anchor_strides) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertTrue(tuple(assign_result.labels.shape) == (0, )) + + def test_atss_assigner_with_empty_boxes_and_gt(self): + """Test corner case where a network might predict no boxes and no + gt.""" + region_assigner = RegionAssigner(center_ratio=0.5) + priors = torch.empty((0, 4)) + valid_flags = torch.BoolTensor([]) + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.empty(0) + num_level_anchors = [0] + + pred_instances = InstanceData(priors=priors, valid_flags=valid_flags) + gt_instances = InstanceData(bboxes=gt_bboxes, labels=gt_labels) + assign_result = region_assigner.assign( + pred_instances, gt_instances, self.img_meta, self.featmap_sizes, + num_level_anchors, self.anchor_scale, self.anchor_strides) + self.assertEqual(len(assign_result.gt_inds), 0) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_simota_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_simota_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..0517f75d23a73e68a9bbc8b34338357167f9276e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_simota_assigner.py @@ -0,0 +1,66 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import SimOTAAssigner + + +class TestSimOTAAssigner(TestCase): + + def test_assign(self): + assigner = SimOTAAssigner( + center_radius=2.5, + candidate_topk=1, + iou_weight=3.0, + cls_weight=1.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43], [4, 5, 6, 7]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[23, 23, 43, 43]]), + labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([1, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_no_valid_bboxes(self): + assigner = SimOTAAssigner( + center_radius=2.5, + candidate_topk=1, + iou_weight=3.0, + cls_weight=1.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[123, 123, 143, 143], [114, 151, 161, 171]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[30, 30, 8, 8], [55, 55, 8, 8]])) + gt_instances = InstanceData( + bboxes=torch.Tensor([[0, 0, 1, 1]]), labels=torch.LongTensor([0])) + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_assign_with_empty_gt(self): + assigner = SimOTAAssigner( + center_radius=2.5, + candidate_topk=1, + iou_weight=3.0, + cls_weight=1.0) + pred_instances = InstanceData( + bboxes=torch.Tensor([[[30, 40, 50, 60]], [[4, 5, 6, 7]]]), + scores=torch.FloatTensor([[0.2], [0.8]]), + priors=torch.Tensor([[0, 12, 23, 34], [4, 5, 6, 7]])) + gt_instances = InstanceData( + bboxes=torch.empty(0, 4), labels=torch.empty(0)) + + assign_result = assigner.assign( + pred_instances=pred_instances, gt_instances=gt_instances) + expected_gt_inds = torch.LongTensor([0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_task_aligned_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_task_aligned_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..9603b897f87b2f87bc0bce55f11e8adeefedd761 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_task_aligned_assigner.py @@ -0,0 +1,57 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData + +from mmdet.models.task_modules.assigners import TaskAlignedAssigner + + +class TestTaskAlignedAssigner(TestCase): + + def test_task_aligned_assigner(self): + + with self.assertRaises(AssertionError): + TaskAlignedAssigner(topk=0) + + assigner = TaskAlignedAssigner(topk=13) + pred_score = torch.FloatTensor([[0.1, 0.2], [0.2, 0.3], [0.3, 0.4], + [0.4, 0.5]]) + pred_bbox = torch.FloatTensor([ + [1, 1, 12, 8], + [4, 4, 20, 20], + [1, 5, 15, 15], + [30, 5, 32, 42], + ]) + anchor = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([0, 1]) + pred_instances = InstanceData() + pred_instances.priors = anchor + pred_instances.bboxes = pred_bbox + pred_instances.scores = pred_score + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + # test empty gt + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0, 2).long() + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + self.assertTrue(torch.all(assign_result.gt_inds == expected_gt_inds)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_task_uniform_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_task_uniform_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4fbca35c758ba3436cb6b4d05172bf26f211a9 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_task_uniform_assigner.py @@ -0,0 +1,93 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.structures import InstanceData +from mmengine.testing import assert_allclose + +from mmdet.models.task_modules.assigners import UniformAssigner + + +class TestUniformAssigner(TestCase): + + def test_uniform_assigner(self): + assigner = UniformAssigner(0.15, 0.7, 1) + pred_bbox = torch.FloatTensor([ + [1, 1, 12, 8], + [4, 4, 20, 20], + [1, 5, 15, 15], + [30, 5, 32, 42], + ]) + anchor = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + pred_instances = InstanceData() + pred_instances.priors = anchor + pred_instances.decoder_priors = pred_bbox + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertEqual(len(assign_result.gt_inds), 4) + self.assertEqual(len(assign_result.labels), 4) + + expected_gt_inds = torch.LongTensor([-1, 0, 2, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_uniform_assigner_with_empty_gt(self): + """Test corner case where an image might have no true detections.""" + assigner = UniformAssigner(0.15, 0.7, 1) + pred_bbox = torch.FloatTensor([ + [1, 1, 12, 8], + [4, 4, 20, 20], + [1, 5, 15, 15], + [30, 5, 32, 42], + ]) + anchor = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [5, 5, 15, 15], + [32, 32, 38, 42], + ]) + gt_bboxes = torch.empty(0, 4) + gt_labels = torch.empty(0) + pred_instances = InstanceData() + pred_instances.priors = anchor + pred_instances.decoder_priors = pred_bbox + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + + expected_gt_inds = torch.LongTensor([0, 0, 0, 0]) + assert_allclose(assign_result.gt_inds, expected_gt_inds) + + def test_uniform_assigner_with_empty_boxes(self): + """Test corner case where a network might predict no boxes.""" + assigner = UniformAssigner(0.15, 0.7, 1) + pred_bbox = torch.empty((0, 4)) + anchor = torch.empty((0, 4)) + gt_bboxes = torch.FloatTensor([ + [0, 0, 10, 9], + [0, 10, 10, 19], + ]) + gt_labels = torch.LongTensor([2, 3]) + pred_instances = InstanceData() + pred_instances.priors = anchor + pred_instances.decoder_priors = pred_bbox + gt_instances = InstanceData() + gt_instances.bboxes = gt_bboxes + gt_instances.labels = gt_labels + + # Test with gt_labels + assign_result = assigner.assign(pred_instances, gt_instances) + self.assertEqual(len(assign_result.gt_inds), 0) + self.assertEqual(tuple(assign_result.labels.shape), (0, )) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_topk_hungarian_assigner.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_topk_hungarian_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..7273787bf0474b9bc825630f88bfe4b8b8feeaac --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_topk_hungarian_assigner.py @@ -0,0 +1,114 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import ConfigDict + +from mmdet.models.task_modules.assigners import TopkHungarianAssigner + + +class TestTopkHungarianAssigner(TestCase): + + def test_init(self): + with self.assertRaises(AssertionError): + TopkHungarianAssigner(topk=0) + + def test_topk_hungarian_match_assigner(self): + num_classes = 80 + topk = 4 + + pred_class_scores = torch.rand((10, num_classes)) + pred_bboxes = torch.randn((10, 4)) + + assigner = TopkHungarianAssigner(topk=topk) + + # test no gt bboxes + gt_bboxes = torch.empty((0, 4)) + gt_labels = torch.LongTensor([]) + img_meta = dict(img_shape=(10, 8)) + + assign_result = assigner.assign(pred_class_scores, pred_bboxes, + gt_bboxes, gt_labels, img_meta) + + self.assertTrue(torch.all(assign_result.gt_inds == 0)) + self.assertTrue(torch.all(assign_result.labels == -1)) + + # test with gt bboxes + gt_bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_labels = torch.LongTensor([1, 20]) + assign_result = assigner.assign(pred_class_scores, pred_bboxes, + gt_bboxes, gt_labels, img_meta) + + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_bboxes.size(0) * topk) + self.assertEqual((assign_result.labels > -1).sum(), + gt_bboxes.size(0) * topk) + + def test_bbox_match_cost(self): + num_classes = 80 + topk = 4 + + pred_class_scores = torch.rand((10, num_classes)) + pred_bboxes = torch.randn((10, 4)) + + gt_bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_labels = torch.LongTensor([1, 20]) + img_meta = dict(img_shape=(10, 8)) + + # test IoUCost + assigner = TopkHungarianAssigner( + topk=topk, + iou_cost=ConfigDict(dict(type='IoUCost', iou_mode='iou'))) + assign_result = assigner.assign(pred_class_scores, pred_bboxes, + gt_bboxes, gt_labels, img_meta) + + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_bboxes.size(0) * topk) + self.assertEqual((assign_result.labels > -1).sum(), + gt_bboxes.size(0) * topk) + + # test BBoxL1Cost + assigner = TopkHungarianAssigner( + topk=4, reg_cost=ConfigDict(dict(type='BBoxL1Cost'))) + assign_result = assigner.assign(pred_class_scores, pred_bboxes, + gt_bboxes, gt_labels, img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_bboxes.size(0) * topk) + self.assertEqual((assign_result.labels > -1).sum(), + gt_bboxes.size(0) * topk) + + def test_cls_match_cost(self): + num_classes = 80 + topk = 4 + + pred_class_scores = torch.rand((10, num_classes)) + pred_bboxes = torch.randn((10, 4)) + + gt_bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]]) + gt_labels = torch.LongTensor([1, 20]) + img_meta = dict(img_shape=(10, 8)) + + # test FocalLossCost + assigner = TopkHungarianAssigner( + topk=topk, cls_cost=dict(type='FocalLossCost')) + assign_result = assigner.assign(pred_class_scores, pred_bboxes, + gt_bboxes, gt_labels, img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_bboxes.size(0) * topk) + self.assertEqual((assign_result.labels > -1).sum(), + gt_bboxes.size(0) * topk) + + # test ClassificationCost + assigner = TopkHungarianAssigner( + topk=4, cls_cost=dict(type='ClassificationCost')) + assign_result = assigner.assign(pred_class_scores, pred_bboxes, + gt_bboxes, gt_labels, img_meta) + self.assertTrue(torch.all(assign_result.gt_inds > -1)) + self.assertEqual((assign_result.gt_inds > 0).sum(), + gt_bboxes.size(0) * topk) + self.assertEqual((assign_result.labels > -1).sum(), + gt_bboxes.size(0) * topk) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_coder/test_delta_xywh_bbox_coder.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_coder/test_delta_xywh_bbox_coder.py new file mode 100644 index 0000000000000000000000000000000000000000..087c6903f6b90d1de6e72ce2ed98f632cb88c6a3 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_coder/test_delta_xywh_bbox_coder.py @@ -0,0 +1,73 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest +import torch + +from mmdet.models.task_modules.coders import (DeltaXYWHBBoxCoder, + DeltaXYWHBBoxCoderForGLIP) + + +def test_delta_bbox_coder(): + coder = DeltaXYWHBBoxCoder() + + rois = torch.Tensor([[0., 0., 1., 1.], [0., 0., 1., 1.], [0., 0., 1., 1.], + [5., 5., 5., 5.]]) + deltas = torch.Tensor([[0., 0., 0., 0.], [1., 1., 1., 1.], + [0., 0., 2., -1.], [0.7, -1.9, -0.5, 0.3]]) + expected_decode_bboxes = torch.Tensor([[0.0000, 0.0000, 1.0000, 1.0000], + [0.1409, 0.1409, 2.8591, 2.8591], + [0.0000, 0.3161, 4.1945, 0.6839], + [5.0000, 5.0000, 5.0000, 5.0000]]) + + out = coder.decode(rois, deltas, max_shape=(32, 32)) + assert expected_decode_bboxes.allclose(out, atol=1e-04) + out = coder.decode(rois, deltas, max_shape=torch.Tensor((32, 32))) + assert expected_decode_bboxes.allclose(out, atol=1e-04) + + batch_rois = rois.unsqueeze(0).repeat(2, 1, 1) + batch_deltas = deltas.unsqueeze(0).repeat(2, 1, 1) + batch_out = coder.decode(batch_rois, batch_deltas, max_shape=(32, 32))[0] + assert out.allclose(batch_out) + batch_out = coder.decode( + batch_rois, batch_deltas, max_shape=[(32, 32), (32, 32)])[0] + assert out.allclose(batch_out) + + # test max_shape is not equal to batch + with pytest.raises(AssertionError): + coder.decode( + batch_rois, batch_deltas, max_shape=[(32, 32), (32, 32), (32, 32)]) + + rois = torch.zeros((0, 4)) + deltas = torch.zeros((0, 4)) + out = coder.decode(rois, deltas, max_shape=(32, 32)) + assert rois.shape == out.shape + + # test add_ctr_clamp + coder = DeltaXYWHBBoxCoder(add_ctr_clamp=True, ctr_clamp=2) + + rois = torch.Tensor([[0., 0., 6., 6.], [0., 0., 1., 1.], [0., 0., 1., 1.], + [5., 5., 5., 5.]]) + deltas = torch.Tensor([[1., 1., 2., 2.], [1., 1., 1., 1.], + [0., 0., 2., -1.], [0.7, -1.9, -0.5, 0.3]]) + expected_decode_bboxes = torch.Tensor([[0.0000, 0.0000, 27.1672, 27.1672], + [0.1409, 0.1409, 2.8591, 2.8591], + [0.0000, 0.3161, 4.1945, 0.6839], + [5.0000, 5.0000, 5.0000, 5.0000]]) + + out = coder.decode(rois, deltas, max_shape=(32, 32)) + assert expected_decode_bboxes.allclose(out, atol=1e-04) + + coder = DeltaXYWHBBoxCoderForGLIP() + + rois = torch.Tensor([[0., 0., 1., 1.], [0., 0., 1., 1.], [0., 0., 1., 1.], + [5., 5., 5., 5.]]) + deltas = torch.Tensor([[0., 0., 0., 0.], [1., 1., 1., 1.], + [0., 0., 2., -1.], [0.7, -1.9, -0.5, 0.3]]) + expected_decode_bboxes = torch.Tensor([[0.0000, 0.0000, 0.0000, 0.0000], + [0.1409, 0.1409, 1.8591, 1.8591], + [0.0000, 0.3161, 3.1945, 0.0000], + [5.0000, 5.0000, 4.0000, 4.0000]]) + + out = coder.decode(rois, deltas, max_shape=(32, 32)) + assert expected_decode_bboxes.allclose(out, atol=1e-04) + out = coder.decode(rois, deltas, max_shape=torch.Tensor((32, 32))) + assert expected_decode_bboxes.allclose(out, atol=1e-04) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_iou2d_calculator.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_iou2d_calculator.py new file mode 100644 index 0000000000000000000000000000000000000000..ce46e69174424f5827a11f7b5a459267eb992717 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_iou2d_calculator.py @@ -0,0 +1,134 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +import pytest +import torch + +from mmdet.evaluation import bbox_overlaps as recall_overlaps +from mmdet.models.task_modules import BboxOverlaps2D +from mmdet.structures.bbox import bbox_overlaps + + +def test_bbox_overlaps_2d(eps=1e-7): + + def _construct_bbox(num_bbox=None): + img_h = int(np.random.randint(3, 1000)) + img_w = int(np.random.randint(3, 1000)) + if num_bbox is None: + num_bbox = np.random.randint(1, 10) + x1y1 = torch.rand((num_bbox, 2)) + x2y2 = torch.max(torch.rand((num_bbox, 2)), x1y1) + bboxes = torch.cat((x1y1, x2y2), -1) + bboxes[:, 0::2] *= img_w + bboxes[:, 1::2] *= img_h + return bboxes, num_bbox + + # is_aligned is True, bboxes.size(-1) == 5 (include score) + self = BboxOverlaps2D() + bboxes1, num_bbox = _construct_bbox() + bboxes2, _ = _construct_bbox(num_bbox) + bboxes1 = torch.cat((bboxes1, torch.rand((num_bbox, 1))), 1) + bboxes2 = torch.cat((bboxes2, torch.rand((num_bbox, 1))), 1) + gious = self(bboxes1, bboxes2, 'giou', True) + assert gious.size() == (num_bbox, ), gious.size() + assert torch.all(gious >= -1) and torch.all(gious <= 1) + + # is_aligned is True, bboxes1.size(-2) == 0 + bboxes1 = torch.empty((0, 4)) + bboxes2 = torch.empty((0, 4)) + gious = self(bboxes1, bboxes2, 'giou', True) + assert gious.size() == (0, ), gious.size() + assert torch.all(gious == torch.empty((0, ))) + assert torch.all(gious >= -1) and torch.all(gious <= 1) + + # is_aligned is True, and bboxes.ndims > 2 + bboxes1, num_bbox = _construct_bbox() + bboxes2, _ = _construct_bbox(num_bbox) + bboxes1 = bboxes1.unsqueeze(0).repeat(2, 1, 1) + # test assertion when batch dim is not the same + with pytest.raises(AssertionError): + self(bboxes1, bboxes2.unsqueeze(0).repeat(3, 1, 1), 'giou', True) + bboxes2 = bboxes2.unsqueeze(0).repeat(2, 1, 1) + gious = self(bboxes1, bboxes2, 'giou', True) + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (2, num_bbox) + bboxes1 = bboxes1.unsqueeze(0).repeat(2, 1, 1, 1) + bboxes2 = bboxes2.unsqueeze(0).repeat(2, 1, 1, 1) + gious = self(bboxes1, bboxes2, 'giou', True) + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (2, 2, num_bbox) + + # is_aligned is False + bboxes1, num_bbox1 = _construct_bbox() + bboxes2, num_bbox2 = _construct_bbox() + gious = self(bboxes1, bboxes2, 'giou') + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (num_bbox1, num_bbox2) + + # is_aligned is False, and bboxes.ndims > 2 + bboxes1 = bboxes1.unsqueeze(0).repeat(2, 1, 1) + bboxes2 = bboxes2.unsqueeze(0).repeat(2, 1, 1) + gious = self(bboxes1, bboxes2, 'giou') + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (2, num_bbox1, num_bbox2) + bboxes1 = bboxes1.unsqueeze(0) + bboxes2 = bboxes2.unsqueeze(0) + gious = self(bboxes1, bboxes2, 'giou') + assert torch.all(gious >= -1) and torch.all(gious <= 1) + assert gious.size() == (1, 2, num_bbox1, num_bbox2) + + # is_aligned is False, bboxes1.size(-2) == 0 + gious = self(torch.empty(1, 2, 0, 4), bboxes2, 'giou') + assert torch.all(gious == torch.empty(1, 2, 0, bboxes2.size(-2))) + assert torch.all(gious >= -1) and torch.all(gious <= 1) + + # test allclose between bbox_overlaps and the original official + # implementation. + bboxes1 = torch.FloatTensor([ + [0, 0, 10, 10], + [10, 10, 20, 20], + [32, 32, 38, 42], + ]) + bboxes2 = torch.FloatTensor([ + [0, 0, 10, 20], + [0, 10, 10, 19], + [10, 10, 20, 20], + ]) + gious = bbox_overlaps(bboxes1, bboxes2, 'giou', is_aligned=True, eps=eps) + gious = gious.numpy().round(4) + # the gt is got with four decimal precision. + expected_gious = np.array([0.5000, -0.0500, -0.8214]) + assert np.allclose(gious, expected_gious, rtol=0, atol=eps) + + # test mode 'iof' + ious = bbox_overlaps(bboxes1, bboxes2, 'iof', is_aligned=True, eps=eps) + assert torch.all(ious >= -1) and torch.all(ious <= 1) + assert ious.size() == (bboxes1.size(0), ) + ious = bbox_overlaps(bboxes1, bboxes2, 'iof', eps=eps) + assert torch.all(ious >= -1) and torch.all(ious <= 1) + assert ious.size() == (bboxes1.size(0), bboxes2.size(0)) + + +def test_voc_recall_overlaps(): + + def _construct_bbox(num_bbox=None): + img_h = int(np.random.randint(3, 1000)) + img_w = int(np.random.randint(3, 1000)) + if num_bbox is None: + num_bbox = np.random.randint(1, 10) + x1y1 = torch.rand((num_bbox, 2)) + x2y2 = torch.max(torch.rand((num_bbox, 2)), x1y1) + bboxes = torch.cat((x1y1, x2y2), -1) + bboxes[:, 0::2] *= img_w + bboxes[:, 1::2] *= img_h + return bboxes.numpy(), num_bbox + + bboxes1, num_bbox = _construct_bbox() + bboxes2, _ = _construct_bbox(num_bbox) + ious = recall_overlaps( + bboxes1, bboxes2, 'iou', use_legacy_coordinate=False) + assert ious.shape == (num_bbox, num_bbox) + assert np.all(ious >= -1) and np.all(ious <= 1) + + ious = recall_overlaps(bboxes1, bboxes2, 'iou', use_legacy_coordinate=True) + assert ious.shape == (num_bbox, num_bbox) + assert np.all(ious >= -1) and np.all(ious <= 1) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_prior_generators/test_anchor_generator.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_prior_generators/test_anchor_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..db0b60717bcf7ba866c8ee2526b9108f04ee13dc --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_prior_generators/test_anchor_generator.py @@ -0,0 +1,771 @@ +# Copyright (c) OpenMMLab. All rights reserved. +""" +CommandLine: + pytest tests/test_utils/test_anchor.py + xdoctest tests/test_utils/test_anchor.py zero + +""" +import pytest +import torch + + +def test_standard_points_generator(): + from mmdet.models.task_modules import build_prior_generator + + # teat init + anchor_generator_cfg = dict( + type='MlvlPointGenerator', strides=[4, 8], offset=0) + anchor_generator = build_prior_generator(anchor_generator_cfg) + assert anchor_generator is not None + assert anchor_generator.num_base_priors == [1, 1] + # test_stride + from mmdet.models.task_modules.prior_generators import MlvlPointGenerator + + # Square strides + mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0) + mlvl_points_half_stride_generator = MlvlPointGenerator( + strides=[4, 10], offset=0.5) + assert mlvl_points.num_levels == 2 + + # assert self.num_levels == len(featmap_sizes) + with pytest.raises(AssertionError): + mlvl_points.grid_priors(featmap_sizes=[(2, 2)], device='cpu') + priors = mlvl_points.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], device='cpu') + priors_with_stride = mlvl_points.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], with_stride=True, device='cpu') + assert len(priors) == 2 + + # assert last dimension is (coord_x, coord_y, stride_w, stride_h). + assert priors_with_stride[0].size(1) == 4 + assert priors_with_stride[0][0][2] == 4 + assert priors_with_stride[0][0][3] == 4 + assert priors_with_stride[1][0][2] == 10 + assert priors_with_stride[1][0][3] == 10 + + stride_4_feat_2_2 = priors[0] + assert (stride_4_feat_2_2[1] - stride_4_feat_2_2[0]).sum() == 4 + assert stride_4_feat_2_2.size(0) == 4 + assert stride_4_feat_2_2.size(1) == 2 + + stride_10_feat_4_8 = priors[1] + assert (stride_10_feat_4_8[1] - stride_10_feat_4_8[0]).sum() == 10 + assert stride_10_feat_4_8.size(0) == 4 * 8 + assert stride_10_feat_4_8.size(1) == 2 + + # assert the offset of 0.5 * stride + priors_half_offset = mlvl_points_half_stride_generator.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], device='cpu') + + assert (priors_half_offset[0][0] - priors[0][0]).sum() == 4 * 0.5 * 2 + assert (priors_half_offset[1][0] - priors[1][0]).sum() == 10 * 0.5 * 2 + if torch.cuda.is_available(): + anchor_generator_cfg = dict( + type='MlvlPointGenerator', strides=[4, 8], offset=0) + anchor_generator = build_prior_generator(anchor_generator_cfg) + assert anchor_generator is not None + # Square strides + mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0) + mlvl_points_half_stride_generator = MlvlPointGenerator( + strides=[4, 10], offset=0.5) + assert mlvl_points.num_levels == 2 + + # assert self.num_levels == len(featmap_sizes) + with pytest.raises(AssertionError): + mlvl_points.grid_priors(featmap_sizes=[(2, 2)], device='cuda') + priors = mlvl_points.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], device='cuda') + priors_with_stride = mlvl_points.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], with_stride=True, device='cuda') + assert len(priors) == 2 + + # assert last dimension is (coord_x, coord_y, stride_w, stride_h). + assert priors_with_stride[0].size(1) == 4 + assert priors_with_stride[0][0][2] == 4 + assert priors_with_stride[0][0][3] == 4 + assert priors_with_stride[1][0][2] == 10 + assert priors_with_stride[1][0][3] == 10 + + stride_4_feat_2_2 = priors[0] + assert (stride_4_feat_2_2[1] - stride_4_feat_2_2[0]).sum() == 4 + assert stride_4_feat_2_2.size(0) == 4 + assert stride_4_feat_2_2.size(1) == 2 + + stride_10_feat_4_8 = priors[1] + assert (stride_10_feat_4_8[1] - stride_10_feat_4_8[0]).sum() == 10 + assert stride_10_feat_4_8.size(0) == 4 * 8 + assert stride_10_feat_4_8.size(1) == 2 + + # assert the offset of 0.5 * stride + priors_half_offset = mlvl_points_half_stride_generator.grid_priors( + featmap_sizes=[(2, 2), (4, 8)], device='cuda') + + assert (priors_half_offset[0][0] - priors[0][0]).sum() == 4 * 0.5 * 2 + assert (priors_half_offset[1][0] - priors[1][0]).sum() == 10 * 0.5 * 2 + + +def test_sparse_prior(): + from mmdet.models.task_modules.prior_generators import MlvlPointGenerator + mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0) + prior_indexs = torch.Tensor([0, 2, 4, 5, 6, 9]).long() + + featmap_sizes = [(3, 5), (6, 4)] + grid_anchors = mlvl_points.grid_priors( + featmap_sizes=featmap_sizes, with_stride=False, device='cpu') + sparse_prior = mlvl_points.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[0], + level_idx=0, + device='cpu') + + assert not sparse_prior.is_cuda + assert (sparse_prior == grid_anchors[0][prior_indexs]).all() + sparse_prior = mlvl_points.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[1], + level_idx=1, + device='cpu') + assert (sparse_prior == grid_anchors[1][prior_indexs]).all() + + from mmdet.models.task_modules.prior_generators import AnchorGenerator + mlvl_anchors = AnchorGenerator( + strides=[16, 32], ratios=[1.], scales=[1.], base_sizes=[4, 8]) + prior_indexs = torch.Tensor([0, 2, 4, 5, 6, 9]).long() + + featmap_sizes = [(3, 5), (6, 4)] + grid_anchors = mlvl_anchors.grid_priors( + featmap_sizes=featmap_sizes, device='cpu') + sparse_prior = mlvl_anchors.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[0], + level_idx=0, + device='cpu') + assert (sparse_prior == grid_anchors[0][prior_indexs]).all() + sparse_prior = mlvl_anchors.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[1], + level_idx=1, + device='cpu') + assert (sparse_prior == grid_anchors[1][prior_indexs]).all() + + # for ssd + from mmdet.models.task_modules.prior_generators import SSDAnchorGenerator + featmap_sizes = [(38, 38), (19, 19), (10, 10)] + anchor_generator = SSDAnchorGenerator( + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32], + ratios=[[2], [2, 3], [2, 3]]) + ssd_anchors = anchor_generator.grid_anchors(featmap_sizes, device='cpu') + for i in range(len(featmap_sizes)): + sparse_ssd_anchors = anchor_generator.sparse_priors( + prior_idxs=prior_indexs, + level_idx=i, + featmap_size=featmap_sizes[i], + device='cpu') + assert (sparse_ssd_anchors == ssd_anchors[i][prior_indexs]).all() + + # for yolo + from mmdet.models.task_modules.prior_generators import YOLOAnchorGenerator + featmap_sizes = [(38, 38), (19, 19), (10, 10)] + anchor_generator = YOLOAnchorGenerator( + strides=[32, 16, 8], + base_sizes=[ + [(116, 90), (156, 198), (373, 326)], + [(30, 61), (62, 45), (59, 119)], + [(10, 13), (16, 30), (33, 23)], + ]) + yolo_anchors = anchor_generator.grid_anchors(featmap_sizes, device='cpu') + for i in range(len(featmap_sizes)): + sparse_yolo_anchors = anchor_generator.sparse_priors( + prior_idxs=prior_indexs, + level_idx=i, + featmap_size=featmap_sizes[i], + device='cpu') + assert (sparse_yolo_anchors == yolo_anchors[i][prior_indexs]).all() + + if torch.cuda.is_available(): + mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0) + prior_indexs = torch.Tensor([0, 3, 4, 5, 6, 7, 1, 2, 4, 5, 6, + 9]).long().cuda() + + featmap_sizes = [(6, 8), (6, 4)] + grid_anchors = mlvl_points.grid_priors( + featmap_sizes=featmap_sizes, with_stride=False, device='cuda') + sparse_prior = mlvl_points.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[0], + level_idx=0, + device='cuda') + assert (sparse_prior == grid_anchors[0][prior_indexs]).all() + sparse_prior = mlvl_points.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[1], + level_idx=1, + device='cuda') + assert (sparse_prior == grid_anchors[1][prior_indexs]).all() + assert sparse_prior.is_cuda + mlvl_anchors = AnchorGenerator( + strides=[16, 32], + ratios=[1., 2.5], + scales=[1., 5.], + base_sizes=[4, 8]) + prior_indexs = torch.Tensor([4, 5, 6, 7, 0, 2, 50, 4, 5, 6, + 9]).long().cuda() + + featmap_sizes = [(13, 5), (16, 4)] + grid_anchors = mlvl_anchors.grid_priors( + featmap_sizes=featmap_sizes, device='cuda') + sparse_prior = mlvl_anchors.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[0], + level_idx=0, + device='cuda') + assert (sparse_prior == grid_anchors[0][prior_indexs]).all() + sparse_prior = mlvl_anchors.sparse_priors( + prior_idxs=prior_indexs, + featmap_size=featmap_sizes[1], + level_idx=1, + device='cuda') + assert (sparse_prior == grid_anchors[1][prior_indexs]).all() + + # for ssd + from mmdet.models.task_modules.prior_generators import \ + SSDAnchorGenerator + featmap_sizes = [(38, 38), (19, 19), (10, 10)] + anchor_generator = SSDAnchorGenerator( + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32], + ratios=[[2], [2, 3], [2, 3]]) + ssd_anchors = anchor_generator.grid_anchors( + featmap_sizes, device='cuda') + for i in range(len(featmap_sizes)): + sparse_ssd_anchors = anchor_generator.sparse_priors( + prior_idxs=prior_indexs, + level_idx=i, + featmap_size=featmap_sizes[i], + device='cuda') + assert (sparse_ssd_anchors == ssd_anchors[i][prior_indexs]).all() + + # for yolo + from mmdet.models.task_modules.prior_generators import \ + YOLOAnchorGenerator + featmap_sizes = [(38, 38), (19, 19), (10, 10)] + anchor_generator = YOLOAnchorGenerator( + strides=[32, 16, 8], + base_sizes=[ + [(116, 90), (156, 198), (373, 326)], + [(30, 61), (62, 45), (59, 119)], + [(10, 13), (16, 30), (33, 23)], + ]) + yolo_anchors = anchor_generator.grid_anchors( + featmap_sizes, device='cuda') + for i in range(len(featmap_sizes)): + sparse_yolo_anchors = anchor_generator.sparse_priors( + prior_idxs=prior_indexs, + level_idx=i, + featmap_size=featmap_sizes[i], + device='cuda') + assert (sparse_yolo_anchors == yolo_anchors[i][prior_indexs]).all() + + +def test_standard_anchor_generator(): + from mmdet.models.task_modules import build_anchor_generator + anchor_generator_cfg = dict( + type='AnchorGenerator', + scales=[8], + ratios=[0.5, 1.0, 2.0], + strides=[4, 8]) + + anchor_generator = build_anchor_generator(anchor_generator_cfg) + assert anchor_generator.num_base_priors == \ + anchor_generator.num_base_anchors + assert anchor_generator.num_base_priors == [3, 3] + assert anchor_generator is not None + + +def test_strides(): + from mmdet.models.task_modules.prior_generators import AnchorGenerator + + # Square strides + self = AnchorGenerator([10], [1.], [1.], [10]) + anchors = self.grid_anchors([(2, 2)], device='cpu') + + expected_anchors = torch.tensor([[-5., -5., 5., 5.], [5., -5., 15., 5.], + [-5., 5., 5., 15.], [5., 5., 15., 15.]]) + + assert torch.equal(anchors[0], expected_anchors) + + # Different strides in x and y direction + self = AnchorGenerator([(10, 20)], [1.], [1.], [10]) + anchors = self.grid_anchors([(2, 2)], device='cpu') + + expected_anchors = torch.tensor([[-5., -5., 5., 5.], [5., -5., 15., 5.], + [-5., 15., 5., 25.], [5., 15., 15., 25.]]) + + assert torch.equal(anchors[0], expected_anchors) + + +def test_ssd_anchor_generator(): + from mmdet.models.task_modules import build_anchor_generator + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + + # min_sizes max_sizes must set at the same time + with pytest.raises(AssertionError): + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + min_sizes=[48, 100, 150, 202, 253, 300], + max_sizes=None, + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + build_anchor_generator(anchor_generator_cfg) + + # length of min_sizes max_sizes must be the same + with pytest.raises(AssertionError): + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + min_sizes=[48, 100, 150, 202, 253, 300], + max_sizes=[100, 150, 202, 253], + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + build_anchor_generator(anchor_generator_cfg) + + # test setting anchor size manually + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + min_sizes=[48, 100, 150, 202, 253, 304], + max_sizes=[100, 150, 202, 253, 304, 320], + strides=[16, 32, 64, 107, 160, 320], + ratios=[[2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3]]) + + featmap_sizes = [(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)] + anchor_generator = build_anchor_generator(anchor_generator_cfg) + + expected_base_anchors = [ + torch.Tensor([[-16.0000, -16.0000, 32.0000, 32.0000], + [-26.6410, -26.6410, 42.6410, 42.6410], + [-25.9411, -8.9706, 41.9411, 24.9706], + [-8.9706, -25.9411, 24.9706, 41.9411], + [-33.5692, -5.8564, 49.5692, 21.8564], + [-5.8564, -33.5692, 21.8564, 49.5692]]), + torch.Tensor([[-34.0000, -34.0000, 66.0000, 66.0000], + [-45.2372, -45.2372, 77.2372, 77.2372], + [-54.7107, -19.3553, 86.7107, 51.3553], + [-19.3553, -54.7107, 51.3553, 86.7107], + [-70.6025, -12.8675, 102.6025, 44.8675], + [-12.8675, -70.6025, 44.8675, 102.6025]]), + torch.Tensor([[-43.0000, -43.0000, 107.0000, 107.0000], + [-55.0345, -55.0345, 119.0345, 119.0345], + [-74.0660, -21.0330, 138.0660, 85.0330], + [-21.0330, -74.0660, 85.0330, 138.0660], + [-97.9038, -11.3013, 161.9038, 75.3013], + [-11.3013, -97.9038, 75.3013, 161.9038]]), + torch.Tensor([[-47.5000, -47.5000, 154.5000, 154.5000], + [-59.5332, -59.5332, 166.5332, 166.5332], + [-89.3356, -17.9178, 196.3356, 124.9178], + [-17.9178, -89.3356, 124.9178, 196.3356], + [-121.4371, -4.8124, 228.4371, 111.8124], + [-4.8124, -121.4371, 111.8124, 228.4371]]), + torch.Tensor([[-46.5000, -46.5000, 206.5000, 206.5000], + [-58.6651, -58.6651, 218.6651, 218.6651], + [-98.8980, -9.4490, 258.8980, 169.4490], + [-9.4490, -98.8980, 169.4490, 258.8980], + [-139.1044, 6.9652, 299.1044, 153.0348], + [6.9652, -139.1044, 153.0348, 299.1044]]), + torch.Tensor([[8.0000, 8.0000, 312.0000, 312.0000], + [4.0513, 4.0513, 315.9487, 315.9487], + [-54.9605, 52.5198, 374.9604, 267.4802], + [52.5198, -54.9605, 267.4802, 374.9604], + [-103.2717, 72.2428, 423.2717, 247.7572], + [72.2428, -103.2717, 247.7572, 423.2717]]) + ] + + base_anchors = anchor_generator.base_anchors + for i, base_anchor in enumerate(base_anchors): + assert base_anchor.allclose(expected_base_anchors[i]) + + # check valid flags + expected_valid_pixels = [2400, 600, 150, 54, 24, 6] + multi_level_valid_flags = anchor_generator.valid_flags( + featmap_sizes, (320, 320), device) + for i, single_level_valid_flag in enumerate(multi_level_valid_flags): + assert single_level_valid_flag.sum() == expected_valid_pixels[i] + + # check number of base anchors for each level + assert anchor_generator.num_base_anchors == [6, 6, 6, 6, 6, 6] + + # check anchor generation + anchors = anchor_generator.grid_anchors(featmap_sizes, device) + assert len(anchors) == 6 + + # test vgg ssd anchor setting + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + + featmap_sizes = [(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)] + anchor_generator = build_anchor_generator(anchor_generator_cfg) + + # check base anchors + expected_base_anchors = [ + torch.Tensor([[-6.5000, -6.5000, 14.5000, 14.5000], + [-11.3704, -11.3704, 19.3704, 19.3704], + [-10.8492, -3.4246, 18.8492, 11.4246], + [-3.4246, -10.8492, 11.4246, 18.8492]]), + torch.Tensor([[-14.5000, -14.5000, 30.5000, 30.5000], + [-25.3729, -25.3729, 41.3729, 41.3729], + [-23.8198, -7.9099, 39.8198, 23.9099], + [-7.9099, -23.8198, 23.9099, 39.8198], + [-30.9711, -4.9904, 46.9711, 20.9904], + [-4.9904, -30.9711, 20.9904, 46.9711]]), + torch.Tensor([[-33.5000, -33.5000, 65.5000, 65.5000], + [-45.5366, -45.5366, 77.5366, 77.5366], + [-54.0036, -19.0018, 86.0036, 51.0018], + [-19.0018, -54.0036, 51.0018, 86.0036], + [-69.7365, -12.5788, 101.7365, 44.5788], + [-12.5788, -69.7365, 44.5788, 101.7365]]), + torch.Tensor([[-44.5000, -44.5000, 108.5000, 108.5000], + [-56.9817, -56.9817, 120.9817, 120.9817], + [-76.1873, -22.0937, 140.1873, 86.0937], + [-22.0937, -76.1873, 86.0937, 140.1873], + [-100.5019, -12.1673, 164.5019, 76.1673], + [-12.1673, -100.5019, 76.1673, 164.5019]]), + torch.Tensor([[-53.5000, -53.5000, 153.5000, 153.5000], + [-66.2185, -66.2185, 166.2185, 166.2185], + [-96.3711, -23.1855, 196.3711, 123.1855], + [-23.1855, -96.3711, 123.1855, 196.3711]]), + torch.Tensor([[19.5000, 19.5000, 280.5000, 280.5000], + [6.6342, 6.6342, 293.3658, 293.3658], + [-34.5549, 57.7226, 334.5549, 242.2774], + [57.7226, -34.5549, 242.2774, 334.5549]]), + ] + base_anchors = anchor_generator.base_anchors + for i, base_anchor in enumerate(base_anchors): + assert base_anchor.allclose(expected_base_anchors[i]) + + # check valid flags + expected_valid_pixels = [5776, 2166, 600, 150, 36, 4] + multi_level_valid_flags = anchor_generator.valid_flags( + featmap_sizes, (300, 300), device) + for i, single_level_valid_flag in enumerate(multi_level_valid_flags): + assert single_level_valid_flag.sum() == expected_valid_pixels[i] + + # check number of base anchors for each level + assert anchor_generator.num_base_anchors == [4, 6, 6, 6, 4, 4] + + # check anchor generation + anchors = anchor_generator.grid_anchors(featmap_sizes, device) + assert len(anchors) == 6 + + +def test_anchor_generator_with_tuples(): + from mmdet.models.task_modules import build_anchor_generator + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + + anchor_generator_cfg = dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[8, 16, 32, 64, 100, 300], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + + featmap_sizes = [(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)] + anchor_generator = build_anchor_generator(anchor_generator_cfg) + anchors = anchor_generator.grid_anchors(featmap_sizes, device) + + anchor_generator_cfg_tuples = dict( + type='SSDAnchorGenerator', + scale_major=False, + input_size=300, + basesize_ratio_range=(0.15, 0.9), + strides=[(8, 8), (16, 16), (32, 32), (64, 64), (100, 100), (300, 300)], + ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]]) + + anchor_generator_tuples = build_anchor_generator( + anchor_generator_cfg_tuples) + anchors_tuples = anchor_generator_tuples.grid_anchors( + featmap_sizes, device) + for anchor, anchor_tuples in zip(anchors, anchors_tuples): + assert torch.equal(anchor, anchor_tuples) + + +def test_yolo_anchor_generator(): + from mmdet.models.task_modules import build_anchor_generator + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + + anchor_generator_cfg = dict( + type='YOLOAnchorGenerator', + strides=[32, 16, 8], + base_sizes=[ + [(116, 90), (156, 198), (373, 326)], + [(30, 61), (62, 45), (59, 119)], + [(10, 13), (16, 30), (33, 23)], + ]) + + featmap_sizes = [(14, 18), (28, 36), (56, 72)] + anchor_generator = build_anchor_generator(anchor_generator_cfg) + + # check base anchors + expected_base_anchors = [ + torch.Tensor([[-42.0000, -29.0000, 74.0000, 61.0000], + [-62.0000, -83.0000, 94.0000, 115.0000], + [-170.5000, -147.0000, 202.5000, 179.0000]]), + torch.Tensor([[-7.0000, -22.5000, 23.0000, 38.5000], + [-23.0000, -14.5000, 39.0000, 30.5000], + [-21.5000, -51.5000, 37.5000, 67.5000]]), + torch.Tensor([[-1.0000, -2.5000, 9.0000, 10.5000], + [-4.0000, -11.0000, 12.0000, 19.0000], + [-12.5000, -7.5000, 20.5000, 15.5000]]) + ] + base_anchors = anchor_generator.base_anchors + for i, base_anchor in enumerate(base_anchors): + assert base_anchor.allclose(expected_base_anchors[i]) + + # check number of base anchors for each level + assert anchor_generator.num_base_anchors == [3, 3, 3] + + # check anchor generation + anchors = anchor_generator.grid_anchors(featmap_sizes, device) + assert len(anchors) == 3 + + +def test_retina_anchor(): + from mmdet.registry import MODELS + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + + # head configs modified from + # configs/nas_fpn/retinanet_r50_fpn_crop640_50e.py + bbox_head = dict( + type='RetinaSepBNHead', + num_classes=4, + num_ins=5, + in_channels=4, + stacked_convs=1, + feat_channels=4, + anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[1.0, 1.0, 1.0, 1.0])) + + retina_head = MODELS.build(bbox_head) + assert retina_head.anchor_generator is not None + + # use the featmap sizes in NASFPN setting to test retina head + featmap_sizes = [(80, 80), (40, 40), (20, 20), (10, 10), (5, 5)] + # check base anchors + expected_base_anchors = [ + torch.Tensor([[-22.6274, -11.3137, 22.6274, 11.3137], + [-28.5088, -14.2544, 28.5088, 14.2544], + [-35.9188, -17.9594, 35.9188, 17.9594], + [-16.0000, -16.0000, 16.0000, 16.0000], + [-20.1587, -20.1587, 20.1587, 20.1587], + [-25.3984, -25.3984, 25.3984, 25.3984], + [-11.3137, -22.6274, 11.3137, 22.6274], + [-14.2544, -28.5088, 14.2544, 28.5088], + [-17.9594, -35.9188, 17.9594, 35.9188]]), + torch.Tensor([[-45.2548, -22.6274, 45.2548, 22.6274], + [-57.0175, -28.5088, 57.0175, 28.5088], + [-71.8376, -35.9188, 71.8376, 35.9188], + [-32.0000, -32.0000, 32.0000, 32.0000], + [-40.3175, -40.3175, 40.3175, 40.3175], + [-50.7968, -50.7968, 50.7968, 50.7968], + [-22.6274, -45.2548, 22.6274, 45.2548], + [-28.5088, -57.0175, 28.5088, 57.0175], + [-35.9188, -71.8376, 35.9188, 71.8376]]), + torch.Tensor([[-90.5097, -45.2548, 90.5097, 45.2548], + [-114.0350, -57.0175, 114.0350, 57.0175], + [-143.6751, -71.8376, 143.6751, 71.8376], + [-64.0000, -64.0000, 64.0000, 64.0000], + [-80.6349, -80.6349, 80.6349, 80.6349], + [-101.5937, -101.5937, 101.5937, 101.5937], + [-45.2548, -90.5097, 45.2548, 90.5097], + [-57.0175, -114.0350, 57.0175, 114.0350], + [-71.8376, -143.6751, 71.8376, 143.6751]]), + torch.Tensor([[-181.0193, -90.5097, 181.0193, 90.5097], + [-228.0701, -114.0350, 228.0701, 114.0350], + [-287.3503, -143.6751, 287.3503, 143.6751], + [-128.0000, -128.0000, 128.0000, 128.0000], + [-161.2699, -161.2699, 161.2699, 161.2699], + [-203.1873, -203.1873, 203.1873, 203.1873], + [-90.5097, -181.0193, 90.5097, 181.0193], + [-114.0350, -228.0701, 114.0350, 228.0701], + [-143.6751, -287.3503, 143.6751, 287.3503]]), + torch.Tensor([[-362.0387, -181.0193, 362.0387, 181.0193], + [-456.1401, -228.0701, 456.1401, 228.0701], + [-574.7006, -287.3503, 574.7006, 287.3503], + [-256.0000, -256.0000, 256.0000, 256.0000], + [-322.5398, -322.5398, 322.5398, 322.5398], + [-406.3747, -406.3747, 406.3747, 406.3747], + [-181.0193, -362.0387, 181.0193, 362.0387], + [-228.0701, -456.1401, 228.0701, 456.1401], + [-287.3503, -574.7006, 287.3503, 574.7006]]) + ] + base_anchors = retina_head.anchor_generator.base_anchors + for i, base_anchor in enumerate(base_anchors): + assert base_anchor.allclose(expected_base_anchors[i]) + + # check valid flags + expected_valid_pixels = [57600, 14400, 3600, 900, 225] + multi_level_valid_flags = retina_head.anchor_generator.valid_flags( + featmap_sizes, (640, 640), device) + for i, single_level_valid_flag in enumerate(multi_level_valid_flags): + assert single_level_valid_flag.sum() == expected_valid_pixels[i] + + # check number of base anchors for each level + assert retina_head.anchor_generator.num_base_anchors == [9, 9, 9, 9, 9] + + # check anchor generation + anchors = retina_head.anchor_generator.grid_anchors(featmap_sizes, device) + assert len(anchors) == 5 + + +def test_guided_anchor(): + from mmdet.registry import MODELS + if torch.cuda.is_available(): + device = 'cuda' + else: + device = 'cpu' + # head configs modified from + # configs/guided_anchoring/ga-retinanet_r50_fpn_1x_coco.py + bbox_head = dict( + type='GARetinaHead', + num_classes=8, + in_channels=4, + stacked_convs=1, + feat_channels=4, + approx_anchor_generator=dict( + type='AnchorGenerator', + octave_base_scale=4, + scales_per_octave=3, + ratios=[0.5, 1.0, 2.0], + strides=[8, 16, 32, 64, 128]), + square_anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + scales=[4], + strides=[8, 16, 32, 64, 128])) + + ga_retina_head = MODELS.build(bbox_head) + assert ga_retina_head.approx_anchor_generator is not None + + # use the featmap sizes in NASFPN setting to test ga_retina_head + featmap_sizes = [(100, 152), (50, 76), (25, 38), (13, 19), (7, 10)] + # check base anchors + expected_approxs = [ + torch.Tensor([[-22.6274, -11.3137, 22.6274, 11.3137], + [-28.5088, -14.2544, 28.5088, 14.2544], + [-35.9188, -17.9594, 35.9188, 17.9594], + [-16.0000, -16.0000, 16.0000, 16.0000], + [-20.1587, -20.1587, 20.1587, 20.1587], + [-25.3984, -25.3984, 25.3984, 25.3984], + [-11.3137, -22.6274, 11.3137, 22.6274], + [-14.2544, -28.5088, 14.2544, 28.5088], + [-17.9594, -35.9188, 17.9594, 35.9188]]), + torch.Tensor([[-45.2548, -22.6274, 45.2548, 22.6274], + [-57.0175, -28.5088, 57.0175, 28.5088], + [-71.8376, -35.9188, 71.8376, 35.9188], + [-32.0000, -32.0000, 32.0000, 32.0000], + [-40.3175, -40.3175, 40.3175, 40.3175], + [-50.7968, -50.7968, 50.7968, 50.7968], + [-22.6274, -45.2548, 22.6274, 45.2548], + [-28.5088, -57.0175, 28.5088, 57.0175], + [-35.9188, -71.8376, 35.9188, 71.8376]]), + torch.Tensor([[-90.5097, -45.2548, 90.5097, 45.2548], + [-114.0350, -57.0175, 114.0350, 57.0175], + [-143.6751, -71.8376, 143.6751, 71.8376], + [-64.0000, -64.0000, 64.0000, 64.0000], + [-80.6349, -80.6349, 80.6349, 80.6349], + [-101.5937, -101.5937, 101.5937, 101.5937], + [-45.2548, -90.5097, 45.2548, 90.5097], + [-57.0175, -114.0350, 57.0175, 114.0350], + [-71.8376, -143.6751, 71.8376, 143.6751]]), + torch.Tensor([[-181.0193, -90.5097, 181.0193, 90.5097], + [-228.0701, -114.0350, 228.0701, 114.0350], + [-287.3503, -143.6751, 287.3503, 143.6751], + [-128.0000, -128.0000, 128.0000, 128.0000], + [-161.2699, -161.2699, 161.2699, 161.2699], + [-203.1873, -203.1873, 203.1873, 203.1873], + [-90.5097, -181.0193, 90.5097, 181.0193], + [-114.0350, -228.0701, 114.0350, 228.0701], + [-143.6751, -287.3503, 143.6751, 287.3503]]), + torch.Tensor([[-362.0387, -181.0193, 362.0387, 181.0193], + [-456.1401, -228.0701, 456.1401, 228.0701], + [-574.7006, -287.3503, 574.7006, 287.3503], + [-256.0000, -256.0000, 256.0000, 256.0000], + [-322.5398, -322.5398, 322.5398, 322.5398], + [-406.3747, -406.3747, 406.3747, 406.3747], + [-181.0193, -362.0387, 181.0193, 362.0387], + [-228.0701, -456.1401, 228.0701, 456.1401], + [-287.3503, -574.7006, 287.3503, 574.7006]]) + ] + approxs = ga_retina_head.approx_anchor_generator.base_anchors + for i, base_anchor in enumerate(approxs): + assert base_anchor.allclose(expected_approxs[i]) + + # check valid flags + expected_valid_pixels = [136800, 34200, 8550, 2223, 630] + multi_level_valid_flags = ga_retina_head.approx_anchor_generator \ + .valid_flags(featmap_sizes, (800, 1216), device) + for i, single_level_valid_flag in enumerate(multi_level_valid_flags): + assert single_level_valid_flag.sum() == expected_valid_pixels[i] + + # check number of base anchors for each level + assert ga_retina_head.approx_anchor_generator.num_base_anchors == [ + 9, 9, 9, 9, 9 + ] + + # check approx generation + squares = ga_retina_head.square_anchor_generator.grid_anchors( + featmap_sizes, device) + assert len(squares) == 5 + + expected_squares = [ + torch.Tensor([[-16., -16., 16., 16.]]), + torch.Tensor([[-32., -32., 32., 32]]), + torch.Tensor([[-64., -64., 64., 64.]]), + torch.Tensor([[-128., -128., 128., 128.]]), + torch.Tensor([[-256., -256., 256., 256.]]) + ] + squares = ga_retina_head.square_anchor_generator.base_anchors + for i, base_anchor in enumerate(squares): + assert base_anchor.allclose(expected_squares[i]) + + # square_anchor_generator does not check valid flags + # check number of base anchors for each level + assert (ga_retina_head.square_anchor_generator.num_base_anchors == [ + 1, 1, 1, 1, 1 + ]) + + # check square generation + anchors = ga_retina_head.square_anchor_generator.grid_anchors( + featmap_sizes, device) + assert len(anchors) == 5 diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_samplers/test_pesudo_sampler.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_samplers/test_pesudo_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..cd428decc5ffaa735ad55f9c11b0cb24b25f76ca --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_samplers/test_pesudo_sampler.py @@ -0,0 +1 @@ +# TODO: follow up diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_aflink.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_aflink.py new file mode 100644 index 0000000000000000000000000000000000000000..51df13a2ab146c3057524326ab7313bfd12a319f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_aflink.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +from mmengine.registry import init_default_scope +from torch import nn + +from mmdet.registry import TASK_UTILS + + +class TestAppearanceFreeLink(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + cls.cfg = dict( + type='AppearanceFreeLink', + checkpoint='', + temporal_threshold=(0, 30), + spatial_threshold=75, + confidence_threshold=0.95, + ) + + def test_init(self): + aflink = TASK_UTILS.build(self.cfg) + assert aflink.temporal_threshold == (0, 30) + assert aflink.spatial_threshold == 75 + assert aflink.confidence_threshold == 0.95 + assert isinstance(aflink.model, nn.Module) + + def test_forward(self): + pred_track = np.random.randn(10, 7) + aflink = TASK_UTILS.build(self.cfg) + linked_track = aflink.forward(pred_track) + assert isinstance(linked_track, np.ndarray) + assert linked_track.shape == (10, 7) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_interpolation.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..413aa2c396bb2ab8275625813b59b51603ca5540 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_interpolation.py @@ -0,0 +1,39 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +from mmengine.registry import init_default_scope + +from mmdet.registry import TASK_UTILS + + +class TestInterpolateTracklets(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + cls.cfg = dict( + type='InterpolateTracklets', + min_num_frames=5, + max_num_frames=20, + use_gsi=True, + smooth_tau=10) + + def test_init(self): + interpolation = TASK_UTILS.build(self.cfg) + assert interpolation.min_num_frames == 5 + assert interpolation.max_num_frames == 20 + assert interpolation.use_gsi + assert interpolation.smooth_tau == 10 + + def test_forward(self): + pred_track = np.random.randn(5, 7) + + # set frame_id and target_id + pred_track[:, 0] = np.array([1, 2, 5, 6, 7]) + pred_track[:, 1] = 1 + + interpolation = TASK_UTILS.build(self.cfg) + linked_track = interpolation.forward(pred_track) + assert isinstance(linked_track, np.ndarray) + assert linked_track.shape == (5, 7) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_kalman_filter.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_kalman_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..a7344757e2f813ddc35f29a3605e87229999ea17 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_kalman_filter.py @@ -0,0 +1,37 @@ +from unittest import TestCase + +import numpy as np +from mmengine.registry import init_default_scope + +from mmdet.registry import TASK_UTILS + + +class TestKalmanFilter(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + motion = dict(type='KalmanFilter', ) + cls.kf = TASK_UTILS.build(motion) + + def test_init(self): + pred_det = np.random.randn(4) + mean, covariance = self.kf.initiate(pred_det) + assert len(mean) == 8 + assert covariance.shape == (8, 8) + + def test_predict(self): + mean = np.random.randn(8) + covariance = np.random.randn(8, 8) + mean, covariance = self.kf.predict(mean, covariance) + assert len(mean) == 8 + assert covariance.shape == (8, 8) + + def test_update(self): + mean = np.ones(8) + covariance = np.ones((8, 8)) + measurement = np.ones(4) + score = 0.1 + mean, covariance = self.kf.update(mean, covariance, measurement, score) + assert len(mean) == 8 + assert covariance.shape == (8, 8) diff --git a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_similarity.py b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..8364ca503efeb583fdf4573efef86e6d0227310e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_track/test_similarity.py @@ -0,0 +1,10 @@ +import torch + +from mmdet.models.task_modules import embed_similarity + + +def test_embed_similarity(): + """Test embed similarity.""" + embeds = torch.rand(2, 3) + similarity = embed_similarity(embeds, embeds) + assert similarity.shape == (2, 2) diff --git a/mmdet_code/mmdetection/tests/test_models/test_trackers/test_byte_tracker.py b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_byte_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..c26ec9703d97758fb61f0ba9742cefa534d81f3b --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_byte_tracker.py @@ -0,0 +1,65 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.testing import demo_track_inputs, random_boxes +from mmdet.utils import register_all_modules + + +class TestByteTracker(TestCase): + + @classmethod + def setUpClass(cls): + register_all_modules(init_default_scope=True) + cfg = dict( + type='ByteTracker', + motion=dict(type='KalmanFilter'), + obj_score_thrs=dict(high=0.6, low=0.1), + init_track_thr=0.7, + weight_iou_with_det_scores=True, + match_iou_thrs=dict(high=0.1, low=0.5, tentative=0.3), + num_tentatives=3, + num_frames_retain=30) + cls.tracker = MODELS.build(cfg) + cls.tracker.kf = TASK_UTILS.build(dict(type='KalmanFilter')) + cls.num_frames_retain = cfg['num_frames_retain'] + cls.num_objs = 30 + + def test_init(self): + bboxes = random_boxes(self.num_objs, 512) + labels = torch.zeros(self.num_objs) + scores = torch.ones(self.num_objs) + ids = torch.arange(self.num_objs) + self.tracker.update( + ids=ids, bboxes=bboxes, scores=scores, labels=labels, frame_ids=0) + + assert self.tracker.ids == list(ids) + assert self.tracker.memo_items == [ + 'ids', 'bboxes', 'scores', 'labels', 'frame_ids' + ] + + def test_track(self): + + with torch.no_grad(): + packed_inputs = demo_track_inputs(batch_size=1, num_frames=2) + track_data_sample = packed_inputs['data_samples'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.gt_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor( + scores) + + pred_track_instances = self.tracker.track( + data_sample=img_data_sample) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] diff --git a/mmdet_code/mmdetection/tests/test_models/test_trackers/test_masktrack_rcnn_tracker.py b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_masktrack_rcnn_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..38648d1e75bd618aba65128833e10345b50415b2 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_masktrack_rcnn_tracker.py @@ -0,0 +1,74 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg, random_boxes + + +class TestMaskTrackRCNNTracker(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + tracker_cfg = dict( + type='MaskTrackRCNNTracker', + match_weights=dict(det_score=1.0, iou=2.0, det_label=10.0), + num_frames_retain=20) + cls.tracker = MODELS.build(tracker_cfg) + cls.num_objs = 5 + + def test_get_match_score(self): + bboxes = random_boxes(self.num_objs, 64) + labels = torch.arange(self.num_objs) + scores = torch.arange(self.num_objs, dtype=torch.float32) + similarity_logits = torch.randn(self.num_objs, self.num_objs + 1) + + match_score = self.tracker.get_match_score(bboxes, labels, scores, + bboxes, labels, + similarity_logits) + assert match_score.size() == similarity_logits.size() + + @parameterized.expand([ + 'masktrack_rcnn/masktrack-rcnn_mask-rcnn_r50_fpn_8xb1-12e_youtubevis2019.py' # noqa: E501 + ]) + def test_track(self, cfg_file): + _model = get_detector_cfg(cfg_file) + # _scope_ will be popped after build + model = MODELS.build(_model) + + packed_inputs = demo_track_inputs( + batch_size=1, num_frames=2, with_mask=True) + track_data_sample = packed_inputs['data_samples'][0] + imgs = packed_inputs['inputs'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + single_image = imgs[frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.pred_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor(scores) + feats = [] + for i in range( + len(model.track_head.roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, 256 // (2**(i + 2)), + 256 // (2**(i + 2))).to(device='cpu')) + pred_track_instances = self.tracker.track( + model=model, + img=single_image, + feats=tuple(feats), + data_sample=img_data_sample) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + ids = pred_track_instances.instances_id + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] + assert bboxes.shape[0] == ids.shape[0] diff --git a/mmdet_code/mmdetection/tests/test_models/test_trackers/test_oc_sort_tracker.py b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_oc_sort_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..d24b801da30086cf29f62eed1b8574a036174abd --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_oc_sort_tracker.py @@ -0,0 +1,54 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.testing import demo_track_inputs +from mmdet.utils import register_all_modules + + +class TestByteTracker(TestCase): + + @classmethod + def setUpClass(cls): + register_all_modules(init_default_scope=True) + cfg = dict( + type='OCSORTTracker', + motion=dict(type='KalmanFilter'), + obj_score_thr=0.3, + init_track_thr=0.7, + weight_iou_with_det_scores=True, + match_iou_thr=0.3, + num_tentatives=3, + vel_consist_weight=0.2, + vel_delta_t=3, + num_frames_retain=30) + cls.tracker = MODELS.build(cfg) + cls.tracker.kf = TASK_UTILS.build(dict(type='KalmanFilter')) + cls.num_frames_retain = cfg['num_frames_retain'] + cls.num_objs = 30 + + def test_track(self): + + with torch.no_grad(): + packed_inputs = demo_track_inputs(batch_size=1, num_frames=2) + track_data_sample = packed_inputs['data_samples'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.gt_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor( + scores) + + pred_track_instances = self.tracker.track( + data_sample=img_data_sample) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] diff --git a/mmdet_code/mmdetection/tests/test_models/test_trackers/test_sort_tracker.py b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_sort_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..14562aa1069464c0986ba09ffa9187c62fbfc0d1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_sort_tracker.py @@ -0,0 +1,82 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import MagicMock + +import torch +from parameterized import parameterized + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.testing import demo_track_inputs, get_detector_cfg, random_boxes +from mmdet.utils import register_all_modules + + +class TestSORTTracker(TestCase): + + @classmethod + def setUpClass(cls): + register_all_modules(init_default_scope=True) + cls.num_objs = 30 + + @parameterized.expand([ + 'deepsort/deepsort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + cfg = get_detector_cfg(cfg_file) + tracker = MODELS.build(cfg['tracker']) + tracker.kf = TASK_UTILS.build(cfg['tracker']['motion']) + + bboxes = random_boxes(self.num_objs, 512) + labels = torch.zeros(self.num_objs) + scores = torch.ones(self.num_objs) + ids = torch.arange(self.num_objs) + tracker.update( + ids=ids, bboxes=bboxes, scores=scores, labels=labels, frame_ids=0) + + assert tracker.ids == list(ids) + assert tracker.memo_items == [ + 'ids', 'bboxes', 'scores', 'labels', 'frame_ids' + ] + + @parameterized.expand([ + 'deepsort/deepsort_faster-rcnn_r50_fpn_8xb2-4e' + '_mot17halftrain_test-mot17halfval.py' + ]) + def test_track(self, cfg_file): + imgs = torch.rand((1, 2, 3, 128, 128)) + + cfg = get_detector_cfg(cfg_file) + tracker = MODELS.build(cfg['tracker']) + tracker.kf = TASK_UTILS.build(cfg['tracker']['motion']) + + model = MagicMock() + model.reid = MODELS.build(cfg['reid']) + + with torch.no_grad(): + packed_inputs = demo_track_inputs(batch_size=1, num_frames=2) + track_data_sample = packed_inputs['data_samples'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + single_img = imgs[:, frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.gt_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor( + scores) + + pred_track_instances = tracker.track( + model=model, + img=single_img, + feats=None, + data_sample=img_data_sample, + data_preprocessor=cfg['data_preprocessor']) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + ids = pred_track_instances.instances_id + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] + assert bboxes.shape[0] == ids.shape[0] diff --git a/mmdet_code/mmdetection/tests/test_models/test_trackers/test_strong_sort_tracker.py b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_strong_sort_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..adef04407bc8afc20ae210dcedd1c66912860b59 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_trackers/test_strong_sort_tracker.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase +from unittest.mock import MagicMock + +import torch +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS, TASK_UTILS +from mmdet.testing import demo_track_inputs, get_detector_cfg, random_boxes + + +class TestStrongSORTTracker(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + cls.num_objs = 30 + + @parameterized.expand([ + 'strongsort/strongsort_yolox_x_8xb4-80e_crowdhuman-mot17halftrain' + '_test-mot17halfval.py' + ]) + def test_init(self, cfg_file): + cfg = get_detector_cfg(cfg_file) + tracker = MODELS.build(cfg['tracker']) + tracker.kf = TASK_UTILS.build(cfg['tracker']['motion']) + tracker.cmc = TASK_UTILS.build(cfg['cmc']) + + bboxes = random_boxes(self.num_objs, 512) + labels = torch.zeros(self.num_objs) + scores = torch.ones(self.num_objs) + ids = torch.arange(self.num_objs) + tracker.update( + ids=ids, bboxes=bboxes, scores=scores, labels=labels, frame_ids=0) + + assert tracker.ids == list(ids) + assert tracker.memo_items == [ + 'ids', 'bboxes', 'scores', 'labels', 'frame_ids' + ] + + @parameterized.expand([ + 'strongsort/strongsort_yolox_x_8xb4-80e_crowdhuman-mot17halftrain' + '_test-mot17halfval.py' + ]) + def test_track(self, cfg_file): + img = torch.rand((1, 3, 128, 128)) + + cfg = get_detector_cfg(cfg_file) + tracker = MODELS.build(cfg['tracker']) + tracker.kf = TASK_UTILS.build(cfg['tracker']['motion']) + + model = MagicMock() + model.reid = MODELS.build(cfg['reid']) + model.cmc = TASK_UTILS.build(cfg['cmc']) + + with torch.no_grad(): + packed_inputs = demo_track_inputs(batch_size=1, num_frames=2) + track_data_sample = packed_inputs['data_samples'][0] + video_len = len(track_data_sample) + for frame_id in range(video_len): + img_data_sample = track_data_sample[frame_id] + img_data_sample.pred_instances = \ + img_data_sample.gt_instances.clone() + # add fake scores + scores = torch.ones(len(img_data_sample.gt_instances.bboxes)) + img_data_sample.pred_instances.scores = torch.FloatTensor( + scores) + + pred_track_instances = tracker.track( + model=model, + img=img, + data_sample=img_data_sample, + data_preprocessor=cfg['data_preprocessor']) + + bboxes = pred_track_instances.bboxes + labels = pred_track_instances.labels + + assert bboxes.shape[1] == 4 + assert bboxes.shape[0] == labels.shape[0] diff --git a/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_mask2former_track_head.py b/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_mask2former_track_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fa11c43f4bdb99c5283efe370cac7f9271372a55 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_mask2former_track_head.py @@ -0,0 +1,160 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import Config + +from mmdet.models.tracking_heads import Mask2FormerTrackHead +from mmdet.structures import DetDataSample, TrackDataSample +from mmdet.testing import demo_track_inputs + + +class TestMask2FormerHead(TestCase): + + @classmethod + def setUpClass(cls): + cls.config = Config( + dict( + in_channels=[256, 512, 1024, + 2048], # pass to pixel_decoder inside + strides=[4, 8, 16, 32], + feat_channels=256, + out_channels=256, + num_classes=40, + num_frames=2, + num_queries=100, + num_transformer_feat_level=3, + pixel_decoder=dict( + type='MSDeformAttnPixelDecoder', + num_outs=3, + norm_cfg=dict(type='GN', num_groups=32), + act_cfg=dict(type='ReLU'), + encoder=dict( + num_layers=6, + layer_cfg=dict( + self_attn_cfg=dict( + embed_dims=256, + num_heads=8, + num_levels=3, + num_points=4, + im2col_step=128, + dropout=0.0, + batch_first=True), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=1024, + num_fcs=2, + ffn_drop=0.0, + act_cfg=dict(type='ReLU', inplace=True)))), + positional_encoding=dict(num_feats=128, normalize=True)), + enforce_decoder_input_project=False, + positional_encoding=dict( + type='SinePositionalEncoding3D', + num_feats=128, + normalize=True), + transformer_decoder=dict( # Mask2FormerTransformerDecoder + return_intermediate=True, + num_layers=9, + layer_cfg=dict( # Mask2FormerTransformerDecoderLayer + self_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.0, + batch_first=True), + cross_attn_cfg=dict( # MultiheadAttention + embed_dims=256, + num_heads=8, + dropout=0.0, + batch_first=True), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + ffn_drop=0.0, + act_cfg=dict(type='ReLU', inplace=True))), + init_cfg=None), + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=2.0, + reduction='mean', + class_weight=[1.0] * 40 + [0.1]), + loss_mask=dict( + type='CrossEntropyLoss', + use_sigmoid=True, + reduction='mean', + loss_weight=5.0), + loss_dice=dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + reduction='mean', + naive_dice=True, + eps=1.0, + loss_weight=5.0), + train_cfg=dict( + num_points=12544, + oversample_ratio=3.0, + importance_sample_ratio=0.75, + assigner=dict( + type='mmdet.HungarianAssigner', + match_costs=[ + dict(type='mmdet.ClassificationCost', weight=2.0), + dict( + type='mmdet.CrossEntropyLossCost', + weight=5.0, + use_sigmoid=True), + dict( + type='mmdet.DiceCost', + weight=5.0, + pred_act=True, + eps=1.0) + ]), + sampler=dict(type='mmdet.MaskPseudoSampler')))) + + def test_mask2former_head_loss(self): + mask2former_head = Mask2FormerTrackHead(**self.config) + mask2former_head.init_weights() + s = 256 + feats = [ + torch.rand(2, 256 * (2**i), s // stride, s // stride) + for i, stride in enumerate([8, 16, 32, 64]) + ] + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=[(3, s, s)], + num_classes=2, + with_mask=True) + data_sample = packed_inputs['data_samples'][0] + loss = mask2former_head.loss(feats, [data_sample]) + # loss_cls, loss_mask and loss_dice + assert len(loss) == 30 + + def test_mask2former_head_predict(self): + mask2former_head = Mask2FormerTrackHead(**self.config) + mask2former_head.training = False + mask2former_head.init_weights() + s = 256 + # assume the video has 30 frames + feats = [ + torch.rand(30, 256 * (2**i), s // stride, s // stride) + for i, stride in enumerate([8, 16, 32, 64]) + ] + + img_metas = dict( + img_shape=(s, s), + ori_shape=(s, s), + scale_factor=(1, 1), + pad_shape=(s, s), + batch_input_shape=(s, s)) + + img_data_samples = [ + DetDataSample(metainfo=img_metas) for _ in range(30) + ] + data_sample = TrackDataSample() + data_sample.video_data_samples = img_data_samples + results = mask2former_head.predict(feats, data_sample) + + assert len(results) == 30 diff --git a/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_quasi_dense_embed_head.py b/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_quasi_dense_embed_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5012aa6adfeabcc4802cf67ebdf6359430ef8de9 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_quasi_dense_embed_head.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import mmengine +import torch +from mmengine.structures import InstanceData + +from mmdet.models.tracking_heads import QuasiDenseEmbedHead +from mmdet.registry import TASK_UTILS + + +def _dummy_bbox_sampling(rpn_results_list, batch_gt_instances): + """Create sample results that can be passed to Head.get_targets.""" + num_imgs = len(rpn_results_list) + feat = torch.rand(1, 1, 3, 3) + assign_config = dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.5, + ignore_iof_thr=-1) + sampler_config = dict( + type='CombinedSampler', + num=4, + pos_fraction=0.5, + neg_pos_ub=3, + add_gt_as_proposals=True, + pos_sampler=dict(type='InstanceBalancedPosSampler'), + neg_sampler=dict(type='RandomSampler')) + bbox_assigner = TASK_UTILS.build(assign_config) + bbox_sampler = TASK_UTILS.build(sampler_config) + + sampling_results = [] + for i in range(num_imgs): + assign_result = bbox_assigner.assign(rpn_results_list[i], + batch_gt_instances[i]) + sampling_result = bbox_sampler.sample( + assign_result, + rpn_results_list[i], + batch_gt_instances[i], + feats=feat) + sampling_results.append(sampling_result) + + return sampling_results + + +class TestQuasiDenseEmbedHead(TestCase): + + def test_quasi_dense_embed_head_loss(self): + cfg = mmengine.Config( + dict( + num_convs=4, + num_fcs=1, + embed_channels=256, + norm_cfg=dict(type='GN', num_groups=32), + loss_track=dict( + type='MultiPosCrossEntropyLoss', loss_weight=0.25), + loss_track_aux=dict( + type='MarginL2Loss', + neg_pos_ub=3, + pos_margin=0, + neg_margin=0.1, + hard_mining=True, + loss_weight=1.0))) + + embed_head = QuasiDenseEmbedHead(**cfg) + + key_feats = torch.rand(2, 256, 7, 7) + ref_feats = key_feats + rpn_results = InstanceData() + rpn_results.labels = torch.LongTensor([1, 2]) + rpn_results.priors = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874], + [23.6667, 23.8757, 238.6326, 151.8874]]) + rpn_results_list = [rpn_results] + + gt_instance = InstanceData() + gt_instance.labels = torch.LongTensor([1, 2]) + gt_instance.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874], + [23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instance.instances_id = torch.LongTensor([1, 2]) + batch_gt_instances = [gt_instance] + + sampling_results = _dummy_bbox_sampling(rpn_results_list, + batch_gt_instances) + gt_match_indices_list = [torch.Tensor([0, 1])] + loss_track = embed_head.loss(key_feats, ref_feats, sampling_results, + sampling_results, gt_match_indices_list) + assert loss_track['loss_track'] >= 0, 'track loss should be zero' + assert loss_track['loss_track_aux'] > 0, 'aux loss should be non-zero' + + def test_quasi_dense_embed_head_predict(self): + cfg = mmengine.Config( + dict( + num_convs=4, + num_fcs=1, + embed_channels=256, + norm_cfg=dict(type='GN', num_groups=32), + loss_track=dict( + type='MultiPosCrossEntropyLoss', loss_weight=0.25), + loss_track_aux=dict( + type='MarginL2Loss', + neg_pos_ub=3, + pos_margin=0, + neg_margin=0.1, + hard_mining=True, + loss_weight=1.0))) + + embed_head = QuasiDenseEmbedHead(**cfg) + + key_feats = torch.rand(2, 256, 7, 7) + track_feats = embed_head.predict(key_feats) + + assert isinstance(track_feats, torch.Tensor) + assert track_feats.size() == (2, 256) diff --git a/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_quasi_dense_track_head.py b/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_quasi_dense_track_head.py new file mode 100644 index 0000000000000000000000000000000000000000..dbce5a0ad1698a207f679ebf8a6cbfa4f37dead4 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_quasi_dense_track_head.py @@ -0,0 +1,104 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import init_default_scope +from mmengine.config import Config +from mmengine.structures import InstanceData + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, random_boxes + + +def _fake_proposals(img_metas, proposal_len): + """Create a fake proposal list.""" + results = [] + for i in range(len(img_metas)): + result = InstanceData(metainfo=img_metas[i]) + proposal = random_boxes(proposal_len, 10).to(device='cpu') + result.bboxes = proposal + results.append(result) + return results + + +class TestQuasiDenseTrackHead(TestCase): + + def setUp(self): + init_default_scope('mmdet') + cfg = Config( + dict( + type='QuasiDenseTrackHead', + 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]), + embed_head=dict( + type='QuasiDenseEmbedHead', + num_convs=4, + num_fcs=1, + embed_channels=256, + norm_cfg=dict(type='GN', num_groups=32), + loss_track=dict( + type='MultiPosCrossEntropyLoss', loss_weight=0.25), + loss_track_aux=dict( + type='MarginL2Loss', + neg_pos_ub=3, + pos_margin=0, + neg_margin=0.1, + hard_mining=True, + loss_weight=1.0)), + loss_bbox=dict(type='L1Loss', loss_weight=1.0), + train_cfg=dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.5, + min_pos_iou=0.5, + match_low_quality=False, + ignore_iof_thr=-1), + sampler=dict( + type='CombinedSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=3, + add_gt_as_proposals=True, + pos_sampler=dict(type='InstanceBalancedPosSampler'), + neg_sampler=dict(type='RandomSampler'))))) + self.track_head = MODELS.build(cfg) + + def test_quasi_dense_track_head_loss(self): + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=[(3, 256, 256)]) + img_metas = [{ + 'img_shape': (256, 256, 3), + 'scale_factor': 1, + }] + proposal_list = _fake_proposals(img_metas, 10) + feats = [] + for i in range(len(self.track_head.roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, 256 // (2**(i + 2)), + 256 // (2**(i + 2))).to(device='cpu')) + key_feats = tuple(feats) + ref_feats = key_feats + loss_track = self.track_head.loss(key_feats, ref_feats, proposal_list, + proposal_list, + [packed_inputs['data_samples'][0]]) + assert loss_track['loss_track'] >= 0, 'track loss should be zero' + assert loss_track['loss_track_aux'] > 0, 'aux loss should be non-zero' + + def test_quasi_dense_track_head_predict(self): + feats = [] + for i in range(len(self.track_head.roi_extractor.featmap_strides)): + feats.append( + torch.rand(1, 256, 256 // (2**(i + 2)), + 256 // (2**(i + 2))).to(device='cpu')) + feats = tuple(feats) + track_feat = self.track_head.predict( + feats, [torch.Tensor([[10, 10, 20, 20]])]) + assert track_feat.size() == (1, 256) diff --git a/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_roi_embed_head.py b/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_roi_embed_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbecd158bc0b62528282555b58a0c7affc65350 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_tracking_heads/test_roi_embed_head.py @@ -0,0 +1,108 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import mmengine +import torch +from mmengine.structures import InstanceData + +from mmdet.models.tracking_heads import RoIEmbedHead +from mmdet.registry import TASK_UTILS + + +def _dummy_bbox_sampling(rpn_results_list, batch_gt_instances): + """Create sample results that can be passed to Head.get_targets.""" + num_imgs = len(rpn_results_list) + feat = torch.rand(1, 1, 3, 3) + assign_config = dict( + type='MaxIoUAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.5, + ignore_iof_thr=-1) + sampler_config = dict( + type='RandomSampler', + num=512, + pos_fraction=0.25, + neg_pos_ub=-1, + add_gt_as_proposals=False) + bbox_assigner = TASK_UTILS.build(assign_config) + bbox_sampler = TASK_UTILS.build(sampler_config) + + sampling_results = [] + for i in range(num_imgs): + assign_result = bbox_assigner.assign(rpn_results_list[i], + batch_gt_instances[i]) + sampling_result = bbox_sampler.sample( + assign_result, + rpn_results_list[i], + batch_gt_instances[i], + feats=feat) + sampling_results.append(sampling_result) + + return sampling_results + + +class TestRoIEmbedHead(TestCase): + + def test_roi_embed_head_loss(self): + """Test roi embed head loss when truth is non-empty.""" + cfg = mmengine.Config( + dict( + num_convs=2, + num_fcs=2, + roi_feat_size=7, + in_channels=16, + fc_out_channels=32)) + + embed_head = RoIEmbedHead(**cfg) + + x = torch.rand(1, 16, 7, 7) + ref_x = torch.rand(1, 16, 7, 7) + num_x_per_img = [1] + num_x_per_ref_img = [1] + x_split, ref_x_split = embed_head.forward(x, ref_x, num_x_per_img, + num_x_per_ref_img) + + gt_instance_ids = [torch.LongTensor([2])] + ref_gt_instance_ids = [torch.LongTensor([2])] + + rpn_results = InstanceData() + rpn_results.labels = torch.LongTensor([2]) + rpn_results.priors = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + rpn_results_list = [rpn_results] + + gt_instance = InstanceData() + gt_instance.labels = torch.LongTensor([2]) + gt_instance.bboxes = torch.Tensor( + [[23.6667, 23.8757, 238.6326, 151.8874]]) + gt_instance.instances_id = torch.LongTensor([2]) + batch_gt_instances = [gt_instance] + + sampling_results = _dummy_bbox_sampling(rpn_results_list, + batch_gt_instances) + + gt_losses = embed_head.loss_by_feat(x_split, ref_x_split, + sampling_results, gt_instance_ids, + ref_gt_instance_ids) + assert gt_losses['loss_match'] > 0, 'match loss should be non-zero' + assert gt_losses[ + 'match_accuracy'] >= 0, 'match accuracy should be non-zero or zero' + + def test_roi_embed_head_predict(self): + cfg = mmengine.Config( + dict( + num_convs=2, + num_fcs=2, + roi_feat_size=7, + in_channels=16, + fc_out_channels=32)) + + embed_head = RoIEmbedHead(**cfg) + + x = torch.rand(1, 16, 7, 7) + ref_x = torch.rand(1, 16, 7, 7) + similarity_logits = embed_head.predict(x, ref_x) + + assert isinstance(similarity_logits, list) + assert len(similarity_logits) == 1 diff --git a/mmdet_code/mmdetection/tests/test_models/test_tta/test_det_tta.py b/mmdet_code/mmdetection/tests/test_models/test_tta/test_det_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..c94483c67eac5f2450c7cc5866c102aec72fa8e9 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_tta/test_det_tta.py @@ -0,0 +1,48 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import torch +from mmengine import ConfigDict + +from mmdet.models import DetTTAModel +from mmdet.registry import MODELS +from mmdet.structures import DetDataSample +from mmdet.testing import get_detector_cfg +from mmdet.utils import register_all_modules + + +class TestDetTTAModel(TestCase): + + def setUp(self): + register_all_modules() + + def test_det_tta_model(self): + + detector_cfg = get_detector_cfg( + 'retinanet/retinanet_r18_fpn_1x_coco.py') + cfg = ConfigDict( + type='DetTTAModel', + module=detector_cfg, + tta_cfg=dict( + nms=dict(type='nms', iou_threshold=0.5), max_per_img=100)) + + model: DetTTAModel = MODELS.build(cfg) + + imgs = [] + data_samples = [] + directions = ['horizontal', 'vertical'] + for i in range(12): + flip_direction = directions[0] if i % 3 == 0 else directions[1] + imgs.append(torch.randn(1, 3, 100 + 10 * i, 100 + 10 * i)) + data_samples.append([ + DetDataSample( + metainfo=dict( + ori_shape=(100, 100), + img_shape=(100 + 10 * i, 100 + 10 * i), + scale_factor=((100 + 10 * i) / 100, + (100 + 10 * i) / 100), + flip=(i % 2 == 0), + flip_direction=flip_direction), ) + ]) + + model.test_step(dict(inputs=imgs, data_samples=data_samples)) diff --git a/mmdet_code/mmdetection/tests/test_models/test_utils/test_misc.py b/mmdet_code/mmdetection/tests/test_models/test_utils/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..2e54ff70f572b0212f607f8d9ee14ddaa5084400 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_utils/test_misc.py @@ -0,0 +1,110 @@ +import copy + +import pytest +import torch +from mmengine.structures import InstanceData + +from mmdet.models.utils import (empty_instances, filter_gt_instances, + rename_loss_dict, reweight_loss_dict, + unpack_gt_instances) +from mmdet.testing import demo_mm_inputs + + +def test_parse_gt_instance_info(): + packed_inputs = demo_mm_inputs()['data_samples'] + batch_gt_instances, batch_gt_instances_ignore, batch_img_metas \ + = unpack_gt_instances(packed_inputs) + assert len(batch_gt_instances) == len(packed_inputs) + assert len(batch_gt_instances_ignore) == len(packed_inputs) + assert len(batch_img_metas) == len(packed_inputs) + + +def test_process_empty_roi(): + batch_size = 2 + batch_img_metas = [{'ori_shape': (10, 12)}] * batch_size + device = torch.device('cpu') + + results_list = empty_instances(batch_img_metas, device, task_type='bbox') + assert len(results_list) == batch_size + for results in results_list: + assert isinstance(results, InstanceData) + assert len(results) == 0 + assert torch.allclose(results.bboxes, torch.zeros(0, 4, device=device)) + + results_list = empty_instances( + batch_img_metas, + device, + task_type='mask', + instance_results=results_list, + mask_thr_binary=0.5) + assert len(results_list) == batch_size + for results in results_list: + assert isinstance(results, InstanceData) + assert len(results) == 0 + assert results.masks.shape == (0, 10, 12) + + # batch_img_metas and instance_results length must be the same + with pytest.raises(AssertionError): + empty_instances( + batch_img_metas, + device, + task_type='mask', + instance_results=[results_list[0]] * 3) + + +def test_filter_gt_instances(): + packed_inputs = demo_mm_inputs()['data_samples'] + score_thr = 0.7 + with pytest.raises(AssertionError): + filter_gt_instances(packed_inputs, score_thr=score_thr) + + # filter no instances by score + for inputs in packed_inputs: + inputs.gt_instances.scores = torch.ones_like( + inputs.gt_instances.labels).float() + filtered_packed_inputs = filter_gt_instances( + copy.deepcopy(packed_inputs), score_thr=score_thr) + for filtered_inputs, inputs in zip(filtered_packed_inputs, packed_inputs): + assert len(filtered_inputs.gt_instances) == len(inputs.gt_instances) + + # filter all instances + for inputs in packed_inputs: + inputs.gt_instances.scores = torch.zeros_like( + inputs.gt_instances.labels).float() + filtered_packed_inputs = filter_gt_instances( + copy.deepcopy(packed_inputs), score_thr=score_thr) + for filtered_inputs in filtered_packed_inputs: + assert len(filtered_inputs.gt_instances) == 0 + + packed_inputs = demo_mm_inputs()['data_samples'] + # filter no instances by size + wh_thr = (0, 0) + filtered_packed_inputs = filter_gt_instances( + copy.deepcopy(packed_inputs), wh_thr=wh_thr) + for filtered_inputs, inputs in zip(filtered_packed_inputs, packed_inputs): + assert len(filtered_inputs.gt_instances) == len(inputs.gt_instances) + + # filter all instances by size + for inputs in packed_inputs: + img_shape = inputs.img_shape + wh_thr = (max(wh_thr[0], img_shape[0]), max(wh_thr[1], img_shape[1])) + filtered_packed_inputs = filter_gt_instances( + copy.deepcopy(packed_inputs), wh_thr=wh_thr) + for filtered_inputs in filtered_packed_inputs: + assert len(filtered_inputs.gt_instances) == 0 + + +def test_rename_loss_dict(): + prefix = 'sup_' + losses = {'cls_loss': torch.tensor(2.), 'reg_loss': torch.tensor(1.)} + sup_losses = rename_loss_dict(prefix, losses) + for name in losses.keys(): + assert sup_losses[prefix + name] == losses[name] + + +def test_reweight_loss_dict(): + weight = 4 + losses = {'cls_loss': torch.tensor(2.), 'reg_loss': torch.tensor(1.)} + weighted_losses = reweight_loss_dict(copy.deepcopy(losses), weight) + for name in losses.keys(): + assert weighted_losses[name] == losses[name] * weight diff --git a/mmdet_code/mmdetection/tests/test_models/test_utils/test_model_misc.py b/mmdet_code/mmdetection/tests/test_models/test_utils/test_model_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..93de33675141032a199261ddb6fdbc83bfe3ef2a --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_utils/test_model_misc.py @@ -0,0 +1,36 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +import torch +from torch.autograd import gradcheck + +from mmdet.models.utils import interpolate_as, sigmoid_geometric_mean + + +def test_interpolate_as(): + source = torch.rand((1, 5, 4, 4)) + target = torch.rand((1, 1, 16, 16)) + + # Test 4D source and target + result = interpolate_as(source, target) + assert result.shape == torch.Size((1, 5, 16, 16)) + + # Test 3D target + result = interpolate_as(source, target.squeeze(0)) + assert result.shape == torch.Size((1, 5, 16, 16)) + + # Test 3D source + result = interpolate_as(source.squeeze(0), target) + assert result.shape == torch.Size((5, 16, 16)) + + # Test type(target) == np.ndarray + target = np.random.rand(16, 16) + result = interpolate_as(source.squeeze(0), target) + assert result.shape == torch.Size((5, 16, 16)) + + +def test_sigmoid_geometric_mean(): + x = torch.randn(20, 20, dtype=torch.double, requires_grad=True) + y = torch.randn(20, 20, dtype=torch.double, requires_grad=True) + inputs = (x, y) + test = gradcheck(sigmoid_geometric_mean, inputs, eps=1e-6, atol=1e-4) + assert test diff --git a/mmdet_code/mmdetection/tests/test_models/test_vis/test_mask2former.py b/mmdet_code/mmdetection/tests/test_models/test_vis/test_mask2former.py new file mode 100644 index 0000000000000000000000000000000000000000..c8d3474e9ca7b0058e0b46d9cb36f35adebd1f53 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_vis/test_mask2former.py @@ -0,0 +1,96 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestMask2Former(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py', + ]) + def test_mask2former_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + + model = MODELS.build(model) + assert model.backbone + assert model.track_head + + @parameterized.expand([ + ('mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py', + ('cpu', 'cuda')), + ]) + def test_mask2former_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_mask2former_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=(3, 128, 128), + num_classes=2, + with_mask=True) + out_data = model.data_preprocessor(packed_inputs, True) + inputs, data_samples = out_data['inputs'], out_data['data_samples'] + losses = model.forward(inputs, data_samples, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ('mask2former_vis/mask2former_r50_8xb2-8e_youtubevis2021.py', + ('cpu', 'cuda')), + ]) + def test_mask2former_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_mask2former_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=1, + image_shapes=(3, 128, 128), + num_classes=2, + with_mask=True) + out_data = model.data_preprocessor(packed_inputs, False) + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/mmdetection/tests/test_models/test_vis/test_masktrack_rcnn.py b/mmdet_code/mmdetection/tests/test_models/test_vis/test_masktrack_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..fb94391f4d1dcf0c5b54fd2c5cb3f33ef9033360 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_models/test_vis/test_masktrack_rcnn.py @@ -0,0 +1,99 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import time +import unittest +from unittest import TestCase + +import torch +from mmengine.logging import MessageHub +from mmengine.registry import init_default_scope +from parameterized import parameterized + +from mmdet.registry import MODELS +from mmdet.testing import demo_track_inputs, get_detector_cfg + + +class TestMaskTrackRCNN(TestCase): + + @classmethod + def setUpClass(cls): + init_default_scope('mmdet') + + @parameterized.expand([ + 'masktrack_rcnn/masktrack-rcnn_mask-rcnn_r50_fpn_8xb1-12e_youtubevis2019.py', # noqa: E501 + ]) + def test_mask_track_rcnn_init(self, cfg_file): + model = get_detector_cfg(cfg_file) + + model = MODELS.build(model) + assert model.detector + assert model.track_head + assert model.tracker + + @parameterized.expand([ + ( + 'masktrack_rcnn/masktrack-rcnn_mask-rcnn_r50_fpn_8xb1-12e_youtubevis2019.py', # noqa: E501 + ('cpu', 'cuda')), + ]) + def test_mask_track_rcnn_forward_loss_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_mask_track_rcnn_forward_loss_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + # _scope_ will be popped after build + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=2, + key_frames_inds=[0], + image_shapes=(3, 128, 128), + num_classes=2, + with_mask=True) + out_data = model.data_preprocessor(packed_inputs, True) + # Test forward + losses = model.forward(**out_data, mode='loss') + assert isinstance(losses, dict) + + @parameterized.expand([ + ( + 'masktrack_rcnn/masktrack-rcnn_mask-rcnn_r50_fpn_8xb1-12e_youtubevis2019.py', # noqa: E501 + ('cpu', 'cuda')), + ]) + def test_mask_track_rcnn_forward_predict_mode(self, cfg_file, devices): + message_hub = MessageHub.get_instance( + f'test_mask_track_rcnn_forward_predict_mode-{time.time()}') + message_hub.update_info('iter', 0) + message_hub.update_info('epoch', 0) + + assert all([device in ['cpu', 'cuda'] for device in devices]) + + for device in devices: + _model = get_detector_cfg(cfg_file) + model = MODELS.build(_model) + + if device == 'cuda': + if not torch.cuda.is_available(): + return unittest.skip('test requires GPU and torch+cuda') + model = model.cuda() + + packed_inputs = demo_track_inputs( + batch_size=1, + num_frames=1, + image_shapes=(3, 128, 128), + num_classes=2, + with_mask=True) + out_data = model.data_preprocessor(packed_inputs, False) + # Test forward test + model.eval() + with torch.no_grad(): + batch_results = model.forward(**out_data, mode='predict') + assert len(batch_results) == 1 diff --git a/mmdet_code/mmdetection/tests/test_structures/__init__.py b/mmdet_code/mmdetection/tests/test_structures/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/mmdetection/tests/test_structures/test_bbox/__init__.py b/mmdet_code/mmdetection/tests/test_structures/test_bbox/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_base_boxes.py b/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_base_boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..651eeefe12071177cdf335094fd4498ae4fb1390 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_base_boxes.py @@ -0,0 +1,276 @@ +from unittest import TestCase + +import numpy as np +import torch +from mmengine.testing import assert_allclose + +from .utils import ToyBaseBoxes + + +class TestBaseBoxes(TestCase): + + def test_init(self): + box_tensor = torch.rand((3, 4, 4)) + boxes = ToyBaseBoxes(box_tensor) + + boxes = ToyBaseBoxes(box_tensor, dtype=torch.float64) + self.assertEqual(boxes.tensor.dtype, torch.float64) + + if torch.cuda.is_available(): + boxes = ToyBaseBoxes(box_tensor, device='cuda') + self.assertTrue(boxes.tensor.is_cuda) + + with self.assertRaises(AssertionError): + box_tensor = torch.rand((4, )) + boxes = ToyBaseBoxes(box_tensor) + + with self.assertRaises(AssertionError): + box_tensor = torch.rand((3, 4, 3)) + boxes = ToyBaseBoxes(box_tensor) + + def test_getitem(self): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + + # test single dimension index + # int + new_boxes = boxes[0] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (4, 4)) + # list + new_boxes = boxes[[0, 2]] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (2, 4, 4)) + # slice + new_boxes = boxes[0:2] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (2, 4, 4)) + # torch.LongTensor + new_boxes = boxes[torch.LongTensor([0, 1])] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (2, 4, 4)) + # torch.BoolTensor + new_boxes = boxes[torch.BoolTensor([True, False, True])] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (2, 4, 4)) + with self.assertRaises(AssertionError): + index = torch.rand((2, 4, 4)) > 0 + new_boxes = boxes[index] + + # test multiple dimension index + # select single box + new_boxes = boxes[1, 2] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (1, 4)) + # select the last dimension + with self.assertRaises(AssertionError): + new_boxes = boxes[1, 2, 1] + # has Ellipsis + new_boxes = boxes[None, ...] + self.assertIsInstance(new_boxes, ToyBaseBoxes) + self.assertEqual(new_boxes.tensor.shape, (1, 3, 4, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes[..., None] + + def test_setitem(self): + values = ToyBaseBoxes(torch.rand(3, 4, 4)) + tensor = torch.rand(3, 4, 4) + + # only support BaseBoxes type + with self.assertRaises(AssertionError): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[0:2] = tensor[0:2] + + # test single dimension index + # int + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[1] = values[1] + assert_allclose(boxes.tensor[1], values.tensor[1]) + # list + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[[1, 2]] = values[[1, 2]] + assert_allclose(boxes.tensor[[1, 2]], values.tensor[[1, 2]]) + # slice + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[0:2] = values[0:2] + assert_allclose(boxes.tensor[0:2], values.tensor[0:2]) + # torch.BoolTensor + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + index = torch.rand(3, 4) > 0.5 + boxes[index] = values[index] + assert_allclose(boxes.tensor[index], values.tensor[index]) + + # multiple dimension index + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[0:2, 0:2] = values[0:2, 0:2] + assert_allclose(boxes.tensor[0:2, 0:2], values.tensor[0:2, 0:2]) + # select single box + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[1, 1] = values[1, 1] + assert_allclose(boxes.tensor[1, 1], values.tensor[1, 1]) + # select the last dimension + with self.assertRaises(AssertionError): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[1, 1, 1] = values[1, 1, 1] + # has Ellipsis + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + boxes[0:2, ...] = values[0:2, ...] + assert_allclose(boxes.tensor[0:2, ...], values.tensor[0:2, ...]) + + def test_tensor_like_functions(self): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + # new_tensor + boxes.new_tensor([1, 2, 3]) + # new_full + boxes.new_full((3, 4), 0) + # new_empty + boxes.new_empty((3, 4)) + # new_ones + boxes.new_ones((3, 4)) + # new_zeros + boxes.new_zeros((3, 4)) + # size + self.assertEqual(boxes.size(0), 3) + self.assertEqual(tuple(boxes.size()), (3, 4, 4)) + # dim + self.assertEqual(boxes.dim(), 3) + # device + self.assertIsInstance(boxes.device, torch.device) + # dtype + self.assertIsInstance(boxes.dtype, torch.dtype) + # numpy + np_boxes = boxes.numpy() + self.assertIsInstance(np_boxes, np.ndarray) + self.assertTrue((np_boxes == np_boxes).all()) + # to + new_boxes = boxes.to(torch.uint8) + self.assertEqual(new_boxes.tensor.dtype, torch.uint8) + if torch.cuda.is_available(): + new_boxes = boxes.to(device='cuda') + self.assertTrue(new_boxes.tensor.is_cuda) + # cpu + if torch.cuda.is_available(): + new_boxes = boxes.to(device='cuda') + new_boxes = new_boxes.cpu() + self.assertFalse(new_boxes.tensor.is_cuda) + # cuda + if torch.cuda.is_available(): + new_boxes = boxes.cuda() + self.assertTrue(new_boxes.tensor.is_cuda) + # clone + boxes.clone() + # detach + boxes.detach() + # view + new_boxes = boxes.view(12, 4) + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + new_boxes = boxes.view(-1, 4) + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.view(-1) + # reshape + new_boxes = boxes.reshape(12, 4) + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + new_boxes = boxes.reshape(-1, 4) + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.reshape(-1) + # expand + new_boxes = boxes[None, ...].expand(4, -1, -1, -1) + self.assertEqual(tuple(new_boxes.size()), (4, 3, 4, 4)) + # repeat + new_boxes = boxes.repeat(2, 2, 1) + self.assertEqual(tuple(new_boxes.size()), (6, 8, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.repeat(2, 2, 2) + # transpose + new_boxes = boxes.transpose(0, 1) + self.assertEqual(tuple(new_boxes.size()), (4, 3, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.transpose(1, 2) + # permute + new_boxes = boxes.permute(1, 0, 2) + self.assertEqual(tuple(new_boxes.size()), (4, 3, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.permute(2, 1, 0) + # split + boxes_list = boxes.split(1, dim=0) + for box in boxes_list: + self.assertIsInstance(box, ToyBaseBoxes) + self.assertEqual(tuple(box.size()), (1, 4, 4)) + boxes_list = boxes.split([1, 2], dim=0) + with self.assertRaises(AssertionError): + boxes_list = boxes.split(1, dim=2) + # chunk + boxes_list = boxes.split(3, dim=1) + self.assertEqual(len(boxes_list), 2) + for box in boxes_list: + self.assertIsInstance(box, ToyBaseBoxes) + with self.assertRaises(AssertionError): + boxes_list = boxes.split(3, dim=2) + # unbind + boxes_list = boxes.unbind(dim=1) + self.assertEqual(len(boxes_list), 4) + for box in boxes_list: + self.assertIsInstance(box, ToyBaseBoxes) + self.assertEqual(tuple(box.size()), (3, 4)) + with self.assertRaises(AssertionError): + boxes_list = boxes.unbind(dim=2) + # flatten + new_boxes = boxes.flatten() + self.assertEqual(tuple(new_boxes.size()), (12, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.flatten(end_dim=2) + # squeeze + boxes = ToyBaseBoxes(torch.rand(1, 3, 1, 4, 4)) + new_boxes = boxes.squeeze() + self.assertEqual(tuple(new_boxes.size()), (3, 4, 4)) + new_boxes = boxes.squeeze(dim=2) + self.assertEqual(tuple(new_boxes.size()), (1, 3, 4, 4)) + # unsqueeze + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + new_boxes = boxes.unsqueeze(0) + self.assertEqual(tuple(new_boxes.size()), (1, 3, 4, 4)) + with self.assertRaises(AssertionError): + new_boxes = boxes.unsqueeze(3) + # cat + with self.assertRaises(ValueError): + ToyBaseBoxes.cat([]) + box_list = [] + box_list.append(ToyBaseBoxes(torch.rand(3, 4, 4))) + box_list.append(ToyBaseBoxes(torch.rand(1, 4, 4))) + with self.assertRaises(AssertionError): + ToyBaseBoxes.cat(box_list, dim=2) + cat_boxes = ToyBaseBoxes.cat(box_list, dim=0) + self.assertIsInstance(cat_boxes, ToyBaseBoxes) + self.assertEqual((cat_boxes.size()), (4, 4, 4)) + # stack + with self.assertRaises(ValueError): + ToyBaseBoxes.stack([]) + box_list = [] + box_list.append(ToyBaseBoxes(torch.rand(3, 4, 4))) + box_list.append(ToyBaseBoxes(torch.rand(3, 4, 4))) + with self.assertRaises(AssertionError): + ToyBaseBoxes.stack(box_list, dim=3) + stack_boxes = ToyBaseBoxes.stack(box_list, dim=1) + self.assertIsInstance(stack_boxes, ToyBaseBoxes) + self.assertEqual((stack_boxes.size()), (3, 2, 4, 4)) + + def test_misc(self): + boxes = ToyBaseBoxes(torch.rand(3, 4, 4)) + # __len__ + self.assertEqual(len(boxes), 3) + # __repr__ + repr(boxes) + # fake_boxes + new_boxes = boxes.fake_boxes((3, 4, 4), 1) + self.assertEqual(tuple(new_boxes.size()), (3, 4, 4)) + self.assertEqual(boxes.dtype, new_boxes.dtype) + self.assertEqual(boxes.device, new_boxes.device) + self.assertTrue((new_boxes.tensor == 1).all()) + with self.assertRaises(AssertionError): + new_boxes = boxes.fake_boxes((3, 4, 1)) + new_boxes = boxes.fake_boxes((3, 4, 4), dtype=torch.uint8) + self.assertEqual(new_boxes.dtype, torch.uint8) + if torch.cuda.is_available(): + new_boxes = boxes.fake_boxes((3, 4, 4), device='cuda') + self.assertTrue(new_boxes.tensor.is_cuda) diff --git a/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_box_type.py b/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_box_type.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f58460743047b3568cd34878ce4b281d2d1c43 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_box_type.py @@ -0,0 +1,191 @@ +from unittest import TestCase +from unittest.mock import MagicMock + +import torch + +from mmdet.structures.bbox.box_type import (_box_type_to_name, box_converters, + box_types, convert_box_type, + get_box_type, register_box, + register_box_converter) +from .utils import ToyBaseBoxes + + +class TestBoxType(TestCase): + + def setUp(self): + self.box_types = box_types.copy() + self.box_converters = box_converters.copy() + self._box_type_to_name = _box_type_to_name.copy() + + def tearDown(self): + # Clear registered items + box_types.clear() + box_converters.clear() + _box_type_to_name.clear() + # Restore original items + box_types.update(self.box_types) + box_converters.update(self.box_converters) + _box_type_to_name.update(self._box_type_to_name) + + def test_register_box(self): + # test usage of decorator + @register_box('A') + class A(ToyBaseBoxes): + pass + + # test usage of normal function + class B(ToyBaseBoxes): + pass + + register_box('B', B) + + # register class without inheriting from BaseBoxes + with self.assertRaises(AssertionError): + + @register_box('C') + class C: + pass + + # test register registered class + with self.assertRaises(KeyError): + + @register_box('A') + class AA(ToyBaseBoxes): + pass + + with self.assertRaises(KeyError): + register_box('BB', B) + + @register_box('A', force=True) + class AAA(ToyBaseBoxes): + pass + + self.assertIs(box_types['a'], AAA) + self.assertEqual(_box_type_to_name[AAA], 'a') + register_box('BB', B, force=True) + self.assertIs(box_types['bb'], B) + self.assertEqual(_box_type_to_name[B], 'bb') + self.assertEqual(len(box_types), len(_box_type_to_name)) + + def test_register_box_converter(self): + + @register_box('A') + class A(ToyBaseBoxes): + pass + + @register_box('B') + class B(ToyBaseBoxes): + pass + + @register_box('C') + class C(ToyBaseBoxes): + pass + + # test usage of decorator + @register_box_converter('A', 'B') + def converter_A(bboxes): + return bboxes + + # test usage of normal function + def converter_B(bboxes): + return bboxes + + register_box_converter('B' + 'A', converter_B) + + # register uncallable object + with self.assertRaises(AssertionError): + register_box_converter('A', 'C', 'uncallable str') + + # test register unregistered bbox mode + with self.assertRaises(AssertionError): + + @register_box_converter('A', 'D') + def converter_C(bboxes): + return bboxes + + # test register registered converter + with self.assertRaises(KeyError): + + @register_box_converter('A', 'B') + def converter_D(bboxes): + return bboxes + + @register_box_converter('A', 'B', force=True) + def converter_E(bboxes): + return bboxes + + self.assertIs(box_converters['a2b'], converter_E) + + def test_get_box_type(self): + + @register_box('A') + class A(ToyBaseBoxes): + pass + + mode_name, mode_cls = get_box_type('A') + self.assertEqual(mode_name, 'a') + self.assertIs(mode_cls, A) + mode_name, mode_cls = get_box_type(A) + self.assertEqual(mode_name, 'a') + self.assertIs(mode_cls, A) + + # get unregistered mode + class B(ToyBaseBoxes): + pass + + with self.assertRaises(AssertionError): + mode_name, mode_cls = get_box_type('B') + with self.assertRaises(AssertionError): + mode_name, mode_cls = get_box_type(B) + + def test_convert_box_type(self): + + @register_box('A') + class A(ToyBaseBoxes): + pass + + @register_box('B') + class B(ToyBaseBoxes): + pass + + @register_box('C') + class C(ToyBaseBoxes): + pass + + converter = MagicMock() + converter.return_value = torch.rand(3, 4, 4) + register_box_converter('A', 'B', converter) + + bboxes_a = A(torch.rand(3, 4, 4)) + th_bboxes_a = bboxes_a.tensor + np_bboxes_a = th_bboxes_a.numpy() + + # test convert to mode + convert_box_type(bboxes_a, dst_type='B') + self.assertTrue(converter.called) + converted_bboxes = convert_box_type(bboxes_a, dst_type='A') + self.assertIs(converted_bboxes, bboxes_a) + # test convert to unregistered mode + with self.assertRaises(AssertionError): + convert_box_type(bboxes_a, dst_type='C') + + # test convert tensor and ndarray + # without specific src_type + with self.assertRaises(AssertionError): + convert_box_type(th_bboxes_a, dst_type='B') + with self.assertRaises(AssertionError): + convert_box_type(np_bboxes_a, dst_type='B') + # test np.ndarray + convert_box_type(np_bboxes_a, src_type='A', dst_type='B') + converted_bboxes = convert_box_type( + np_bboxes_a, src_type='A', dst_type='A') + self.assertIs(converted_bboxes, np_bboxes_a) + # test tensor + convert_box_type(th_bboxes_a, src_type='A', dst_type='B') + converted_bboxes = convert_box_type( + th_bboxes_a, src_type='A', dst_type='A') + self.assertIs(converted_bboxes, th_bboxes_a) + # test other type + with self.assertRaises(TypeError): + convert_box_type([[1, 2, 3, 4]], src_type='A', dst_type='B') diff --git a/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_horizontal_boxes.py b/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_horizontal_boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..1030e956def578cdf025d79f6a347994b5043c3e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_structures/test_bbox/test_horizontal_boxes.py @@ -0,0 +1,187 @@ +import random +from math import sqrt +from unittest import TestCase + +import cv2 +import numpy as np +import torch +from mmengine.testing import assert_allclose + +from mmdet.structures.bbox import HorizontalBoxes +from mmdet.structures.mask import BitmapMasks, PolygonMasks + + +class TestHorizontalBoxes(TestCase): + + def test_init(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + th_boxes_cxcywh = torch.Tensor([15, 15, 10, 10]).reshape(1, 1, 4) + + boxes = HorizontalBoxes(th_boxes) + assert_allclose(boxes.tensor, th_boxes) + boxes = HorizontalBoxes(th_boxes, in_mode='xyxy') + assert_allclose(boxes.tensor, th_boxes) + boxes = HorizontalBoxes(th_boxes_cxcywh, in_mode='cxcywh') + assert_allclose(boxes.tensor, th_boxes) + with self.assertRaises(ValueError): + boxes = HorizontalBoxes(th_boxes, in_mode='invalid') + + def test_cxcywh(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + th_boxes_cxcywh = torch.Tensor([15, 15, 10, 10]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + + assert_allclose( + HorizontalBoxes.xyxy_to_cxcywh(th_boxes), th_boxes_cxcywh) + assert_allclose(th_boxes, + HorizontalBoxes.cxcywh_to_xyxy(th_boxes_cxcywh)) + assert_allclose(boxes.cxcywh, th_boxes_cxcywh) + + def test_propoerty(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + + # Centers + centers = torch.Tensor([15, 15]).reshape(1, 1, 2) + assert_allclose(boxes.centers, centers) + # Areas + areas = torch.Tensor([100]).reshape(1, 1) + assert_allclose(boxes.areas, areas) + # widths + widths = torch.Tensor([10]).reshape(1, 1) + assert_allclose(boxes.widths, widths) + # heights + heights = torch.Tensor([10]).reshape(1, 1) + assert_allclose(boxes.heights, heights) + + def test_flip(self): + img_shape = [50, 85] + # horizontal flip + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + flipped_boxes_th = torch.Tensor([65, 10, 75, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.flip_(img_shape, direction='horizontal') + assert_allclose(boxes.tensor, flipped_boxes_th) + # vertical flip + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + flipped_boxes_th = torch.Tensor([10, 30, 20, 40]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.flip_(img_shape, direction='vertical') + assert_allclose(boxes.tensor, flipped_boxes_th) + # diagonal flip + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + flipped_boxes_th = torch.Tensor([65, 30, 75, 40]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.flip_(img_shape, direction='diagonal') + assert_allclose(boxes.tensor, flipped_boxes_th) + + def test_translate(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.translate_([23, 46]) + translated_boxes_th = torch.Tensor([33, 56, 43, 66]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, translated_boxes_th) + + def test_clip(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + img_shape = [13, 14] + boxes = HorizontalBoxes(th_boxes) + boxes.clip_(img_shape) + cliped_boxes_th = torch.Tensor([10, 10, 14, 13]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, cliped_boxes_th) + + def test_rotate(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + center = (15, 15) + angle = -45 + boxes = HorizontalBoxes(th_boxes) + boxes.rotate_(center, angle) + rotated_boxes_th = torch.Tensor([ + 15 - 5 * sqrt(2), 15 - 5 * sqrt(2), 15 + 5 * sqrt(2), + 15 + 5 * sqrt(2) + ]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, rotated_boxes_th) + + def test_project(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes1 = HorizontalBoxes(th_boxes) + boxes2 = boxes1.clone() + + matrix = np.zeros((3, 3), dtype=np.float32) + center = [random.random() * 80, random.random() * 80] + angle = random.random() * 180 + matrix[:2, :3] = cv2.getRotationMatrix2D(center, angle, 1) + x_translate = random.random() * 40 + y_translate = random.random() * 40 + matrix[0, 2] = matrix[0, 2] + x_translate + matrix[1, 2] = matrix[1, 2] + y_translate + scale_factor = random.random() * 2 + matrix[2, 2] = 1 / scale_factor + boxes1.project_(matrix) + + boxes2.rotate_(center, -angle) + boxes2.translate_([x_translate, y_translate]) + boxes2.rescale_([scale_factor, scale_factor]) + assert_allclose(boxes1.tensor, boxes2.tensor) + # test empty boxes + empty_boxes = HorizontalBoxes(torch.zeros((0, 4))) + empty_boxes.project_(matrix) + + def test_rescale(self): + scale_factor = [0.4, 0.8] + # rescale + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.rescale_(scale_factor) + rescaled_boxes_th = torch.Tensor([4, 8, 8, 16]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, rescaled_boxes_th) + + def test_resize(self): + scale_factor = [0.4, 0.8] + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 1, 4) + boxes = HorizontalBoxes(th_boxes) + boxes.resize_(scale_factor) + resized_boxes_th = torch.Tensor([13, 11, 17, 19]).reshape(1, 1, 4) + assert_allclose(boxes.tensor, resized_boxes_th) + + def test_is_inside(self): + th_boxes = torch.Tensor([[10, 10, 20, 20], [-5, -5, 15, 15], + [45, 45, 55, 55]]).reshape(1, 3, 4) + img_shape = [30, 30] + boxes = HorizontalBoxes(th_boxes) + + index = boxes.is_inside(img_shape) + index_th = torch.BoolTensor([True, True, False]).reshape(1, 3) + assert_allclose(index, index_th) + + def test_find_inside_points(self): + th_boxes = torch.Tensor([10, 10, 20, 20]).reshape(1, 4) + boxes = HorizontalBoxes(th_boxes) + points = torch.Tensor([[0, 0], [0, 15], [15, 0], [15, 15]]) + index = boxes.find_inside_points(points) + index_th = torch.BoolTensor([False, False, False, True]).reshape(4, 1) + assert_allclose(index, index_th) + # is_aligned + boxes = boxes.expand(4, 4) + index = boxes.find_inside_points(points, is_aligned=True) + index_th = torch.BoolTensor([False, False, False, True]) + assert_allclose(index, index_th) + + def test_from_instance_masks(self): + bitmap_masks = BitmapMasks.random() + boxes = HorizontalBoxes.from_instance_masks(bitmap_masks) + self.assertIsInstance(boxes, HorizontalBoxes) + self.assertEqual(len(boxes), len(bitmap_masks)) + polygon_masks = PolygonMasks.random() + boxes = HorizontalBoxes.from_instance_masks(polygon_masks) + self.assertIsInstance(boxes, HorizontalBoxes) + self.assertEqual(len(boxes), len(bitmap_masks)) + # zero length masks + bitmap_masks = BitmapMasks.random(num_masks=0) + boxes = HorizontalBoxes.from_instance_masks(bitmap_masks) + self.assertIsInstance(boxes, HorizontalBoxes) + self.assertEqual(len(boxes), 0) + polygon_masks = PolygonMasks.random(num_masks=0) + boxes = HorizontalBoxes.from_instance_masks(polygon_masks) + self.assertIsInstance(boxes, HorizontalBoxes) + self.assertEqual(len(boxes), 0) diff --git a/mmdet_code/mmdetection/tests/test_structures/test_bbox/utils.py b/mmdet_code/mmdetection/tests/test_structures/test_bbox/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0d15414bd990ac50197c7bf96b779a685fa24203 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_structures/test_bbox/utils.py @@ -0,0 +1,55 @@ +from mmdet.structures.bbox import BaseBoxes + + +class ToyBaseBoxes(BaseBoxes): + + box_dim = 4 + + @property + def centers(self): + pass + + @property + def areas(self): + pass + + @property + def widths(self): + pass + + @property + def heights(self): + pass + + def flip_(self, img_shape, direction='horizontal'): + pass + + def translate_(self, distances): + pass + + def clip_(self, img_shape): + pass + + def rotate_(self, center, angle): + pass + + def project_(self, homography_matrix): + pass + + def rescale_(self, scale_factor): + pass + + def resize_(self, scale_factor): + pass + + def is_inside(self, img_shape): + pass + + def find_inside_points(self, points, is_aligned=False): + pass + + def overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6): + pass + + def from_instance_masks(masks): + pass diff --git a/mmdet_code/mmdetection/tests/test_structures/test_det_data_sample.py b/mmdet_code/mmdetection/tests/test_structures/test_det_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc7bdb90ddbed9ae017cd5bc845e3b3d1734e8f --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_structures/test_det_data_sample.py @@ -0,0 +1,166 @@ +from unittest import TestCase + +import numpy as np +import pytest +import torch +from mmengine.structures import InstanceData, PixelData + +from mmdet.structures import DetDataSample + + +def _equal(a, b): + if isinstance(a, (torch.Tensor, np.ndarray)): + return (a == b).all() + else: + return a == b + + +class TestDetDataSample(TestCase): + + def test_init(self): + meta_info = dict( + img_size=[256, 256], + scale_factor=np.array([1.5, 1.5]), + img_shape=torch.rand(4)) + + det_data_sample = DetDataSample(metainfo=meta_info) + assert 'img_size' in det_data_sample + assert det_data_sample.img_size == [256, 256] + assert det_data_sample.get('img_size') == [256, 256] + + def test_setter(self): + det_data_sample = DetDataSample() + # test gt_instances + gt_instances_data = dict( + bboxes=torch.rand(4, 4), + labels=torch.rand(4), + masks=np.random.rand(4, 2, 2)) + gt_instances = InstanceData(**gt_instances_data) + det_data_sample.gt_instances = gt_instances + assert 'gt_instances' in det_data_sample + assert _equal(det_data_sample.gt_instances.bboxes, + gt_instances_data['bboxes']) + assert _equal(det_data_sample.gt_instances.labels, + gt_instances_data['labels']) + assert _equal(det_data_sample.gt_instances.masks, + gt_instances_data['masks']) + + # test pred_instances + pred_instances_data = dict( + bboxes=torch.rand(2, 4), + labels=torch.rand(2), + masks=np.random.rand(2, 2, 2)) + pred_instances = InstanceData(**pred_instances_data) + det_data_sample.pred_instances = pred_instances + assert 'pred_instances' in det_data_sample + assert _equal(det_data_sample.pred_instances.bboxes, + pred_instances_data['bboxes']) + assert _equal(det_data_sample.pred_instances.labels, + pred_instances_data['labels']) + assert _equal(det_data_sample.pred_instances.masks, + pred_instances_data['masks']) + + # test pred_track_instances + pred_track_instances_data = dict( + bboxes=torch.rand(2, 4), + labels=torch.rand(2), + masks=np.random.rand(2, 2, 2)) + pred_instances = InstanceData(**pred_track_instances_data) + det_data_sample.pred_instances = pred_instances + assert 'pred_instances' in det_data_sample + assert _equal(det_data_sample.pred_instances.bboxes, + pred_track_instances_data['bboxes']) + assert _equal(det_data_sample.pred_instances.labels, + pred_track_instances_data['labels']) + assert _equal(det_data_sample.pred_instances.masks, + pred_track_instances_data['masks']) + + # test proposals + proposals_data = dict(bboxes=torch.rand(4, 4), labels=torch.rand(4)) + proposals = InstanceData(**proposals_data) + det_data_sample.proposals = proposals + assert 'proposals' in det_data_sample + assert _equal(det_data_sample.proposals.bboxes, + proposals_data['bboxes']) + assert _equal(det_data_sample.proposals.labels, + proposals_data['labels']) + + # test ignored_instances + ignored_instances_data = dict( + bboxes=torch.rand(4, 4), labels=torch.rand(4)) + ignored_instances = InstanceData(**ignored_instances_data) + det_data_sample.ignored_instances = ignored_instances + assert 'ignored_instances' in det_data_sample + assert _equal(det_data_sample.ignored_instances.bboxes, + ignored_instances_data['bboxes']) + assert _equal(det_data_sample.ignored_instances.labels, + ignored_instances_data['labels']) + + # test gt_panoptic_seg + gt_panoptic_seg_data = dict(panoptic_seg=torch.rand(5, 4)) + gt_panoptic_seg = PixelData(**gt_panoptic_seg_data) + det_data_sample.gt_panoptic_seg = gt_panoptic_seg + assert 'gt_panoptic_seg' in det_data_sample + assert _equal(det_data_sample.gt_panoptic_seg.panoptic_seg, + gt_panoptic_seg_data['panoptic_seg']) + + # test pred_panoptic_seg + pred_panoptic_seg_data = dict(panoptic_seg=torch.rand(5, 4)) + pred_panoptic_seg = PixelData(**pred_panoptic_seg_data) + det_data_sample.pred_panoptic_seg = pred_panoptic_seg + assert 'pred_panoptic_seg' in det_data_sample + assert _equal(det_data_sample.pred_panoptic_seg.panoptic_seg, + pred_panoptic_seg_data['panoptic_seg']) + + # test gt_sem_seg + gt_segm_seg_data = dict(segm_seg=torch.rand(5, 4, 2)) + gt_segm_seg = PixelData(**gt_segm_seg_data) + det_data_sample.gt_segm_seg = gt_segm_seg + assert 'gt_segm_seg' in det_data_sample + assert _equal(det_data_sample.gt_segm_seg.segm_seg, + gt_segm_seg_data['segm_seg']) + + # test pred_segm_seg + pred_segm_seg_data = dict(segm_seg=torch.rand(5, 4, 2)) + pred_segm_seg = PixelData(**pred_segm_seg_data) + det_data_sample.pred_segm_seg = pred_segm_seg + assert 'pred_segm_seg' in det_data_sample + assert _equal(det_data_sample.pred_segm_seg.segm_seg, + pred_segm_seg_data['segm_seg']) + + # test type error + with pytest.raises(AssertionError): + det_data_sample.pred_instances = torch.rand(2, 4) + + with pytest.raises(AssertionError): + det_data_sample.pred_panoptic_seg = torch.rand(2, 4) + + with pytest.raises(AssertionError): + det_data_sample.pred_sem_seg = torch.rand(2, 4) + + def test_deleter(self): + gt_instances_data = dict( + bboxes=torch.rand(4, 4), + labels=torch.rand(4), + masks=np.random.rand(4, 2, 2)) + + det_data_sample = DetDataSample() + gt_instances = InstanceData(data=gt_instances_data) + det_data_sample.gt_instances = gt_instances + assert 'gt_instances' in det_data_sample + del det_data_sample.gt_instances + assert 'gt_instances' not in det_data_sample + + pred_panoptic_seg_data = torch.rand(5, 4) + pred_panoptic_seg = PixelData(data=pred_panoptic_seg_data) + det_data_sample.pred_panoptic_seg = pred_panoptic_seg + assert 'pred_panoptic_seg' in det_data_sample + del det_data_sample.pred_panoptic_seg + assert 'pred_panoptic_seg' not in det_data_sample + + pred_segm_seg_data = dict(segm_seg=torch.rand(5, 4, 2)) + pred_segm_seg = PixelData(**pred_segm_seg_data) + det_data_sample.pred_segm_seg = pred_segm_seg + assert 'pred_segm_seg' in det_data_sample + del det_data_sample.pred_segm_seg + assert 'pred_segm_seg' not in det_data_sample diff --git a/mmdet_code/mmdetection/tests/test_structures/test_mask/test_mask_structures.py b/mmdet_code/mmdetection/tests/test_structures/test_mask/test_mask_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..051db7f1319f8146e5bf64f788c327381065e36d --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_structures/test_mask/test_mask_structures.py @@ -0,0 +1,73 @@ +from unittest import TestCase + +import numpy as np +from mmengine.testing import assert_allclose + +from mmdet.structures.mask import BitmapMasks, PolygonMasks + + +class TestMaskStructures(TestCase): + + def test_bitmap_translate_same_size(self): + mask_array = np.zeros((5, 10, 10), dtype=np.uint8) + mask_array[:, 0:5, 0:5] = 1 + mask_target = np.zeros((5, 10, 10), dtype=np.uint8) + mask_target[:, 0:5, 5:10] = 1 + + mask = BitmapMasks(mask_array, 10, 10) + mask = mask.translate((10, 10), 5) + assert mask.masks.shape == (5, 10, 10) + assert_allclose(mask_target, mask.masks) + + def test_bitmap_translate_diff_size(self): + # test out shape larger + mask_array = np.zeros((5, 10, 10), dtype=np.uint8) + mask_array[:, 0:5, 0:5] = 1 + + mask_target = np.zeros((5, 20, 20), dtype=np.uint8) + mask_target[:, 0:5, 5:10] = 1 + mask = BitmapMasks(mask_array, 10, 10) + mask = mask.translate((20, 20), 5) + assert mask.masks.shape == (5, 20, 20) + assert_allclose(mask_target, mask.masks) + + # test out shape smaller + mask_array = np.zeros((5, 10, 10), dtype=np.uint8) + mask_array[:, 0:5, 0:5] = 1 + + mask_target = np.zeros((5, 20, 8), dtype=np.uint8) + mask_target[:, 0:5, 5:] = 1 + mask = BitmapMasks(mask_array, 10, 10) + mask = mask.translate((20, 8), 5) + assert mask.masks.shape == (5, 20, 8) + assert_allclose(mask_target, mask.masks) + + def test_bitmap_cat(self): + # test invalid inputs + with self.assertRaises(AssertionError): + BitmapMasks.cat(BitmapMasks.random(4)) + with self.assertRaises(ValueError): + BitmapMasks.cat([]) + with self.assertRaises(AssertionError): + BitmapMasks.cat([BitmapMasks.random(2), PolygonMasks.random(3)]) + + masks = [BitmapMasks.random(num_masks=3) for _ in range(5)] + cat_mask = BitmapMasks.cat(masks) + assert len(cat_mask) == 3 * 5 + for i, m in enumerate(masks): + assert_allclose(m.masks, cat_mask.masks[i * 3:(i + 1) * 3]) + + def test_polygon_cat(self): + # test invalid inputs + with self.assertRaises(AssertionError): + PolygonMasks.cat(PolygonMasks.random(4)) + with self.assertRaises(ValueError): + PolygonMasks.cat([]) + with self.assertRaises(AssertionError): + PolygonMasks.cat([BitmapMasks.random(2), PolygonMasks.random(3)]) + + masks = [PolygonMasks.random(num_masks=3) for _ in range(5)] + cat_mask = PolygonMasks.cat(masks) + assert len(cat_mask) == 3 * 5 + for i, m in enumerate(masks): + assert_allclose(m.masks, cat_mask.masks[i * 3:(i + 1) * 3]) diff --git a/mmdet_code/mmdetection/tests/test_structures/test_reid_data_sample.py b/mmdet_code/mmdetection/tests/test_structures/test_reid_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..d9f2ebb2f86df9bace88b3e78f963d42d1796580 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_structures/test_reid_data_sample.py @@ -0,0 +1,129 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from unittest import TestCase + +import numpy as np +import torch +from mmengine.structures import LabelData + +from mmdet.structures import ReIDDataSample + + +def _equal(a, b): + if isinstance(a, (torch.Tensor, np.ndarray)): + return (a == b).all() + else: + return a == b + + +class TestReIDDataSample(TestCase): + + def test_init(self): + img_shape = (256, 128) + ori_shape = (64, 64) + num_classes = 5 + meta_info = dict( + img_shape=img_shape, ori_shape=ori_shape, num_classes=num_classes) + data_sample = ReIDDataSample(metainfo=meta_info) + self.assertIn('img_shape', data_sample) + self.assertIn('ori_shape', data_sample) + self.assertIn('num_classes', data_sample) + self.assertTrue(_equal(data_sample.get('img_shape'), img_shape)) + self.assertTrue(_equal(data_sample.get('ori_shape'), ori_shape)) + self.assertTrue(_equal(data_sample.get('num_classes'), num_classes)) + + def test_set_gt_label(self): + data_sample = ReIDDataSample(metainfo=dict(num_classes=5)) + method = getattr(data_sample, 'set_' + 'gt_label') + + # Test number + method(1) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.LongTensor) + + # Test tensor with single number + method(torch.tensor(2)) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.LongTensor) + + # Test array with single number + method(np.array(3)) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.LongTensor) + + # Test tensor + _label = torch.tensor([1, 2, 3]) + method(_label) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.Tensor) + self.assertTrue(_equal(label.label, _label)) + + # Test array + _label = np.array([1, 2, 3]) + method(_label) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.Tensor) + self.assertTrue(_equal(label.label, torch.from_numpy(_label))) + + # Test Sequence + _label = [1, 2, 3.] + method(_label) + label = data_sample.get('gt_label') + self.assertIsInstance(label, LabelData) + self.assertIsInstance(label.label, torch.Tensor) + self.assertTrue(_equal(label.label, torch.tensor(_label))) + + # Test set num_classes + self.assertEqual(label.num_classes, 5) + + # Test unavailable type + with self.assertRaisesRegex(TypeError, " is not"): + method('hi') + + def test_set_gt_score(self): + data_sample = ReIDDataSample(metainfo={'num_classes': 5}) + method = getattr(data_sample, 'set_' + 'gt_score') + + # Test set + score = [0.1, 0.1, 0.6, 0.1, 0.1] + method(torch.tensor(score)) + sample_gt_label = getattr(data_sample, 'gt_label') + self.assertIn('score', sample_gt_label) + torch.testing.assert_allclose(sample_gt_label.score, score) + self.assertEqual(sample_gt_label.num_classes, 5) + + # Test set again + score = [0.2, 0.1, 0.5, 0.1, 0.1] + method(torch.tensor(score)) + torch.testing.assert_allclose(sample_gt_label.score, score) + + # Test invalid type + with self.assertRaisesRegex(AssertionError, 'be a torch.Tensor'): + method(score) + + # Test invalid dims + with self.assertRaisesRegex(AssertionError, 'but got 2'): + method(torch.tensor([score])) + + # Test invalid num_classes + with self.assertRaisesRegex(AssertionError, r'length of value \(6\)'): + method(torch.tensor(score + [0.1])) + + # Test auto inter num_classes + data_sample = ReIDDataSample() + method = getattr(data_sample, 'set_gt_score') + method(torch.tensor(score)) + sample_gt_label = getattr(data_sample, 'gt_label') + self.assertEqual(sample_gt_label.num_classes, len(score)) + + def test_del_gt_label(self): + data_sample = ReIDDataSample() + self.assertNotIn('gt_label', data_sample) + data_sample.set_gt_label(1) + self.assertIn('gt_label', data_sample) + del data_sample.gt_label + self.assertNotIn('gt_label', data_sample) diff --git a/mmdet_code/mmdetection/tests/test_structures/test_track_data_sample.py b/mmdet_code/mmdetection/tests/test_structures/test_track_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..c926707a7ddc87f31aca0a31d55c8e8759722b2e --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_structures/test_track_data_sample.py @@ -0,0 +1,47 @@ +from unittest import TestCase + +import pytest + +from mmdet.structures import DetDataSample, TrackDataSample + + +class TestDetDataSample(TestCase): + + def test_init(self): + track_data_sample = TrackDataSample( + metainfo=dict(key_frames_inds=[0], ref_frames_inds=[1])) + + assert 'key_frames_inds' in track_data_sample.metainfo and \ + 'ref_frames_inds' in track_data_sample.metainfo + assert track_data_sample.key_frames_inds == [0] + assert track_data_sample.ref_frames_inds == [1] + with pytest.raises(AssertionError): + track_data_sample.get_key_frames() + with pytest.raises(AssertionError): + track_data_sample.get_ref_frames() + + def test_setter(self): + det_data_sample_1 = DetDataSample( + metainfo=dict(scale_factor=(1.5, 1.5))) + det_data_sample_2 = DetDataSample(metainfo=dict(scale_factor=(2., 2.))) + track_data_sample = TrackDataSample( + metainfo=dict(key_frames_inds=[0], ref_frames_inds=[1])) + track_data_sample.video_data_samples = [ + det_data_sample_1, det_data_sample_2 + ] + + assert track_data_sample.get_key_frames()[0].scale_factor == (1.5, 1.5) + assert track_data_sample.get_ref_frames()[0].scale_factor == (2., 2.) + + def test_deleter(self): + det_data_sample_1 = DetDataSample( + metainfo=dict(scale_factor=(1.5, 1.5))) + det_data_sample_2 = DetDataSample(metainfo=dict(scale_factor=(2., 2.))) + track_data_sample = TrackDataSample( + metainfo=dict(key_frames_inds=[0], ref_frames_inds=[1])) + track_data_sample.video_data_samples = [ + det_data_sample_1, det_data_sample_2 + ] + assert 'video_data_samples' in track_data_sample + del track_data_sample.video_data_samples + assert 'video_data_samples' not in track_data_sample diff --git a/mmdet_code/mmdetection/tests/test_utils/test_benchmark.py b/mmdet_code/mmdetection/tests/test_utils/test_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..939a7eca4e5e340e905287c2289ab769c6d946a1 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_utils/test_benchmark.py @@ -0,0 +1,309 @@ +import copy +import os +import tempfile +import unittest + +import torch +from mmengine import Config, MMLogger +from mmengine.dataset import Compose +from mmengine.model import BaseModel +from torch.utils.data import Dataset + +from mmdet.registry import DATASETS, MODELS +from mmdet.utils import register_all_modules +from mmdet.utils.benchmark import (DataLoaderBenchmark, DatasetBenchmark, + InferenceBenchmark) + + +@MODELS.register_module() +class ToyDetector(BaseModel): + + def __init__(self, *args, **kwargs): + super().__init__() + + def forward(self, *args, **kwargs): + pass + + +@DATASETS.register_module() +class ToyDataset(Dataset): + METAINFO = dict() # type: ignore + data = torch.randn(12, 2) + label = torch.ones(12) + + def __init__(self): + self.pipeline = Compose([lambda x: x]) + + def __len__(self): + return self.data.size(0) + + def get_data_info(self, index): + return dict(inputs=self.data[index], data_sample=self.label[index]) + + def __getitem__(self, index): + return dict(inputs=self.data[index], data_sample=self.label[index]) + + +@DATASETS.register_module() +class ToyFullInitDataset(Dataset): + METAINFO = dict() # type: ignore + data = torch.randn(12, 2) + label = torch.ones(12) + + def __init__(self): + self.pipeline = Compose([lambda x: x]) + + def __len__(self): + return self.data.size(0) + + def get_data_info(self, index): + return dict(inputs=self.data[index], data_sample=self.label[index]) + + def full_init(self): + pass + + def __getitem__(self, index): + return dict(inputs=self.data[index], data_sample=self.label[index]) + + +class TestInferenceBenchmark(unittest.TestCase): + + def setUp(self) -> None: + register_all_modules() + + self.cfg = Config( + dict( + model=dict(type='ToyDetector'), + test_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=1), + env_cfg=dict(dist_cfg=dict(backend='nccl')))) + self.max_iter = 10 + self.log_interval = 5 + + @unittest.skipIf(not torch.cuda.is_available(), + 'test requires GPU and torch+cuda') + def test_init_and_run(self): + checkpoint_path = os.path.join(tempfile.gettempdir(), 'checkpoint.pth') + torch.save(ToyDetector().state_dict(), checkpoint_path) + + cfg = copy.deepcopy(self.cfg) + inference_benchmark = InferenceBenchmark(cfg, checkpoint_path, False, + False, self.max_iter, + self.log_interval) + results = inference_benchmark.run() + + self.assertTrue(isinstance(results, dict)) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 1) + self.assertTrue(inference_benchmark.data_loader.num_workers == 0) + self.assertTrue(inference_benchmark.data_loader.batch_size == 1) + + results = inference_benchmark.run(1) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 1) + self.assertTrue(inference_benchmark.data_loader.num_workers == 0) + self.assertTrue(inference_benchmark.data_loader.batch_size == 1) + + # test repeat + results = inference_benchmark.run(3) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 3) + + # test cudnn_benchmark + cfg = copy.deepcopy(self.cfg) + cfg.env_cfg.cudnn_benchmark = True + inference_benchmark = InferenceBenchmark(cfg, checkpoint_path, False, + False, self.max_iter, + self.log_interval) + inference_benchmark.run(1) + + # test mp_cfg + cfg = copy.deepcopy(self.cfg) + cfg.env_cfg.cudnn_benchmark = True + cfg.env_cfg.mp_cfg = { + 'mp_start_method': 'fork', + 'opencv_num_threads': 1 + } + inference_benchmark = InferenceBenchmark(cfg, checkpoint_path, False, + False, self.max_iter, + self.log_interval) + inference_benchmark.run(1) + + # test fp16 + cfg = copy.deepcopy(self.cfg) + cfg.fp16 = True + inference_benchmark = InferenceBenchmark(cfg, checkpoint_path, False, + False, self.max_iter, + self.log_interval) + inference_benchmark.run(1) + + # test logger + logger = MMLogger.get_instance( + 'mmdet', log_file='temp.log', log_level='INFO') + inference_benchmark = InferenceBenchmark( + cfg, + checkpoint_path, + False, + False, + self.max_iter, + self.log_interval, + logger=logger) + inference_benchmark.run(1) + self.assertTrue(os.path.exists('temp.log')) + + os.remove(checkpoint_path) + os.remove('temp.log') + + +class TestDataLoaderBenchmark(unittest.TestCase): + + def setUp(self) -> None: + register_all_modules() + + self.cfg = Config( + dict( + model=dict(type='ToyDetector'), + train_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=2, + num_workers=1), + val_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=1, + num_workers=2), + test_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=1), + env_cfg=dict(dist_cfg=dict(backend='nccl')))) + self.max_iter = 5 + self.log_interval = 1 + self.num_warmup = 1 + + def test_init_and_run(self): + cfg = copy.deepcopy(self.cfg) + dataloader_benchmark = DataLoaderBenchmark(cfg, False, 'train', + self.max_iter, + self.log_interval, + self.num_warmup) + results = dataloader_benchmark.run(1) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 1) + self.assertTrue(dataloader_benchmark.data_loader.num_workers == 1) + self.assertTrue(dataloader_benchmark.data_loader.batch_size == 2) + + # test repeat + results = dataloader_benchmark.run(3) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 3) + + # test dataset_type input parameters error + with self.assertRaises(AssertionError): + DataLoaderBenchmark(cfg, False, 'training', self.max_iter, + self.log_interval, self.num_warmup) + + dataloader_benchmark = DataLoaderBenchmark(cfg, False, 'val', + self.max_iter, + self.log_interval, + self.num_warmup) + self.assertTrue(dataloader_benchmark.data_loader.num_workers == 2) + self.assertTrue(dataloader_benchmark.data_loader.batch_size == 1) + + dataloader_benchmark = DataLoaderBenchmark(cfg, False, 'test', + self.max_iter, + self.log_interval, + self.num_warmup) + self.assertTrue(dataloader_benchmark.data_loader.num_workers == 1) + self.assertTrue(dataloader_benchmark.data_loader.batch_size == 3) + + # test mp_cfg + cfg = copy.deepcopy(self.cfg) + cfg.env_cfg.mp_cfg = { + 'mp_start_method': 'fork', + 'opencv_num_threads': 1 + } + dataloader_benchmark = DataLoaderBenchmark(cfg, False, 'train', + self.max_iter, + self.log_interval, + self.num_warmup) + dataloader_benchmark.run(1) + + +class TestDatasetBenchmark(unittest.TestCase): + + def setUp(self) -> None: + register_all_modules() + + self.cfg = Config( + dict( + model=dict(type='ToyDetector'), + train_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=True), + batch_size=2, + num_workers=1), + val_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=1, + num_workers=2), + test_dataloader=dict( + dataset=dict(type='ToyDataset'), + sampler=dict(type='DefaultSampler', shuffle=False), + batch_size=3, + num_workers=1))) + self.max_iter = 5 + self.log_interval = 1 + self.num_warmup = 1 + + def test_init_and_run(self): + cfg = copy.deepcopy(self.cfg) + dataset_benchmark = DatasetBenchmark(cfg, 'train', self.max_iter, + self.log_interval, + self.num_warmup) + results = dataset_benchmark.run(1) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 1) + + # test repeat + results = dataset_benchmark.run(3) + self.assertTrue('avg_fps' in results) + self.assertTrue('fps_list' in results) + self.assertEqual(len(results['fps_list']), 3) + + # test test dataset + dataset_benchmark = DatasetBenchmark(cfg, 'test', self.max_iter, + self.log_interval, + self.num_warmup) + dataset_benchmark.run(1) + + # test val dataset + dataset_benchmark = DatasetBenchmark(cfg, 'val', self.max_iter, + self.log_interval, + self.num_warmup) + dataset_benchmark.run(1) + + # test dataset_type input parameters error + with self.assertRaises(AssertionError): + DatasetBenchmark(cfg, 'training', self.max_iter, self.log_interval, + self.num_warmup) + + # test full_init + cfg = copy.deepcopy(self.cfg) + cfg.test_dataloader.dataset = dict(type='ToyFullInitDataset') + dataset_benchmark = DatasetBenchmark(cfg, 'train', self.max_iter, + self.log_interval, + self.num_warmup) + dataset_benchmark.run(1) diff --git a/mmdet_code/mmdetection/tests/test_utils/test_memory.py b/mmdet_code/mmdetection/tests/test_utils/test_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..840601c114cc22bb7350ba8be91c7f23cedc4d61 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_utils/test_memory.py @@ -0,0 +1,98 @@ +import numpy as np +import pytest +import torch + +from mmdet.utils import AvoidOOM +from mmdet.utils.memory import cast_tensor_type + + +def test_avoidoom(): + tensor = torch.from_numpy(np.random.random((20, 20))) + if torch.cuda.is_available(): + tensor = tensor.cuda() + # get default result + default_result = torch.mm(tensor, tensor.transpose(1, 0)) + + # when not occurred OOM error + AvoidCudaOOM = AvoidOOM() + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert default_result.device == result.device and \ + default_result.dtype == result.dtype and \ + torch.equal(default_result, result) + + # calculate with fp16 and convert back to source type + AvoidCudaOOM = AvoidOOM(test=True) + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert default_result.device == result.device and \ + default_result.dtype == result.dtype and \ + torch.allclose(default_result, result, 1e-3) + + # calculate on cpu and convert back to source device + AvoidCudaOOM = AvoidOOM(test=True) + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert result.dtype == default_result.dtype and \ + result.device == default_result.device and \ + torch.allclose(default_result, result) + + # do not calculate on cpu and the outputs will be same as input + AvoidCudaOOM = AvoidOOM(test=True, to_cpu=False) + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert result.dtype == default_result.dtype and \ + result.device == default_result.device + + else: + default_result = torch.mm(tensor, tensor.transpose(1, 0)) + AvoidCudaOOM = AvoidOOM() + result = AvoidCudaOOM.retry_if_cuda_oom(torch.mm)(tensor, + tensor.transpose( + 1, 0)) + assert default_result.device == result.device and \ + default_result.dtype == result.dtype and \ + torch.equal(default_result, result) + + +def test_cast_tensor_type(): + inputs = torch.rand(10) + if torch.cuda.is_available(): + inputs = inputs.cuda() + with pytest.raises(AssertionError): + cast_tensor_type(inputs, src_type=None, dst_type=None) + # input is a float + out = cast_tensor_type(10., dst_type=torch.half) + assert out == 10. and isinstance(out, float) + # convert Tensor to fp16 and re-convert to fp32 + fp16_out = cast_tensor_type(inputs, dst_type=torch.half) + assert fp16_out.dtype == torch.half + fp32_out = cast_tensor_type(fp16_out, dst_type=torch.float32) + assert fp32_out.dtype == torch.float32 + + # input is a list + list_input = [inputs, inputs] + list_outs = cast_tensor_type(list_input, dst_type=torch.half) + assert len(list_outs) == len(list_input) and \ + isinstance(list_outs, list) + for out in list_outs: + assert out.dtype == torch.half + # input is a dict + dict_input = {'test1': inputs, 'test2': inputs} + dict_outs = cast_tensor_type(dict_input, dst_type=torch.half) + assert len(dict_outs) == len(dict_input) and \ + isinstance(dict_outs, dict) + + # convert the input tensor to CPU and re-convert to GPU + if torch.cuda.is_available(): + cpu_device = torch.empty(0).device + gpu_device = inputs.device + cpu_out = cast_tensor_type(inputs, dst_type=cpu_device) + assert cpu_out.device == cpu_device + + gpu_out = cast_tensor_type(inputs, dst_type=gpu_device) + assert gpu_out.device == gpu_device diff --git a/mmdet_code/mmdetection/tests/test_utils/test_replace_cfg_vals.py b/mmdet_code/mmdetection/tests/test_utils/test_replace_cfg_vals.py new file mode 100644 index 0000000000000000000000000000000000000000..de039f95eee41cbc69aec15c397fd9acd5cbf948 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_utils/test_replace_cfg_vals.py @@ -0,0 +1,83 @@ +import os.path as osp +import tempfile +from copy import deepcopy + +import pytest +from mmengine.config import Config + +from mmdet.utils import replace_cfg_vals + + +def test_replace_cfg_vals(): + temp_file = tempfile.NamedTemporaryFile() + cfg_path = f'{temp_file.name}.py' + with open(cfg_path, 'w') as f: + f.write('configs') + + ori_cfg_dict = dict() + ori_cfg_dict['cfg_name'] = osp.basename(temp_file.name) + ori_cfg_dict['work_dir'] = 'work_dirs/${cfg_name}/${percent}/${fold}' + ori_cfg_dict['percent'] = 5 + ori_cfg_dict['fold'] = 1 + ori_cfg_dict['model_wrapper'] = dict( + type='SoftTeacher', detector='${model}') + ori_cfg_dict['model'] = dict( + type='FasterRCNN', + backbone=dict(type='ResNet'), + neck=dict(type='FPN'), + rpn_head=dict(type='RPNHead'), + roi_head=dict(type='StandardRoIHead'), + train_cfg=dict( + rpn=dict( + assigner=dict(type='MaxIoUAssigner'), + sampler=dict(type='RandomSampler'), + ), + rpn_proposal=dict(nms=dict(type='nms', iou_threshold=0.7)), + rcnn=dict( + assigner=dict(type='MaxIoUAssigner'), + sampler=dict(type='RandomSampler'), + ), + ), + test_cfg=dict( + rpn=dict(nms=dict(type='nms', iou_threshold=0.7)), + rcnn=dict(nms=dict(type='nms', iou_threshold=0.5)), + ), + ) + ori_cfg_dict['iou_threshold'] = dict( + rpn_proposal_nms='${model.train_cfg.rpn_proposal.nms.iou_threshold}', + test_rpn_nms='${model.test_cfg.rpn.nms.iou_threshold}', + test_rcnn_nms='${model.test_cfg.rcnn.nms.iou_threshold}', + ) + + ori_cfg_dict['str'] = 'Hello, world!' + ori_cfg_dict['dict'] = {'Hello': 'world!'} + ori_cfg_dict['list'] = [ + 'Hello, world!', + ] + ori_cfg_dict['tuple'] = ('Hello, world!', ) + ori_cfg_dict['test_str'] = 'xxx${str}xxx' + + ori_cfg = Config(ori_cfg_dict, filename=cfg_path) + updated_cfg = replace_cfg_vals(deepcopy(ori_cfg)) + + assert updated_cfg.work_dir \ + == f'work_dirs/{osp.basename(temp_file.name)}/5/1' + assert updated_cfg.model.detector == ori_cfg.model + assert updated_cfg.iou_threshold.rpn_proposal_nms \ + == ori_cfg.model.train_cfg.rpn_proposal.nms.iou_threshold + assert updated_cfg.test_str == 'xxxHello, world!xxx' + ori_cfg_dict['test_dict'] = 'xxx${dict}xxx' + ori_cfg_dict['test_list'] = 'xxx${list}xxx' + ori_cfg_dict['test_tuple'] = 'xxx${tuple}xxx' + with pytest.raises(AssertionError): + cfg = deepcopy(ori_cfg) + cfg['test_dict'] = 'xxx${dict}xxx' + updated_cfg = replace_cfg_vals(cfg) + with pytest.raises(AssertionError): + cfg = deepcopy(ori_cfg) + cfg['test_list'] = 'xxx${list}xxx' + updated_cfg = replace_cfg_vals(cfg) + with pytest.raises(AssertionError): + cfg = deepcopy(ori_cfg) + cfg['test_tuple'] = 'xxx${tuple}xxx' + updated_cfg = replace_cfg_vals(cfg) diff --git a/mmdet_code/mmdetection/tests/test_utils/test_setup_env.py b/mmdet_code/mmdetection/tests/test_utils/test_setup_env.py new file mode 100644 index 0000000000000000000000000000000000000000..34c37161c3f3657c9ac6977c66d439193c42b173 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_utils/test_setup_env.py @@ -0,0 +1,38 @@ +import datetime +import sys +from unittest import TestCase + +from mmengine import DefaultScope + +from mmdet.utils import register_all_modules + + +class TestSetupEnv(TestCase): + + def test_register_all_modules(self): + from mmdet.registry import DATASETS + + # not init default scope + sys.modules.pop('mmdet.datasets', None) + sys.modules.pop('mmdet.datasets.coco', None) + DATASETS._module_dict.pop('CocoDataset', None) + self.assertFalse('CocoDataset' in DATASETS.module_dict) + register_all_modules(init_default_scope=False) + self.assertTrue('CocoDataset' in DATASETS.module_dict) + + # init default scope + sys.modules.pop('mmdet.datasets') + sys.modules.pop('mmdet.datasets.coco') + DATASETS._module_dict.pop('CocoDataset', None) + self.assertFalse('CocoDataset' in DATASETS.module_dict) + register_all_modules(init_default_scope=True) + self.assertTrue('CocoDataset' in DATASETS.module_dict) + self.assertEqual(DefaultScope.get_current_instance().scope_name, + 'mmdet') + + # init default scope when another scope is init + name = f'test-{datetime.datetime.now()}' + DefaultScope.get_instance(name, scope_name='test') + with self.assertWarnsRegex( + Warning, 'The current default scope "test" is not "mmdet"'): + register_all_modules(init_default_scope=True) diff --git a/mmdet_code/mmdetection/tests/test_visualization/test_local_visualizer.py b/mmdet_code/mmdetection/tests/test_visualization/test_local_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..b745adf74fc252a9fd67c44040769b52aa489247 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_visualization/test_local_visualizer.py @@ -0,0 +1,199 @@ +import os +from unittest import TestCase + +import cv2 +import numpy as np +import torch +from mmengine.structures import InstanceData, PixelData + +from mmdet.evaluation import INSTANCE_OFFSET +from mmdet.structures import DetDataSample +from mmdet.visualization import DetLocalVisualizer, TrackLocalVisualizer + + +def _rand_bboxes(num_boxes, h, w): + cx, cy, bw, bh = torch.rand(num_boxes, 4).T + + tl_x = ((cx * w) - (w * bw / 2)).clamp(0, w) + tl_y = ((cy * h) - (h * bh / 2)).clamp(0, h) + br_x = ((cx * w) + (w * bw / 2)).clamp(0, w) + br_y = ((cy * h) + (h * bh / 2)).clamp(0, h) + + bboxes = torch.stack([tl_x, tl_y, br_x, br_y], dim=0).T + return bboxes + + +def _create_panoptic_data(num_boxes, h, w): + sem_seg = np.zeros((h, w), dtype=np.int64) + 2 + bboxes = _rand_bboxes(num_boxes, h, w).int() + labels = torch.randint(2, (num_boxes, )) + for i in range(num_boxes): + x, y, w, h = bboxes[i] + sem_seg[y:y + h, x:x + w] = (i + 1) * INSTANCE_OFFSET + labels[i] + + return sem_seg[None] + + +class TestDetLocalVisualizer(TestCase): + + def test_add_datasample(self): + h = 12 + w = 10 + num_class = 3 + num_bboxes = 5 + out_file = 'out_file.jpg' + + image = np.random.randint(0, 256, size=(h, w, 3)).astype('uint8') + + # test gt_instances + gt_instances = InstanceData() + gt_instances.bboxes = _rand_bboxes(num_bboxes, h, w) + gt_instances.labels = torch.randint(0, num_class, (num_bboxes, )) + det_data_sample = DetDataSample() + det_data_sample.gt_instances = gt_instances + + det_local_visualizer = DetLocalVisualizer() + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, draw_pred=False) + + # test out_file + det_local_visualizer.add_datasample( + 'image', + image, + det_data_sample, + draw_pred=False, + out_file=out_file) + assert os.path.exists(out_file) + drawn_img = cv2.imread(out_file) + assert drawn_img.shape == (h, w, 3) + os.remove(out_file) + + # test gt_instances and pred_instances + pred_instances = InstanceData() + pred_instances.bboxes = _rand_bboxes(num_bboxes, h, w) + pred_instances.labels = torch.randint(0, num_class, (num_bboxes, )) + pred_instances.scores = torch.rand((num_bboxes, )) + det_data_sample.pred_instances = pred_instances + + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, out_file=out_file) + self._assert_image_and_shape(out_file, (h, w * 2, 3)) + + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, draw_gt=False, out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) + + det_local_visualizer.add_datasample( + 'image', + image, + det_data_sample, + draw_pred=False, + out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) + + # test gt_panoptic_seg and pred_panoptic_seg + det_local_visualizer.dataset_meta = dict(classes=('1', '2')) + gt_sem_seg = _create_panoptic_data(num_bboxes, h, w) + panoptic_seg = PixelData(sem_seg=gt_sem_seg) + + det_data_sample = DetDataSample() + det_data_sample.gt_panoptic_seg = panoptic_seg + + pred_sem_seg = _create_panoptic_data(num_bboxes, h, w) + panoptic_seg = PixelData(sem_seg=pred_sem_seg) + det_data_sample.pred_panoptic_seg = panoptic_seg + + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, out_file=out_file) + self._assert_image_and_shape(out_file, (h, w * 2, 3)) + + # class information must be provided + det_local_visualizer.dataset_meta = {} + with self.assertRaises(AssertionError): + det_local_visualizer.add_datasample( + 'image', image, det_data_sample, out_file=out_file) + + def _assert_image_and_shape(self, out_file, out_shape): + assert os.path.exists(out_file) + drawn_img = cv2.imread(out_file) + assert drawn_img.shape == out_shape + os.remove(out_file) + + +class TestTrackLocalVisualizer(TestCase): + + @staticmethod + def _get_gt_instances(): + bboxes = np.array([[912, 484, 1009, 593], [1338, 418, 1505, 797]]) + masks = np.zeros((2, 1080, 1920), dtype=np.bool_) + for i, bbox in enumerate(bboxes): + masks[i, bbox[1]:bbox[3], bbox[0]:bbox[2]] = True + instances_data = dict( + bboxes=torch.tensor(bboxes), + masks=masks, + instances_id=torch.tensor([1, 2]), + labels=torch.tensor([0, 1])) + instances = InstanceData(**instances_data) + return instances + + @staticmethod + def _get_pred_instances(): + instances_data = dict( + bboxes=torch.tensor([[900, 500, 1000, 600], [1300, 400, 1500, + 800]]), + instances_id=torch.tensor([1, 2]), + labels=torch.tensor([0, 1]), + scores=torch.tensor([0.955, 0.876])) + instances = InstanceData(**instances_data) + return instances + + @staticmethod + def _assert_image_and_shape(out_file, out_shape): + assert os.path.exists(out_file) + drawn_img = cv2.imread(out_file) + assert drawn_img.shape == out_shape + os.remove(out_file) + + def test_add_datasample(self): + out_file = 'out_file.jpg' + h, w = 1080, 1920 + image = np.random.randint(0, 256, size=(h, w, 3)).astype('uint8') + gt_instances = self._get_gt_instances() + pred_instances = self._get_pred_instances() + image_data_sample = DetDataSample() + image_data_sample.gt_instances = gt_instances + image_data_sample.pred_track_instances = pred_instances + + track_local_visualizer = TrackLocalVisualizer(alpha=0.2) + track_local_visualizer.dataset_meta = dict( + classes=['pedestrian', 'vehicle']) + + # test gt_instances + track_local_visualizer.add_datasample('image', image, + image_data_sample, None) + + # test out_file + track_local_visualizer.add_datasample( + 'image', image, image_data_sample, None, out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) + + # test gt_instances and pred_instances + track_local_visualizer.add_datasample( + 'image', image, image_data_sample, out_file=out_file) + self._assert_image_and_shape(out_file, (h, 2 * w, 3)) + + track_local_visualizer.add_datasample( + 'image', + image, + image_data_sample, + draw_gt=False, + out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) + + track_local_visualizer.add_datasample( + 'image', + image, + image_data_sample, + draw_pred=False, + out_file=out_file) + self._assert_image_and_shape(out_file, (h, w, 3)) diff --git a/mmdet_code/mmdetection/tests/test_visualization/test_palette.py b/mmdet_code/mmdetection/tests/test_visualization/test_palette.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1fd65e9827f625adc4dda8599238b6a627cfd5 --- /dev/null +++ b/mmdet_code/mmdetection/tests/test_visualization/test_palette.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np + +from mmdet.datasets import CocoDataset +from mmdet.visualization import get_palette, jitter_color, palette_val + + +def test_palette(): + assert palette_val([(1, 2, 3)])[0] == (1 / 255, 2 / 255, 3 / 255) + + # test list + palette = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] + palette_ = get_palette(palette, 3) + for color, color_ in zip(palette, palette_): + assert color == color_ + + # test tuple + palette = get_palette((1, 2, 3), 3) + assert len(palette) == 3 + for color in palette: + assert color == (1, 2, 3) + + # test color str + palette = get_palette('red', 3) + assert len(palette) == 3 + for color in palette: + assert color == (255, 0, 0) + + # test dataset str + palette = get_palette('coco', len(CocoDataset.METAINFO['classes'])) + assert len(palette) == len(CocoDataset.METAINFO['classes']) + assert palette[0] == (220, 20, 60) + + # TODO: Awaiting refactoring + # palette = get_palette('coco', len(CocoPanopticDataset.METAINFO['CLASSES'])) # noqa + # assert len(palette) == len(CocoPanopticDataset.METAINFO['CLASSES']) + # assert palette[-1] == (250, 141, 255) + # palette = get_palette('voc', len(VOCDataset.METAINFO['CLASSES'])) + # assert len(palette) == len(VOCDataset.METAINFO['CLASSES']) + # assert palette[0] == (106, 0, 228) + # palette = get_palette('citys', len(CityscapesDataset.METAINFO['CLASSES'])) # noqa + # assert len(palette) == len(CityscapesDataset.METAINFO['CLASSES']) + # assert palette[0] == (220, 20, 60) + + # test random + palette1 = get_palette('random', 3) + palette2 = get_palette(None, 3) + for color1, color2 in zip(palette1, palette2): + assert isinstance(color1, tuple) + assert isinstance(color2, tuple) + assert color1 == color2 + + +def test_jitter_color(): + color = tuple(np.random.randint(0, 255, 3, np.uint8)) + jittered_color = jitter_color(color) + for c in jittered_color: + assert 0 <= c <= 255