detection.py 99.6 KB
Newer Older
1
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
2 3 4 5 6
#
# 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
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8 9 10 11 12 13 14 15 16 17
#
# 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.
"""
All layers just related to the detection neural network.
"""

18 19
import paddle

20
from .layer_function_generator import templatedoc
21
from ..layer_helper import LayerHelper
Z
zhiboniu 已提交
22
from ..framework import Variable, _non_static_mode, static_only, in_dygraph_mode
23
from .. import core
24
from paddle.fluid.layers import softmax_with_cross_entropy
25 26
from . import tensor
from . import nn
27
from ..data_feeder import check_variable_and_dtype, check_type, check_dtype
C
chengduoZH 已提交
28
import math
29
import numpy as np
30
from functools import reduce
31 32 33 34 35 36
from ..data_feeder import (
    convert_dtype,
    check_variable_and_dtype,
    check_type,
    check_dtype,
)
37
from paddle.utils import deprecated
38
from paddle import _C_ops, _legacy_C_ops
L
lyq 已提交
39
from ..framework import in_dygraph_mode
40

C
chengduoZH 已提交
41
__all__ = [
42 43 44 45 46 47 48
    'prior_box',
    'density_prior_box',
    'multi_box_head',
    'anchor_generator',
    'roi_perspective_transform',
    'generate_proposal_labels',
    'generate_proposals',
49
    'generate_mask_labels',
50 51 52
    'box_coder',
    'polygon_box_transform',
    'box_clip',
J
jerrywgz 已提交
53
    'multiclass_nms',
54
    'locality_aware_nms',
Y
Yang Zhang 已提交
55
    'matrix_nms',
56
    'retinanet_detection_output',
57
    'distribute_fpn_proposals',
58
    'box_decoder_and_assign',
59
    'collect_fpn_proposals',
C
chengduoZH 已提交
60
]
61 62


X
Xin Pan 已提交
63
@templatedoc()
64 65 66 67 68 69 70 71 72
def box_coder(
    prior_box,
    prior_box_var,
    target_box,
    code_type="encode_center_size",
    box_normalized=True,
    name=None,
    axis=0,
):
73
    r"""
S
swtkiwi 已提交
74

75 76 77
    **Box Coder Layer**

    Encode/Decode the target bounding box with the priorbox information.
78

79 80 81 82 83 84 85 86
    The Encoding schema described below:

    .. math::

        ox = (tx - px) / pw / pxv

        oy = (ty - py) / ph / pyv

87
        ow = \log(\abs(tw / pw)) / pwv
88

89
        oh = \log(\abs(th / ph)) / phv
90 91

    The Decoding schema described below:
92

93
    .. math::
94

95 96 97 98 99 100
        ox = (pw * pxv * tx * + px) - tw / 2

        oy = (ph * pyv * ty * + py) - th / 2

        ow = \exp(pwv * tw) * pw + tw / 2

101
        oh = \exp(phv * th) * ph + th / 2
102

103 104 105 106 107
    where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates,
    width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote
    the priorbox's (anchor) center coordinates, width and height. `pxv`,
    `pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`,
    `ow`, `oh` denote the encoded/decoded coordinates, width and height.
108

109 110 111 112
    During Box Decoding, two modes for broadcast are supported. Say target
    box has shape [N, M, 4], and the shape of prior box can be [N, 4] or
    [M, 4]. Then prior box will broadcast to target box along the
    assigned axis.
X
Xin Pan 已提交
113 114

    Args:
115
        prior_box(Variable): Box list prior_box is a 2-D Tensor with shape
W
wangguanzhong 已提交
116
            [M, 4] holds M boxes and data type is float32 or float64. Each box
117
            is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the
W
wangguanzhong 已提交
118
            left top coordinate of the anchor box, if the input is image feature
119 120 121 122 123 124 125 126 127 128 129 130 131
            map, they are close to the origin of the coordinate system.
            [xmax, ymax] is the right bottom coordinate of the anchor box.
        prior_box_var(List|Variable|None): prior_box_var supports three types
            of input. One is variable with shape [M, 4] which holds M group and
            data type is float32 or float64. The second is list consist of
            4 elements shared by all boxes and data type is float32 or float64.
            Other is None and not involved in calculation.
        target_box(Variable): This input can be a 2-D LoDTensor with shape
            [N, 4] when code_type is 'encode_center_size'. This input also can
            be a 3-D Tensor with shape [N, M, 4] when code_type is
            'decode_center_size'. Each box is represented as
            [xmin, ymin, xmax, ymax]. The data type is float32 or float64.
            This tensor can contain LoD information to represent a batch of inputs.
W
wangguanzhong 已提交
132
        code_type(str): The code type used with the target box. It can be
133
            `encode_center_size` or `decode_center_size`. `encode_center_size`
W
wangguanzhong 已提交
134
            by default.
T
tianshuo78520a 已提交
135
        box_normalized(bool): Whether treat the priorbox as a normalized box.
W
wangguanzhong 已提交
136
            Set true by default.
137 138 139 140 141
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
            None by default.
        axis(int): Which axis in PriorBox to broadcast for box decode,
            for example, if axis is 0 and TargetBox has shape [N, M, 4] and
W
wangguanzhong 已提交
142
            PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]
143 144
            for decoding. It is only valid when code type is
            `decode_center_size`. Set 0 by default.
X
Xin Pan 已提交
145 146

    Returns:
W
wangguanzhong 已提交
147 148
        Variable:

149 150 151 152
        output_box(Variable): When code_type is 'encode_center_size', the
        output tensor of box_coder_op with shape [N, M, 4] representing the
        result of N target boxes encoded with M Prior boxes and variances.
        When code_type is 'decode_center_size', N represents the batch size
T
tianshuo78520a 已提交
153
        and M represents the number of decoded boxes.
154 155

    Examples:
156

157
        .. code-block:: python
158

159
            import paddle.fluid as fluid
160 161
            import paddle
            paddle.enable_static()
W
wangguanzhong 已提交
162
            # For encode
163
            prior_box_encode = fluid.data(name='prior_box_encode',
W
wangguanzhong 已提交
164
                                  shape=[512, 4],
165 166 167 168
                                  dtype='float32')
            target_box_encode = fluid.data(name='target_box_encode',
                                   shape=[81, 4],
                                   dtype='float32')
W
wangguanzhong 已提交
169 170 171 172 173
            output_encode = fluid.layers.box_coder(prior_box=prior_box_encode,
                                    prior_box_var=[0.1,0.1,0.2,0.2],
                                    target_box=target_box_encode,
                                    code_type="encode_center_size")
            # For decode
174
            prior_box_decode = fluid.data(name='prior_box_decode',
W
wangguanzhong 已提交
175
                                  shape=[512, 4],
176 177 178 179
                                  dtype='float32')
            target_box_decode = fluid.data(name='target_box_decode',
                                   shape=[512, 81, 4],
                                   dtype='float32')
W
wangguanzhong 已提交
180 181 182 183 184 185
            output_decode = fluid.layers.box_coder(prior_box=prior_box_decode,
                                    prior_box_var=[0.1,0.1,0.2,0.2],
                                    target_box=target_box_decode,
                                    code_type="decode_center_size",
                                    box_normalized=False,
                                    axis=1)
X
Xin Pan 已提交
186
    """
187 188 189 190 191 192 193 194
    return paddle.vision.ops.box_coder(
        prior_box=prior_box,
        prior_box_var=prior_box_var,
        target_box=target_box,
        code_type=code_type,
        box_normalized=box_normalized,
        axis=axis,
        name=name,
195
    )
X
Xin Pan 已提交
196 197 198 199 200 201 202 203


@templatedoc()
def polygon_box_transform(input, name=None):
    """
    ${comment}

    Args:
204 205 206 207
        input(Variable): The input with shape [batch_size, geometry_channels, height, width].
                         A Tensor with type float32, float64.
        name(str, Optional): For details, please refer to :ref:`api_guide_Name`.
                        Generally, no setting is required. Default: None.
X
Xin Pan 已提交
208 209

    Returns:
210
        Variable: The output with the same shape as input. A Tensor with type float32, float64.
B
Bai Yifan 已提交
211 212 213

    Examples:
        .. code-block:: python
214

B
Bai Yifan 已提交
215
            import paddle.fluid as fluid
B
Bai Yifan 已提交
216
            input = fluid.data(name='input', shape=[4, 10, 5, 5], dtype='float32')
B
Bai Yifan 已提交
217
            out = fluid.layers.polygon_box_transform(input)
X
Xin Pan 已提交
218
    """
219 220 221
    check_variable_and_dtype(
        input, "input", ['float32', 'float64'], 'polygon_box_transform'
    )
X
Xin Pan 已提交
222
    helper = LayerHelper("polygon_box_transform", **locals())
223
    output = helper.create_variable_for_type_inference(dtype=input.dtype)
X
Xin Pan 已提交
224

225 226 227 228 229 230
    helper.append_op(
        type="polygon_box_transform",
        inputs={"Input": input},
        attrs={},
        outputs={"Output": output},
    )
X
Xin Pan 已提交
231 232 233
    return output


Z
zhiboniu 已提交
234 235 236 237 238
def prior_box(
    input,
    image,
    min_sizes,
    max_sizes=None,
239
    aspect_ratios=[1.0],
Z
zhiboniu 已提交
240 241 242 243 244 245 246 247
    variance=[0.1, 0.1, 0.2, 0.2],
    flip=False,
    clip=False,
    steps=[0.0, 0.0],
    offset=0.5,
    name=None,
    min_max_aspect_ratios_order=False,
):
248
    """
S
swtkiwi 已提交
249

R
ruri 已提交
250
    This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm.
251 252 253 254 255
    Each position of the input produce N prior boxes, N is determined by
    the count of min_sizes, max_sizes and aspect_ratios, The size of the
    box is in range(min_size, max_size) interval, which is generated in
    sequence according to the aspect_ratios.

R
ruri 已提交
256
    Parameters:
T
tianshuo78520a 已提交
257
       input(Variable): 4-D tensor(NCHW), the data type should be float32 or float64.
R
ruri 已提交
258 259 260 261
       image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp,
            the data type should be float32 or float64.
       min_sizes(list|tuple|float): the min sizes of generated prior boxes.
       max_sizes(list|tuple|None): the max sizes of generated prior boxes.
262
            Default: None.
R
ruri 已提交
263
       aspect_ratios(list|tuple|float): the aspect ratios of generated
264
            prior boxes. Default: [1.].
265 266 267 268
       variance(list|tuple): the variances to be encoded in prior boxes.
            Default:[0.1, 0.1, 0.2, 0.2].
       flip(bool): Whether to flip aspect ratios. Default:False.
       clip(bool): Whether to clip out-of-boundary boxes. Default: False.
翟飞跃 已提交
269
       step(list|tuple): Prior boxes step across width and height, If
R
ruri 已提交
270 271
            step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across
            height or weight of the input will be automatically calculated.
272
            Default: [0., 0.]
273
       offset(float): Prior boxes center offset. Default: 0.5
274
       min_max_aspect_ratios_order(bool): If set True, the output prior box is
M
minqiyang 已提交
275
            in order of [min, max, aspect_ratios], which is consistent with
276 277 278
            Caffe. Please note, this order affects the weights order of
            convolution layer followed by and does not affect the final
            detection results. Default: False.
R
ruri 已提交
279
       name(str, optional): The default value is None.  Normally there is no need for user to set this property.  For more information, please refer to :ref:`api_guide_Name`
280 281

    Returns:
R
ruri 已提交
282
        Tuple: A tuple with two Variable (boxes, variances)
Q
update  
qiaolongfei 已提交
283

R
ruri 已提交
284
        boxes(Variable): the output prior boxes of PriorBox.
285
        4-D tensor, the layout is [H, W, num_priors, 4].
Q
update  
qiaolongfei 已提交
286
        H is the height of input, W is the width of input,
R
ruri 已提交
287
        num_priors is the total box count of each position of input.
Q
update  
qiaolongfei 已提交
288

R
ruri 已提交
289
        variances(Variable): the expanded variances of PriorBox.
290
        4-D tensor, the layput is [H, W, num_priors, 4].
Q
update  
qiaolongfei 已提交
291
        H is the height of input, W is the width of input
R
ruri 已提交
292
        num_priors is the total box count of each position of input
293 294 295

    Examples:
        .. code-block:: python
Q
update  
qiaolongfei 已提交
296

297 298 299
            #declarative mode
            import paddle.fluid as fluid
            import numpy as np
300 301
            import paddle
            paddle.enable_static()
302 303 304
            input = fluid.data(name="input", shape=[None,3,6,9])
            image = fluid.data(name="image", shape=[None,3,9,12])
            box, var = fluid.layers.prior_box(
R
ruri 已提交
305 306
                 input=input,
                 image=image,
307
                 min_sizes=[100.],
R
ruri 已提交
308 309 310
                 clip=True,
                 flip=True)

311 312 313
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
314

315 316 317
            # prepare a batch of data
            input_data = np.random.rand(1,3,6,9).astype("float32")
            image_data = np.random.rand(1,3,9,12).astype("float32")
318

319
            box_out, var_out = exe.run(fluid.default_main_program(),
R
ruri 已提交
320 321 322
                feed={"input":input_data,"image":image_data},
                fetch_list=[box,var],
                return_numpy=True)
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
            # print(box_out.shape)
            # (6, 9, 1, 4)
            # print(var_out.shape)
            # (6, 9, 1, 4)

            # imperative mode
            import paddle.fluid.dygraph as dg

            with dg.guard(place) as g:
                input = dg.to_variable(input_data)
                image = dg.to_variable(image_data)
                box, var = fluid.layers.prior_box(
                    input=input,
                    image=image,
                    min_sizes=[100.],
                    clip=True,
                    flip=True)
                # print(box.shape)
                # [6L, 9L, 1L, 4L]
R
ruri 已提交
343
                # print(var.shape)
344
                # [6L, 9L, 1L, 4L]
R
ruri 已提交
345

346
    """
