We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
run image_demo.py with cascade_rpn model show error
### Prerequisite

- [X] I have searched [the existing and past issues](https://github.com/open-mmlab/mmdetection/issues) but cannot get the expected help.
- [X] I have read the [FAQ documentation](https://mmdetection.readthedocs.io/en/latest/faq.html) but cannot get the expected help.
- [X] The bug has not been fixed in the [latest version](https://github.com/open-mmlab/mmdetection).

### 🐞 Describe the bug

``` python demo/image_demo.py demo/demo.jpg configs/cascade_rpn/crpn_r50_caffe_fpn_1x_coco.py checkpoints/cascade_rpn_r50_caffe_fpn_1x_coco-7aa93cef.pth```

```
UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at  ../aten/src/ATen/native/TensorShape.cpp:2895.)
  return _VF.meshgrid(tensors, **kwargs)  # type: ignore[attr-defined]
Traceback (most recent call last):
  File "demo/image_demo.py", line 68, in <module>
    main(args)
  File "demo/image_demo.py", line 38, in main
    show_result_pyplot(
  File "/home/ngi/IdeaProjects/mmlab/mmdetection/mmdet/apis/inference.py", line 241, in show_result_pyplot
    model.show_result(
  File "/home/ngi/IdeaProjects/mmlab/mmdetection/mmdet/models/detectors/rpn.py", line 159, in show_result
    mmcv.imshow_bboxes(data, result, top_k=top_k, **kwargs)
TypeError: imshow_bboxes() got an unexpected keyword argument 'mask_color'

```

### Environment

```
Python: 3.8.13 (default, Mar 28 2022, 11:38:47) [GCC 7.5.0]
CUDA available: True
GPU 0: GeForce RTX 2080 SUPER
CUDA_HOME: /usr/local/cuda-10.2
NVCC: Cuda compilation tools, release 10.2, V10.2.8
GCC: gcc (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
PyTorch: 1.12.1+cu102
PyTorch compiling details: PyTorch built with:
  - GCC 7.3
  - C++ Version: 201402
  - Intel(R) Math Kernel Library Version 2020.0.0 Product Build 20191122 for Intel(R) 64 architecture applications
  - Intel(R) MKL-DNN v2.6.0 (Git Hash 52b5f107dd9cf10910aaa19cb47f3abf9b349815)
  - OpenMP 201511 (a.k.a. OpenMP 4.5)
  - LAPACK is enabled (usually provided by MKL)
  - NNPACK is enabled
  - CPU capability usage: AVX2
  - CUDA Runtime 10.2
  - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_70,code=sm_70
  - CuDNN 7.6.5
  - Magma 2.5.2
  - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=10.2, CUDNN_VERSION=7.6.5, CXX_COMPILER=/opt/rh/devtoolset-7/root/usr/bin/c++, CXX_FLAGS= -fabi-version=11 -Wno-deprecated -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -fopenmp -DNDEBUG -DUSE_KINETO -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -DEDGE_PROFILER_USE_KINETO -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-unused-parameter -Wno-unused-function -Wno-unused-result -Wno-unused-local-typedefs -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-psabi -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, TORCH_VERSION=1.12.1, USE_CUDA=ON, USE_CUDNN=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=OFF, USE_MPI=OFF, USE_NCCL=ON, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, 

TorchVision: 0.13.1+cu102
OpenCV: 4.6.0
MMCV: 1.6.2
MMCV Compiler: GCC 7.3
MMCV CUDA Compiler: 10.2
MMDetection: 2.25.2+9d3e162
```

### Additional information

_No response_

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mmdet/models/detectors/rpn.py`
Content:
```
1 # Copyright (c) OpenMMLab. All rights reserved.
2 import warnings
3 
4 import mmcv
5 import torch
6 from mmcv.image import tensor2imgs
7 
8 from mmdet.core import bbox_mapping
9 from ..builder import DETECTORS, build_backbone, build_head, build_neck
10 from .base import BaseDetector
11 
12 
13 @DETECTORS.register_module()
14 class RPN(BaseDetector):
15     """Implementation of Region Proposal Network."""
16 
17     def __init__(self,
18                  backbone,
19                  neck,
20                  rpn_head,
21                  train_cfg,
22                  test_cfg,
23                  pretrained=None,
24                  init_cfg=None):
25         super(RPN, self).__init__(init_cfg)
26         if pretrained:
27             warnings.warn('DeprecationWarning: pretrained is deprecated, '
28                           'please use "init_cfg" instead')
29             backbone.pretrained = pretrained
30         self.backbone = build_backbone(backbone)
31         self.neck = build_neck(neck) if neck is not None else None
32         rpn_train_cfg = train_cfg.rpn if train_cfg is not None else None
33         rpn_head.update(train_cfg=rpn_train_cfg)
34         rpn_head.update(test_cfg=test_cfg.rpn)
35         self.rpn_head = build_head(rpn_head)
36         self.train_cfg = train_cfg
37         self.test_cfg = test_cfg
38 
39     def extract_feat(self, img):
40         """Extract features.
41 
42         Args:
43             img (torch.Tensor): Image tensor with shape (n, c, h ,w).
44 
45         Returns:
46             list[torch.Tensor]: Multi-level features that may have
47                 different resolutions.
48         """
49         x = self.backbone(img)
50         if self.with_neck:
51             x = self.neck(x)
52         return x
53 
54     def forward_dummy(self, img):
55         """Dummy forward function."""
56         x = self.extract_feat(img)
57         rpn_outs = self.rpn_head(x)
58         return rpn_outs
59 
60     def forward_train(self,
61                       img,
62                       img_metas,
63                       gt_bboxes=None,
64                       gt_bboxes_ignore=None):
65         """
66         Args:
67             img (Tensor): Input images of shape (N, C, H, W).
68                 Typically these should be mean centered and std scaled.
69             img_metas (list[dict]): A List of image info dict where each dict
70                 has: 'img_shape', 'scale_factor', 'flip', and may also contain
71                 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.
72                 For details on the values of these keys see
73                 :class:`mmdet.datasets.pipelines.Collect`.
74             gt_bboxes (list[Tensor]): Each item are the truth boxes for each
75                 image in [tl_x, tl_y, br_x, br_y] format.
76             gt_bboxes_ignore (None | list[Tensor]): Specify which bounding
77                 boxes can be ignored when computing the loss.
78 
79         Returns:
80             dict[str, Tensor]: A dictionary of loss components.
81         """
82         if (isinstance(self.train_cfg.rpn, dict)
83                 and self.train_cfg.rpn.get('debug', False)):
84             self.rpn_head.debug_imgs = tensor2imgs(img)
85 
86         x = self.extract_feat(img)
87         losses = self.rpn_head.forward_train(x, img_metas, gt_bboxes, None,
88                                              gt_bboxes_ignore)
89         return losses
90 
91     def simple_test(self, img, img_metas, rescale=False):
92         """Test function without test time augmentation.
93 
94         Args:
95             imgs (list[torch.Tensor]): List of multiple images
96             img_metas (list[dict]): List of image information.
97             rescale (bool, optional): Whether to rescale the results.
98                 Defaults to False.
99 
100         Returns:
101             list[np.ndarray]: proposals
102         """
103         x = self.extract_feat(img)
104         # get origin input shape to onnx dynamic input shape
105         if torch.onnx.is_in_onnx_export():
106             img_shape = torch._shape_as_tensor(img)[2:]
107             img_metas[0]['img_shape_for_onnx'] = img_shape
108         proposal_list = self.rpn_head.simple_test_rpn(x, img_metas)
109         if rescale:
110             for proposals, meta in zip(proposal_list, img_metas):
111                 proposals[:, :4] /= proposals.new_tensor(meta['scale_factor'])
112         if torch.onnx.is_in_onnx_export():
113             return proposal_list
114 
115         return [proposal.cpu().numpy() for proposal in proposal_list]
116 
117     def aug_test(self, imgs, img_metas, rescale=False):
118         """Test function with test time augmentation.
119 
120         Args:
121             imgs (list[torch.Tensor]): List of multiple images
122             img_metas (list[dict]): List of image information.
123             rescale (bool, optional): Whether to rescale the results.
124                 Defaults to False.
125 
126         Returns:
127             list[np.ndarray]: proposals
128         """
129         proposal_list = self.rpn_head.aug_test_rpn(
130             self.extract_feats(imgs), img_metas)
131         if not rescale:
132             for proposals, img_meta in zip(proposal_list, img_metas[0]):
133                 img_shape = img_meta['img_shape']
134                 scale_factor = img_meta['scale_factor']
135                 flip = img_meta['flip']
136                 flip_direction = img_meta['flip_direction']
137                 proposals[:, :4] = bbox_mapping(proposals[:, :4], img_shape,
138                                                 scale_factor, flip,
139                                                 flip_direction)
140         return [proposal.cpu().numpy() for proposal in proposal_list]
141 
142     def show_result(self, data, result, top_k=20, **kwargs):
143         """Show RPN proposals on the image.
144 
145         Args:
146             data (str or np.ndarray): Image filename or loaded image.
147             result (Tensor or tuple): The results to draw over `img`
148                 bbox_result or (bbox_result, segm_result).
149             top_k (int): Plot the first k bboxes only
150                if set positive. Default: 20
151 
152         Returns:
153             np.ndarray: The image with bboxes drawn on it.
154         """
155         if kwargs is not None:
156             kwargs.pop('score_thr', None)
157             kwargs.pop('text_color', None)
158             kwargs['colors'] = kwargs.pop('bbox_color', 'green')
159         mmcv.imshow_bboxes(data, result, top_k=top_k, **kwargs)
160
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mmdet/models/detectors/rpn.py b/mmdet/models/detectors/rpn.py
--- a/mmdet/models/detectors/rpn.py
+++ b/mmdet/models/detectors/rpn.py
@@ -1,5 +1,6 @@
 # Copyright (c) OpenMMLab. All rights reserved.
 import warnings
+from inspect import signature
 
 import mmcv
 import torch
@@ -153,7 +154,9 @@
             np.ndarray: The image with bboxes drawn on it.
         """
         if kwargs is not None:
-            kwargs.pop('score_thr', None)
-            kwargs.pop('text_color', None)
-            kwargs['colors'] = kwargs.pop('bbox_color', 'green')
+            kwargs['colors'] = 'green'
+            sig = signature(mmcv.imshow_bboxes)
+            for k in list(kwargs.keys()):
+                if k not in sig.parameters:
+                    kwargs.pop(k)
         mmcv.imshow_bboxes(data, result, top_k=top_k, **kwargs)

{"golden_diff": "diff --git a/mmdet/models/detectors/rpn.py b/mmdet/models/detectors/rpn.py\n--- a/mmdet/models/detectors/rpn.py\n+++ b/mmdet/models/detectors/rpn.py\n@@ -1,5 +1,6 @@\n # Copyright (c) OpenMMLab. All rights reserved.\n import warnings\n+from inspect import signature\n \n import mmcv\n import torch\n@@ -153,7 +154,9 @@\n             np.ndarray: The image with bboxes drawn on it.\n         \"\"\"\n         if kwargs is not None:\n-            kwargs.pop('score_thr', None)\n-            kwargs.pop('text_color', None)\n-            kwargs['colors'] = kwargs.pop('bbox_color', 'green')\n+            kwargs['colors'] = 'green'\n+            sig = signature(mmcv.imshow_bboxes)\n+            for k in list(kwargs.keys()):\n+                if k not in sig.parameters:\n+                    kwargs.pop(k)\n         mmcv.imshow_bboxes(data, result, top_k=top_k, **kwargs)\n", "issue": "run image_demo.py with cascade_rpn model show error\n### Prerequisite\n\n- [X] I have searched [the existing and past issues](https://github.com/open-mmlab/mmdetection/issues) but cannot get the expected help.\n- [X] I have read the [FAQ documentation](https://mmdetection.readthedocs.io/en/latest/faq.html) but cannot get the expected help.\n- [X] The bug has not been fixed in the [latest version](https://github.com/open-mmlab/mmdetection).\n\n### \ud83d\udc1e Describe the bug\n\n``` python demo/image_demo.py demo/demo.jpg configs/cascade_rpn/crpn_r50_caffe_fpn_1x_coco.py checkpoints/cascade_rpn_r50_caffe_fpn_1x_coco-7aa93cef.pth```\r\n\r\n```\r\nUserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at  ../aten/src/ATen/native/TensorShape.cpp:2895.)\r\n  return _VF.meshgrid(tensors, **kwargs)  # type: ignore[attr-defined]\r\nTraceback (most recent call last):\r\n  File \"demo/image_demo.py\", line 68, in <module>\r\n    main(args)\r\n  File \"demo/image_demo.py\", line 38, in main\r\n    show_result_pyplot(\r\n  File \"/home/ngi/IdeaProjects/mmlab/mmdetection/mmdet/apis/inference.py\", line 241, in show_result_pyplot\r\n    model.show_result(\r\n  File \"/home/ngi/IdeaProjects/mmlab/mmdetection/mmdet/models/detectors/rpn.py\", line 159, in show_result\r\n    mmcv.imshow_bboxes(data, result, top_k=top_k, **kwargs)\r\nTypeError: imshow_bboxes() got an unexpected keyword argument 'mask_color'\r\n\r\n```\n\n### Environment\n\n```\r\nPython: 3.8.13 (default, Mar 28 2022, 11:38:47) [GCC 7.5.0]\r\nCUDA available: True\r\nGPU 0: GeForce RTX 2080 SUPER\r\nCUDA_HOME: /usr/local/cuda-10.2\r\nNVCC: Cuda compilation tools, release 10.2, V10.2.8\r\nGCC: gcc (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609\r\nPyTorch: 1.12.1+cu102\r\nPyTorch compiling details: PyTorch built with:\r\n  - GCC 7.3\r\n  - C++ Version: 201402\r\n  - Intel(R) Math Kernel Library Version 2020.0.0 Product Build 20191122 for Intel(R) 64 architecture applications\r\n  - Intel(R) MKL-DNN v2.6.0 (Git Hash 52b5f107dd9cf10910aaa19cb47f3abf9b349815)\r\n  - OpenMP 201511 (a.k.a. OpenMP 4.5)\r\n  - LAPACK is enabled (usually provided by MKL)\r\n  - NNPACK is enabled\r\n  - CPU capability usage: AVX2\r\n  - CUDA Runtime 10.2\r\n  - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_70,code=sm_70\r\n  - CuDNN 7.6.5\r\n  - Magma 2.5.2\r\n  - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=10.2, CUDNN_VERSION=7.6.5, CXX_COMPILER=/opt/rh/devtoolset-7/root/usr/bin/c++, CXX_FLAGS= -fabi-version=11 -Wno-deprecated -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -fopenmp -DNDEBUG -DUSE_KINETO -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -DEDGE_PROFILER_USE_KINETO -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-unused-parameter -Wno-unused-function -Wno-unused-result -Wno-unused-local-typedefs -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-psabi -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, TORCH_VERSION=1.12.1, USE_CUDA=ON, USE_CUDNN=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=OFF, USE_MPI=OFF, USE_NCCL=ON, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, \r\n\r\nTorchVision: 0.13.1+cu102\r\nOpenCV: 4.6.0\r\nMMCV: 1.6.2\r\nMMCV Compiler: GCC 7.3\r\nMMCV CUDA Compiler: 10.2\r\nMMDetection: 2.25.2+9d3e162\r\n```\n\n### Additional information\n\n_No response_\n", "before_files": [{"content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport warnings\n\nimport mmcv\nimport torch\nfrom mmcv.image import tensor2imgs\n\nfrom mmdet.core import bbox_mapping\nfrom ..builder import DETECTORS, build_backbone, build_head, build_neck\nfrom .base import BaseDetector\n\n\n@DETECTORS.register_module()\nclass RPN(BaseDetector):\n    \"\"\"Implementation of Region Proposal Network.\"\"\"\n\n    def __init__(self,\n                 backbone,\n                 neck,\n                 rpn_head,\n                 train_cfg,\n                 test_cfg,\n                 pretrained=None,\n                 init_cfg=None):\n        super(RPN, self).__init__(init_cfg)\n        if pretrained:\n            warnings.warn('DeprecationWarning: pretrained is deprecated, '\n                          'please use \"init_cfg\" instead')\n            backbone.pretrained = pretrained\n        self.backbone = build_backbone(backbone)\n        self.neck = build_neck(neck) if neck is not None else None\n        rpn_train_cfg = train_cfg.rpn if train_cfg is not None else None\n        rpn_head.update(train_cfg=rpn_train_cfg)\n        rpn_head.update(test_cfg=test_cfg.rpn)\n        self.rpn_head = build_head(rpn_head)\n        self.train_cfg = train_cfg\n        self.test_cfg = test_cfg\n\n    def extract_feat(self, img):\n        \"\"\"Extract features.\n\n        Args:\n            img (torch.Tensor): Image tensor with shape (n, c, h ,w).\n\n        Returns:\n            list[torch.Tensor]: Multi-level features that may have\n                different resolutions.\n        \"\"\"\n        x = self.backbone(img)\n        if self.with_neck:\n            x = self.neck(x)\n        return x\n\n    def forward_dummy(self, img):\n        \"\"\"Dummy forward function.\"\"\"\n        x = self.extract_feat(img)\n        rpn_outs = self.rpn_head(x)\n        return rpn_outs\n\n    def forward_train(self,\n                      img,\n                      img_metas,\n                      gt_bboxes=None,\n                      gt_bboxes_ignore=None):\n        \"\"\"\n        Args:\n            img (Tensor): Input images of shape (N, C, H, W).\n                Typically these should be mean centered and std scaled.\n            img_metas (list[dict]): A List of image info dict where each dict\n                has: 'img_shape', 'scale_factor', 'flip', and may also contain\n                'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n                For details on the values of these keys see\n                :class:`mmdet.datasets.pipelines.Collect`.\n            gt_bboxes (list[Tensor]): Each item are the truth boxes for each\n                image in [tl_x, tl_y, br_x, br_y] format.\n            gt_bboxes_ignore (None | list[Tensor]): Specify which bounding\n                boxes can be ignored when computing the loss.\n\n        Returns:\n            dict[str, Tensor]: A dictionary of loss components.\n        \"\"\"\n        if (isinstance(self.train_cfg.rpn, dict)\n                and self.train_cfg.rpn.get('debug', False)):\n            self.rpn_head.debug_imgs = tensor2imgs(img)\n\n        x = self.extract_feat(img)\n        losses = self.rpn_head.forward_train(x, img_metas, gt_bboxes, None,\n                                             gt_bboxes_ignore)\n        return losses\n\n    def simple_test(self, img, img_metas, rescale=False):\n        \"\"\"Test function without test time augmentation.\n\n        Args:\n            imgs (list[torch.Tensor]): List of multiple images\n            img_metas (list[dict]): List of image information.\n            rescale (bool, optional): Whether to rescale the results.\n                Defaults to False.\n\n        Returns:\n            list[np.ndarray]: proposals\n        \"\"\"\n        x = self.extract_feat(img)\n        # get origin input shape to onnx dynamic input shape\n        if torch.onnx.is_in_onnx_export():\n            img_shape = torch._shape_as_tensor(img)[2:]\n            img_metas[0]['img_shape_for_onnx'] = img_shape\n        proposal_list = self.rpn_head.simple_test_rpn(x, img_metas)\n        if rescale:\n            for proposals, meta in zip(proposal_list, img_metas):\n                proposals[:, :4] /= proposals.new_tensor(meta['scale_factor'])\n        if torch.onnx.is_in_onnx_export():\n            return proposal_list\n\n        return [proposal.cpu().numpy() for proposal in proposal_list]\n\n    def aug_test(self, imgs, img_metas, rescale=False):\n        \"\"\"Test function with test time augmentation.\n\n        Args:\n            imgs (list[torch.Tensor]): List of multiple images\n            img_metas (list[dict]): List of image information.\n            rescale (bool, optional): Whether to rescale the results.\n                Defaults to False.\n\n        Returns:\n            list[np.ndarray]: proposals\n        \"\"\"\n        proposal_list = self.rpn_head.aug_test_rpn(\n            self.extract_feats(imgs), img_metas)\n        if not rescale:\n            for proposals, img_meta in zip(proposal_list, img_metas[0]):\n                img_shape = img_meta['img_shape']\n                scale_factor = img_meta['scale_factor']\n                flip = img_meta['flip']\n                flip_direction = img_meta['flip_direction']\n                proposals[:, :4] = bbox_mapping(proposals[:, :4], img_shape,\n                                                scale_factor, flip,\n                                                flip_direction)\n        return [proposal.cpu().numpy() for proposal in proposal_list]\n\n    def show_result(self, data, result, top_k=20, **kwargs):\n        \"\"\"Show RPN proposals on the image.\n\n        Args:\n            data (str or np.ndarray): Image filename or loaded image.\n            result (Tensor or tuple): The results to draw over `img`\n                bbox_result or (bbox_result, segm_result).\n            top_k (int): Plot the first k bboxes only\n               if set positive. Default: 20\n\n        Returns:\n            np.ndarray: The image with bboxes drawn on it.\n        \"\"\"\n        if kwargs is not None:\n            kwargs.pop('score_thr', None)\n            kwargs.pop('text_color', None)\n            kwargs['colors'] = kwargs.pop('bbox_color', 'green')\n        mmcv.imshow_bboxes(data, result, top_k=top_k, **kwargs)\n", "path": "mmdet/models/detectors/rpn.py"}], "after_files": [{"content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport warnings\nfrom inspect import signature\n\nimport mmcv\nimport torch\nfrom mmcv.image import tensor2imgs\n\nfrom mmdet.core import bbox_mapping\nfrom ..builder import DETECTORS, build_backbone, build_head, build_neck\nfrom .base import BaseDetector\n\n\n@DETECTORS.register_module()\nclass RPN(BaseDetector):\n    \"\"\"Implementation of Region Proposal Network.\"\"\"\n\n    def __init__(self,\n                 backbone,\n                 neck,\n                 rpn_head,\n                 train_cfg,\n                 test_cfg,\n                 pretrained=None,\n                 init_cfg=None):\n        super(RPN, self).__init__(init_cfg)\n        if pretrained:\n            warnings.warn('DeprecationWarning: pretrained is deprecated, '\n                          'please use \"init_cfg\" instead')\n            backbone.pretrained = pretrained\n        self.backbone = build_backbone(backbone)\n        self.neck = build_neck(neck) if neck is not None else None\n        rpn_train_cfg = train_cfg.rpn if train_cfg is not None else None\n        rpn_head.update(train_cfg=rpn_train_cfg)\n        rpn_head.update(test_cfg=test_cfg.rpn)\n        self.rpn_head = build_head(rpn_head)\n        self.train_cfg = train_cfg\n        self.test_cfg = test_cfg\n\n    def extract_feat(self, img):\n        \"\"\"Extract features.\n\n        Args:\n            img (torch.Tensor): Image tensor with shape (n, c, h ,w).\n\n        Returns:\n            list[torch.Tensor]: Multi-level features that may have\n                different resolutions.\n        \"\"\"\n        x = self.backbone(img)\n        if self.with_neck:\n            x = self.neck(x)\n        return x\n\n    def forward_dummy(self, img):\n        \"\"\"Dummy forward function.\"\"\"\n        x = self.extract_feat(img)\n        rpn_outs = self.rpn_head(x)\n        return rpn_outs\n\n    def forward_train(self,\n                      img,\n                      img_metas,\n                      gt_bboxes=None,\n                      gt_bboxes_ignore=None):\n        \"\"\"\n        Args:\n            img (Tensor): Input images of shape (N, C, H, W).\n                Typically these should be mean centered and std scaled.\n            img_metas (list[dict]): A List of image info dict where each dict\n                has: 'img_shape', 'scale_factor', 'flip', and may also contain\n                'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n                For details on the values of these keys see\n                :class:`mmdet.datasets.pipelines.Collect`.\n            gt_bboxes (list[Tensor]): Each item are the truth boxes for each\n                image in [tl_x, tl_y, br_x, br_y] format.\n            gt_bboxes_ignore (None | list[Tensor]): Specify which bounding\n                boxes can be ignored when computing the loss.\n\n        Returns:\n            dict[str, Tensor]: A dictionary of loss components.\n        \"\"\"\n        if (isinstance(self.train_cfg.rpn, dict)\n                and self.train_cfg.rpn.get('debug', False)):\n            self.rpn_head.debug_imgs = tensor2imgs(img)\n\n        x = self.extract_feat(img)\n        losses = self.rpn_head.forward_train(x, img_metas, gt_bboxes, None,\n                                             gt_bboxes_ignore)\n        return losses\n\n    def simple_test(self, img, img_metas, rescale=False):\n        \"\"\"Test function without test time augmentation.\n\n        Args:\n            imgs (list[torch.Tensor]): List of multiple images\n            img_metas (list[dict]): List of image information.\n            rescale (bool, optional): Whether to rescale the results.\n                Defaults to False.\n\n        Returns:\n            list[np.ndarray]: proposals\n        \"\"\"\n        x = self.extract_feat(img)\n        # get origin input shape to onnx dynamic input shape\n        if torch.onnx.is_in_onnx_export():\n            img_shape = torch._shape_as_tensor(img)[2:]\n            img_metas[0]['img_shape_for_onnx'] = img_shape\n        proposal_list = self.rpn_head.simple_test_rpn(x, img_metas)\n        if rescale:\n            for proposals, meta in zip(proposal_list, img_metas):\n                proposals[:, :4] /= proposals.new_tensor(meta['scale_factor'])\n        if torch.onnx.is_in_onnx_export():\n            return proposal_list\n\n        return [proposal.cpu().numpy() for proposal in proposal_list]\n\n    def aug_test(self, imgs, img_metas, rescale=False):\n        \"\"\"Test function with test time augmentation.\n\n        Args:\n            imgs (list[torch.Tensor]): List of multiple images\n            img_metas (list[dict]): List of image information.\n            rescale (bool, optional): Whether to rescale the results.\n                Defaults to False.\n\n        Returns:\n            list[np.ndarray]: proposals\n        \"\"\"\n        proposal_list = self.rpn_head.aug_test_rpn(\n            self.extract_feats(imgs), img_metas)\n        if not rescale:\n            for proposals, img_meta in zip(proposal_list, img_metas[0]):\n                img_shape = img_meta['img_shape']\n                scale_factor = img_meta['scale_factor']\n                flip = img_meta['flip']\n                flip_direction = img_meta['flip_direction']\n                proposals[:, :4] = bbox_mapping(proposals[:, :4], img_shape,\n                                                scale_factor, flip,\n                                                flip_direction)\n        return [proposal.cpu().numpy() for proposal in proposal_list]\n\n    def show_result(self, data, result, top_k=20, **kwargs):\n        \"\"\"Show RPN proposals on the image.\n\n        Args:\n            data (str or np.ndarray): Image filename or loaded image.\n            result (Tensor or tuple): The results to draw over `img`\n                bbox_result or (bbox_result, segm_result).\n            top_k (int): Plot the first k bboxes only\n               if set positive. Default: 20\n\n        Returns:\n            np.ndarray: The image with bboxes drawn on it.\n        \"\"\"\n        if kwargs is not None:\n            kwargs['colors'] = 'green'\n            sig = signature(mmcv.imshow_bboxes)\n            for k in list(kwargs.keys()):\n                if k not in sig.parameters:\n                    kwargs.pop(k)\n        mmcv.imshow_bboxes(data, result, top_k=top_k, **kwargs)\n", "path": "mmdet/models/detectors/rpn.py"}]}