test_matrix_nms_op.py 13.5 KB
Newer Older
Y
Yang Zhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

from __future__ import print_function
import unittest
import numpy as np
import copy
from op_test import OpTest
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
22
import paddle
Y
Yang Zhang 已提交
23 24


Z
zhiboniu 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
def python_matrix_nms(bboxes,
                      scores,
                      score_threshold,
                      nms_top_k,
                      keep_top_k,
                      post_threshold,
                      use_gaussian=False,
                      gaussian_sigma=2.,
                      background_label=0,
                      normalized=True,
                      return_index=True,
                      return_rois_num=True):
    out, rois_num, index = paddle.vision.ops.matrix_nms(
        bboxes, scores, score_threshold, post_threshold, nms_top_k, keep_top_k,
        use_gaussian, gaussian_sigma, background_label, normalized,
        return_index, return_rois_num)
    if not return_index:
        index = None
    if not return_rois_num:
        rois_num = None
    return out, index, rois_num


Y
Yang Zhang 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
def softmax(x):
    # clip to shiftx, otherwise, when calc loss with
    # log(exp(shiftx)), may get log(0)=INF
    shiftx = (x - np.max(x)).clip(-64.)
    exps = np.exp(shiftx)
    return exps / np.sum(exps)


def iou_matrix(a, b, norm=True):
    tl_i = np.maximum(a[:, np.newaxis, :2], b[:, :2])
    br_i = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])

    pad = not norm and 1 or 0

    area_i = np.prod(br_i - tl_i + pad, axis=2) * (tl_i < br_i).all(axis=2)
    area_a = np.prod(a[:, 2:] - a[:, :2] + pad, axis=1)
    area_b = np.prod(b[:, 2:] - b[:, :2] + pad, axis=1)
    area_o = (area_a[:, np.newaxis] + area_b - area_i)
    return area_i / (area_o + 1e-10)


def matrix_nms(boxes,
               scores,
               score_threshold,
               post_threshold=0.,
               nms_top_k=400,
               normalized=True,
               use_gaussian=False,
               gaussian_sigma=2.):
    all_scores = copy.deepcopy(scores)
    all_scores = all_scores.flatten()
    selected_indices = np.where(all_scores > score_threshold)[0]
    all_scores = all_scores[selected_indices]

    sorted_indices = np.argsort(-all_scores, axis=0, kind='mergesort')
    sorted_scores = all_scores[sorted_indices]
    sorted_indices = selected_indices[sorted_indices]
    if nms_top_k > -1 and nms_top_k < sorted_indices.shape[0]:
        sorted_indices = sorted_indices[:nms_top_k]
        sorted_scores = sorted_scores[:nms_top_k]

    selected_boxes = boxes[sorted_indices, :]
    ious = iou_matrix(selected_boxes, selected_boxes)
    ious = np.triu(ious, k=1)
    iou_cmax = ious.max(0)
    N = iou_cmax.shape[0]
    iou_cmax = np.repeat(iou_cmax[:, np.newaxis], N, axis=1)

    if use_gaussian:
        decay = np.exp((iou_cmax**2 - ious**2) * gaussian_sigma)
    else:
        decay = (1 - ious) / (1 - iou_cmax)
    decay = decay.min(0)
    decayed_scores = sorted_scores * decay

    if post_threshold > 0.:
        inds = np.where(decayed_scores > post_threshold)[0]
        selected_boxes = selected_boxes[inds, :]
        decayed_scores = decayed_scores[inds]
        sorted_indices = sorted_indices[inds]

    return decayed_scores, selected_boxes, sorted_indices


def multiclass_nms(boxes, scores, background, score_threshold, post_threshold,
                   nms_top_k, keep_top_k, normalized, use_gaussian,
                   gaussian_sigma):
    all_boxes = []
    all_cls = []
    all_scores = []
    all_indices = []
    for c in range(scores.shape[0]):
        if c == background:
            continue
        decayed_scores, selected_boxes, indices = matrix_nms(
            boxes, scores[c], score_threshold, post_threshold, nms_top_k,
            normalized, use_gaussian, gaussian_sigma)
        all_cls.append(np.full(len(decayed_scores), c, decayed_scores.dtype))
        all_boxes.append(selected_boxes)
        all_scores.append(decayed_scores)
        all_indices.append(indices)

    all_cls = np.concatenate(all_cls)
    all_boxes = np.concatenate(all_boxes)
    all_scores = np.concatenate(all_scores)
    all_indices = np.concatenate(all_indices)
    all_pred = np.concatenate(
        (all_cls[:, np.newaxis], all_scores[:, np.newaxis], all_boxes), axis=1)

    num_det = len(all_pred)
    if num_det == 0:
        return all_pred, np.array([], dtype=np.float32)

    inds = np.argsort(-all_scores, axis=0, kind='mergesort')
    all_pred = all_pred[inds, :]
    all_indices = all_indices[inds]

    if keep_top_k > -1 and num_det > keep_top_k:
        num_det = keep_top_k
        all_pred = all_pred[:keep_top_k, :]
        all_indices = all_indices[:keep_top_k]

    return all_pred, all_indices


