• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2020 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15import numpy as np
16
17import mindspore.common.dtype as mstype
18import mindspore.context as context
19import mindspore.nn as nn
20from mindspore import Tensor
21from mindspore.common.api import ms_function
22
23context.set_context(device_target="Ascend")
24
25
26class Net(nn.Cell):
27    def __init__(self):
28        super(Net, self).__init__()
29        self.image_gradients = nn.ImageGradients()
30
31    @ms_function
32    def construct(self, x):
33        return self.image_gradients(x)
34
35
36def test_image_gradients():
37    image = Tensor(np.array([[[[1, 2], [3, 4]]]]), dtype=mstype.int32)
38    expected_dy = np.array([[[[2, 2], [0, 0]]]]).astype(np.int32)
39    expected_dx = np.array([[[[1, 0], [1, 0]]]]).astype(np.int32)
40    net = Net()
41    dy, dx = net(image)
42    assert not np.any(dx.asnumpy() - expected_dx)
43    assert not np.any(dy.asnumpy() - expected_dy)
44
45
46def test_image_gradients_multi_channel_depth():
47    # 4 x 2 x 2 x 2
48    dtype = mstype.int32
49    image = Tensor(np.array([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]],
50                             [[[3, 5], [7, 9]], [[11, 13], [15, 17]]],
51                             [[[5, 10], [15, 20]], [[25, 30], [35, 40]]],
52                             [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]]), dtype=dtype)
53    expected_dy = Tensor(np.array([[[[2, 2], [0, 0]], [[2, 2], [0, 0]]],
54                                   [[[4, 4], [0, 0]], [[4, 4], [0, 0]]],
55                                   [[[10, 10], [0, 0]], [[10, 10], [0, 0]]],
56                                   [[[20, 20], [0, 0]], [[20, 20], [0, 0]]]]), dtype=dtype)
57    expected_dx = Tensor(np.array([[[[1, 0], [1, 0]], [[1, 0], [1, 0]]],
58                                   [[[2, 0], [2, 0]], [[2, 0], [2, 0]]],
59                                   [[[5, 0], [5, 0]], [[5, 0], [5, 0]]],
60                                   [[[10, 0], [10, 0]], [[10, 0], [10, 0]]]]), dtype=dtype)
61    net = Net()
62    dy, dx = net(image)
63
64    assert not np.any(dx.asnumpy() - expected_dx.asnumpy())
65    assert not np.any(dy.asnumpy() - expected_dy.asnumpy())
66