test_detection.py 11.0 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
import contextlib
16 17
import unittest

18
import numpy as np
19

P
pangyoki 已提交
20
import paddle
21
from paddle import fluid
22 23 24
from paddle.fluid import core
from paddle.fluid.dygraph import base
from paddle.fluid.framework import Program, program_guard
P
pangyoki 已提交
25 26

paddle.enable_static()
27 28


29 30 31 32 33 34 35 36 37 38 39
@contextlib.contextmanager
def new_program_scope(main=None, startup=None, scope=None):
    prog = main if main else fluid.Program()
    startup_prog = startup if startup else fluid.Program()
    scope = scope if scope else fluid.core.Scope()
    with fluid.scope_guard(scope):
        with fluid.program_guard(prog, startup_prog):
            with fluid.unique_name.guard():
                yield


40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
class LayerTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.seed = 111

    @classmethod
    def tearDownClass(cls):
        pass

    def _get_place(self, force_to_use_cpu=False):
        # this option for ops that only have cpu kernel
        if force_to_use_cpu:
            return core.CPUPlace()
        else:
            if core.is_compiled_with_cuda():
                return core.CUDAPlace(0)
            return core.CPUPlace()

    @contextlib.contextmanager
    def static_graph(self):
        with new_program_scope():
            fluid.default_startup_program().random_seed = self.seed
            fluid.default_main_program().random_seed = self.seed
            yield

65 66 67
    def get_static_graph_result(
        self, feed, fetch_list, with_lod=False, force_to_use_cpu=False
    ):
68 69
        exe = fluid.Executor(self._get_place(force_to_use_cpu))
        exe.run(fluid.default_startup_program())
70 71 72 73 74 75
        return exe.run(
            fluid.default_main_program(),
            feed=feed,
            fetch_list=fetch_list,
            return_numpy=(not with_lod),
        )
76 77 78 79

    @contextlib.contextmanager
    def dynamic_graph(self, force_to_use_cpu=False):
        with fluid.dygraph.guard(
80 81
            self._get_place(force_to_use_cpu=force_to_use_cpu)
        ):
82 83 84
            fluid.default_startup_program().random_seed = self.seed
            fluid.default_main_program().random_seed = self.seed
            yield
85 86


87
class TestGenerateProposals(LayerTest):
88
    def test_generate_proposals(self):
89 90 91
        scores_np = np.random.rand(2, 3, 4, 4).astype('float32')
        bbox_deltas_np = np.random.rand(2, 12, 4, 4).astype('float32')
        im_info_np = np.array([[8, 8, 0.5], [6, 6, 0.5]]).astype('float32')
92 93 94
        anchors_np = np.reshape(np.arange(4 * 4 * 3 * 4), [4, 4, 3, 4]).astype(
            'float32'
        )
95 96 97
        variances_np = np.ones((4, 4, 3, 4)).astype('float32')

        with self.static_graph():
98
            scores = paddle.static.data(
99 100
                name='scores', shape=[2, 3, 4, 4], dtype='float32'
            )
101
            bbox_deltas = paddle.static.data(
102 103
                name='bbox_deltas', shape=[2, 12, 4, 4], dtype='float32'
            )
104 105 106 107
            im_info = paddle.static.data(
                name='im_info', shape=[2, 3], dtype='float32'
            )
            anchors = paddle.static.data(
108 109
                name='anchors', shape=[4, 4, 3, 4], dtype='float32'
            )
110
            variances = paddle.static.data(
111 112
                name='var', shape=[4, 4, 3, 4], dtype='float32'
            )
113
            rois, roi_probs, rois_num = paddle.vision.ops.generate_proposals(
114 115
                scores,
                bbox_deltas,
116
                im_info[:2],
117 118 119 120
                anchors,
                variances,
                pre_nms_top_n=10,
                post_nms_top_n=5,
121 122 123 124 125 126 127
                return_rois_num=True,
            )
            (
                rois_stat,
                roi_probs_stat,
                rois_num_stat,
            ) = self.get_static_graph_result(
128 129 130 131 132
                feed={
                    'scores': scores_np,
                    'bbox_deltas': bbox_deltas_np,
                    'im_info': im_info_np,
                    'anchors': anchors_np,
133
                    'var': variances_np,
134 135
                },
                fetch_list=[rois, roi_probs, rois_num],
136 137
                with_lod=False,
            )
138 139 140 141 142 143 144

        with self.dynamic_graph():
            scores_dy = base.to_variable(scores_np)
            bbox_deltas_dy = base.to_variable(bbox_deltas_np)
            im_info_dy = base.to_variable(im_info_np)
            anchors_dy = base.to_variable(anchors_np)
            variances_dy = base.to_variable(variances_np)
145
            rois, roi_probs, rois_num = paddle.vision.ops.generate_proposals(
146 147
                scores_dy,
                bbox_deltas_dy,
148
                im_info_dy[:2],
149 150 151 152
                anchors_dy,
                variances_dy,
                pre_nms_top_n=10,
                post_nms_top_n=5,
153 154
                return_rois_num=True,
            )
155 156 157 158
            rois_dy = rois.numpy()
            roi_probs_dy = roi_probs.numpy()
            rois_num_dy = rois_num.numpy()

159 160 161
        np.testing.assert_array_equal(np.array(rois_stat), rois_dy)
        np.testing.assert_array_equal(np.array(roi_probs_stat), roi_probs_dy)
        np.testing.assert_array_equal(np.array(rois_num_stat), rois_num_dy)