def batched_multiclass_nms(boxes,
                           scores,
                           background,
                           score_threshold,
                           post_threshold,
                           nms_top_k,
                           keep_top_k,
                           normalized=True,
                           use_gaussian=False,
                           gaussian_sigma=2.):
    batch_size = scores.shape[0]
    det_outs = []
    index_outs = []
    lod = []
    for n in range(batch_size):
168 169 170 171
        nmsed_outs, indices = multiclass_nms(boxes[n], scores[n], background,
                                             score_threshold, post_threshold,
                                             nms_top_k, keep_top_k, normalized,
                                             use_gaussian, gaussian_sigma)
Y
Yang Zhang 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185
        nmsed_num = len(nmsed_outs)
        lod.append(nmsed_num)
        if nmsed_num == 0:
            continue
        indices += n * scores.shape[2]
        det_outs.append(nmsed_outs)
        index_outs.append(indices)
    if det_outs:
        det_outs = np.concatenate(det_outs)
        index_outs = np.concatenate(index_outs)
    return det_outs, index_outs, lod


class TestMatrixNMSOp(OpTest):
186

Y
Yang Zhang 已提交
187 188 189 190 191 192
    def set_argument(self):
        self.post_threshold = 0.
        self.use_gaussian = False

    def setUp(self):
        self.set_argument()
Z
zhiboniu 已提交
193
        self.python_api = python_matrix_nms
Y
Yang Zhang 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        N = 7
        M = 1200
        C = 21
        BOX_SIZE = 4
        background = 0
        nms_top_k = 400
        keep_top_k = 200
        score_threshold = 0.01
        post_threshold = self.post_threshold
        use_gaussian = False
        if hasattr(self, 'use_gaussian'):
            use_gaussian = self.use_gaussian
        gaussian_sigma = 2.

        scores = np.random.random((N * M, C)).astype('float32')

        scores = np.apply_along_axis(softmax, 1, scores)
        scores = np.reshape(scores, (N, M, C))
        scores = np.transpose(scores, (0, 2, 1))

        boxes = np.random.random((N, M, BOX_SIZE)).astype('float32')
        boxes[:, :, 0:2] = boxes[:, :, 0:2] * 0.5
        boxes[:, :, 2:4] = boxes[:, :, 2:4] * 0.5 + 0.5

        det_outs, index_outs, lod = batched_multiclass_nms(
            boxes, scores, background, score_threshold, post_threshold,
            nms_top_k, keep_top_k, True, use_gaussian, gaussian_sigma)

        empty = len(det_outs) == 0
        det_outs = np.array([], dtype=np.float32) if empty else det_outs
        index_outs = np.array([], dtype=np.float32) if empty else index_outs
        nmsed_outs = det_outs.astype('float32')

        self.op_type = 'matrix_nms'
        self.inputs = {'BBoxes': boxes, 'Scores': scores}
        self.outputs = {
Z
zhiboniu 已提交
230 231
            'Out': nmsed_outs,
            'Index': index_outs[:, None],
232
            'RoisNum': np.array(lod).astype('int32')
Y
Yang Zhang 已提交
233 234
        }
        self.attrs = {
Z
zhiboniu 已提交
235
            'score_threshold': score_threshold,
Y
Yang Zhang 已提交
236 237 238 239 240
            'nms_top_k': nms_top_k,
            'keep_top_k': keep_top_k,
            'post_threshold': post_threshold,
            'use_gaussian': use_gaussian,
            'gaussian_sigma': gaussian_sigma,
Z
zhiboniu 已提交
241
            'background_label': 0,
Y
Yang Zhang 已提交
242 243 244 245
            'normalized': True,
        }

    def test_check_output(self):
Z
zhiboniu 已提交
246
        self.check_output(check_eager=True)
Y
Yang Zhang 已提交
247 248 249


class TestMatrixNMSOpNoOutput(TestMatrixNMSOp):
250

Y
Yang Zhang 已提交
251 252 253 254 255
    def set_argument(self):
        self.post_threshold = 2.0


class TestMatrixNMSOpGaussian(TestMatrixNMSOp):
256

Y
Yang Zhang 已提交
257 258 259 260 261 262
    def set_argument(self):
        self.post_threshold = 0.
        self.use_gaussian = True


class TestMatrixNMSError(unittest.TestCase):
263

Y
Yang Zhang 已提交
264
    def test_errors(self):
