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

15
from ...device import get_cudnn_version
16
from ...static import Variable
R
ruri 已提交
17
from ...fluid.layer_helper import LayerHelper
18 19 20
from ...fluid.data_feeder import check_variable_and_dtype
from ...fluid import dygraph_utils
import numpy as np
21
from paddle import _C_ops, _legacy_C_ops
Z
zhiboniu 已提交
22 23
from ...device import is_compiled_with_rocm
from paddle import in_dynamic_mode
H
hong 已提交
24
from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph
25
from paddle.framework import _non_static_mode
R
ruri 已提交
26

27 28
__all__ = []

29 30 31

def affine_grid(theta, out_shape, align_corners=True, name=None):
    """
32
    It generates a grid of (x,y) or (x,y,z) coordinates using the parameters of
33 34 35 36 37
    the affine transformation that correspond to a set of points where
    the input feature map should be sampled to produce the transformed
    output feature map.

    Args:
38
        theta (Tensor) - A tensor with shape [N, 2, 3] or [N, 3, 4]. It contains a batch of affine transform parameters.
39
                           The data type can be float32 or float64.
40
        out_shape (Tensor | list | tuple): Type can be a 1-D Tensor, list, or tuple. It is used to represent the shape of the output in an affine transformation, in the format ``[N, C, H, W]`` or ``[N, C, D, H, W]``.
41 42 43 44
                                           When the format is ``[N, C, H, W]``, it represents the batch size, number of channels, height and width. When the format is ``[N, C, D, H, W]``, it represents the batch size, number of channels, depth, height and width.
                                           The data type must be int32.
        align_corners(bool, optional): if True, aligns the centers of the 4 (4D) or 8 (5D) corner pixels of the input and output tensors, and preserves the value of the corner pixels. Default: True
        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`.
45 46

    Returns:
47
        Tensor, A Tensor with shape [batch_size, H, W, 2] or [batch, D, H, W, 3] while ('D')'H', 'W' are the (depth)height, width of feature map in affine transformation. The data type is the same as `theta`.
48 49 50 51 52 53 54 55

    Examples:

        .. code-block:: python

            import paddle
            import paddle.nn.functional as F
            # theta shape = [1, 2, 3]
56 57
            theta = paddle.to_tensor([[[-0.7, -0.4, 0.3],
                                       [ 0.6,  0.5, 1.5]]], dtype="float32")
58
            y_t = F.affine_grid(
59
                    theta,
60 61
                    [1, 2, 3, 3],
                    align_corners=False)
W
whs 已提交
62
            print(y_t)
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77
            #[[[[ 1.0333333   0.76666665]
            #   [ 0.76666665  1.0999999 ]
            #   [ 0.5         1.4333333 ]]
            #
            #  [[ 0.5666667   1.1666666 ]
            #   [ 0.3         1.5       ]
            #   [ 0.03333333  1.8333334 ]]
            #
            #  [[ 0.10000002  1.5666667 ]
            #   [-0.16666666  1.9000001 ]
            #   [-0.43333334  2.2333333 ]]]]
    """
    if not isinstance(theta, Variable):
        raise ValueError("The theta should be a Tensor.")
78

79 80 81 82 83
    cudnn_version = get_cudnn_version()
    if cudnn_version is not None and cudnn_version >= 6000 and align_corners:
        use_cudnn = True
    else:
        use_cudnn = False
84 85
    if theta.shape[1] == 3:
        use_cudnn = False
Z
zhiboniu 已提交
86
    if is_compiled_with_rocm():
87
        use_cudnn = False  # ROCM platform do not have MIOPEN kernel for affine_grid
88

89 90 91
    if in_dygraph_mode():
        _out_shape = out_shape.numpy().tolist() if isinstance(
            out_shape, Variable) else out_shape
92
        return _C_ops.affine_grid(theta, _out_shape, use_cudnn, align_corners)
93
    elif in_dynamic_mode():
94 95
        _out_shape = out_shape.numpy().tolist() if isinstance(
            out_shape, Variable) else out_shape