347 348 349 350 351 352 353 354 355 356 357 358 359
    return paddle.vision.ops.prior_box(
        input=input,
        image=image,
        min_sizes=min_sizes,
        max_sizes=max_sizes,
        aspect_ratios=aspect_ratios,
        variance=variance,
        flip=flip,
        clip=clip,
        steps=steps,
        offset=offset,
        min_max_aspect_ratios_order=min_max_aspect_ratios_order,
        name=name,
360
    )
361 362


363 364 365 366 367 368 369 370 371 372 373 374 375
def density_prior_box(
    input,
    image,
    densities=None,
    fixed_sizes=None,
    fixed_ratios=None,
    variance=[0.1, 0.1, 0.2, 0.2],
    clip=False,
    steps=[0.0, 0.0],
    offset=0.5,
    flatten_to_2d=False,
    name=None,
):
376
    r"""
R
ruri 已提交
377

378 379 380 381 382 383
    This op generates density prior boxes for SSD(Single Shot MultiBox Detector)
    algorithm. Each position of the input produce N prior boxes, N is
    determined by the count of densities, fixed_sizes and fixed_ratios.
    Boxes center at grid points around each input position is generated by
    this operator, and the grid points is determined by densities and
    the count of density prior box is determined by fixed_sizes and fixed_ratios.
R
ruri 已提交
384
    Obviously, the number of fixed_sizes is equal to the number of densities.
385

R
ruri 已提交
386
    For densities_i in densities:
387

R
ruri 已提交
388
    .. math::
R
ruri 已提交
389

R
ruri 已提交
390 391 392 393 394 395 396
        N\_density_prior\_box = SUM(N\_fixed\_ratios * densities\_i^2)

    N_density_prior_box is the number of density_prior_box and N_fixed_ratios is the number of fixed_ratios.

    Parameters:
       input(Variable): 4-D tensor(NCHW), the data type should be float32 of float64.
       image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64.
R
ruri 已提交
397
            the layout is NCHW.
398 399
       densities(list|tuple|None): The densities of generated density prior
            boxes, this attribute should be a list or tuple of integers.
R
ruri 已提交
400
            Default: None.
R
ruri 已提交
401
       fixed_sizes(list|tuple|None): The fixed sizes of generated density
402
            prior boxes, this attribute should a list or tuple of same
R
ruri 已提交
403
            length with :attr:`densities`. Default: None.
R
ruri 已提交
404
       fixed_ratios(list|tuple|None): The fixed ratios of generated density
R
ruri 已提交
405 406 407
            prior boxes, if this attribute is not set and :attr:`densities`
            and :attr:`fix_sizes` is set, :attr:`aspect_ratios` will be used
            to generate density prior boxes.
R
ruri 已提交
408
       variance(list|tuple): The variances to be encoded in density prior boxes.
R
ruri 已提交
409
            Default:[0.1, 0.1, 0.2, 0.2].
R
ruri 已提交
410
       clip(bool): Whether to clip out of boundary boxes. Default: False.
翟飞跃 已提交
411
       step(list|tuple): Prior boxes step across width and height, If
R
ruri 已提交
412 413
            step[0] equals 0.0 or step[1] equals 0.0, the density prior boxes step across
            height or weight of the input will be automatically calculated.
R
ruri 已提交
414 415
            Default: [0., 0.]
       offset(float): Prior boxes center offset. Default: 0.5
416 417
       flatten_to_2d(bool): Whether to flatten output prior boxes and variance
           to 2D shape, the second dim is 4. Default: False.
R
ruri 已提交
418
       name(str, optional): The default value is None.  Normally there is no need for user to set this property.  For more information, please refer to :ref:`api_guide_Name`
419

R
ruri 已提交
420
    Returns:
R
ruri 已提交
421
        Tuple: A tuple with two Variable (boxes, variances)
R
ruri 已提交
422 423

        boxes: the output density prior boxes of PriorBox.
R
ruri 已提交
424 425 426
        4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.
        2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.
        H is the height of input, W is the width of input, and num_priors is the total box count of each position of input.
R
ruri 已提交
427 428

        variances: the expanded variances of PriorBox.
R
ruri 已提交
429 430 431
        4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.
        2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.
        H is the height of input, W is the width of input, and num_priors is the total box count of each position of input.
R
ruri 已提交
432 433 434


    Examples:
R
ruri 已提交
435

R
ruri 已提交
436 437
        .. code-block:: python

R
ruri 已提交
438
            #declarative mode
R
ruri 已提交
439

R
ruri 已提交
440 441
            import paddle.fluid as fluid
            import numpy as np
442 443
            import paddle
            paddle.enable_static()
R
ruri 已提交
444

R
ruri 已提交
445 446 447
            input = fluid.data(name="input", shape=[None,3,6,9])
            image = fluid.data(name="image", shape=[None,3,9,12])
            box, var = fluid.layers.density_prior_box(
R
ruri 已提交
448 449 450 451 452 453 454 455
                 input=input,
                 image=image,
                 densities=[4, 2, 1],
                 fixed_sizes=[32.0, 64.0, 128.0],
                 fixed_ratios=[1.],
                 clip=True,
                 flatten_to_2d=True)

R
ruri 已提交
456 457 458
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
459

R
ruri 已提交
460 461 462 463 464 465
            # prepare a batch of data
            input_data = np.random.rand(1,3,6,9).astype("float32")
            image_data = np.random.rand(1,3,9,12).astype("float32")

            box_out, var_out = exe.run(
                fluid.default_main_program(),
R
ruri 已提交
466
                feed={"input":input_data,
R
ruri 已提交
467
                      "image":image_data},
R
ruri 已提交
468 469 470
                fetch_list=[box,var],
                return_numpy=True)

R
ruri 已提交
471 472 473 474
            # print(box_out.shape)
            # (1134, 4)
            # print(var_out.shape)
            # (1134, 4)
R
ruri 已提交
475 476


R
ruri 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
            #imperative mode
            import paddle.fluid.dygraph as dg

            with dg.guard(place) as g:
                input = dg.to_variable(input_data)
                image = dg.to_variable(image_data)
                box, var = fluid.layers.density_prior_box(
                    input=input,
                    image=image,
                    densities=[4, 2, 1],
                    fixed_sizes=[32.0, 64.0, 128.0],
                    fixed_ratios=[1.],
                    clip=True)

                # print(box.shape)
                # [6L, 9L, 21L, 4L]
                # print(var.shape)
                # [6L, 9L, 21L, 4L]
R
ruri 已提交
495

R
ruri 已提交
496 497 498
    """
    helper = LayerHelper("density_prior_box", **locals())
    dtype = helper.input_dtype()
499 500 501
    check_variable_and_dtype(
        input, 'input', ['float32', 'float64'], 'density_prior_box'
    )
R
ruri 已提交
502 503

    def _is_list_or_tuple_(data):
504
        return isinstance(data, list) or isinstance(data, tuple)
R
ruri 已提交
505

506 507 508
    check_type(densities, 'densities', (list, tuple), 'density_prior_box')
    check_type(fixed_sizes, 'fixed_sizes', (list, tuple), 'density_prior_box')
    check_type(fixed_ratios, 'fixed_ratios', (list, tuple), 'density_prior_box')
R
ruri 已提交
509 510
    if len(densities) != len(fixed_sizes):
        raise ValueError('densities and fixed_sizes length should be euqal.')
511

R
ruri 已提交
512
    if not (_is_list_or_tuple_(steps) and len(steps) == 2):
513 514 515 516
        raise ValueError(
            'steps should be a list or tuple ',
            'with length 2, (step_width, step_height).',
        )
R
ruri 已提交
517 518 519 520 521 522 523 524 525 526 527 528

    densities = list(map(int, densities))
    fixed_sizes = list(map(float, fixed_sizes))
    fixed_ratios = list(map(float, fixed_ratios))
    steps = list(map(float, steps))

    attrs = {
        'variances': variance,
        'clip': clip,
        'step_w': steps[0],
        'step_h': steps[1],
        'offset': offset,
529 530 531 532
        'densities': densities,
        'fixed_sizes': fixed_sizes,
        'fixed_ratios': fixed_ratios,
        'flatten_to_2d': flatten_to_2d,
R
ruri 已提交
533 534 535 536 537
    }
    box = helper.create_variable_for_type_inference(dtype)
    var = helper.create_variable_for_type_inference(dtype)
    helper.append_op(
        type="density_prior_box",
538 539
        inputs={"Input": input, "Image": image},
        outputs={"Boxes": box, "Variances": var},
540 541
        attrs=attrs,
    )
R
ruri 已提交
542 543 544 545 546
    box.stop_gradient = True
    var.stop_gradient = True
    return box, var


547
@static_only
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
def multi_box_head(
    inputs,
    image,
    base_size,
    num_classes,
    aspect_ratios,
    min_ratio=None,
    max_ratio=None,
    min_sizes=None,
    max_sizes=None,
    steps=None,
    step_w=None,
    step_h=None,
    offset=0.5,
    variance=[0.1, 0.1, 0.2, 0.2],
    flip=True,
    clip=False,
    kernel_size=1,
    pad=0,
    stride=1,
    name=None,
    min_max_aspect_ratios_order=False,
):
C
chengduoZH 已提交
571
    """
572
        :api_attr: Static Graph
S
swtkiwi 已提交
573

Q
qingqing01 已提交
574 575 576 577
    Base on SSD ((Single Shot MultiBox Detector) algorithm, generate prior boxes,
    regression location and classification confidence on multiple input feature
    maps, then output the concatenate results. The details of this algorithm,
    please refer the section 2.2 of SSD paper `SSD: Single Shot MultiBox Detector
C
chengduoZH 已提交
578
    <https://arxiv.org/abs/1512.02325>`_ .
C
chengduoZH 已提交
579 580

    Args:
Q
qingqing01 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
       inputs (list(Variable)|tuple(Variable)): The list of input variables,
           the format of all Variables are 4-D Tensor, layout is NCHW.
           Data type should be float32 or float64.
       image (Variable): The input image, layout is NCHW. Data type should be
           the same as inputs.
       base_size(int): the base_size is input image size. When len(inputs) > 2
           and `min_size` and `max_size` are None, the `min_size` and `max_size`
           are calculated by `baze_size`, 'min_ratio' and `max_ratio`. The
           formula is as follows:

              ..  code-block:: text

                  min_sizes = []
                  max_sizes = []
                  step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))
596
                  for ratio in range(min_ratio, max_ratio + 1, step):
Q
qingqing01 已提交
597 598 599 600 601
                      min_sizes.append(base_size * ratio / 100.)
                      max_sizes.append(base_size * (ratio + step) / 100.)
                      min_sizes = [base_size * .10] + min_sizes
                      max_sizes = [base_size * .20] + max_sizes

C
chengduoZH 已提交
602
       num_classes(int): The number of classes.
Q
qingqing01 已提交
603 604
       aspect_ratios(list(float) | tuple(float)): the aspect ratios of generated
           prior boxes. The length of input and aspect_ratios must be equal.
C
chengduoZH 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
       min_ratio(int): the min ratio of generated prior boxes.
       max_ratio(int): the max ratio of generated prior boxes.
       min_sizes(list|tuple|None): If `len(inputs) <=2`,
            min_sizes must be set up, and the length of min_sizes
            should equal to the length of inputs. Default: None.
       max_sizes(list|tuple|None): If `len(inputs) <=2`,
            max_sizes must be set up, and the length of min_sizes
            should equal to the length of inputs. Default: None.
       steps(list|tuple): If step_w and step_h are the same,
            step_w and step_h can be replaced by steps.
       step_w(list|tuple): Prior boxes step
            across width. If step_w[i] == 0.0, the prior boxes step
            across width of the inputs[i] will be automatically
            calculated. Default: None.
       step_h(list|tuple): Prior boxes step across height, If
            step_h[i] == 0.0, the prior boxes step across height of
            the inputs[i] will be automatically calculated. Default: None.
       offset(float): Prior boxes center offset. Default: 0.5
       variance(list|tuple): the variances to be encoded in prior boxes.
624
            Default:[0.1, 0.1, 0.2, 0.2].
C
chengduoZH 已提交
625 626 627 628 629
       flip(bool): Whether to flip aspect ratios. Default:False.
       clip(bool): Whether to clip out-of-boundary boxes. Default: False.
       kernel_size(int): The kernel size of conv2d. Default: 1.
       pad(int|list|tuple): The padding of conv2d. Default:0.
       stride(int|list|tuple): The stride of conv2d. Default:1,
Q
qingqing01 已提交
630 631 632
       name(str): The default value is None.  Normally there is no need
           for user to set this property.  For more information, please
           refer to :ref:`api_guide_Name`.
633
       min_max_aspect_ratios_order(bool): If set True, the output prior box is
M
minqiyang 已提交
634
            in order of [min, max, aspect_ratios], which is consistent with
635
            Caffe. Please note, this order affects the weights order of
T
tianshuo78520a 已提交
636
            convolution layer followed by and does not affect the final
637
            detection results. Default: False.
C
chengduoZH 已提交
638 639

    Returns:
Q
update  
qiaolongfei 已提交
640 641
        tuple: A tuple with four Variables. (mbox_loc, mbox_conf, boxes, variances)

Q
qingqing01 已提交
642 643 644
        mbox_loc (Variable): The predicted boxes' location of the inputs. The
        layout is [N, num_priors, 4], where N is batch size, ``num_priors``
        is the number of prior boxes. Data type is the same as input.
Q
update  
qiaolongfei 已提交
645

Q
qingqing01 已提交
646
        mbox_conf (Variable): The predicted boxes' confidence of the inputs.
647
        The layout is [N, num_priors, C], where ``N`` and ``num_priors``
Q
qingqing01 已提交
648 649
        has the same meaning as above. C is the number of Classes.
        Data type is the same as input.
Q
update  
qiaolongfei 已提交
650

Q
qingqing01 已提交
651 652 653
        boxes (Variable): the output prior boxes. The layout is [num_priors, 4].
        The meaning of num_priors is the same as above.
        Data type is the same as input.
C
chengduoZH 已提交
654

Q
qingqing01 已提交
655 656
        variances (Variable): the expanded variances for prior boxes.
        The layout is [num_priors, 4]. Data type is the same as input.
C
chengduoZH 已提交
657

Q
qingqing01 已提交
658
    Examples 1: set min_ratio and max_ratio:
C
chengduoZH 已提交
659
        .. code-block:: python
Q
update  
qiaolongfei 已提交
660

661 662
          import paddle
          paddle.enable_static()
663

664 665 666 667 668 669 670
          images = paddle.static.data(name='data', shape=[None, 3, 300, 300], dtype='float32')
          conv1 = paddle.static.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')
          conv2 = paddle.static.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')
          conv3 = paddle.static.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')
          conv4 = paddle.static.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')
          conv5 = paddle.static.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')
          conv6 = paddle.static.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')
671

672
          mbox_locs, mbox_confs, box, var = paddle.static.nn.multi_box_head(
673
            inputs=[conv1, conv2, conv3, conv4, conv5, conv6],
C
chengduoZH 已提交
674 675 676 677 678 679 680 681 682
            image=images,
            num_classes=21,
            min_ratio=20,
            max_ratio=90,
            aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],
            base_size=300,
            offset=0.5,
            flip=True,
            clip=True)
Q
qingqing01 已提交
683 684 685 686

    Examples 2: set min_sizes and max_sizes:
        .. code-block:: python

687 688
          import paddle
          paddle.enable_static()
Q
qingqing01 已提交
689

690 691 692 693 694 695 696
          images = paddle.static.data(name='data', shape=[None, 3, 300, 300], dtype='float32')
          conv1 = paddle.static.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')
          conv2 = paddle.static.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')
          conv3 = paddle.static.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')
          conv4 = paddle.static.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')
          conv5 = paddle.static.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')
          conv6 = paddle.static.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')
Q
qingqing01 已提交
697

698
          mbox_locs, mbox_confs, box, var = paddle.static.nn.multi_box_head(
Q
qingqing01 已提交
699 700 701 702 703 704 705 706 707 708 709
            inputs=[conv1, conv2, conv3, conv4, conv5, conv6],
            image=images,
            num_classes=21,
            min_sizes=[60.0, 105.0, 150.0, 195.0, 240.0, 285.0],
            max_sizes=[[], 150.0, 195.0, 240.0, 285.0, 300.0],
            aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],
            base_size=300,
            offset=0.5,
            flip=True,
            clip=True)

C
chengduoZH 已提交
710 711
    """

