Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support the instance segmentation task in projects #730

Open
wants to merge 3 commits into
base: dev-1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions projects/rotated_mask_rcnn/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Rotated Mask RCNN

## Description

<!-- Share any information you would like others to know. For example:
Author: @xxx.
This is an implementation of \[XXX\]. -->

This project implements a Mask RCNN for rotated boxes. Benefiting from the BoxType design, we only need to modify the code slightly in mmrotate, and then we can support the instance segmentation task.

<center>
<img src="https://user-images.githubusercontent.com/10410257/218915978-f09bbf87-360d-4751-b52c-66d765d98035.png">
</center>

## Usage

<!-- For a typical model, this section should contain the commands for training and testing. You are also suggested to dump your environment specification to env.yml by `conda env export > env.yml`. -->

### Training commands

In MMRotate's root directory, run the following command to train the model:

```bash
python tools/train.py projects/rotated_mask_rcnn/configs/rotated-mask-rcnn_r50_fpn_1x_dota.py
```

### Testing commands

In MMRotate's root directory, run the following command to test the model:

```bash
python tools/test.py projects/rotated_mask_rcnn/configs/rotated-mask-rcnn_r50_fpn_1x_dota.py ${CHECKPOINT_PATH}
```

## Results

<!-- List the results as usually done in other model's README. [Example](https://github.com/open-mmlab/mmrotate/blob/1.x/configs/r3det/README.md#results-and-models)
You should claim whether this is based on the pre-trained weights, which are converted from the official release; or it's a reproduced result obtained from retraining the model in this project. -->

| Backbone | mAP | Angle | lr schd | Mem (GB) | Inf Time (fps) | Aug | Batch Size | Configs | Download |
| :----------------------: | :---: | :---: | :-----: | :------: | :------------: | :-: | :--------: | :----------------------------------------------------------------------------------: | :----------------------: |
| ResNet50 (1024,1024,200) | 72.71 | le90 | 1x | - | - | - | 2 | [rotated-mask-rcnn_r50_fpn_1x_dota](confsigs/rotated-mask-rcnn_r50_fpn_1x_dota.py) | [model](<>) \| [log](<>) |
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have model weights to upload?

| ResNet50 (1024,1024,200) | 70.74 | le90 | 1x | - | - | - | 2 | [rotated-mask-orcnn_r50_fpn_1x_dota](confsigs/rotated-mask-orcnn_r50_fpn_1x_dota.py) | [model](<>) \| [log](<>) |

Although the rotated box indicator will drop slightly after adding mask head, it may help improve the instance segmentation task. We hope this project can inspire you and welcome you to explore more uses of mmrotate!

## Citation

<!-- You may remove this section if not applicable. -->

```bibtex
@article{He_2017,
title={Mask R-CNN},
journal={2017 IEEE International Conference on Computer Vision (ICCV)},
publisher={IEEE},
author={He, Kaiming and Gkioxari, Georgia and Dollar, Piotr and Girshick, Ross},
year={2017},
month={Oct}
}
```

## Checklist

<!-- Here is a checklist illustrating a usual development workflow of a successful project, and also serves as an overview of this project's progress. The PIC (person in charge) or contributors of this project should check all the items that they believe have been finished, which will further be verified by codebase maintainers via a PR.
OpenMMLab's maintainer will review the code to ensure the project's quality. Reaching the first milestone means that this project suffices the minimum requirement of being merged into 'projects/'. But this project is only eligible to become a part of the core package upon attaining the last milestone.
Note that keeping this section up-to-date is crucial not only for this project's developers but the entire community, since there might be some other contributors joining this project and deciding their starting point from this list. It also helps maintainers accurately estimate time and effort on further code polishing, if needed.
A project does not necessarily have to be finished in a single PR, but it's essential for the project to at least reach the first milestone in its very first PR. -->

- [x] Milestone 1: PR-ready, and acceptable to be one of the `projects/`.

- [x] Finish the code

<!-- The code's design shall follow existing interfaces and convention. For example, each model component should be registered into `mmrotate.registry.MODELS` and configurable via a config file. -->

- [x] Basic docstrings & proper citation

<!-- Each major object should contain a docstring, describing its functionality and arguments. If you have adapted the code from other open-source projects, don't forget to cite the source project in docstring and make sure your behavior is not against its license. Typically, we do not accept any code snippet under GPL license. [A Short Guide to Open Source Licenses](https://medium.com/nationwide-technology/a-short-guide-to-open-source-licenses-cf5b1c329edd) -->

- [x] Test-time correctness

<!-- If you are reproducing the result from a paper, make sure your model's inference-time performance matches that in the original paper. The weights usually could be obtained by simply renaming the keys in the official pre-trained weights. This test could be skipped though, if you are able to prove the training-time correctness and check the second milestone. -->

