test_detection.py 8.7 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 19
import numpy as np
from unittests.test_imperative_base import new_program_scope
20

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

paddle.enable_static()
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54


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

55 56 57
    def get_static_graph_result(
        self, feed, fetch_list, with_lod=False, force_to_use_cpu=False
    ):
58 59
        exe = fluid.Executor(self._get_place(force_to_use_cpu))
        exe.run(fluid.default_startup_program())
60 61 62 63 64 65
        return exe.run(
            fluid.default_main_program(),
            feed=feed,
            fetch_list=fetch_list,
            return_numpy=(not with_lod),
        )
66 67 68 69

    @contextlib.contextmanager
    def dynamic_graph(self, force_to_use_cpu=False):
        with fluid.dygraph.guard(
70 71
            self._get_place(force_to_use_cpu=force_to_use_cpu)
        ):
72 73 74
            fluid.default_startup_program().random_seed = self.seed
            fluid.default_main_program().random_seed = self.seed
            yield
75 76


77
class TestGenerateProposals(LayerTest):
78
    def test_generate_proposals(self):
79 80 81
        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')
82 83 84
        anchors_np = np.reshape(np.arange(4 * 4 * 3 * 4), [4, 4, 3, 4]).astype(
            'float32'
        )
85 86 87
        variances_np = np.ones((4, 4, 3, 4)).astype('float32')

        with self.static_graph():
88 89 90 91 92 93
            scores = fluid.data(
                name='scores', shape=[2, 3, 4, 4], dtype='float32'
            )
            bbox_deltas = fluid.data(
                name='bbox_deltas', shape=[2, 12, 4, 4], dtype='float32'
            )
94
            im_info = fluid.data(name='im_info', shape=[2, 3], dtype='float32')
95 96 97 98 99 100
            anchors = fluid.data(
                name='anchors', shape=[4, 4, 3, 4], dtype='float32'
            )
            variances = fluid.data(
                name='var', shape=[4, 4, 3, 4], dtype='float32'
            )
101
            rois, roi_probs, rois_num = paddle.vision.ops.generate_proposals(
102 103
                scores,
                bbox_deltas,
104
                im_info[:2],
105 106 107 108
                anchors,
                variances,
                pre_nms_top_n=10,
                post_nms_top_n=5,
109 110 111 112 113 114 115
                return_rois_num=True,
            )
            (
                rois_stat,
                roi_probs_stat,
                rois_num_stat,
            ) = self.get_static_graph_result(
116 117 118 119 120
                feed={
                    'scores': scores_np,
                    'bbox_deltas': bbox_deltas_np,
                    'im_info': im_info_np,
                    'anchors': anchors_np,
121
                    'var': variances_np,
122 123
                },
                fetch_list=[rois, roi_probs, rois_num],
124 125
                with_lod=False,
            )
126 127 128 129 130 131 132

        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)
133
            rois, roi_probs, rois_num = paddle.vision.ops.generate_proposals(
134 135
                scores_dy,
                bbox_deltas_dy,
136
                im_info_dy[:2],
137 138 139 140
                anchors_dy,
                variances_dy,
                pre_nms_top_n=10,
                post_nms_top_n=5,
141 142
                return_rois_num=True,
            )
143 144 145 146
            rois_dy = rois.numpy()
            roi_probs_dy = roi_probs.numpy()
            rois_num_dy = rois_num.numpy()

147 148 149
        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)
150 151


152 153 154 155
class TestMulticlassNMS2(unittest.TestCase):
    def test_multiclass_nms2(self):
        program = Program()
        with program_guard(program):
G
GGBond8488 已提交
156
            bboxes = paddle.static.data(
157 158
                name='bboxes', shape=[-1, 10, 4], dtype='float32'
            )
G
GGBond8488 已提交
159 160 161
            scores = paddle.static.data(
                name='scores', shape=[-1, 10], dtype='float32'
            )
162 163 164 165 166 167
            output = fluid.contrib.multiclass_nms2(
                bboxes, scores, 0.3, 400, 200, 0.7
            )
            output2, index = fluid.contrib.multiclass_nms2(
                bboxes, scores, 0.3, 400, 200, 0.7, return_index=True
            )
168 169 170 171 172
            self.assertIsNotNone(output)
            self.assertIsNotNone(output2)
            self.assertIsNotNone(index)


173
class TestDistributeFpnProposals(LayerTest):
174
    def test_distribute_fpn_proposals(self):
175 176 177 178 179
        rois_np = np.random.rand(10, 4).astype('float32')
        rois_num_np = np.array([4, 6]).astype('int32')
        with self.static_graph():
            rois = fluid.data(name='rois', shape=[10, 4], dtype='float32')
            rois_num = fluid.data(name='rois_num', shape=[None], dtype='int32')
180 181 182 183
            (
                multi_rois,
                restore_ind,
                rois_num_per_level,
184
            ) = paddle.vision.ops.distribute_fpn_proposals(
185 186 187 188 189
                fpn_rois=rois,
                min_level=2,
                max_level=5,
                refer_level=4,
                refer_scale=224,
190 191
                rois_num=rois_num,
            )
192
            fetch_list = multi_rois + [restore_ind] + rois_num_per_level
193 194 195 196 197
            output_stat = self.get_static_graph_result(
                feed={'rois': rois_np, 'rois_num': rois_num_np},
                fetch_list=fetch_list,
                with_lod=True,
            )
198 199 200 201 202 203 204 205 206
            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)
207 208 209 210
            (
                multi_rois_dy,
                restore_ind_dy,
                rois_num_per_level_dy,
211
            ) = paddle.vision.ops.distribute_fpn_proposals(
212
                fpn_rois=rois_dy,
213 214 215
                min_level=2,
                max_level=5,
                refer_level=4,
216
                refer_scale=224,
217 218
                rois_num=rois_num_dy,
            )
H
hong 已提交
219
            print(type(multi_rois_dy))
220 221 222 223 224 225 226 227
            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):
228
            np.testing.assert_array_equal(res_stat, res_dy)
229

230 231 232
    def test_distribute_fpn_proposals_error(self):
        program = Program()
        with program_guard(program):
233 234 235 236 237
            fpn_rois = fluid.data(
                name='data_error', shape=[10, 4], dtype='int32', lod_level=1
            )
            self.assertRaises(
                TypeError,
238
                paddle.vision.ops.distribute_fpn_proposals,
239 240 241 242 243 244
                fpn_rois=fpn_rois,
                min_level=2,
                max_level=5,
                refer_level=4,
                refer_scale=224,
            )
245 246


247
if __name__ == '__main__':
H
hong 已提交
248
    paddle.enable_static()
249
    unittest.main()