96 97 98
        return _legacy_C_ops.affine_grid(theta, "output_shape", _out_shape,
                                         "align_corners", align_corners,
                                         "use_cudnn", use_cudnn)
99

100 101 102
    helper = LayerHelper('affine_grid')
    check_variable_and_dtype(theta, 'theta', ['float32', 'float64'],
                             'affine_grid')
103 104 105 106 107 108 109 110 111 112
    out = helper.create_variable_for_type_inference(theta.dtype)
    ipts = {'Theta': theta}
    attrs = {"align_corners": align_corners, "use_cudnn": use_cudnn}
    if isinstance(out_shape, Variable):
        ipts['OutputShape'] = out_shape
        check_variable_and_dtype(out_shape, 'out_shape', ['int32'],
                                 'affine_grid')
    else:
        attrs['output_shape'] = out_shape

113 114 115 116
    helper.append_op(type='affine_grid',
                     inputs=ipts,
                     outputs={'Output': out},
                     attrs=None if len(attrs) == 0 else attrs)
117
    return out
118 119 120 121 122 123 124 125 126 127 128


def grid_sample(x,
                grid,
                mode='bilinear',
                padding_mode='zeros',
                align_corners=True,
                name=None):
    """
    This operation samples input X by using bilinear interpolation or
    nearest interpolation based on flow field grid, which is usually
129 130 131 132 133
    generated by :code:`affine_grid` . When the input X is 4-D Tensor,
    the grid of shape [N, H, W, 2] is the concatenation of (x, y)
    coordinates with shape [N, H, W] each, where x is indexing the 4th
    dimension (in width dimension) of input data x and y is indexing
    the 3rd dimension (in height dimension), finally results is the
134
    bilinear interpolation or nearest value of 4 nearest corner
135 136 137 138 139 140 141 142
    points. The output tensor shape will be [N, C, H, W]. When the input X
    is 5-D Tensor, the grid of shape [N, D, H, W, 3] is the concatenation
    of (x, y, z) coordinates with shape [N, D, H, W] each, where x is
    indexing the 5th dimension (in width dimension) of input data x, y is
    indexing the 4th dimension (in height dimension) and z is indexing the
    3rd dimension (in depth dimension) finally results is the bilinear
    interpolation or nearest value of 8 nearest cornerpoints. The output
    tensor shape will be [N, C, D, H, W].
143

144 145 146 147 148 149 150 151 152 153 154 155


    Step 1:

    Get (x, y) grid coordinates and scale to [0, H-1/W-1].

    .. code-block:: text

        grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1)
        grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1)

    Step 2:
156

157 158 159 160
    Indices input data X with grid (x, y) in each [H, W] area, and bilinear
    interpolate point value by 4 nearest points or nearest interpolate point value
    by nearest point.

161
    .. code-block:: text
162 163 164 165 166 167 168 169 170 171 172

        wn ------- y_n ------- en
        |           |           |
        |          d_n          |
        |           |           |
        x_w --d_w-- grid--d_e-- x_e
        |           |           |
        |          d_s          |
        |           |           |
        ws ------- y_s ------- wn

173 174 175 176 177 178 179 180 181 182 183 184 185
        For bilinear interpolation:
        x_w = floor(x)              // west side x coord
        x_e = x_w + 1               // east side x coord
        y_n = floor(y)              // north side y coord
        y_s = y_s + 1               // south side y coord
        d_w = grid_x - x_w          // distance to west side
        d_e = x_e - grid_x          // distance to east side
        d_n = grid_y - y_n          // distance to north side
        d_s = y_s - grid_y          // distance to south side
        wn = X[:, :, y_n, x_w]      // north-west point value
        en = X[:, :, y_n, x_e]      // north-east point value
        ws = X[:, :, y_s, x_w]      // south-east point value
        es = X[:, :, y_s, x_w]      // north-east point value
186

187
        output = wn * d_e * d_s + en * d_w * d_s
188 189
                + ws * d_e * d_n + es * d_w * d_n

190 191
    Args:
        x(Tensor): The input tensor, which is a 4-d tensor with shape
192 193
                     [N, C, H, W] or a 5-d tensor with shape [N, C, D, H, W],
                     N is the batch size, C is the channel number,
194
                     D, H and W is the feature depth, height and width.
195
                     The data type is float32 or float64.
196 197
        grid(Tensor): Input grid tensor, which is a 4-d tensor with shape [N, grid_H,
                        grid_W, 2] or a 5-d tensor with shape [N, grid_D, grid_H,
198
                        grid_W, 3]. The data type is float32 or float64.
199 200 201
        mode(str, optional): The interpolation method which can be 'bilinear' or 'nearest'.
                         Default: 'bilinear'.
        padding_mode(str, optional) The padding method used when source index
202
                   is out of input images. It can be 'zeros', 'reflection' and 'border'.
203 204 205 206 207 208 209
                   Default: zeros.
        align_corners(bool, optional): If `align_corners` is true, it will projects
                   -1 and 1 to the centers of the corner pixels. Otherwise, it will
                   projects -1 and 1 to the image edges.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.
210 211

    Returns:
212
        Tensor, The shape of output is [N, C, grid_H, grid_W] or [N, C, grid_D, grid_H, grid_W] in which `grid_D` is the depth of grid,
213
                `grid_H` is the height of grid and `grid_W` is the width of grid. The data type is same as input tensor.
214

215
    Examples:
216

217
        .. code-block:: python
218

219 220
            import paddle
            import paddle.nn.functional as F
221 222

            # x shape=[1, 1, 3, 3]
223 224 225
            x = paddle.to_tensor([[[[-0.6,  0.8, -0.5],
                                    [-0.5,  0.2,  1.2],
                                    [ 1.4,  0.3, -0.2]]]],dtype='float64')
226
            # grid shape = [1, 3, 4, 2]
227 228 229 230 231 232 233 234 235 236 237 238
            grid = paddle.to_tensor([[[[ 0.2,  0.3],
                                       [-0.4, -0.3],
                                       [-0.9,  0.3],
                                       [-0.9, -0.6]],
                                      [[ 0.4,  0.1],
                                       [ 0.9, -0.8],
                                       [ 0.4,  0.5],
                                       [ 0.5, -0.2]],
                                      [[ 0.1, -0.8],
                                       [-0.3, -1. ],
                                       [ 0.7,  0.4],
                                       [ 0.2,  0.8]]]],dtype='float64')
239 240 241 242 243 244
            y_t = F.grid_sample(
                x,
                grid,
                mode='bilinear',
                padding_mode='border',
                align_corners=True)
W
whs 已提交
245
            print(y_t)
246

247 248 249 250 251
            # output shape = [1, 1, 3, 4]
            # [[[[ 0.34   0.016  0.086 -0.448]
            #    [ 0.55  -0.076  0.35   0.59 ]
            #    [ 0.596  0.38   0.52   0.24 ]]]]
    """