C
chengduoZH 已提交
712
    def _reshape_with_axis_(input, axis=1):
713 714 715 716 717 718 719 720 721
        # Note : axis!=0 in current references to this func
        # if axis == 0:
        #     x = paddle.flatten(input, 0, -1)
        #     x = paddle.unsqueeze(x, 0)
        #     return x
        # else:
        x = paddle.flatten(input, axis, -1)
        x = paddle.flatten(x, 0, axis - 1)
        return x
722

723
    def _is_list_or_tuple_(data):
724
        return isinstance(data, list) or isinstance(data, tuple)
725

C
chengduoZH 已提交
726 727 728 729
    def _is_list_or_tuple_and_equal(data, length, err_info):
        if not (_is_list_or_tuple_(data) and len(data) == length):
            raise ValueError(err_info)

730 731
    if not _is_list_or_tuple_(inputs):
        raise ValueError('inputs should be a list or tuple.')
C
chengduoZH 已提交
732

C
chengduoZH 已提交
733 734 735 736 737
    num_layer = len(inputs)

    if num_layer <= 2:
        assert min_sizes is not None and max_sizes is not None
        assert len(min_sizes) == num_layer and len(max_sizes) == num_layer
738
    elif min_sizes is None and max_sizes is None:
C
chengduoZH 已提交
739 740 741
        min_sizes = []
        max_sizes = []
        step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))
742
        for ratio in range(min_ratio, max_ratio + 1, step):
743 744 745 746
            min_sizes.append(base_size * ratio / 100.0)
            max_sizes.append(base_size * (ratio + step) / 100.0)
        min_sizes = [base_size * 0.10] + min_sizes
        max_sizes = [base_size * 0.20] + max_sizes
C
chengduoZH 已提交
747

C
chengduoZH 已提交
748 749
    if aspect_ratios:
        _is_list_or_tuple_and_equal(
750 751
            aspect_ratios,
            num_layer,
C
chengduoZH 已提交
752
            'aspect_ratios should be list or tuple, and the length of inputs '
753 754
            'and aspect_ratios should be the same.',
        )
Z
zhongpu 已提交
755
    if step_h is not None:
C
chengduoZH 已提交
756
        _is_list_or_tuple_and_equal(
757 758
            step_h,
            num_layer,
C
chengduoZH 已提交
759
            'step_h should be list or tuple, and the length of inputs and '
760 761
            'step_h should be the same.',
        )
Z
zhongpu 已提交
762
    if step_w is not None:
C
chengduoZH 已提交
763
        _is_list_or_tuple_and_equal(
764 765
            step_w,
            num_layer,
C
chengduoZH 已提交
766
            'step_w should be list or tuple, and the length of inputs and '
767 768
            'step_w should be the same.',
        )
Z
zhongpu 已提交
769
    if steps is not None:
C
chengduoZH 已提交
770
        _is_list_or_tuple_and_equal(
771 772
            steps,
            num_layer,
C
chengduoZH 已提交
773
            'steps should be list or tuple, and the length of inputs and '
774 775
            'step_w should be the same.',
        )
C
chengduoZH 已提交
776 777 778
        step_w = steps
        step_h = steps

C
chengduoZH 已提交
779 780
    mbox_locs = []
    mbox_confs = []
C
chengduoZH 已提交
781 782
    box_results = []
    var_results = []
C
chengduoZH 已提交
783 784
    for i, input in enumerate(inputs):
        min_size = min_sizes[i]
C
chengduoZH 已提交
785 786
        max_size = max_sizes[i]

787
        if not _is_list_or_tuple_(min_size):
C
chengduoZH 已提交
788
            min_size = [min_size]
C
chengduoZH 已提交
789 790
        if not _is_list_or_tuple_(max_size):
            max_size = [max_size]
C
chengduoZH 已提交
791 792 793 794

        aspect_ratio = []
        if aspect_ratios is not None:
            aspect_ratio = aspect_ratios[i]
795
            if not _is_list_or_tuple_(aspect_ratio):
C
chengduoZH 已提交
796
                aspect_ratio = [aspect_ratio]
797
        step = [step_w[i] if step_w else 0.0, step_h[i] if step_w else 0.0]
C
chengduoZH 已提交
798

799 800 801 802 803 804 805 806 807 808 809 810 811 812
        box, var = prior_box(
            input,
            image,
            min_size,
            max_size,
            aspect_ratio,
            variance,
            flip,
            clip,
            step,
            offset,
            None,
            min_max_aspect_ratios_order,
        )
C
chengduoZH 已提交
813 814 815 816 817

        box_results.append(box)
        var_results.append(var)

        num_boxes = box.shape[2]
C
chengduoZH 已提交
818

819
        # get loc
Y
Yuan Gao 已提交
820
        num_loc_output = num_boxes * 4
821 822 823 824 825 826 827
        mbox_loc = nn.conv2d(
            input=input,
            num_filters=num_loc_output,
            filter_size=kernel_size,
            padding=pad,
            stride=stride,
        )
828

829
        mbox_loc = paddle.transpose(mbox_loc, perm=[0, 2, 3, 1])
830
        mbox_loc_flatten = paddle.flatten(mbox_loc, 1, -1)
Y
Yuan Gao 已提交
831
        mbox_locs.append(mbox_loc_flatten)
C
chengduoZH 已提交
832

833
        # get conf
C
chengduoZH 已提交
834
        num_conf_output = num_boxes * num_classes
835 836 837 838 839 840 841
        conf_loc = nn.conv2d(
            input=input,
            num_filters=num_conf_output,
            filter_size=kernel_size,
            padding=pad,
            stride=stride,
        )
842

843
        conf_loc = paddle.transpose(conf_loc, perm=[0, 2, 3, 1])
844
        conf_loc_flatten = paddle.flatten(conf_loc, 1, -1)
Y
Yuan Gao 已提交
845
        mbox_confs.append(conf_loc_flatten)
C
chengduoZH 已提交
846

C
chengduoZH 已提交
847 848 849
    if len(box_results) == 1:
        box = box_results[0]
        var = var_results[0]
Y
Yuan Gao 已提交
850 851
        mbox_locs_concat = mbox_locs[0]
        mbox_confs_concat = mbox_confs[0]
C
chengduoZH 已提交
852 853 854 855 856 857 858 859 860
    else:
        reshaped_boxes = []
        reshaped_vars = []
        for i in range(len(box_results)):
            reshaped_boxes.append(_reshape_with_axis_(box_results[i], axis=3))
            reshaped_vars.append(_reshape_with_axis_(var_results[i], axis=3))

        box = tensor.concat(reshaped_boxes)
        var = tensor.concat(reshaped_vars)
Y
Yuan Gao 已提交
861
        mbox_locs_concat = tensor.concat(mbox_locs, axis=1)
862
        mbox_locs_concat = paddle.reshape(mbox_locs_concat, shape=[0, -1, 4])
Y
Yuan Gao 已提交
863
        mbox_confs_concat = tensor.concat(mbox_confs, axis=1)
864
        mbox_confs_concat = paddle.reshape(
865 866
            mbox_confs_concat, shape=[0, -1, num_classes]
        )
C
chengduoZH 已提交
867

868 869
    box.stop_gradient = True
    var.stop_gradient = True
Y
Yuan Gao 已提交
870
    return mbox_locs_concat, mbox_confs_concat, box, var
871 872


873 874 875 876 877 878 879 880 881
def anchor_generator(
    input,
    anchor_sizes=None,
    aspect_ratios=None,
    variance=[0.1, 0.1, 0.2, 0.2],
    stride=None,
    offset=0.5,
    name=None,
):
882
    """
S
swtkiwi 已提交
883

884 885 886 887 888 889 890 891
    **Anchor generator operator**

    Generate anchors for Faster RCNN algorithm.
    Each position of the input produce N anchors, N =
    size(anchor_sizes) * size(aspect_ratios). The order of generated anchors
    is firstly aspect_ratios loop then anchor_sizes loop.

    Args:
W
wangguanzhong 已提交
892 893 894
       input(Variable): 4-D Tensor with shape [N,C,H,W]. The input feature map.
       anchor_sizes(float32|list|tuple, optional): The anchor sizes of generated
          anchors, given in absolute pixels e.g. [64., 128., 256., 512.].
895
          For instance, the anchor size of 64 means the area of this anchor
W
wangguanzhong 已提交
896
          equals to 64**2. None by default.
897
       aspect_ratios(float32|list|tuple, optional): The height / width ratios
W
wangguanzhong 已提交
898
           of generated anchors, e.g. [0.5, 1.0, 2.0]. None by default.
899 900
       variance(list|tuple, optional): The variances to be used in box
           regression deltas. The data type is float32, [0.1, 0.1, 0.2, 0.2] by
W
wangguanzhong 已提交
901 902 903 904
           default.
       stride(list|tuple, optional): The anchors stride across width and height.
           The data type is float32. e.g. [16.0, 16.0]. None by default.
       offset(float32, optional): Prior boxes center offset. 0.5 by default.
905 906 907
       name(str, optional): For detailed information, please refer
           to :ref:`api_guide_Name`. Usually name is no need to set and None
           by default.
908 909

    Returns:
W
wangguanzhong 已提交
910 911 912 913
        Tuple:

        Anchors(Variable): The output anchors with a layout of [H, W, num_anchors, 4].
        H is the height of input, W is the width of input,
914
        num_anchors is the box count of each position.
W
wangguanzhong 已提交
915
        Each anchor is in (xmin, ymin, xmax, ymax) format an unnormalized.
916

W
wangguanzhong 已提交
917 918 919 920 921
        Variances(Variable): The expanded variances of anchors
        with a layout of [H, W, num_priors, 4].
        H is the height of input, W is the width of input
        num_anchors is the box count of each position.
        Each variance is in (xcenter, ycenter, w, h) format.
922 923 924 925 926 927


    Examples:

        .. code-block:: python

928
            import paddle.fluid as fluid
929 930 931
            import paddle

            paddle.enable_static()
932
            conv1 = fluid.data(name='conv1', shape=[None, 48, 16, 16], dtype='float32')
J
jerrywgz 已提交
933
            anchor, var = fluid.layers.anchor_generator(
934 935 936 937 938 939 940 941 942 943 944
                input=conv1,
                anchor_sizes=[64, 128, 256, 512],
                aspect_ratios=[0.5, 1.0, 2.0],
                variance=[0.1, 0.1, 0.2, 0.2],
                stride=[16.0, 16.0],
                offset=0.5)
    """
    helper = LayerHelper("anchor_generator", **locals())
    dtype = helper.input_dtype()

    def _is_list_or_tuple_(data):