162 163


164 165 166 167
class TestMulticlassNMS2(unittest.TestCase):
    def test_multiclass_nms2(self):
        program = Program()
        with program_guard(program):
G
GGBond8488 已提交
168
            bboxes = paddle.static.data(
169 170
                name='bboxes', shape=[-1, 10, 4], dtype='float32'
            )
G
GGBond8488 已提交
171 172 173
            scores = paddle.static.data(
                name='scores', shape=[-1, 10], dtype='float32'
            )
174
            output = paddle.incubate.layers.multiclass_nms2(
175 176
                bboxes, scores, 0.3, 400, 200, 0.7
            )
177
            output2, index = paddle.incubate.layers.multiclass_nms2(
178 179
                bboxes, scores, 0.3, 400, 200, 0.7, return_index=True
            )
180 181 182 183 184
            self.assertIsNotNone(output)
            self.assertIsNotNone(output2)
            self.assertIsNotNone(index)


185
class TestDistributeFpnProposals(LayerTest):
186
    def test_distribute_fpn_proposals(self):
187 188 189
        rois_np = np.random.rand(10, 4).astype('float32')
        rois_num_np = np.array([4, 6]).astype('int32')
        with self.static_graph():
190 191 192 193 194 195
            rois = paddle.static.data(
                name='rois', shape=[10, 4], dtype='float32'
            )
            rois_num = paddle.static.data(
                name='rois_num', shape=[None], dtype='int32'
            )
196 197 198 199
            (
                multi_rois,
                restore_ind,
                rois_num_per_level,
200
            ) = paddle.vision.ops.distribute_fpn_proposals(
201 202 203 204 205
                fpn_rois=rois,
                min_level=2,
                max_level=5,
                refer_level=4,
                refer_scale=224,
206 207
                rois_num=rois_num,
            )
208
            fetch_list = multi_rois + [restore_ind] + rois_num_per_level
209 210 211 212 213
            output_stat = self.get_static_graph_result(
                feed={'rois': rois_np, 'rois_num': rois_num_np},
                fetch_list=fetch_list,
                with_lod=True,
            )
214 215 216 217 218 219 220 221 222
            output_stat_np = []
            for output in output_stat:
                output_np = np.array(output)
                if len(output_np) > 0:
                    output_stat_np.append(output_np)

        with self.dynamic_graph():
            rois_dy = base.to_variable(rois_np)
            rois_num_dy = base.to_variable(rois_num_np)
223 224 225 226
            (
                multi_rois_dy,
                restore_ind_dy,
                rois_num_per_level_dy,
227
            ) = paddle.vision.ops.distribute_fpn_proposals(
228
                fpn_rois=rois_dy,
229 230 231
                min_level=2,
                max_level=5,
                refer_level=4,
232
                refer_scale=224,
233 234
                rois_num=rois_num_dy,
            )
H
hong 已提交
235
            print(type(multi_rois_dy))
236 237 238 239 240 241 242 243
            output_dy = multi_rois_dy + [restore_ind_dy] + rois_num_per_level_dy
            output_dy_np = []
            for output in output_dy:
                output_np = output.numpy()
                if len(output_np) > 0:
                    output_dy_np.append(output_np)

        for res_stat, res_dy in zip(output_stat_np, output_dy_np):
244
            np.testing.assert_array_equal(res_stat, res_dy)
245

246 247 248
    def test_distribute_fpn_proposals_error(self):
        program = Program()
        with program_guard(program):
249
            fpn_rois = paddle.static.data(
250 251 252 253
                name='data_error', shape=[10, 4], dtype='int32', lod_level=1
            )
            self.assertRaises(
                TypeError,
254
                paddle.vision.ops.distribute_fpn_proposals,
255 256 257 258 259 260
                fpn_rois=fpn_rois,
                min_level=2,
                max_level=5,
                refer_level=4,
                refer_scale=224,
            )
261

J
JYChen 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    def test_distribute_fpn_proposals_error2(self):
        program = Program()
        with program_guard(program):
            fpn_rois = paddle.static.data(
                name='min_max_level_error1',
                shape=[10, 4],
                dtype='float32',
                lod_level=1,
            )
            self.assertRaises(
                AssertionError,
                paddle.vision.ops.distribute_fpn_proposals,
                fpn_rois=fpn_rois,
                min_level=0,
                max_level=-1,
                refer_level=4,
                refer_scale=224,
            )

    def test_distribute_fpn_proposals_error3(self):
        program = Program()
        with program_guard(program):
            fpn_rois = paddle.static.data(
                name='min_max_level_error2',
                shape=[10, 4],
                dtype='float32',
                lod_level=1,
            )
            self.assertRaises(
                AssertionError,
                paddle.vision.ops.distribute_fpn_proposals,
                fpn_rois=fpn_rois,
                min_level=2,
                max_level=2,
                refer_level=4,
                refer_scale=224,
            )

    def test_distribute_fpn_proposals_error4(self):
        program = Program()
        with program_guard(program):
            fpn_rois = paddle.static.data(
                name='min_max_level_error3',
                shape=[10, 4],
                dtype='float32',
                lod_level=1,
            )
            self.assertRaises(
                AssertionError,
                paddle.vision.ops.distribute_fpn_proposals,
                fpn_rois=fpn_rois,
                min_level=2,
                max_level=500,
                refer_level=4,
                refer_scale=224,
            )

319

320
if __name__ == '__main__':
H
hong 已提交
321
    paddle.enable_static()
322
    unittest.main()