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 26
import paddle.fluid as fluid
import paddle.fluid.layers as layers
from paddle.fluid import core
from paddle.fluid.dygraph import base
from paddle.fluid.framework import Program, program_guard
P
pangyoki 已提交
27 28

paddle.enable_static()
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 55


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

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

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


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

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

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

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


153 154 155 156
class TestMulticlassNMS2(unittest.TestCase):
    def test_multiclass_nms2(self):
        program = Program()
        with program_guard(program):
157 158 159
            bboxes = layers.data(
                name='bboxes', shape=[-1, 10, 4], dtype='float32'
            )
160
            scores = layers.data(name='scores', shape=[-1, 10], dtype='float32')
161 162 163 164 165 166
            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
            )
167 168 169 170 171
            self.assertIsNotNone(output)
            self.assertIsNotNone(output2)
            self.assertIsNotNone(index)


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

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


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