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""" 16Testing HorizontalFlip Python API 17""" 18import cv2 19 20import mindspore.dataset as ds 21import mindspore.dataset.vision.c_transforms as c_vision 22 23from mindspore import log as logger 24from util import visualize_image, diff_mse 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" 28IMAGE_FILE = "../data/dataset/apple.jpg" 29 30 31def test_horizontal_flip_pipeline(plot=False): 32 """ 33 Test HorizontalFlip of c_transforms 34 """ 35 logger.info("test_horizontal_flip_pipeline") 36 37 # First dataset 38 dataset1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, shuffle=False) 39 decode_op = c_vision.Decode() 40 horizontal_flip_op = c_vision.HorizontalFlip() 41 dataset1 = dataset1.map(operations=decode_op, input_columns=["image"]) 42 dataset1 = dataset1.map(operations=horizontal_flip_op, input_columns=["image"]) 43 44 # Second dataset 45 dataset2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False) 46 dataset2 = dataset2.map(operations=decode_op, input_columns=["image"]) 47 48 num_iter = 0 49 for data1, data2 in zip(dataset1.create_dict_iterator(num_epochs=1, output_numpy=True), 50 dataset2.create_dict_iterator(num_epochs=1, output_numpy=True)): 51 if num_iter > 0: 52 break 53 horizontal_flip_ms = data1["image"] 54 original = data2["image"] 55 horizontal_flip_cv = cv2.flip(original, 1) 56 mse = diff_mse(horizontal_flip_ms, horizontal_flip_cv) 57 logger.info("horizontal_flip_{}, mse: {}".format(num_iter + 1, mse)) 58 assert mse == 0 59 num_iter += 1 60 if plot: 61 visualize_image(original, horizontal_flip_ms, mse, horizontal_flip_cv) 62 63 64def test_horizontal_flip_eager(): 65 """ 66 Test HorizontalFlip with eager mode 67 """ 68 logger.info("test_horizontal_flip_eager") 69 img = cv2.imread(IMAGE_FILE) 70 71 img_ms = c_vision.HorizontalFlip()(img) 72 img_cv = cv2.flip(img, 1) 73 mse = diff_mse(img_ms, img_cv) 74 assert mse == 0 75 76 77if __name__ == "__main__": 78 test_horizontal_flip_pipeline(plot=False) 79 test_horizontal_flip_eager() 80