252

253
    _modes = ['bilinear', 'nearest']
254
    _padding_modes = ['zeros', 'reflection', 'border']
255 256 257 258 259 260
    if mode not in _modes:
        raise ValueError(
            "The mode of grid sample function should be in {}, but got: {}".
            format(_modes, mode))
    if padding_mode not in _padding_modes:
        raise ValueError(
261 262
            "The padding mode of grid sample function should be in {}, but got: {}"
            .format(_padding_modes, padding_mode))
263 264 265 266 267 268 269

    if not isinstance(align_corners, bool):
        raise ValueError("The align corners should be bool, but got: {}".format(
            align_corners))

    cudnn_version = get_cudnn_version()
    use_cudnn = False
Z
zhiboniu 已提交
270
    if not is_compiled_with_rocm() and (
271 272
            cudnn_version is not None
    ) and align_corners and mode == 'bilinear' and padding_mode == 'zeros':
273
        use_cudnn = True
W
whs 已提交
274 275 276
        # CUDNN always computes gradients for all inputs
        x.stop_gradient = False
        grid.stop_gradient = False
277

278 279 280
    if len(grid.shape) == 5:
        use_cudnn = False

W
Wang Bojun 已提交
281
    if in_dygraph_mode():
282
        return _C_ops.grid_sample(x, grid, mode, padding_mode, align_corners)