945
        return isinstance(data, list) or isinstance(data, tuple)
946 947 948 949 950 951

    if not _is_list_or_tuple_(anchor_sizes):
        anchor_sizes = [anchor_sizes]
    if not _is_list_or_tuple_(aspect_ratios):
        aspect_ratios = [aspect_ratios]
    if not (_is_list_or_tuple_(stride) and len(stride) == 2):
952 953 954 955
        raise ValueError(
            'stride should be a list or tuple ',
            'with length 2, (stride_width, stride_height).',
        )
956 957 958 959 960 961 962 963 964 965

    anchor_sizes = list(map(float, anchor_sizes))
    aspect_ratios = list(map(float, aspect_ratios))
    stride = list(map(float, stride))

    attrs = {
        'anchor_sizes': anchor_sizes,
        'aspect_ratios': aspect_ratios,
        'variances': variance,
        'stride': stride,
966
        'offset': offset,
967 968
    }

X
Xin Pan 已提交
969 970
    anchor = helper.create_variable_for_type_inference(dtype)
    var = helper.create_variable_for_type_inference(dtype)
971 972 973
    helper.append_op(
        type="anchor_generator",
        inputs={"Input": input},
974
        outputs={"Anchors": anchor, "Variances": var},
975 976
        attrs=attrs,
    )
977 978 979
    anchor.stop_gradient = True
    var.stop_gradient = True
    return anchor, var
980 981


982 983 984 985 986 987 988 989
def roi_perspective_transform(
    input,
    rois,
    transformed_height,
    transformed_width,
    spatial_scale=1.0,
    name=None,
):
W
whs 已提交
990
    """
S
SunGaofeng 已提交
991
    **The** `rois` **of this op should be a LoDTensor.**
W
whs 已提交
992

993
    ROI perspective transform op applies perspective transform to map each roi into an
S
SunGaofeng 已提交
994 995 996
    rectangular region. Perspective transform is a type of transformation in linear algebra.

    Parameters:
997
        input (Variable): 4-D Tensor, input of ROIPerspectiveTransformOp. The format of
W
whs 已提交
998 999
                          input tensor is NCHW. Where N is batch size, C is the
                          number of input channels, H is the height of the feature,
S
SunGaofeng 已提交
1000
                          and W is the width of the feature. The data type is float32.
1001 1002 1003 1004 1005
        rois (Variable):  2-D LoDTensor, ROIs (Regions of Interest) to be transformed.
                          It should be a 2-D LoDTensor of shape (num_rois, 8). Given as
                          [[x1, y1, x2, y2, x3, y3, x4, y4], ...], (x1, y1) is the
                          top left coordinates, and (x2, y2) is the top right
                          coordinates, and (x3, y3) is the bottom right coordinates,
S
SunGaofeng 已提交
1006
                          and (x4, y4) is the bottom left coordinates. The data type is the
1007
                          same as `input`
S
SunGaofeng 已提交
1008 1009
        transformed_height (int): The height of transformed output.
        transformed_width (int): The width of transformed output.
W
whs 已提交
1010
        spatial_scale (float): Spatial scale factor to scale ROI coords. Default: 1.0
1011 1012
        name(str, optional): The default value is None.
                             Normally there is no need for user to set this property.
S
SunGaofeng 已提交
1013
                             For more information, please refer to :ref:`api_guide_Name`
W
whs 已提交
1014 1015

    Returns:
S
SunGaofeng 已提交
1016
            A tuple with three Variables. (out, mask, transform_matrix)
1017 1018

            out: The output of ROIPerspectiveTransformOp which is a 4-D tensor with shape
S
SunGaofeng 已提交
1019
            (num_rois, channels, transformed_h, transformed_w). The data type is the same as `input`
1020 1021

            mask: The mask of ROIPerspectiveTransformOp which is a 4-D tensor with shape
S
SunGaofeng 已提交
1022
            (num_rois, 1, transformed_h, transformed_w). The data type is int32
1023 1024

            transform_matrix: The transform matrix of ROIPerspectiveTransformOp which is
S
SunGaofeng 已提交
1025 1026 1027 1028
            a 2-D tensor with shape (num_rois, 9). The data type is the same as `input`

    Return Type:
        tuple
W
whs 已提交
1029 1030 1031 1032

    Examples:
        .. code-block:: python

S
SunGaofeng 已提交
1033
            import paddle.fluid as fluid
1034

S
SunGaofeng 已提交
1035 1036
            x = fluid.data(name='x', shape=[100, 256, 28, 28], dtype='float32')
            rois = fluid.data(name='rois', shape=[None, 8], lod_level=1, dtype='float32')
1037
            out, mask, transform_matrix = fluid.layers.roi_perspective_transform(x, rois, 7, 7, 1.0)
W
whs 已提交
1038
    """
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    check_variable_and_dtype(
        input, 'input', ['float32'], 'roi_perspective_transform'
    )
    check_variable_and_dtype(
        rois, 'rois', ['float32'], 'roi_perspective_transform'
    )
    check_type(
        transformed_height,
        'transformed_height',
        int,
        'roi_perspective_transform',
    )
    check_type(
        transformed_width, 'transformed_width', int, 'roi_perspective_transform'
    )
    check_type(
        spatial_scale, 'spatial_scale', float, 'roi_perspective_transform'
    )
1057

W
whs 已提交
1058 1059
    helper = LayerHelper('roi_perspective_transform', **locals())
    dtype = helper.input_dtype()
X
Xin Pan 已提交
1060
    out = helper.create_variable_for_type_inference(dtype)
1061 1062
    mask = helper.create_variable_for_type_inference(dtype="int32")
    transform_matrix = helper.create_variable_for_type_inference(dtype)
1063 1064
    out2in_idx = helper.create_variable_for_type_inference(dtype="int32")
    out2in_w = helper.create_variable_for_type_inference(dtype)
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    helper.append_op(
        type="roi_perspective_transform",
        inputs={"X": input, "ROIs": rois},
        outputs={
            "Out": out,
            "Out2InIdx": out2in_idx,
            "Out2InWeights": out2in_w,
            "Mask": mask,
            "TransformMatrix": transform_matrix,
        },
        attrs={
            "transformed_height": transformed_height,
            "transformed_width": transformed_width,
            "spatial_scale": spatial_scale,
        },
    )
1081
    return out, mask, transform_matrix
W
whs 已提交
1082 1083


1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
def generate_proposal_labels(
    rpn_rois,
    gt_classes,
    is_crowd,
    gt_boxes,
    im_info,
    batch_size_per_im=256,
    fg_fraction=0.25,
    fg_thresh=0.25,
    bg_thresh_hi=0.5,
    bg_thresh_lo=0.0,
    bbox_reg_weights=[0.1, 0.1, 0.2, 0.2],
    class_nums=None,
    use_random=True,
    is_cls_agnostic=False,
    is_cascade_rcnn=False,
    max_overlap=None,
    return_max_overlap=False,
):
1103
    """
S
swtkiwi 已提交
1104

1105
    **Generate Proposal Labels of Faster-RCNN**
1106

B
buxingyuan 已提交
1107
    This operator can be, for given the GenerateProposalOp output bounding boxes and groundtruth,
B
buxingyuan 已提交
1108
    to sample foreground boxes and background boxes, and compute loss target.
B
buxingyuan 已提交
1109 1110 1111

    RpnRois is the output boxes of RPN and was processed by generate_proposal_op, these boxes
    were combined with groundtruth boxes and sampled according to batch_size_per_im and fg_fraction,
B
buxingyuan 已提交
1112
    If an instance with a groundtruth overlap greater than fg_thresh, then it was considered as a foreground sample.
B
buxingyuan 已提交
1113 1114
    If an instance with a groundtruth overlap greater than bg_thresh_lo and lower than bg_thresh_hi,
    then it was considered as a background sample.
B
buxingyuan 已提交
1115
    After all foreground and background boxes are chosen (so called Rois),
B
buxingyuan 已提交
1116
    then we apply random sampling to make sure
B
buxingyuan 已提交
1117
    the number of foreground boxes is no more than batch_size_per_im * fg_fraction.
B
buxingyuan 已提交
1118 1119 1120 1121 1122

    For each box in Rois, we assign the classification (class label) and regression targets (box label) to it.
    Finally BboxInsideWeights and BboxOutsideWeights are used to specify whether it would contribute to training loss.

    Args:
1123 1124 1125
        rpn_rois(Variable): A 2-D LoDTensor with shape [N, 4]. N is the number of the GenerateProposalOp's output, each element is a bounding box with [xmin, ymin, xmax, ymax] format. The data type can be float32 or float64.
        gt_classes(Variable): A 2-D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a class label of groundtruth. The data type must be int32.
        is_crowd(Variable): A 2-D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a flag indicates whether a groundtruth is crowd. The data type must be int32.
B
buxingyuan 已提交
1126 1127 1128
        gt_boxes(Variable): A 2-D LoDTensor with shape [M, 4]. M is the number of groundtruth, each element is a bounding box with [xmin, ymin, xmax, ymax] format.
        im_info(Variable): A 2-D LoDTensor with shape [B, 3]. B is the number of input images, each element consists of im_height, im_width, im_scale.

1129 1130 1131 1132 1133 1134 1135
        batch_size_per_im(int): Batch size of rois per images. The data type must be int32.
        fg_fraction(float): Foreground fraction in total batch_size_per_im. The data type must be float32.
        fg_thresh(float): Overlap threshold which is used to chose foreground sample. The data type must be float32.
        bg_thresh_hi(float): Overlap threshold upper bound which is used to chose background sample. The data type must be float32.
        bg_thresh_lo(float): Overlap threshold lower bound which is used to chose background sample. The data type must be float32.
        bbox_reg_weights(list|tuple): Box regression weights. The data type must be float32.
        class_nums(int): Class number. The data type must be int32.
B
buxingyuan 已提交
1136
        use_random(bool): Use random sampling to choose foreground and background boxes.
1137 1138
        is_cls_agnostic(bool): bbox regression use class agnostic simply which only represent fg and bg boxes.
        is_cascade_rcnn(bool): it will filter some bbox crossing the image's boundary when setting True.
1139 1140
        max_overlap(Variable): Maximum overlap between each proposal box and ground-truth.
        return_max_overlap(bool): Whether return the maximum overlap between each sampled RoI and ground-truth.
B
Bai Yifan 已提交
1141

1142 1143
    Returns:
        tuple:
1144
        A tuple with format``(rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights, max_overlap)``.
1145 1146 1147 1148 1149 1150

        - **rois**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4]``. The data type is the same as ``rpn_rois``.
        - **labels_int32**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 1]``. The data type must be int32.
        - **bbox_targets**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The regression targets of all RoIs. The data type is the same as ``rpn_rois``.
        - **bbox_inside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of foreground boxes' regression loss. The data type is the same as ``rpn_rois``.
        - **bbox_outside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of regression loss. The data type is the same as ``rpn_rois``.
1151
        - **max_overlap**: 1-D LoDTensor with shape ``[P]``. P is the number of output ``rois``. The maximum overlap between each sampled RoI and ground-truth.
1152

B
Bai Yifan 已提交
1153 1154 1155
    Examples:
        .. code-block:: python

1156
            import paddle
B
Bai Yifan 已提交
1157
            import paddle.fluid as fluid
1158
            paddle.enable_static()
1159
            rpn_rois = fluid.data(name='rpn_rois', shape=[None, 4], dtype='float32')
1160 1161
            gt_classes = fluid.data(name='gt_classes', shape=[None, 1], dtype='int32')
            is_crowd = fluid.data(name='is_crowd', shape=[None, 1], dtype='int32')
1162 1163
            gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32')
            im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')
1164
            rois, labels, bbox, inside_weights, outside_weights = fluid.layers.generate_proposal_labels(
B
Bai Yifan 已提交
1165 1166 1167
                           rpn_rois, gt_classes, is_crowd, gt_boxes, im_info,
                           class_nums=10)

1168 1169 1170 1171
    """

    helper = LayerHelper('generate_proposal_labels', **locals())

1172 1173 1174 1175 1176 1177 1178 1179 1180
    check_variable_and_dtype(
        rpn_rois, 'rpn_rois', ['float32', 'float64'], 'generate_proposal_labels'
    )
    check_variable_and_dtype(
        gt_classes, 'gt_classes', ['int32'], 'generate_proposal_labels'
    )
    check_variable_and_dtype(
        is_crowd, 'is_crowd', ['int32'], 'generate_proposal_labels'
    )
1181
    if is_cascade_rcnn:
1182 1183 1184
        assert (
            max_overlap is not None
        ), "Input max_overlap of generate_proposal_labels should not be None if is_cascade_rcnn is True"
1185

X
Xin Pan 已提交
1186 1187
    rois = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
    labels_int32 = helper.create_variable_for_type_inference(
1188 1189
        dtype=gt_classes.dtype
    )
X
Xin Pan 已提交
1190
    bbox_targets = helper.create_variable_for_type_inference(
1191 1192
        dtype=rpn_rois.dtype
    )
X
Xin Pan 已提交
1193
    bbox_inside_weights = helper.create_variable_for_type_inference(
1194 1195
        dtype=rpn_rois.dtype
    )
X
Xin Pan 已提交
1196
    bbox_outside_weights = helper.create_variable_for_type_inference(
1197 1198
        dtype=rpn_rois.dtype
    )
1199
    max_overlap_with_gt = helper.create_variable_for_type_inference(
1200 1201
        dtype=rpn_rois.dtype
    )
