test_random_vertical_flip.py 8.0 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
20 21
import mindspore.dataset.transforms.vision.c_transforms as c_vision
import mindspore.dataset.transforms.vision.py_transforms as py_vision
Z
zhunaipan 已提交
22
from mindspore import log as logger
T
Tinazhang 已提交
23
from util import save_and_check_md5, visualize_list, visualize_image, diff_mse, \
24 25 26
    config_get_set_seed, config_get_set_num_parallel_workers

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

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 已提交
43
def test_random_vertical_op(plot=False):
Z
zhunaipan 已提交
44
    """
45
    Test random_vertical with default probability
Z
zhunaipan 已提交
46 47 48 49 50
    """
    logger.info("Test random_vertical")

    # First dataset
    data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
51
    decode_op = c_vision.Decode()
52
    random_vertical_op = c_vision.RandomVerticalFlip(1.0)
Z
zhunaipan 已提交
53 54 55 56 57 58 59 60
    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
61
    for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
Z
zhunaipan 已提交
62 63 64 65 66 67 68 69 70

        # 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)

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

Z
zhunaipan 已提交
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
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 已提交
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
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()
    ]
    transform = py_vision.ComposeOp(transforms)
    data = data.map(input_columns=["image"], operations=transform())

    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 已提交
127

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
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 已提交
144
        assert 'Input prob is not within the required interval of (0.0 to 1.0).' in str(e)
145

T
Tinazhang 已提交
146

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
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()
        ]
        transform = py_vision.ComposeOp(transforms)
        data = data.map(input_columns=["image"], operations=transform())
    except ValueError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
N
nhussain 已提交
166
        assert 'Input prob is not within the required interval of (0.0 to 1.0).' in str(e)
167

T
Tinazhang 已提交
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
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()
    ]
    transform = py_vision.ComposeOp(transforms)
    data2 = data2.map(input_columns=["image"], operations=transform())

    images_list_c = []
    images_list_py = []
196
    for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
197 198 199 200 201 202 203 204 205
        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 已提交
206
        visualize_list(images_list_c, images_list_py, visualize_mode=2)
207

Z
zhunaipan 已提交
208 209

if __name__ == "__main__":
T
Tinazhang 已提交
210
    test_random_vertical_op(plot=True)
211 212 213 214
    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 已提交
215
    test_random_vertical_comp(plot=True)