You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_image_gradients.py 2.7 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. # ============================================================================
  15. import numpy as np
  16. import mindspore.nn as nn
  17. import mindspore.context as context
  18. import mindspore.common.dtype as mstype
  19. from mindspore import Tensor
  20. from mindspore.common.api import ms_function
  21. context.set_context(device_target="Ascend")
  22. class Net(nn.Cell):
  23. def __init__(self):
  24. super(Net, self).__init__()
  25. self.image_gradients = nn.ImageGradients()
  26. @ms_function
  27. def construct(self, x):
  28. return self.image_gradients(x)
  29. def test_image_gradients():
  30. image = Tensor(np.array([[[[1, 2], [3, 4]]]]), dtype=mstype.int32)
  31. expected_dy = np.array([[[[2, 2], [0, 0]]]]).astype(np.int32)
  32. expected_dx = np.array([[[[1, 0], [1, 0]]]]).astype(np.int32)
  33. net = Net()
  34. dy, dx = net(image)
  35. assert np.any(dx.asnumpy() - expected_dx) == False
  36. assert np.any(dy.asnumpy() - expected_dy) == False
  37. def test_image_gradients_multi_channel_depth():
  38. # 4 x 2 x 2 x 2
  39. dtype = mstype.int32
  40. image = Tensor(np.array([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]],
  41. [[[3, 5], [7, 9]], [[11, 13], [15, 17]]],
  42. [[[5, 10], [15, 20]], [[25, 30], [35, 40]]],
  43. [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]]), dtype=dtype)
  44. expected_dy = Tensor(np.array([[[[2, 2], [0, 0]], [[2, 2], [0, 0]]],
  45. [[[4, 4], [0, 0]], [[4, 4], [0, 0]]],
  46. [[[10, 10], [0, 0]], [[10, 10], [0, 0]]],
  47. [[[20, 20], [0, 0]], [[20, 20], [0, 0]]]]), dtype=dtype)
  48. expected_dx = Tensor(np.array([[[[1, 0], [1, 0]], [[1, 0], [1, 0]]],
  49. [[[2, 0], [2, 0]], [[2, 0], [2, 0]]],
  50. [[[5, 0], [5, 0]], [[5, 0], [5, 0]]],
  51. [[[10, 0], [10, 0]], [[10, 0], [10, 0]]]]), dtype=dtype)
  52. net = Net()
  53. dy, dx = net(image)
  54. assert np.any(dx.asnumpy() - expected_dx.asnumpy()) == False
  55. assert np.any(dy.asnumpy() - expected_dy.asnumpy()) == False