265 266 267 268 269 270 271 272
        M = 1200
        N = 7
        C = 21
        BOX_SIZE = 4
        nms_top_k = 400
        keep_top_k = 200
        score_threshold = 0.01
        post_threshold = 0.
Y
Yang Zhang 已提交
273

274 275 276 277 278 279 280
        boxes_np = np.random.random((M, C, BOX_SIZE)).astype('float32')
        scores = np.random.random((N * M, C)).astype('float32')
        scores = np.apply_along_axis(softmax, 1, scores)
        scores = np.reshape(scores, (N, M, C))
        scores_np = np.transpose(scores, (0, 2, 1))

        with program_guard(Program(), Program()):
281 282 283 284 285 286
            boxes_data = fluid.data(name='bboxes',
                                    shape=[M, C, BOX_SIZE],
                                    dtype='float32')
            scores_data = fluid.data(name='scores',
                                     shape=[N, C, M],
                                     dtype='float32')
Y
Yang Zhang 已提交
287 288 289

            def test_bboxes_Variable():
                # the bboxes type must be Variable
290 291 292
                fluid.layers.matrix_nms(bboxes=boxes_np,
                                        scores=scores_data,
                                        score_threshold=score_threshold,
Z
zhiboniu 已提交
293 294 295
                                        post_threshold=post_threshold,
                                        nms_top_k=nms_top_k,
                                        keep_top_k=keep_top_k)
296 297 298
                paddle.vision.ops.matrix_nms(bboxes=boxes_np,
                                             scores=scores_data,
                                             score_threshold=score_threshold,
Z
zhiboniu 已提交
299 300 301
                                             post_threshold=post_threshold,
                                             nms_top_k=nms_top_k,
                                             keep_top_k=keep_top_k)
Y
Yang Zhang 已提交
302 303 304

            def test_scores_Variable():
                # the scores type must be Variable
305 306 307
                fluid.layers.matrix_nms(bboxes=boxes_data,
                                        scores=scores_np,
                                        score_threshold=score_threshold,
Z
zhiboniu 已提交
308 309 310
                                        post_threshold=post_threshold,
                                        nms_top_k=nms_top_k,
                                        keep_top_k=keep_top_k)
311 312 313
                paddle.vision.ops.matrix_nms(bboxes=boxes_data,
                                             scores=scores_np,
                                             score_threshold=score_threshold,
Z
zhiboniu 已提交
314 315 316
                                             post_threshold=post_threshold,
                                             nms_top_k=nms_top_k,
                                             keep_top_k=keep_top_k)
Y
Yang Zhang 已提交
317 318 319 320

            def test_empty():
                # when all score are lower than threshold
                try:
321 322
                    fluid.layers.matrix_nms(bboxes=boxes_data,
                                            scores=scores_data,
Z
zhiboniu 已提交
323 324
                                            score_threshold=score_threshold,
                                            post_threshold=post_threshold,
325
                                            nms_top_k=nms_top_k,
Z
zhiboniu 已提交
326
                                            keep_top_k=keep_top_k)
Y
Yang Zhang 已提交
327 328
                except Exception as e:
                    self.fail(e)
329
                try:
Z
zhiboniu 已提交
330 331 332 333 334 335 336
                    paddle.vision.ops.matrix_nms(
                        bboxes=boxes_data,
                        scores=scores_data,
                        score_threshold=score_threshold,
                        post_threshold=post_threshold,
                        nms_top_k=nms_top_k,
                        keep_top_k=keep_top_k)
337 338
                except Exception as e:
                    self.fail(e)
Y
Yang Zhang 已提交
339 340 341 342

            def test_coverage():
                # cover correct workflow
                try:
343 344 345
                    fluid.layers.matrix_nms(bboxes=boxes_data,
                                            scores=scores_data,
                                            score_threshold=score_threshold,
Z
zhiboniu 已提交
346 347 348
                                            post_threshold=post_threshold,
                                            nms_top_k=nms_top_k,
                                            keep_top_k=keep_top_k)
Y
Yang Zhang 已提交
349 350
                except Exception as e:
                    self.fail(e)
351 352 353 354 355
                try:
                    paddle.vision.ops.matrix_nms(
                        bboxes=boxes_data,
                        scores=scores_data,
                        score_threshold=score_threshold,
Z
zhiboniu 已提交
356 357 358
                        post_threshold=post_threshold,
                        nms_top_k=nms_top_k,
                        keep_top_k=keep_top_k)
359 360
                except Exception as e:
                    self.fail(e)
Y
Yang Zhang 已提交
361 362 363 364 365 366 367

            self.assertRaises(TypeError, test_bboxes_Variable)
            self.assertRaises(TypeError, test_scores_Variable)
            test_coverage()


if __name__ == '__main__':
Z
zhiboniu 已提交
368
    paddle.enable_static()
Y
Yang Zhang 已提交
369
    unittest.main()