- [x] A full README

<!-- As this template does. -->

- [ ] Milestone 2: Indicates a successful model implementation.

- [ ] Training-time correctness

<!-- If you are reproducing the result from a paper, checking this item means that you should have trained your model from scratch based on the original paper's specification and verified that the final result matches the report within a minor error range. -->

- [ ] Milestone 3: Good to be a part of our core package!

- [ ] Type hints and docstrings

<!-- Ideally *all* the methods should have [type hints](https://www.pythontutorial.net/python-basics/python-type-hints/) and [docstrings](https://google.github.io/styleguide/pyguide.html#381-docstrings). [Example](https://github.com/open-mmlab/mmrotate/blob/766185ed317f99379cb14035a6f9e5cf8a5340ad/mmrotate/structures/bbox/box_converters.py#L61-L78) -->

- [ ] Unit tests

<!-- Unit tests for each module are required. [Example](https://github.com/open-mmlab/mmrotate/blob/766185ed317f99379cb14035a6f9e5cf8a5340ad/tests/test_structures/test_bbox/test_box_converters.py#L43-L52) -->

- [ ] Code polishing

<!-- Refactor your code according to reviewer's comment. -->

- [ ] Metafile.yml

<!-- It will be parsed by MIM and Inferencer. [Example](https://github.com/open-mmlab/mmrotate/blob/1.x/configs/r3det/metafile.yml) -->

- [ ] Move your modules into the core package following the codebase's file hierarchy structure.

<!-- In particular, you may have to refactor this README into a standard one. [Example](https://github.com/open-mmlab/mmrotate/blob/1.x/configs/r3det/README.md) -->

- [ ] Refactor your modules into the core package following the codebase's file hierarchy structure.
118 changes: 118 additions & 0 deletions projects/rotated_mask_rcnn/configs/_base_/dota_mask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# dataset settings
dataset_type = 'mmdet.CocoDataset'
data_root = 'data/split_ms_dota/'
file_client_args = dict(backend='disk')

train_pipeline = [
dict(type='mmdet.LoadImageFromFile', file_client_args=file_client_args),
dict(
type='mmdet.LoadAnnotations',
with_bbox=True,
with_mask=True,
poly2mask=False),
dict(type='ConvertMask2BoxType', box_type='rbox', keep_mask=True),
dict(type='mmdet.Resize', scale=(1024, 1024), keep_ratio=True),
dict(
type='mmdet.RandomFlip',
prob=0.75,
direction=['horizontal', 'vertical', 'diagonal']),
dict(type='mmdet.PackDetInputs')
]
val_pipeline = [
dict(type='mmdet.LoadImageFromFile', file_client_args=file_client_args),
dict(type='mmdet.Resize', scale=(1024, 1024), keep_ratio=True),
# avoid bboxes being resized
dict(
type='mmdet.LoadAnnotations',
with_bbox=True,
with_mask=True,
poly2mask=False),
dict(type='ConvertMask2BoxType', box_type='qbox', keep_mask=True),
dict(
type='mmdet.PackDetInputs',
meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',
'scale_factor', 'instances'))
]
test_pipeline = [
dict(type='mmdet.LoadImageFromFile', file_client_args=file_client_args),
dict(type='mmdet.Resize', scale=(1024, 1024), keep_ratio=True),
dict(
type='mmdet.PackDetInputs',
meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',
'scale_factor'))
]

metainfo = dict(
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'))

train_dataloader = dict(
batch_size=2,
num_workers=2,
persistent_workers=True,
sampler=dict(type='DefaultSampler', shuffle=True),
batch_sampler=None,
dataset=dict(
type=dataset_type,
metainfo=metainfo,
data_root=data_root,
ann_file='train/train.json',
data_prefix=dict(img='train/images/'),
filter_cfg=dict(filter_empty_gt=True),
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,
metainfo=metainfo,
data_root=data_root,
ann_file='val/val.json',
data_prefix=dict(img='val/images/'),
test_mode=True,
pipeline=val_pipeline))
test_dataloader = val_dataloader

val_evaluator = dict(
type='RotatedCocoMetric', metric=['bbox', 'segm'], classwise=True)
test_evaluator = val_evaluator

# inference on test dataset and format the output results
# for submission. Note: the test set has no annotation.
# 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,
# ann_file='test/test.json',
# data_prefix=dict(img='test/images/'),
# test_mode=True,
# pipeline=test_pipeline))
# test_evaluator = dict(
# type='DOTAMetric',
# format_only=True,
# merge_patches=True,
# outfile_prefix='./work_dirs/dota/Task1')

# If you don't have test.json, please use this test_dataloader.
# test_dataloader = dict(
# batch_size=1,
# num_workers=2,
# persistent_workers=True,
# drop_last=False,
# sampler=dict(type='DefaultSampler', shuffle=False),
# dataset=dict(
# type='DOTADataset',
# data_root=data_root,
# data_prefix=dict(img_path='test/images/'),
# img_shape=(1024, 1024),
# test_mode=True,
# pipeline=test_pipeline))
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
_base_ = [
'./_base_/dota_mask.py', 'mmrotate::_base_/schedules/schedule_1x.py',
'mmrotate::_base_/default_runtime.py'
]

custom_imports = dict(imports=['projects.mask_rcnn_rbox.module'])

angle_version = 'le90'
model = dict(
type='mmdet.MaskRCNN',
data_preprocessor=dict(
type='mmdet.DetDataPreprocessor',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
bgr_to_rgb=True,
pad_mask=True,
pad_size_divisor=32,
boxtype2tensor=False),
backbone=dict(
type='mmdet.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(
type='mmdet.FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs=5),
rpn_head=dict(
type='OrientedRPNHead',
in_channels=256,
feat_channels=256,
anchor_generator=dict(
type='mmdet.AnchorGenerator',
scales=[8],
ratios=[0.5, 1.0, 2.0],
strides=[4, 8, 16, 32, 64],
use_box_type=True),
bbox_coder=dict(
type='MidpointOffsetCoder',
angle_version=angle_version,
target_means=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
target_stds=[1.0, 1.0, 1.0, 1.0, 0.5, 0.5]),
loss_cls=dict(
type='mmdet.CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
loss_bbox=dict(
type='mmdet.SmoothL1Loss',
beta=0.1111111111111111,
loss_weight=1.0)),
roi_head=dict(
type='mmdet.StandardRoIHead',
bbox_roi_extractor=dict(
type='RotatedSingleRoIExtractor',
roi_layer=dict(
type='RoIAlignRotated',
out_size=7,
sample_num=2,
clockwise=True),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
bbox_head=dict(
type='mmdet.Shared2FCBBoxHead',
predict_box_type='rbox',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=15,
reg_predictor_cfg=dict(type='mmdet.Linear'),
cls_predictor_cfg=dict(type='mmdet.Linear'),
bbox_coder=dict(
type='DeltaXYWHTRBBoxCoder',
angle_version=angle_version,
norm_factor=None,
edge_swap=True,
proj_xy=True,
target_means=(.0, .0, .0, .0, .0),
target_stds=(0.1, 0.1, 0.2, 0.2, 0.1)),
reg_class_agnostic=True,
loss_cls=dict(
type='mmdet.CrossEntropyLoss',
use_sigmoid=False,
loss_weight=1.0),
loss_bbox=dict(
type='mmdet.SmoothL1Loss', beta=1.0, loss_weight=1.0)),
mask_roi_extractor=dict(
type='RotatedSingleRoIExtractor',
roi_layer=dict(
type='RoIAlignRotated',
out_size=14,
sample_num=2,
clockwise=True),
out_channels=256,
featmap_strides=[4, 8, 16, 32]),
mask_head=dict(
type='ORCNNFCNMaskHead',
num_convs=4,
in_channels=256,
conv_out_channels=256,
num_classes=15,
loss_mask=dict(
type='mmdet.CrossEntropyLoss', use_mask=True,
loss_weight=1.0))),
train_cfg=dict(
rpn=dict(
assigner=dict(
type='mmdet.MaxIoUAssigner',
pos_iou_thr=0.7,
neg_iou_thr=0.3,
min_pos_iou=0.3,
match_low_quality=True,
ignore_iof_thr=-1,
iou_calculator=dict(type='RBbox2HBboxOverlaps2D')),
sampler=dict(
type='mmdet.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_proposal=dict(
nms_pre=2000,
max_per_img=2000,
nms=dict(type='nms', iou_threshold=0.8),
min_bbox_size=0),
rcnn=dict(
assigner=dict(
type='mmdet.MaxIoUAssigner',
pos_iou_thr=0.5,
neg_iou_thr=0.5,
min_pos_iou=0.5,
match_low_quality=True,
ignore_iof_thr=-1,
iou_calculator=dict(type='RBboxOverlaps2D')),
sampler=dict(
type='mmdet.RandomSampler',
num=512,
pos_fraction=0.25,
neg_pos_ub=-1,
add_gt_as_proposals=True),
mask_size=28,
pos_weight=-1,
debug=False)),
test_cfg=dict(
rpn=dict(
nms_pre=2000,
max_per_img=2000,
nms=dict(type='nms', iou_threshold=0.8),
min_bbox_size=0),
rcnn=dict(
nms_pre=2000,
min_bbox_size=0,
score_thr=0.05,
nms=dict(type='nms_rotated', iou_threshold=0.1),
max_per_img=2000,
mask_thr_binary=0.5)))

optim_wrapper = dict(optimizer=dict(lr=0.005))
Loading