test_random_vertical_flip.py 8.1 KB
Newer Older
Z
zhunaipan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""
Testing the random vertical flip op in DE
"""
import numpy as np
import mindspore.dataset as ds
N
nhussain 已提交
20 21 22
import mindspore.dataset.transforms.py_transforms
import mindspore.dataset.vision.c_transforms as c_vision
import mindspore.dataset.vision.py_transforms as py_vision
Z
zhunaipan 已提交
23
from mindspore import log as logger
T
Tinazhang 已提交
24
from util import save_and_check_md5, visualize_list, visualize_image, diff_mse, \
25 26 27
    config_get_set_seed, config_get_set_num_parallel_workers

GENERATE_GOLDEN = False
Z
zhunaipan 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"


def v_flip(image):
    """
    Apply the random_vertical
    """

    # with the seed provided in this test case, it will always flip.
    # that's why we flip here too
    image = image[::-1, :, :]
    return image


T
Tinazhang 已提交
44
def test_random_vertical_op(plot=False):
Z
zhunaipan 已提交
45
    """
46
    Test random_vertical with default probability
Z
zhunaipan 已提交
47 48 49 50 51
    """
    logger.info("Test random_vertical")

    # First dataset
    data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
52
    decode_op = c_vision.Decode()
53
    random_vertical_op = c_vision.RandomVerticalFlip(1.0)
Z
zhunaipan 已提交
54 55 56 57 58 59 60 61
    data1 = data1.map(input_columns=["image"], operations=decode_op)
    data1 = data1.map(input_columns=["image"], operations=random_vertical_op)

    # Second dataset
    data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    data2 = data2.map(input_columns=["image"], operations=decode_op)

    num_iter = 0
62
    for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
Z
zhunaipan 已提交
63 64 65 66 67 68 69 70 71

        # with the seed value, we can only guarantee the first number generated
        if num_iter > 0:
            break

        image_v_flipped = item1["image"]
        image = item2["image"]
        image_v_flipped_2 = v_flip(image)

72 73
        mse = diff_mse(image_v_flipped, image_v_flipped_2)
        assert mse == 0
Z
zhunaipan 已提交
74 75
        logger.info("image_{}, mse: {}".format(num_iter + 1, mse))
        num_iter += 1
T
Tinazhang 已提交
76 77 78
        if plot:
            visualize_image(image, image_v_flipped, mse, image_v_flipped_2)

Z
zhunaipan 已提交
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
def test_random_vertical_valid_prob_c():
    """
    Test RandomVerticalFlip op with c_transforms: valid non-default input, expect to pass
    """
    logger.info("test_random_vertical_valid_prob_c")
    original_seed = config_get_set_seed(0)
    original_num_parallel_workers = config_get_set_num_parallel_workers(1)

    # Generate dataset
    data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    decode_op = c_vision.Decode()
    random_horizontal_op = c_vision.RandomVerticalFlip(0.8)
    data = data.map(input_columns=["image"], operations=decode_op)
    data = data.map(input_columns=["image"], operations=random_horizontal_op)

    filename = "random_vertical_01_c_result.npz"
    save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)

    # Restore config setting
    ds.config.set_seed(original_seed)
    ds.config.set_num_parallel_workers(original_num_parallel_workers)

T
Tinazhang 已提交
102

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
def test_random_vertical_valid_prob_py():
    """
    Test RandomVerticalFlip op with py_transforms: valid non-default input, expect to pass
    """
    logger.info("test_random_vertical_valid_prob_py")
    original_seed = config_get_set_seed(0)
    original_num_parallel_workers = config_get_set_num_parallel_workers(1)

    # Generate dataset
    data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    transforms = [
        py_vision.Decode(),
        py_vision.RandomVerticalFlip(0.8),
        py_vision.ToTensor()
    ]
N
nhussain 已提交
118 119
    transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
    data = data.map(input_columns=["image"], operations=transform)
120 121 122 123 124 125 126 127

    filename = "random_vertical_01_py_result.npz"
    save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)

    # Restore config setting
    ds.config.set_seed(original_seed)
    ds.config.set_num_parallel_workers(original_num_parallel_workers)

T
Tinazhang 已提交
128

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
def test_random_vertical_invalid_prob_c():
    """
    Test RandomVerticalFlip op in c_transforms: invalid input, expect to raise error
    """
    logger.info("test_random_vertical_invalid_prob_c")

    # Generate dataset
    data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    decode_op = c_vision.Decode()
    try:
        # Note: Valid range of prob should be [0.0, 1.0]
        random_horizontal_op = c_vision.RandomVerticalFlip(1.5)
        data = data.map(input_columns=["image"], operations=decode_op)
        data = data.map(input_columns=["image"], operations=random_horizontal_op)
    except ValueError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
N
nhussain 已提交
145
        assert 'Input prob is not within the required interval of (0.0 to 1.0).' in str(e)
146

T
Tinazhang 已提交
147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
def test_random_vertical_invalid_prob_py():
    """
    Test RandomVerticalFlip op in py_transforms: invalid input, expect to raise error
    """
    logger.info("test_random_vertical_invalid_prob_py")

    # Generate dataset
    data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    try:
        transforms = [
            py_vision.Decode(),
            # Note: Valid range of prob should be [0.0, 1.0]
            py_vision.RandomVerticalFlip(1.5),
            py_vision.ToTensor()
        ]
N
nhussain 已提交
163 164
        transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
        data = data.map(input_columns=["image"], operations=transform)
165 166
    except ValueError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
N
nhussain 已提交
167
        assert 'Input prob is not within the required interval of (0.0 to 1.0).' in str(e)
168

T
Tinazhang 已提交
169

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
def test_random_vertical_comp(plot=False):
    """
    Test test_random_vertical_flip and compare between python and c image augmentation ops
    """
    logger.info("test_random_vertical_comp")

    # First dataset
    data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    decode_op = c_vision.Decode()
    # Note: The image must be flipped if prob is set to be 1
    random_horizontal_op = c_vision.RandomVerticalFlip(1)
    data1 = data1.map(input_columns=["image"], operations=decode_op)
    data1 = data1.map(input_columns=["image"], operations=random_horizontal_op)

    # Second dataset
    data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    transforms = [
        py_vision.Decode(),
        # Note: The image must be flipped if prob is set to be 1
        py_vision.RandomVerticalFlip(1),
        py_vision.ToTensor()
    ]
N
nhussain 已提交
192 193
    transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
    data2 = data2.map(input_columns=["image"], operations=transform)
194 195 196

    images_list_c = []
    images_list_py = []
197
    for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
198 199 200 201 202 203 204 205 206
        image_c = item1["image"]
        image_py = (item2["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
        images_list_c.append(image_c)
        images_list_py.append(image_py)

        # Check if the output images are the same
        mse = diff_mse(image_c, image_py)
        assert mse < 0.001
    if plot:
T
Tinazhang 已提交
207
        visualize_list(images_list_c, images_list_py, visualize_mode=2)
208

Z
zhunaipan 已提交
209 210

if __name__ == "__main__":
T
Tinazhang 已提交
211
    test_random_vertical_op(plot=True)
212 213 214 215
    test_random_vertical_valid_prob_c()
    test_random_vertical_valid_prob_py()
    test_random_vertical_invalid_prob_c()
    test_random_vertical_invalid_prob_py()
T
Tinazhang 已提交
216
    test_random_vertical_comp(plot=True)