1202

1203 1204 1205 1206 1207 1208 1209 1210 1211
    inputs = {
        'RpnRois': rpn_rois,
        'GtClasses': gt_classes,
        'IsCrowd': is_crowd,
        'GtBoxes': gt_boxes,
        'ImInfo': im_info,
    }
    if max_overlap is not None:
        inputs['MaxOverlap'] = max_overlap
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
    helper.append_op(
        type="generate_proposal_labels",
        inputs=inputs,
        outputs={
            'Rois': rois,
            'LabelsInt32': labels_int32,
            'BboxTargets': bbox_targets,
            'BboxInsideWeights': bbox_inside_weights,
            'BboxOutsideWeights': bbox_outside_weights,
            'MaxOverlapWithGT': max_overlap_with_gt,
        },
        attrs={
            'batch_size_per_im': batch_size_per_im,
            'fg_fraction': fg_fraction,
            'fg_thresh': fg_thresh,
            'bg_thresh_hi': bg_thresh_hi,
            'bg_thresh_lo': bg_thresh_lo,
            'bbox_reg_weights': bbox_reg_weights,
            'class_nums': class_nums,
            'use_random': use_random,
            'is_cls_agnostic': is_cls_agnostic,
            'is_cascade_rcnn': is_cascade_rcnn,
        },
    )
1236 1237 1238 1239 1240 1241

    rois.stop_gradient = True
    labels_int32.stop_gradient = True
    bbox_targets.stop_gradient = True
    bbox_inside_weights.stop_gradient = True
    bbox_outside_weights.stop_gradient = True
1242
    max_overlap_with_gt.stop_gradient = True
1243

1244
    if return_max_overlap:
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        return (
            rois,
            labels_int32,
            bbox_targets,
            bbox_inside_weights,
            bbox_outside_weights,
            max_overlap_with_gt,
        )
    return (
        rois,
        labels_int32,
        bbox_targets,
        bbox_inside_weights,
        bbox_outside_weights,
    )
1260 1261


1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
def generate_mask_labels(
    im_info,
    gt_classes,
    is_crowd,
    gt_segms,
    rois,
    labels_int32,
    num_classes,
    resolution,
):
1272
    r"""
S
swtkiwi 已提交
1273

Q
qingqing01 已提交
1274
    **Generate Mask Labels for Mask-RCNN**
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302

    This operator can be, for given the RoIs and corresponding labels,
    to sample foreground RoIs. This mask branch also has
    a :math: `K \\times M^{2}` dimensional output targets for each foreground
    RoI, which encodes K binary masks of resolution M x M, one for each of the
    K classes. This mask targets are used to compute loss of mask branch.

    Please note, the data format of groud-truth segmentation, assumed the
    segmentations are as follows. The first instance has two gt objects.
    The second instance has one gt object, this object has two gt segmentations.

        .. code-block:: python

            #[
            #  [[[229.14, 370.9, 229.14, 370.9, ...]],
            #   [[343.7, 139.85, 349.01, 138.46, ...]]], # 0-th instance
            #  [[[500.0, 390.62, ...],[115.48, 187.86, ...]]] # 1-th instance
            #]

            batch_masks = []
            for semgs in batch_semgs:
                gt_masks = []
                for semg in semgs:
                    gt_segm = []
                    for polys in semg:
                        gt_segm.append(np.array(polys).reshape(-1, 2))
                    gt_masks.append(gt_segm)
                batch_masks.append(gt_masks)
1303 1304


1305 1306 1307 1308 1309
            place = fluid.CPUPlace()
            feeder = fluid.DataFeeder(place=place, feed_list=feeds)
            feeder.feed(batch_masks)

    Args:
Q
qingqing01 已提交
1310 1311 1312 1313 1314 1315
        im_info (Variable): A 2-D Tensor with shape [N, 3] and float32
            data type. N is the batch size, each element is
            [height, width, scale] of image. Image scale is
            target_size / original_size, target_size is the size after resize,
            original_size is the original image size.
        gt_classes (Variable): A 2-D LoDTensor with shape [M, 1]. Data type
T
tianshuo78520a 已提交
1316
            should be int. M is the total number of ground-truth, each
Q
qingqing01 已提交
1317 1318 1319 1320 1321 1322 1323
            element is a class label.
        is_crowd (Variable): A 2-D LoDTensor with same shape and same data type
            as gt_classes, each element is a flag indicating whether a
            groundtruth is crowd.
        gt_segms (Variable): This input is a 2D LoDTensor with shape [S, 2] and
            float32 data type, it's LoD level is 3.
            Usually users do not needs to understand LoD,
1324
            The users should return correct data format in reader.
Q
qingqing01 已提交
1325
            The LoD[0] represents the ground-truth objects number of
1326 1327 1328 1329
            each instance. LoD[1] represents the segmentation counts of each
            objects. LoD[2] represents the polygons number of each segmentation.
            S the total number of polygons coordinate points. Each element is
            (x, y) coordinate points.
Q
qingqing01 已提交
1330 1331 1332 1333
        rois (Variable): A 2-D LoDTensor with shape [R, 4] and float32 data type
            float32. R is the total number of RoIs, each element is a bounding
            box with (xmin, ymin, xmax, ymax) format in the range of original image.
        labels_int32 (Variable): A 2-D LoDTensor in shape of [R, 1] with type
T
tianshuo78520a 已提交
1334
            of int32. R is the same as it in `rois`. Each element represents
1335
            a class label of a RoI.
Q
qingqing01 已提交
1336 1337
        num_classes (int): Class number.
        resolution (int): Resolution of mask predictions.
1338 1339

    Returns:
Q
qingqing01 已提交
1340 1341 1342
        mask_rois (Variable):  A 2D LoDTensor with shape [P, 4] and same data
        type as `rois`. P is the total number of sampled RoIs. Each element
        is a bounding box with [xmin, ymin, xmax, ymax] format in range of
T
tianshuo78520a 已提交
1343
        original image size.
Q
qingqing01 已提交
1344 1345

        mask_rois_has_mask_int32 (Variable): A 2D LoDTensor with shape [P, 1]
T
tianshuo78520a 已提交
1346
        and int data type, each element represents the output mask RoI
Q
qingqing01 已提交
1347 1348 1349 1350
        index with regard to input RoIs.

        mask_int32 (Variable): A 2D LoDTensor with shape [P, K * M * M] and int
        data type, K is the classes number and M is the resolution of mask
T
tianshuo78520a 已提交
1351
        predictions. Each element represents the binary mask targets.
1352 1353 1354 1355

    Examples:
        .. code-block:: python

1356 1357
          import paddle.fluid as fluid

Q
qingqing01 已提交
1358
          im_info = fluid.data(name="im_info", shape=[None, 3],
1359
              dtype="float32")
Q
qingqing01 已提交
1360
          gt_classes = fluid.data(name="gt_classes", shape=[None, 1],
1361
              dtype="float32", lod_level=1)
Q
qingqing01 已提交
1362
          is_crowd = fluid.data(name="is_crowd", shape=[None, 1],
1363
              dtype="float32", lod_level=1)
Q
qingqing01 已提交
1364
          gt_masks = fluid.data(name="gt_masks", shape=[None, 2],
1365
              dtype="float32", lod_level=3)
1366
          # rois, roi_labels can be the output of
1367
          # fluid.layers.generate_proposal_labels.
Q
qingqing01 已提交
1368
          rois = fluid.data(name="rois", shape=[None, 4],
1369
              dtype="float32", lod_level=1)
Q
qingqing01 已提交
1370
          roi_labels = fluid.data(name="roi_labels", shape=[None, 1],
1371
              dtype="int32", lod_level=1)
1372 1373 1374 1375 1376 1377
          mask_rois, mask_index, mask_int32 = fluid.layers.generate_mask_labels(
              im_info=im_info,
              gt_classes=gt_classes,
              is_crowd=is_crowd,
              gt_segms=gt_masks,
              rois=rois,
1378
              labels_int32=roi_labels,
1379 1380 1381 1382 1383 1384 1385 1386
              num_classes=81,
              resolution=14)
    """

    helper = LayerHelper('generate_mask_labels', **locals())

    mask_rois = helper.create_variable_for_type_inference(dtype=rois.dtype)
    roi_has_mask_int32 = helper.create_variable_for_type_inference(
1387 1388
        dtype=gt_classes.dtype
    )
1389
    mask_int32 = helper.create_variable_for_type_inference(
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
        dtype=gt_classes.dtype
    )

    helper.append_op(
        type="generate_mask_labels",
        inputs={
            'ImInfo': im_info,
            'GtClasses': gt_classes,
            'IsCrowd': is_crowd,
            'GtSegms': gt_segms,
            'Rois': rois,
            'LabelsInt32': labels_int32,
        },
        outputs={
            'MaskRois': mask_rois,
            'RoiHasMaskInt32': roi_has_mask_int32,
            'MaskInt32': mask_int32,
        },
        attrs={'num_classes': num_classes, 'resolution': resolution},
    )
1410 1411 1412 1413 1414 1415 1416 1417

    mask_rois.stop_gradient = True
    roi_has_mask_int32.stop_gradient = True
    mask_int32.stop_gradient = True

    return mask_rois, roi_has_mask_int32, mask_int32


1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
def generate_proposals(
    scores,
    bbox_deltas,
    im_info,
    anchors,
    variances,
    pre_nms_top_n=6000,
    post_nms_top_n=1000,
    nms_thresh=0.5,
    min_size=0.1,
    eta=1.0,
    return_rois_num=False,
    name=None,
):
1432
    """
S
swtkiwi 已提交
1433

H
haowang101779990 已提交
1434 1435
    **Generate proposal Faster-RCNN**

1436
    This operation proposes RoIs according to each box with their
1437
    probability to be a foreground object and
1438 1439
    the box can be calculated by anchors. Bbox_deltais and scores
    to be an object are the output of RPN. Final proposals
H
haowang101779990 已提交
1440 1441 1442 1443
    could be used to train detection net.

    For generating proposals, this operation performs following steps:

1444 1445
    1. Transposes and resizes scores and bbox_deltas in size of
       (H*W*A, 1) and (H*W*A, 4)
1446
    2. Calculate box locations as proposals candidates.
H
haowang101779990 已提交
1447
    3. Clip boxes to image
1448
    4. Remove predicted boxes with small area.
H
haowang101779990 已提交
1449 1450 1451
    5. Apply NMS to get final proposals as output.

    Args:
1452 1453 1454
        scores(Variable): A 4-D Tensor with shape [N, A, H, W] represents
            the probability for each box to be an object.
            N is batch size, A is number of anchors, H and W are height and
1455
            width of the feature map. The data type must be float32.
1456
        bbox_deltas(Variable): A 4-D Tensor with shape [N, 4*A, H, W]
T
tianshuo78520a 已提交
1457
            represents the difference between predicted box location and
1458
            anchor location. The data type must be float32.
1459
        im_info(Variable): A 2-D Tensor with shape [N, 3] represents origin
1460 1461
            image information for N batch. Height and width are the input sizes
            and scale is the ratio of network input size and original size.
1462
            The data type can be float32 or float64.
1463 1464 1465
        anchors(Variable):   A 4-D Tensor represents the anchors with a layout
            of [H, W, A, 4]. H and W are height and width of the feature map,
            num_anchors is the box count of each position. Each anchor is
1466 1467
            in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32.
        variances(Variable): A 4-D Tensor. The expanded variances of anchors with a layout of
1468
            [H, W, num_priors, 4]. Each variance is in
1469
            (xcenter, ycenter, w, h) format. The data type must be float32.
1470
        pre_nms_top_n(float): Number of total bboxes to be kept per
1471
            image before NMS. The data type must be float32. `6000` by default.
1472
        post_nms_top_n(float): Number of total bboxes to be kept per
1473 1474
            image after NMS. The data type must be float32. `1000` by default.
        nms_thresh(float): Threshold in NMS. The data type must be float32. `0.5` by default.
1475
        min_size(float): Remove predicted boxes with either height or
1476 1477 1478
            width < min_size. The data type must be float32. `0.1` by default.
        eta(float): Apply in adaptive NMS, if adaptive `threshold > 0.5`,
            `adaptive_threshold = adaptive_threshold * eta` in each iteration.
1479
        return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's
F
FDInSky 已提交
1480
            num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents
1481 1482 1483 1484 1485
            the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model.
            'False' by default.
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
            None by default.
1486

1487 1488 1489 1490 1491 1492
    Returns:
        tuple:
        A tuple with format ``(rpn_rois, rpn_roi_probs)``.

        - **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
        - **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
B
Bai Yifan 已提交
1493 1494 1495

    Examples:
        .. code-block:: python
1496

B
Bai Yifan 已提交
1497
            import paddle.fluid as fluid
1498 1499
            import paddle
            paddle.enable_static()
1500 1501 1502 1503 1504
            scores = fluid.data(name='scores', shape=[None, 4, 5, 5], dtype='float32')
            bbox_deltas = fluid.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32')
            im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')
            anchors = fluid.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32')
            variances = fluid.data(name='variances', shape=[None, 5, 10, 4], dtype='float32')
B
Bai Yifan 已提交
1505 1506 1507
            rois, roi_probs = fluid.layers.generate_proposals(scores, bbox_deltas,
                         im_info, anchors, variances)

1508
    """
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    return paddle.vision.ops.generate_proposals(
        scores=scores,
        bbox_deltas=bbox_deltas,
        img_size=im_info[:2],
        anchors=anchors,
        variances=variances,
        pre_nms_top_n=pre_nms_top_n,
        post_nms_top_n=post_nms_top_n,
        nms_thresh=nms_thresh,
        min_size=min_size,
        eta=eta,
        return_rois_num=return_rois_num,
        name=name,
    )
