1# Copyright 2021 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 16import numpy as np 17import pytest 18 19import mindspore.context as context 20from mindspore import Tensor 21from mindspore.ops import operations as P 22 23 24@pytest.mark.level0 25@pytest.mark.platform_x86_cpu 26@pytest.mark.env_onecard 27def test_roi_align(): 28 def roi_align_case(data_type): 29 context.set_context(mode=context.PYNATIVE_MODE, device_target="CPU") 30 x = Tensor(np.array([[ 31 [[1, 2, 3, 4, 5, 6], 32 [7, 8, 9, 10, 11, 12], 33 [13, 14, 15, 16, 17, 18], 34 [19, 20, 21, 22, 23, 24], 35 [25, 26, 27, 28, 29, 30], 36 [31, 32, 33, 34, 35, 36]] 37 ]], data_type)) 38 39 # test case 1 40 rois = Tensor(np.array([[0, -2.0, -2.0, 21.0, 21.0]], data_type)) 41 pooled_height, pooled_width, spatial_scale, sample_num = 3, 3, 0.25, 2 42 roi_align = P.ROIAlign(pooled_height, pooled_width, 43 spatial_scale, sample_num, 1) 44 output = roi_align(x, rois) 45 #print(output) 46 expect = [[[[4.5, 6.5, 8.5], 47 [16.5, 18.5, 20.5], 48 [28.5, 30.5, 32.5]]]] 49 assert (output.asnumpy() == expect).all() 50 51 # test case 2 52 rois = Tensor(np.array([[0, -2.0, -2.0, 22.0, 22.0]], data_type)) 53 pooled_height, pooled_width, spatial_scale, sample_num = 3, 3, 0.25, 2 54 roi_align = P.ROIAlign(pooled_height, pooled_width, 55 spatial_scale, sample_num, 0) 56 output = roi_align(x, rois) 57 #print(output) 58 expect = [[[[4.5, 6.5, 8.5], 59 [16.5, 18.5, 20.5], 60 [28.5, 30.5, 32.5]]]] 61 assert (output.asnumpy() == expect).all() 62 63 # test case 3 64 pooled_height, pooled_width, spatial_scale, sample_num = 2, 2, 1.0, -1 65 rois = Tensor(np.array([[0, -2.0, -2.0, 22.0, 22.0]], data_type)) 66 roi_align = P.ROIAlign(pooled_height, pooled_width, 67 spatial_scale, sample_num, 0) 68 output = roi_align(x, rois) 69 #print(output) 70 expect = [[[[6.295, 0.], 71 [0., 0.]]]] 72 np.testing.assert_almost_equal(output.asnumpy(), expect, decimal=2) 73 74 roi_align_case(np.float32) 75 roi_align_case(np.float16) 76