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""" 16Testing Normalize op in DE 17""" 18import numpy as np 19import mindspore.dataset as ds 20import mindspore.dataset.transforms.py_transforms 21import mindspore.dataset.vision.c_transforms as c_vision 22import mindspore.dataset.vision.py_transforms as py_vision 23from mindspore import log as logger 24from util import diff_mse, visualize_image 25 26DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"] 27SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json" 28 29GENERATE_GOLDEN = False 30 31 32def normalizepad_np(image, mean, std): 33 """ 34 Apply the normalize+pad 35 """ 36 # DE decodes the image in RGB by default, hence 37 # the values here are in RGB 38 image = np.array(image, np.float32) 39 image = image - np.array(mean) 40 image = image * (1.0 / np.array(std)) 41 zeros = np.zeros([image.shape[0], image.shape[1], 1], dtype=np.float32) 42 output = np.concatenate((image, zeros), axis=2) 43 return output 44 45 46def test_normalizepad_op_c(plot=False): 47 """ 48 Test NormalizePad in cpp transformations 49 """ 50 logger.info("Test Normalize in cpp") 51 mean = [121.0, 115.0, 100.0] 52 std = [70.0, 68.0, 71.0] 53 # define map operations 54 decode_op = c_vision.Decode() 55 normalizepad_op = c_vision.NormalizePad(mean, std) 56 57 # First dataset 58 data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False) 59 data1 = data1.map(operations=decode_op, input_columns=["image"]) 60 data1 = data1.map(operations=normalizepad_op, input_columns=["image"]) 61 62 # Second dataset 63 data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False) 64 data2 = data2.map(operations=decode_op, input_columns=["image"]) 65 66 num_iter = 0 67 for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True), 68 data2.create_dict_iterator(num_epochs=1, output_numpy=True)): 69 image_de_normalized = item1["image"] 70 image_original = item2["image"] 71 image_np_normalized = normalizepad_np(image_original, mean, std) 72 mse = diff_mse(image_de_normalized, image_np_normalized) 73 logger.info("image_{}, mse: {}".format(num_iter + 1, mse)) 74 assert mse < 0.01 75 if plot: 76 visualize_image(image_original, image_de_normalized, mse, image_np_normalized) 77 num_iter += 1 78 79 80def test_normalizepad_op_py(plot=False): 81 """ 82 Test NormalizePad in python transformations 83 """ 84 logger.info("Test Normalize in python") 85 mean = [0.475, 0.45, 0.392] 86 std = [0.275, 0.267, 0.278] 87 # define map operations 88 transforms = [ 89 py_vision.Decode(), 90 py_vision.ToTensor() 91 ] 92 transform = mindspore.dataset.transforms.py_transforms.Compose(transforms) 93 normalizepad_op = py_vision.NormalizePad(mean, std) 94 95 # First dataset 96 data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False) 97 data1 = data1.map(operations=transform, input_columns=["image"]) 98 data1 = data1.map(operations=normalizepad_op, input_columns=["image"]) 99 100 # Second dataset 101 data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False) 102 data2 = data2.map(operations=transform, input_columns=["image"]) 103 104 num_iter = 0 105 for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True), 106 data2.create_dict_iterator(num_epochs=1, output_numpy=True)): 107 image_de_normalized = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8) 108 image_np_normalized = (normalizepad_np(item2["image"].transpose(1, 2, 0), mean, std) * 255).astype(np.uint8) 109 image_original = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8) 110 mse = diff_mse(image_de_normalized, image_np_normalized) 111 logger.info("image_{}, mse: {}".format(num_iter + 1, mse)) 112 assert mse < 0.01 113 if plot: 114 visualize_image(image_original, image_de_normalized, mse, image_np_normalized) 115 num_iter += 1 116 117 118def test_decode_normalizepad_op(): 119 """ 120 Test Decode op followed by NormalizePad op 121 """ 122 logger.info("Test [Decode, Normalize] in one Map") 123 124 data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image", "label"], num_parallel_workers=1, 125 shuffle=False) 126 127 # define map operations 128 decode_op = c_vision.Decode() 129 normalizepad_op = c_vision.NormalizePad([121.0, 115.0, 100.0], [70.0, 68.0, 71.0], "float16") 130 131 # apply map operations on images 132 data1 = data1.map(operations=[decode_op, normalizepad_op], input_columns=["image"]) 133 134 num_iter = 0 135 for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True): 136 logger.info("Looping inside iterator {}".format(num_iter)) 137 assert item["image"].dtype == np.float16 138 num_iter += 1 139 140 141def test_normalizepad_exception_unequal_size_c(): 142 """ 143 Test NormalizePad in c transformation: len(mean) != len(std) 144 expected to raise ValueError 145 """ 146 logger.info("test_normalize_exception_unequal_size_c") 147 try: 148 _ = c_vision.NormalizePad([100, 250, 125], [50, 50, 75, 75]) 149 except ValueError as e: 150 logger.info("Got an exception in DE: {}".format(str(e))) 151 assert str(e) == "Length of mean and std must be equal." 152 153 try: 154 _ = c_vision.NormalizePad([100, 250, 125], [50, 50, 75], 1) 155 except TypeError as e: 156 logger.info("Got an exception in DE: {}".format(str(e))) 157 assert str(e) == "dtype should be string." 158 159 try: 160 _ = c_vision.NormalizePad([100, 250, 125], [50, 50, 75], "") 161 except ValueError as e: 162 logger.info("Got an exception in DE: {}".format(str(e))) 163 assert str(e) == "dtype only support float32 or float16." 164 165 166def test_normalizepad_exception_unequal_size_py(): 167 """ 168 Test NormalizePad in python transformation: len(mean) != len(std) 169 expected to raise ValueError 170 """ 171 logger.info("test_normalizepad_exception_unequal_size_py") 172 try: 173 _ = py_vision.NormalizePad([0.50, 0.30, 0.75], [0.18, 0.32, 0.71, 0.72]) 174 except ValueError as e: 175 logger.info("Got an exception in DE: {}".format(str(e))) 176 assert str(e) == "Length of mean and std must be equal." 177 178 try: 179 _ = py_vision.NormalizePad([0.50, 0.30, 0.75], [0.18, 0.32, 0.71], 1) 180 except TypeError as e: 181 logger.info("Got an exception in DE: {}".format(str(e))) 182 assert str(e) == "dtype should be string." 183 184 try: 185 _ = py_vision.NormalizePad([0.50, 0.30, 0.75], [0.18, 0.32, 0.71], "") 186 except ValueError as e: 187 logger.info("Got an exception in DE: {}".format(str(e))) 188 assert str(e) == "dtype only support float32 or float16." 189 190 191def test_normalizepad_exception_invalid_range_py(): 192 """ 193 Test NormalizePad in python transformation: value is not in range [0,1] 194 expected to raise ValueError 195 """ 196 logger.info("test_normalizepad_exception_invalid_range_py") 197 try: 198 _ = py_vision.NormalizePad([0.75, 1.25, 0.5], [0.1, 0.18, 1.32]) 199 except ValueError as e: 200 logger.info("Got an exception in DE: {}".format(str(e))) 201 assert "Input mean_value is not within the required interval of [0.0, 1.0]." in str(e) 202