J
jerrywgz 已提交
1523 1524


J
jerrywgz 已提交
1525
def box_clip(input, im_info, name=None):
J
jerrywgz 已提交
1526
    """
1527

J
jerrywgz 已提交
1528
    Clip the box into the size given by im_info
J
jerrywgz 已提交
1529
    For each input box, The formula is given as follows:
1530

1531 1532
    .. code-block:: text

J
jerrywgz 已提交
1533
        xmin = max(min(xmin, im_w - 1), 0)
1534
        ymin = max(min(ymin, im_h - 1), 0)
J
jerrywgz 已提交
1535 1536
        xmax = max(min(xmax, im_w - 1), 0)
        ymax = max(min(ymax, im_h - 1), 0)
1537

J
jerrywgz 已提交
1538
    where im_w and im_h are computed from im_info:
1539

J
jerrywgz 已提交
1540 1541 1542 1543
    .. code-block:: text

        im_h = round(height / scale)
        im_w = round(weight / scale)
J
jerrywgz 已提交
1544 1545

    Args:
W
wangguanzhong 已提交
1546 1547
        input(Variable): The input Tensor with shape :math:`[N_1, N_2, ..., N_k, 4]`,
            the last dimension is 4 and data type is float32 or float64.
1548 1549
        im_info(Variable): The 2-D Tensor with shape [N, 3] with layout
            (height, width, scale) representing the information of image.
1550
            Height and width are the input sizes and scale is the ratio of network input
W
wangguanzhong 已提交
1551
            size and original size. The data type is float32 or float64.
1552 1553 1554 1555
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
            None by default.

J
jerrywgz 已提交
1556
    Returns:
W
wangguanzhong 已提交
1557 1558
        Variable:

1559
        output(Variable): The clipped tensor with data type float32 or float64.
W
wangguanzhong 已提交
1560 1561
        The shape is same as input.

1562

J
jerrywgz 已提交
1563 1564
    Examples:
        .. code-block:: python
1565

1566
            import paddle.fluid as fluid
1567 1568
            import paddle
            paddle.enable_static()
1569 1570 1571
            boxes = fluid.data(
                name='boxes', shape=[None, 8, 4], dtype='float32', lod_level=1)
            im_info = fluid.data(name='im_info', shape=[-1 ,3])
J
jerrywgz 已提交
1572
            out = fluid.layers.box_clip(
J
jerrywgz 已提交
1573
                input=boxes, im_info=im_info)
J
jerrywgz 已提交
1574 1575
    """

1576
    check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'box_clip')
1577 1578 1579
    check_variable_and_dtype(
        im_info, 'im_info', ['float32', 'float64'], 'box_clip'
    )
1580

J
jerrywgz 已提交
1581
    helper = LayerHelper("box_clip", **locals())
J
jerrywgz 已提交
1582
    output = helper.create_variable_for_type_inference(dtype=input.dtype)
1583
    inputs = {"Input": input, "ImInfo": im_info}
J
jerrywgz 已提交
1584
    helper.append_op(type="box_clip", inputs=inputs, outputs={"Output": output})
J
jerrywgz 已提交
1585

1586 1587
    return output

J
jerrywgz 已提交
1588

1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
def retinanet_detection_output(
    bboxes,
    scores,
    anchors,
    im_info,
    score_threshold=0.05,
    nms_top_k=1000,
    keep_top_k=100,
    nms_threshold=0.3,
    nms_eta=1.0,
):
1600
    """
1601
    **Detection Output Layer for the detector RetinaNet.**
1602

1603
    In the detector `RetinaNet <https://arxiv.org/abs/1708.02002>`_ , many
1604 1605 1606
    `FPN <https://arxiv.org/abs/1612.03144>`_ levels output the category
    and location predictions, this OP is to get the detection results by
    performing following steps:
1607

1608 1609 1610
    1. For each FPN level, decode box predictions according to the anchor
       boxes from at most :attr:`nms_top_k` top-scoring predictions after
       thresholding detector confidence at :attr:`score_threshold`.
1611
    2. Merge top predictions from all levels and apply multi-class non
1612 1613 1614
       maximum suppression (NMS) on them to get the final detections.

    Args:
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
        bboxes(List): A list of Tensors from multiple FPN levels represents
            the location prediction for all anchor boxes. Each element is
            a 3-D Tensor with shape :math:`[N, Mi, 4]`, :math:`N` is the
            batch size, :math:`Mi` is the number of bounding boxes from
            :math:`i`-th FPN level and each bounding box has four coordinate
            values and the layout is [xmin, ymin, xmax, ymax]. The data type
            of each element is float32 or float64.
        scores(List): A list of Tensors from multiple FPN levels represents
            the category prediction for all anchor boxes. Each element is a
            3-D Tensor with shape :math:`[N, Mi, C]`,  :math:`N` is the batch
            size, :math:`C` is the class number (**excluding background**),
            :math:`Mi` is the number of bounding boxes from :math:`i`-th FPN
            level. The data type of each element is float32 or float64.
        anchors(List): A list of Tensors from multiple FPN levels represents
            the locations of all anchor boxes. Each element is a 2-D Tensor
            with shape :math:`[Mi, 4]`, :math:`Mi` is the number of bounding
            boxes from :math:`i`-th FPN level, and each bounding box has four
1632
            coordinate values and the layout is [xmin, ymin, xmax, ymax].
1633 1634 1635
            The data type of each element is float32 or float64.
        im_info(Variable): A 2-D Tensor with shape :math:`[N, 3]` represents the size
            information of input images. :math:`N` is the batch size, the size
T
tianshuo78520a 已提交
1636
            information of each image is a 3-vector which are the height and width
1637 1638
            of the network input along with the factor scaling the origin image to
            the network input. The data type of :attr:`im_info` is float32.
1639
        score_threshold(float): Threshold to filter out bounding boxes
1640
            with a confidence score before NMS, default value is set to 0.05.
1641
        nms_top_k(int): Maximum number of detections per FPN layer to be
1642 1643
            kept according to the confidences before NMS, default value is set to
            1000.
1644
        keep_top_k(int): Number of total bounding boxes to be kept per image after
1645 1646
            NMS step. Default value is set to 100, -1 means keeping all bounding
            boxes after NMS step.
1647
        nms_threshold(float): The Intersection-over-Union(IoU) threshold used to
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
            filter out boxes in NMS.
        nms_eta(float): The parameter for adjusting :attr:`nms_threshold` in NMS.
            Default value is set to 1., which represents the value of
            :attr:`nms_threshold` keep the same in NMS. If :attr:`nms_eta` is set
            to be lower than 1. and the value of :attr:`nms_threshold` is set to
            be higher than 0.5, everytime a bounding box is filtered out,
            the adjustment for :attr:`nms_threshold` like :attr:`nms_threshold`
            = :attr:`nms_threshold` * :attr:`nms_eta`  will not be stopped until
            the actual value of :attr:`nms_threshold` is lower than or equal to
            0.5.

    **Notice**: In some cases where the image sizes are very small, it's possible
    that there is no detection if :attr:`score_threshold` are used at all
    levels. Hence, this OP do not filter out anchors from the highest FPN level
    before NMS. And the last element in :attr:`bboxes`:, :attr:`scores` and
T
tianshuo78520a 已提交
1663
    :attr:`anchors` is required to be from the highest FPN level.
1664 1665

    Returns:
1666 1667
        Variable(The data type is float32 or float64):
            The detection output is a 1-level LoDTensor with shape :math:`[No, 6]`.
1668
            Each row has six values: [label, confidence, xmin, ymin, xmax, ymax].
1669 1670 1671
            :math:`No` is the total number of detections in this mini-batch.
            The :math:`i`-th image has `LoD[i + 1] - LoD[i]` detected
            results, if `LoD[i + 1] - LoD[i]` is 0, the :math:`i`-th image
1672 1673 1674 1675 1676 1677
            has no detected results. If all images have no detected results,
            LoD will be set to 0, and the output tensor is empty (None).

    Examples:
        .. code-block:: python

1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
           import paddle.fluid as fluid

           bboxes_low = fluid.data(
               name='bboxes_low', shape=[1, 44, 4], dtype='float32')
           bboxes_high = fluid.data(
               name='bboxes_high', shape=[1, 11, 4], dtype='float32')
           scores_low = fluid.data(
               name='scores_low', shape=[1, 44, 10], dtype='float32')
           scores_high = fluid.data(
               name='scores_high', shape=[1, 11, 10], dtype='float32')
           anchors_low = fluid.data(
               name='anchors_low', shape=[44, 4], dtype='float32')
           anchors_high = fluid.data(
               name='anchors_high', shape=[11, 4], dtype='float32')
           im_info = fluid.data(
               name="im_info", shape=[1, 3], dtype='float32')
           nmsed_outs = fluid.layers.retinanet_detection_output(
1695 1696 1697 1698 1699 1700 1701 1702 1703
               bboxes=[bboxes_low, bboxes_high],
               scores=[scores_low, scores_high],
               anchors=[anchors_low, anchors_high],
               im_info=im_info,
               score_threshold=0.05,
               nms_top_k=1000,
               keep_top_k=100,
               nms_threshold=0.45,
               nms_eta=1.0)
1704 1705
    """

1706 1707
    check_type(bboxes, 'bboxes', (list), 'retinanet_detection_output')
    for i, bbox in enumerate(bboxes):
1708 1709 1710 1711 1712 1713
        check_variable_and_dtype(
            bbox,
            'bbox{}'.format(i),
            ['float32', 'float64'],
            'retinanet_detection_output',
        )
1714 1715
    check_type(scores, 'scores', (list), 'retinanet_detection_output')
    for i, score in enumerate(scores):
1716 1717 1718 1719 1720 1721
        check_variable_and_dtype(
            score,
            'score{}'.format(i),
            ['float32', 'float64'],
            'retinanet_detection_output',
        )
1722 1723
    check_type(anchors, 'anchors', (list), 'retinanet_detection_output')
    for i, anchor in enumerate(anchors):
1724 1725 1726 1727 1728 1729 1730 1731 1732
        check_variable_and_dtype(
            anchor,
            'anchor{}'.format(i),
            ['float32', 'float64'],
            'retinanet_detection_output',
        )
    check_variable_and_dtype(
        im_info, 'im_info', ['float32', 'float64'], 'retinanet_detection_output'
    )
1733

1734 1735
    helper = LayerHelper('retinanet_detection_output', **locals())
    output = helper.create_variable_for_type_inference(
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
        dtype=helper.input_dtype('scores')
    )
    helper.append_op(
        type="retinanet_detection_output",
        inputs={
            'BBoxes': bboxes,
            'Scores': scores,
            'Anchors': anchors,
            'ImInfo': im_info,
        },
        attrs={
            'score_threshold': score_threshold,
            'nms_top_k': nms_top_k,
            'nms_threshold': nms_threshold,
            'keep_top_k': keep_top_k,
            'nms_eta': 1.0,
        },
        outputs={'Out': output},
    )
1755 1756 1757 1758
    output.stop_gradient = True
    return output


