• 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# ==============================================================================
15"""
16Testing Resize op in DE
17"""
18import pytest
19import mindspore.dataset as ds
20import mindspore.dataset.vision.c_transforms as vision
21import mindspore.dataset.vision.py_transforms as py_vision
22from mindspore.dataset.vision.utils import Inter
23from mindspore import log as logger
24from util import visualize_list, save_and_check_md5, \
25    config_get_set_seed, config_get_set_num_parallel_workers
26
27DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
28SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
29
30GENERATE_GOLDEN = False
31
32
33def test_resize_op(plot=False):
34    def test_resize_op_parameters(test_name, size, plot):
35        """
36        Test resize_op
37        """
38        logger.info("Test resize: {0}".format(test_name))
39        data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
40
41        # define map operations
42        decode_op = vision.Decode()
43        resize_op = vision.Resize(size)
44
45        # apply map operations on images
46        data1 = data1.map(operations=decode_op, input_columns=["image"])
47
48        data2 = data1.map(operations=resize_op, input_columns=["image"])
49        image_original = []
50        image_resized = []
51        for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
52                                data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
53            image_1 = item1["image"]
54            image_2 = item2["image"]
55            image_original.append(image_1)
56            image_resized.append(image_2)
57        if plot:
58            visualize_list(image_original, image_resized)
59
60    test_resize_op_parameters("Test single int for size", 10, plot=False)
61    test_resize_op_parameters("Test tuple for size", (10, 15), plot=False)
62
63def test_resize_op_ANTIALIAS():
64    """
65    Test resize_op
66    """
67    logger.info("Test resize for ANTIALIAS")
68    data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
69
70    # define map operations
71    decode_op = py_vision.Decode()
72    resize_op = py_vision.Resize(20, Inter.ANTIALIAS)
73
74    # apply map operations on images
75    data1 = data1.map(operations=[decode_op, resize_op, py_vision.ToTensor()], input_columns=["image"])
76
77    num_iter = 0
78    for _ in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
79        num_iter += 1
80    logger.info("use Resize by Inter.ANTIALIAS process {} images.".format(num_iter))
81
82def test_resize_md5(plot=False):
83    def test_resize_md5_parameters(test_name, size, filename, seed, plot):
84        """
85        Test Resize with md5 check
86        """
87        logger.info("Test Resize with md5 check: {0}".format(test_name))
88        original_seed = config_get_set_seed(seed)
89        original_num_parallel_workers = config_get_set_num_parallel_workers(1)
90
91        # Generate dataset
92        data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
93        decode_op = vision.Decode()
94        resize_op = vision.Resize(size)
95        data1 = data1.map(operations=decode_op, input_columns=["image"])
96        data2 = data1.map(operations=resize_op, input_columns=["image"])
97        image_original = []
98        image_resized = []
99        # Compare with expected md5 from images
100        save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)
101
102        for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
103                                data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
104            image_1 = item1["image"]
105            image_2 = item2["image"]
106            image_original.append(image_1)
107            image_resized.append(image_2)
108        if plot:
109            visualize_list(image_original, image_resized)
110
111        # Restore configuration
112        ds.config.set_seed(original_seed)
113        ds.config.set_num_parallel_workers(original_num_parallel_workers)
114
115    test_resize_md5_parameters("Test single int for size", 5, "resize_01_result.npz", 5, plot)
116    test_resize_md5_parameters("Test tuple for size", (5, 7), "resize_02_result.npz", 7, plot)
117
118
119def test_resize_op_invalid_input():
120    def test_invalid_input(test_name, size, interpolation, error, error_msg):
121        logger.info("Test Resize with bad input: {0}".format(test_name))
122        with pytest.raises(error) as error_info:
123            vision.Resize(size, interpolation)
124        assert error_msg in str(error_info.value)
125
126    test_invalid_input("invalid size parameter type as a single number", 4.5, Inter.LINEAR, TypeError,
127                       "Size should be a single integer or a list/tuple (h, w) of length 2.")
128    test_invalid_input("invalid size parameter shape", (2, 3, 4), Inter.LINEAR, TypeError,
129                       "Size should be a single integer or a list/tuple (h, w) of length 2.")
130    test_invalid_input("invalid size parameter type in a tuple", (2.3, 3), Inter.LINEAR, TypeError,
131                       "Argument size at dim 0 with value 2.3 is not of type [<class 'int'>]")
132    test_invalid_input("invalid Interpolation value", (2.3, 3), None, KeyError, "None")
133
134
135if __name__ == "__main__":
136    test_resize_op(plot=True)
137    test_resize_op_ANTIALIAS()
138    test_resize_md5(plot=True)
139    test_resize_op_invalid_input()
140