W
Wang Bojun 已提交
283
    elif in_dynamic_mode():
284 285
        attrs = ('mode', mode, 'padding_mode', padding_mode, 'align_corners',
                 align_corners, 'use_cudnn', use_cudnn)
286
        out = getattr(_legacy_C_ops, 'grid_sampler')(x, grid, *attrs)
287
    else:
288 289 290 291 292 293 294 295 296 297 298
        helper = LayerHelper("grid_sample", **locals())
        check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'grid_sample')
        check_variable_and_dtype(grid, 'grid', ['float32', 'float64'],
                                 'grid_sample')
        ipts = {'X': x, 'Grid': grid}
        attrs = {
            'mode': mode,
            'padding_mode': padding_mode,
            'align_corners': align_corners,
            'use_cudnn': use_cudnn
        }
299
        out = helper.create_variable_for_type_inference(x.dtype)
300 301 302 303
        helper.append_op(type='grid_sampler',
                         inputs=ipts,
                         attrs=attrs,
                         outputs={'Output': out})
304
    return out
R
ruri 已提交
305 306 307 308 309 310


def pixel_shuffle(x, upscale_factor, data_format="NCHW", name=None):
    """
    This API implements pixel shuffle operation.
    See more details in :ref:`api_nn_vision_PixelShuffle` .
311 312


R
ruri 已提交
313 314 315
    Parameters:
        x(Tensor): 4-D tensor, the data type should be float32 or float64.
        upscale_factor(int): factor to increase spatial resolution.
316
        data_format (str, optional): The data format of the input and output data. An optional string from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in the order of: [batch_size, input_channels, input_height, input_width].
R
ruri 已提交
317
        name (str, optional): The default value is None.  Normally there is no need for user to set this property.
318

R
ruri 已提交
319 320
    Returns:
        Out(tensor): Reshaped tensor according to the new dimension.
321

R
ruri 已提交
322 323
    Examples:
        .. code-block:: python
324

R
ruri 已提交
325 326
            import paddle
            import paddle.nn.functional as F
327 328 329

            x = paddle.randn(shape=[2,9,4,4])
            out_var = F.pixel_shuffle(x, 3)
R
ruri 已提交
330
            out = out_var.numpy()
331
            print(out.shape)
R
ruri 已提交
332 333 334 335 336 337
            # (2, 1, 12, 12)
    """
    if not isinstance(upscale_factor, int):
        raise TypeError("upscale factor must be int type")

    if data_format not in ["NCHW", "NHWC"]:
338 339 340
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'."
            "But recevie Attr(data_format): {} ".format(data_format))
H
hong 已提交
341
    if in_dygraph_mode():
342
        return _C_ops.pixel_shuffle(x, upscale_factor, data_format)
R
ruri 已提交
343

H
hong 已提交
344
    if _in_legacy_dygraph():
345 346
        return _legacy_C_ops.pixel_shuffle(x, "upscale_factor", upscale_factor,
                                           "data_format", data_format)
R
ruri 已提交
347 348

    helper = LayerHelper("pixel_shuffle", **locals())
349
    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'pixel_shuffle')
R
ruri 已提交
350
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
351 352 353 354 355 356 357
    helper.append_op(type="pixel_shuffle",
                     inputs={"X": x},
                     outputs={"Out": out},
                     attrs={
                         "upscale_factor": upscale_factor,
                         "data_format": data_format
                     })
R
ruri 已提交
358
    return out
359 360