1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
def multiclass_nms(
    bboxes,
    scores,
    score_threshold,
    nms_top_k,
    keep_top_k,
    nms_threshold=0.3,
    normalized=True,
    nms_eta=1.0,
    background_label=0,
    name=None,
):
J
jerrywgz 已提交
1771
    """
S
swtkiwi 已提交
1772

1773
    **Multiclass NMS**
1774

1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    This operator is to do multi-class non maximum suppression (NMS) on
    boxes and scores.

    In the NMS step, this operator greedily selects a subset of detection bounding
    boxes that have high scores larger than score_threshold, if providing this
    threshold, then selects the largest nms_top_k confidences scores if nms_top_k
    is larger than -1. Then this operator pruns away boxes that have high IOU
    (intersection over union) overlap with already selected boxes by adaptive
    threshold NMS based on parameters of nms_threshold and nms_eta.
    Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
    per image if keep_top_k is larger than -1.

1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
    See below for an example:

    .. code-block:: text

        if:
            box1.data = (2.0, 3.0, 7.0, 5.0) format is (xmin, ymin, xmax, ymax)
            box1.scores = (0.7, 0.2, 0.4)  which is (label0.score=0.7, label1.score=0.2, label2.cores=0.4)

            box2.data = (3.0, 4.0, 8.0, 5.0)
            box2.score = (0.3, 0.3, 0.1)

            nms_threshold = 0.3
            background_label = 0
            score_threshold = 0
1801

1802 1803 1804

        Then:
            iou = 4/11 > 0.3
1805
            out.data = [[1, 0.3, 3.0, 4.0, 8.0, 5.0],
1806
                         [2, 0.4, 2.0, 3.0, 7.0, 5.0]]
1807

1808
            Out format is (label, confidence, xmin, ymin, xmax, ymax)
1809 1810 1811 1812 1813 1814
    Args:
        bboxes (Variable): Two types of bboxes are supported:
                           1. (Tensor) A 3-D Tensor with shape
                           [N, M, 4 or 8 16 24 32] represents the
                           predicted locations of M bounding bboxes,
                           N is the batch size. Each bounding box has four
1815
                           coordinate values and the layout is
1816
                           [xmin, ymin, xmax, ymax], when box size equals to 4.
X
xiaoting 已提交
1817
                           The data type is float32 or float64.
1818
                           2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]
1819 1820
                           M is the number of bounding boxes, C is the
                           class number. The data type is float32 or float64.
1821 1822 1823
        scores (Variable): Two types of scores are supported:
                           1. (Tensor) A 3-D Tensor with shape [N, C, M]
                           represents the predicted confidence predictions.
1824 1825
                           N is the batch size, C is the class number, M is
                           number of bounding boxes. For each category there
1826 1827
                           are total M scores which corresponding M bounding
                           boxes. Please note, M is equal to the 2nd dimension
1828
                           of BBoxes.The data type is float32 or float64.
1829 1830 1831
                           2. (LoDTensor) A 2-D LoDTensor with shape [M, C].
                           M is the number of bbox, C is the class number.
                           In this case, input BBoxes should be the second
1832 1833
                           case with shape [M, C, 4].The data type is float32 or float64.
        background_label (int): The index of background label, the background
1834 1835 1836
                                label will be ignored. If set to -1, then all
                                categories will be considered. Default: 0
        score_threshold (float): Threshold to filter out bounding boxes with
1837
                                 low confidence score. If not provided,
1838 1839
                                 consider all boxes.
        nms_top_k (int): Maximum number of detections to be kept according to
T
tianshuo78520a 已提交
1840
                         the confidences after the filtering detections based
1841 1842 1843 1844 1845 1846 1847 1848 1849
                         on score_threshold.
        nms_threshold (float): The threshold to be used in NMS. Default: 0.3
        nms_eta (float): The threshold to be used in NMS. Default: 1.0
        keep_top_k (int): Number of total bboxes to be kept per image after NMS
                          step. -1 means keeping all bboxes after NMS step.
        normalized (bool): Whether detections are normalized. Default: True
        name(str): Name of the multiclass nms op. Default: None.

    Returns:
X
xiaoting 已提交
1850
        Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.
1851 1852
             Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
             or A 2-D LoDTensor with shape [No, 10] represents the detections.
1853 1854
             Each row has 10 values:
             [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the
1855
             total number of detections. If there is no detected boxes for all
J
jerrywgz 已提交
1856 1857
             images, lod will be set to {1} and Out only contains one value
             which is -1.
1858 1859
             (After version 1.3, when no boxes detected, the lod is changed
             from {0} to {1})
1860

1861

1862 1863 1864
    Examples:
        .. code-block:: python

1865

1866
            import paddle.fluid as fluid
1867 1868
            import paddle
            paddle.enable_static()
X
xiaoting 已提交
1869
            boxes = fluid.data(name='bboxes', shape=[None,81, 4],
1870
                                      dtype='float32', lod_level=1)
X
xiaoting 已提交
1871
            scores = fluid.data(name='scores', shape=[None,81],
1872 1873 1874 1875 1876 1877 1878 1879 1880
                                      dtype='float32', lod_level=1)
            out = fluid.layers.multiclass_nms(bboxes=boxes,
                                              scores=scores,
                                              background_label=0,
                                              score_threshold=0.5,
                                              nms_top_k=400,
                                              nms_threshold=0.3,
                                              keep_top_k=200,
                                              normalized=False)
J
jerrywgz 已提交
1881
    """
1882 1883 1884 1885 1886 1887
    check_variable_and_dtype(
        bboxes, 'BBoxes', ['float32', 'float64'], 'multiclass_nms'
    )
    check_variable_and_dtype(
        scores, 'Scores', ['float32', 'float64'], 'multiclass_nms'
    )
X
xiaoting 已提交
1888 1889 1890 1891 1892 1893 1894 1895
    check_type(score_threshold, 'score_threshold', float, 'multicalss_nms')
    check_type(nms_top_k, 'nums_top_k', int, 'multiclass_nms')
    check_type(keep_top_k, 'keep_top_k', int, 'mutliclass_nms')
    check_type(nms_threshold, 'nms_threshold', float, 'multiclass_nms')
    check_type(normalized, 'normalized', bool, 'multiclass_nms')
    check_type(nms_eta, 'nms_eta', float, 'multiclass_nms')
    check_type(background_label, 'background_label', int, 'multiclass_nms')

J
jerrywgz 已提交
1896 1897
    helper = LayerHelper('multiclass_nms', **locals())
    output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
    helper.append_op(
        type="multiclass_nms",
        inputs={'BBoxes': bboxes, 'Scores': scores},
        attrs={
            'background_label': background_label,
            'score_threshold': score_threshold,
            'nms_top_k': nms_top_k,
            'nms_threshold': nms_threshold,
            'nms_eta': nms_eta,
            'keep_top_k': keep_top_k,
            'normalized': normalized,
        },
        outputs={'Out': output},
    )
J
jerrywgz 已提交
1912
    output.stop_gradient = True
J
jerrywgz 已提交
1913 1914

    return output
1915 1916


1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
def locality_aware_nms(
    bboxes,
    scores,
    score_threshold,
    nms_top_k,
    keep_top_k,
    nms_threshold=0.3,
    normalized=True,
    nms_eta=1.0,
    background_label=-1,
    name=None,
):
1929 1930
    """
    **Local Aware NMS**
1931

1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
    `Local Aware NMS <https://arxiv.org/abs/1704.03155>`_ is to do locality-aware non maximum
    suppression (LANMS) on boxes and scores.

    Firstly, this operator merge box and score according their IOU
    (intersection over union). In the NMS step, this operator greedily selects a
    subset of detection bounding boxes that have high scores larger than score_threshold,
    if providing this threshold, then selects the largest nms_top_k confidences scores
    if nms_top_k is larger than -1. Then this operator pruns away boxes that have high
    IOU overlap with already selected boxes by adaptive threshold NMS based on parameters
    of nms_threshold and nms_eta.

    Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
    per image if keep_top_k is larger than -1.

    Args:
        bboxes (Variable): A 3-D Tensor with shape [N, M, 4 or 8 16 24 32]
                           represents the predicted locations of M bounding
                           bboxes, N is the batch size. Each bounding box
                           has four coordinate values and the layout is
                           [xmin, ymin, xmax, ymax], when box size equals to 4.
                           The data type is float32 or float64.
        scores (Variable): A 3-D Tensor with shape [N, C, M] represents the
                           predicted confidence predictions. N is the batch
                           size, C is the class number, M is number of bounding
                           boxes. Now only support 1 class. For each category
                           there are total M scores which corresponding M bounding
                           boxes. Please note, M is equal to the 2nd dimension of
                           BBoxes. The data type is float32 or float64.
        background_label (int): The index of background label, the background
                                label will be ignored. If set to -1, then all
                                categories will be considered. Default: -1
        score_threshold (float): Threshold to filter out bounding boxes with
                                 low confidence score. If not provided,
                                 consider all boxes.
        nms_top_k (int): Maximum number of detections to be kept according to
T
tianshuo78520a 已提交
1967
                         the confidences after the filtering detections based
1968 1969 1970
                         on score_threshold.
        keep_top_k (int): Number of total bboxes to be kept per image after NMS
                          step. -1 means keeping all bboxes after NMS step.
1971 1972
        nms_threshold (float): The threshold to be used in NMS. Default: 0.3
        nms_eta (float): The threshold to be used in NMS. Default: 1.0
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
        normalized (bool): Whether detections are normalized. Default: True
        name(str): Name of the locality aware nms op, please refer to :ref:`api_guide_Name` .
                          Default: None.

    Returns:
        Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.
             Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
             or A 2-D LoDTensor with shape [No, 10] represents the detections.
             Each row has 10 values:
             [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the
             total number of detections. If there is no detected boxes for all
             images, lod will be set to {1} and Out only contains one value
             which is -1.
             (After version 1.3, when no boxes detected, the lod is changed
             from {0} to {1}). The data type is float32 or float64.


    Examples:
        .. code-block:: python


            import paddle.fluid as fluid
            boxes = fluid.data(name='bboxes', shape=[None, 81, 8],
                                      dtype='float32')
            scores = fluid.data(name='scores', shape=[None, 1, 81],
                                      dtype='float32')
            out = fluid.layers.locality_aware_nms(bboxes=boxes,
                                              scores=scores,
                                              score_threshold=0.5,
                                              nms_top_k=400,
                                              nms_threshold=0.3,
                                              keep_top_k=200,
                                              normalized=False)
    """
2007 2008 2009 2010 2011 2012
    check_variable_and_dtype(
        bboxes, 'bboxes', ['float32', 'float64'], 'locality_aware_nms'
    )
    check_variable_and_dtype(
        scores, 'scores', ['float32', 'float64'], 'locality_aware_nms'
    )
2013 2014 2015 2016 2017 2018 2019 2020
    check_type(background_label, 'background_label', int, 'locality_aware_nms')
    check_type(score_threshold, 'score_threshold', float, 'locality_aware_nms')
    check_type(nms_top_k, 'nms_top_k', int, 'locality_aware_nms')
    check_type(nms_eta, 'nms_eta', float, 'locality_aware_nms')
    check_type(nms_threshold, 'nms_threshold', float, 'locality_aware_nms')
    check_type(keep_top_k, 'keep_top_k', int, 'locality_aware_nms')
    check_type(normalized, 'normalized', bool, 'locality_aware_nms')

2021 2022
    shape = scores.shape
    assert len(shape) == 3, "dim size of scores must be 3"
2023 2024 2025
    assert (
        shape[1] == 1
    ), "locality_aware_nms only support one class, Tensor score shape must be [N, 1, M]"
2026 2027 2028 2029 2030 2031

    helper = LayerHelper('locality_aware_nms', **locals())

    output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
    out = {'Out': output}

2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
    helper.append_op(
        type="locality_aware_nms",
        inputs={'BBoxes': bboxes, 'Scores': scores},
        attrs={
            'background_label': background_label,
            'score_threshold': score_threshold,
            'nms_top_k': nms_top_k,
            'nms_threshold': nms_threshold,
            'nms_eta': nms_eta,
            'keep_top_k': keep_top_k,
            'nms_eta': nms_eta,
            'normalized': normalized,
        },
        outputs={'Out': output},
    )
2047 2048 2049 2050 2051
    output.stop_gradient = True

    return output


2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
def matrix_nms(
    bboxes,
    scores,
    score_threshold,
    post_threshold,
    nms_top_k,
    keep_top_k,
    use_gaussian=False,
    gaussian_sigma=2.0,
    background_label=0,
    normalized=True,
    return_index=False,
    name=None,
):
Y
Yang Zhang 已提交
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
    """
    **Matrix NMS**

    This operator does matrix non maximum suppression (NMS).

    First selects a subset of candidate bounding boxes that have higher scores
    than score_threshold (if provided), then the top k candidate is selected if
    nms_top_k is larger than -1. Score of the remaining candidate are then
    decayed according to the Matrix NMS scheme.
    Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
    per image if keep_top_k is larger than -1.

    Args:
        bboxes (Variable): A 3-D Tensor with shape [N, M, 4] represents the
                           predicted locations of M bounding bboxes,
                           N is the batch size. Each bounding box has four
                           coordinate values and the layout is
                           [xmin, ymin, xmax, ymax], when box size equals to 4.
                           The data type is float32 or float64.
        scores (Variable): A 3-D Tensor with shape [N, C, M]
                           represents the predicted confidence predictions.
                           N is the batch size, C is the class number, M is
                           number of bounding boxes. For each category there
                           are total M scores which corresponding M bounding
                           boxes. Please note, M is equal to the 2nd dimension
                           of BBoxes. The data type is float32 or float64.
        score_threshold (float): Threshold to filter out bounding boxes with
                                 low confidence score.
        post_threshold (float): Threshold to filter out bounding boxes with
                                low confidence score AFTER decaying.
        nms_top_k (int): Maximum number of detections to be kept according to
                         the confidences after the filtering detections based
                         on score_threshold.
        keep_top_k (int): Number of total bboxes to be kept per image after NMS
                          step. -1 means keeping all bboxes after NMS step.
        use_gaussian (bool): Use Gaussian as the decay function. Default: False
        gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0
        background_label (int): The index of background label, the background
                                label will be ignored. If set to -1, then all
                                categories will be considered. Default: 0
        normalized (bool): Whether detections are normalized. Default: True
        return_index(bool): Whether return selected index. Default: False
        name(str): Name of the matrix nms op. Default: None.

    Returns:
        A tuple with two Variables: (Out, Index) if return_index is True,
        otherwise, one Variable(Out) is returned.

        Out (Variable): A 2-D LoDTensor with shape [No, 6] containing the
             detection results.
             Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
             (After version 1.3, when no boxes detected, the lod is changed
             from {0} to {1})

        Index (Variable): A 2-D LoDTensor with shape [No, 1] containing the
            selected indices, which are absolute values cross batches.

    Examples:
        .. code-block:: python


            import paddle.fluid as fluid
            boxes = fluid.data(name='bboxes', shape=[None,81, 4],
                                      dtype='float32', lod_level=1)
            scores = fluid.data(name='scores', shape=[None,81],
                                      dtype='float32', lod_level=1)
            out = fluid.layers.matrix_nms(bboxes=boxes,
                                          scores=scores,
                                          background_label=0,
                                          score_threshold=0.5,
                                          post_threshold=0.1,
                                          nms_top_k=400,
                                          keep_top_k=200,
                                          normalized=False)
    """
Z
zhiboniu 已提交
2141
    if in_dygraph_mode():
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
        attrs = (
            score_threshold,
            nms_top_k,
            keep_top_k,
            post_threshold,
            use_gaussian,
            gaussian_sigma,
            background_label,
            normalized,
        )
Z
zhiboniu 已提交
2152

2153
        out, index = _C_ops.matrix_nms(bboxes, scores, *attrs)
Z
zhiboniu 已提交
2154 2155 2156 2157 2158
        if return_index:
            return out, index
        else:
            return out

2159 2160 2161 2162 2163 2164
    check_variable_and_dtype(
        bboxes, 'BBoxes', ['float32', 'float64'], 'matrix_nms'
    )
    check_variable_and_dtype(
        scores, 'Scores', ['float32', 'float64'], 'matrix_nms'
    )
Y
Yang Zhang 已提交
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
    check_type(score_threshold, 'score_threshold', float, 'matrix_nms')
    check_type(post_threshold, 'post_threshold', float, 'matrix_nms')
    check_type(nms_top_k, 'nums_top_k', int, 'matrix_nms')
    check_type(keep_top_k, 'keep_top_k', int, 'matrix_nms')
    check_type(normalized, 'normalized', bool, 'matrix_nms')
    check_type(use_gaussian, 'use_gaussian', bool, 'matrix_nms')
    check_type(gaussian_sigma, 'gaussian_sigma', float, 'matrix_nms')
    check_type(background_label, 'background_label', int, 'matrix_nms')

    helper = LayerHelper('matrix_nms', **locals())
    output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
    index = helper.create_variable_for_type_inference(dtype='int')
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
    helper.append_op(
        type="matrix_nms",
        inputs={'BBoxes': bboxes, 'Scores': scores},
        attrs={
            'score_threshold': score_threshold,
            'post_threshold': post_threshold,
            'nms_top_k': nms_top_k,
            'keep_top_k': keep_top_k,
            'use_gaussian': use_gaussian,
            'gaussian_sigma': gaussian_sigma,
            'background_label': background_label,
            'normalized': normalized,
        },
        outputs={'Out': output, 'Index': index},
    )
Y
Yang Zhang 已提交
2192 2193 2194 2195 2196 2197 2198 2199
    output.stop_gradient = True

    if return_index:
        return output, index
    else:
        return output


2200 2201 2202 2203 2204 2205 2206 2207 2208
def distribute_fpn_proposals(
    fpn_rois,
    min_level,
    max_level,
    refer_level,
    refer_scale,
    rois_num=None,
    name=None,
):
2209
    r"""
2210 2211 2212 2213 2214 2215

    **This op only takes LoDTensor as input.** In Feature Pyramid Networks
    (FPN) models, it is needed to distribute all proposals into different FPN
    level, with respect to scale of the proposals, the referring scale and the
    referring level. Besides, to restore the order of proposals, we return an
    array which indicates the original index of rois in current proposals.
W
wangguanzhong 已提交
2216
    To compute FPN level for each roi, the formula is given as follows:
2217

J
jerrywgz 已提交
2218
    .. math::
2219

J
jerrywgz 已提交
2220
        roi\_scale &= \sqrt{BBoxArea(fpn\_roi)}
2221

J
jerrywgz 已提交
2222 2223 2224
        level = floor(&\log(\\frac{roi\_scale}{refer\_scale}) + refer\_level)

    where BBoxArea is a function to compute the area of each roi.
2225 2226

    Args:
W
wangguanzhong 已提交
2227

2228
        fpn_rois(Variable): 2-D Tensor with shape [N, 4] and data type is
W
wangguanzhong 已提交
2229
            float32 or float64. The input fpn_rois.
2230
        min_level(int32): The lowest level of FPN layer where the proposals come
W
wangguanzhong 已提交
2231 2232 2233 2234 2235
            from.
        max_level(int32): The highest level of FPN layer where the proposals
            come from.
        refer_level(int32): The referring level of FPN layer with specified scale.
        refer_scale(int32): The referring scale of FPN layer with specified level.
2236
        rois_num(Tensor): 1-D Tensor contains the number of RoIs in each image.
2237
            The shape is [B] and data type is int32. B is the number of images.
2238
            If it is not None then return a list of 1-D Tensor. Each element
2239 2240
            is the output RoIs' number of each image on the corresponding level
            and the shape is [B]. None by default.
2241 2242 2243
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
            None by default.
J
jerrywgz 已提交
2244

2245
    Returns:
W
wangguanzhong 已提交
2246 2247
        Tuple:

2248 2249
        multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4]
        and data type of float32 and float64. The length is
W
wangguanzhong 已提交
2250 2251
        max_level-min_level+1. The proposals in each FPN level.

2252
        restore_ind(Variable): A 2-D Tensor with shape [N, 1], N is
W
wangguanzhong 已提交
2253 2254 2255
        the number of total rois. The data type is int32. It is
        used to restore the order of fpn_rois.

2256 2257
        rois_num_per_level(List): A list of 1-D Tensor and each Tensor is
        the RoIs' number in each image on the corresponding level. The shape
2258 2259
        is [B] and data type of int32. B is the number of images

2260 2261 2262 2263

    Examples:
        .. code-block:: python

2264
            import paddle.fluid as fluid
2265 2266
            import paddle
            paddle.enable_static()
2267 2268
            fpn_rois = fluid.data(
                name='data', shape=[None, 4], dtype='float32', lod_level=1)
2269
            multi_rois, restore_ind = fluid.layers.distribute_fpn_proposals(
2270 2271 2272
                fpn_rois=fpn_rois,
                min_level=2,
                max_level=5,
2273 2274 2275
                refer_level=4,
                refer_scale=224)
    """
2276 2277 2278 2279 2280 2281 2282 2283 2284
    return paddle.vision.ops.distribute_fpn_proposals(
        fpn_rois=fpn_rois,
        min_level=min_level,
        max_level=max_level,
        refer_level=refer_level,
        refer_scale=refer_scale,
        rois_num=rois_num,
        name=name,
    )
2285 2286


2287
@templatedoc()
2288 2289 2290
def box_decoder_and_assign(
    prior_box, prior_box_var, target_box, box_score, box_clip, name=None
):
2291
    """
2292

2293 2294 2295 2296 2297 2298
    ${comment}
    Args:
        prior_box(${prior_box_type}): ${prior_box_comment}
        prior_box_var(${prior_box_var_type}): ${prior_box_var_comment}
        target_box(${target_box_type}): ${target_box_comment}
        box_score(${box_score_type}): ${box_score_comment}
J
jerrywgz 已提交
2299
        box_clip(${box_clip_type}): ${box_clip_comment}
2300 2301 2302
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
            None by default.
W
wangguanzhong 已提交
2303

2304
    Returns:
W
wangguanzhong 已提交
2305
        Tuple:
J
jerrywgz 已提交
2306

W
wangguanzhong 已提交
2307 2308 2309
        decode_box(${decode_box_type}): ${decode_box_comment}

        output_assign_box(${output_assign_box_type}): ${output_assign_box_comment}
J
jerrywgz 已提交
2310 2311


2312 2313 2314
    Examples:
        .. code-block:: python

2315
            import paddle.fluid as fluid
2316 2317
            import paddle
            paddle.enable_static()
2318 2319 2320 2321 2322 2323 2324 2325
            pb = fluid.data(
                name='prior_box', shape=[None, 4], dtype='float32')
            pbv = fluid.data(
                name='prior_box_var', shape=[4], dtype='float32')
            loc = fluid.data(
                name='target_box', shape=[None, 4*81], dtype='float32')
            scores = fluid.data(
                name='scores', shape=[None, 81], dtype='float32')
J
jerrywgz 已提交
2326
            decoded_box, output_assign_box = fluid.layers.box_decoder_and_assign(
J
jerrywgz 已提交
2327
                pb, pbv, loc, scores, 4.135)
2328 2329

    """
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
    check_variable_and_dtype(
        prior_box, 'prior_box', ['float32', 'float64'], 'box_decoder_and_assign'
    )
    check_variable_and_dtype(
        target_box,
        'target_box',
        ['float32', 'float64'],
        'box_decoder_and_assign',
    )
    check_variable_and_dtype(
        box_score, 'box_score', ['float32', 'float64'], 'box_decoder_and_assign'
    )
2342 2343
    helper = LayerHelper("box_decoder_and_assign", **locals())

J
jerrywgz 已提交
2344
    decoded_box = helper.create_variable_for_type_inference(
2345 2346
        dtype=prior_box.dtype
    )
2347
    output_assign_box = helper.create_variable_for_type_inference(
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
        dtype=prior_box.dtype
    )

    helper.append_op(
        type="box_decoder_and_assign",
        inputs={
            "PriorBox": prior_box,
            "PriorBoxVar": prior_box_var,
            "TargetBox": target_box,
            "BoxScore": box_score,
        },
        attrs={"box_clip": box_clip},
        outputs={
            "DecodeBox": decoded_box,
            "OutputAssignBox": output_assign_box,
        },
    )
J
jerrywgz 已提交
2365
    return decoded_box, output_assign_box
2366 2367


2368 2369 2370 2371 2372 2373 2374 2375 2376
def collect_fpn_proposals(
    multi_rois,
    multi_scores,
    min_level,
    max_level,
    post_nms_top_n,
    rois_num_per_level=None,
    name=None,
):
2377
    """
2378 2379 2380

    **This OP only supports LoDTensor as input**. Concat multi-level RoIs
    (Region of Interest) and select N RoIs with respect to multi_scores.
W
wangguanzhong 已提交
2381
    This operation performs the following steps:
2382 2383 2384 2385 2386 2387 2388 2389

    1. Choose num_level RoIs and scores as input: num_level = max_level - min_level
    2. Concat multi-level RoIs and scores
    3. Sort scores and select post_nms_top_n scores
    4. Gather RoIs by selected indices from scores
    5. Re-sort RoIs by corresponding batch_id

    Args:
2390 2391
        multi_rois(list): List of RoIs to collect. Element in list is 2-D
            LoDTensor with shape [N, 4] and data type is float32 or float64,
W
wangguanzhong 已提交
2392
            N is the number of RoIs.
2393
        multi_scores(list): List of scores of RoIs to collect. Element in list
W
wangguanzhong 已提交
2394 2395
            is 2-D LoDTensor with shape [N, 1] and data type is float32 or
            float64, N is the number of RoIs.
2396 2397 2398
        min_level(int): The lowest level of FPN layer to collect
        max_level(int): The highest level of FPN layer to collect
        post_nms_top_n(int): The number of selected RoIs
2399 2400 2401 2402 2403
        rois_num_per_level(list, optional): The List of RoIs' numbers.
            Each element is 1-D Tensor which contains the RoIs' number of each
            image on each level and the shape is [B] and data type is
            int32, B is the number of images. If it is not None then return
            a 1-D Tensor contains the output RoIs' number of each image and
2404
            the shape is [B]. Default: None
2405 2406 2407
        name(str, optional): For detailed information, please refer
            to :ref:`api_guide_Name`. Usually name is no need to set and
            None by default.
W
wangguanzhong 已提交
2408

2409
    Returns:
W
wangguanzhong 已提交
2410 2411
        Variable:

2412 2413
        fpn_rois(Variable): 2-D LoDTensor with shape [N, 4] and data type is
        float32 or float64. Selected RoIs.
W
wangguanzhong 已提交
2414

2415 2416 2417
        rois_num(Tensor): 1-D Tensor contains the RoIs's number of each
        image. The shape is [B] and data type is int32. B is the number of
        images.
2418 2419 2420

    Examples:
        .. code-block:: python
2421

2422
            import paddle.fluid as fluid
2423 2424
            import paddle
            paddle.enable_static()
2425 2426 2427
            multi_rois = []
            multi_scores = []
            for i in range(4):
2428 2429
                multi_rois.append(fluid.data(
                    name='roi_'+str(i), shape=[None, 4], dtype='float32', lod_level=1))
2430
            for i in range(4):
2431 2432
                multi_scores.append(fluid.data(
                    name='score_'+str(i), shape=[None, 1], dtype='float32', lod_level=1))
2433 2434

            fpn_rois = fluid.layers.collect_fpn_proposals(
2435
                multi_rois=multi_rois,
2436
                multi_scores=multi_scores,
2437 2438
                min_level=2,
                max_level=5,
2439 2440
                post_nms_top_n=2000)
    """
2441 2442 2443 2444
    num_lvl = max_level - min_level + 1
    input_rois = multi_rois[:num_lvl]
    input_scores = multi_scores[:num_lvl]

J
Jiabin Yang 已提交
2445
    if _non_static_mode():
2446 2447 2448
        assert (
            rois_num_per_level is not None
        ), "rois_num_per_level should not be None in dygraph mode."
2449
        attrs = ('post_nms_topN', post_nms_top_n)
2450
        output_rois, rois_num = _legacy_C_ops.collect_fpn_proposals(
2451 2452
            input_rois, input_scores, rois_num_per_level, *attrs
        )
2453

2454 2455
    check_type(multi_rois, 'multi_rois', list, 'collect_fpn_proposals')
    check_type(multi_scores, 'multi_scores', list, 'collect_fpn_proposals')
2456 2457
    helper = LayerHelper('collect_fpn_proposals', **locals())
    dtype = helper.input_dtype('multi_rois')
2458 2459 2460
    check_dtype(
        dtype, 'multi_rois', ['float32', 'float64'], 'collect_fpn_proposals'
    )
2461 2462
    output_rois = helper.create_variable_for_type_inference(dtype)
    output_rois.stop_gradient = True
2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473

    inputs = {
        'MultiLevelRois': input_rois,
        'MultiLevelScores': input_scores,
    }
    outputs = {'FpnRois': output_rois}
    if rois_num_per_level is not None:
        inputs['MultiLevelRoIsNum'] = rois_num_per_level
        rois_num = helper.create_variable_for_type_inference(dtype='int32')
        rois_num.stop_gradient = True
        outputs['RoisNum'] = rois_num
2474 2475 2476 2477 2478 2479
    helper.append_op(
        type='collect_fpn_proposals',
        inputs=inputs,
        outputs=outputs,
        attrs={'post_nms_topN': post_nms_top_n},
    )
2480 2481
    if rois_num_per_level is not None:
        return output_rois, rois_num
2482
    return output_rois