361 362 363 364 365 366 367 368
def pixel_unshuffle(x, downscale_factor, data_format="NCHW", name=None):
    """
    This API implements pixel unshuffle operation.
    See more details in :ref:`api_nn_vision_PixelUnshuffle` .

    Parameters:
        x (Tensor): 4-D tensor, the data type should be float32 or float64.
        downscale_factor (int): Factor to decrease spatial resolution.
369
        data_format (str, optional): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width].
370 371 372 373 374 375 376 377 378 379 380 381
        name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Out (Tensor): Reshaped tensor according to the new dimension.

    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn.functional as F
            x = paddle.randn([2, 1, 12, 12])
            out = F.pixel_unshuffle(x, 3)
382 383
            print(out.shape)
            # [2, 9, 4, 4]
384 385 386 387 388 389 390 391 392 393 394 395 396
    """
    if len(x.shape) != 4:
        raise ValueError(
            "Input x should be 4D tensor, but received x with the shape of {}".
            format(x.shape))

    if not isinstance(downscale_factor, int):
        raise TypeError("Downscale factor must be int type")

    if downscale_factor <= 0:
        raise ValueError("Downscale factor must be positive")

    if data_format not in ["NCHW", "NHWC"]:
397 398 399
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'."
            "But recevie Attr(data_format): {} ".format(data_format))
400 401

    if _non_static_mode():
402 403 404
        return _legacy_C_ops.pixel_unshuffle(x, "downscale_factor",
                                             downscale_factor, "data_format",
                                             data_format)
405 406 407 408

    helper = LayerHelper("pixel_unshuffle", **locals())
    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'pixel_unshuffle')
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
409 410 411 412 413 414 415
    helper.append_op(type="pixel_unshuffle",
                     inputs={"X": x},
                     outputs={"Out": out},
                     attrs={
                         "downscale_factor": downscale_factor,
                         "data_format": data_format
                     })
416 417 418
    return out


419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
def channel_shuffle(x, groups, data_format="NCHW", name=None):
    """
    This API implements channel shuffle operation.
    See more details in :ref:`api_nn_vision_ChannelShuffle` .

    Parameters:
        x (Tensor): 4-D tensor, the data type should be float32 or float64.
        groups (int): Number of groups to divide channels in.
        data_format (str): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width].
        name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Out (Tensor): Rearranged tensor keeping the original tensor shape.

    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn.functional as F
            x = paddle.arange(0, 0.6, 0.1, 'float32')
            x = paddle.reshape(x, [1, 6, 1, 1])
            # [[[[0.        ]],
            #   [[0.10000000]],
            #   [[0.20000000]],
            #   [[0.30000001]],
            #   [[0.40000001]],
            #   [[0.50000000]]]]
            y = F.channel_shuffle(x, 3)
            # [[[[0.        ]],
            #   [[0.20000000]],
            #   [[0.40000001]],
            #   [[0.10000000]],
            #   [[0.30000001]],
            #   [[0.50000000]]]]
    """
    if len(x.shape) != 4:
        raise ValueError(
            "Input x should be 4D tensor, but received x with the shape of {}".
            format(x.shape))

    if not isinstance(groups, int):
        raise TypeError("groups must be int type")

    if groups <= 0:
        raise ValueError("groups must be positive")

    if data_format not in ["NCHW", "NHWC"]:
466 467 468
        raise ValueError(
            "Attr(data_format) should be 'NCHW' or 'NHWC'."
            "But recevie Attr(data_format): {} ".format(data_format))
469 470

    if _non_static_mode():
471 472
        return _legacy_C_ops.channel_shuffle(x, "groups", groups, "data_format",
                                             data_format)
473 474 475 476

    helper = LayerHelper("channel_shuffle", **locals())
    check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'channel_shuffle')
    out = helper.create_variable_for_type_inference(dtype=x.dtype)
477 478 479 480 481 482 483
    helper.append_op(type="channel_shuffle",
                     inputs={"X": x},
                     outputs={"Out": out},
                     attrs={
                         "groups": groups,
                         "data_format": data_format
                     })
484
    return out