test_random_posterize.py 5.9 KB
Newer Older
I
islam_amin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright 2020 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 RandomPosterize op in DE
"""
I
islam_amin 已提交
18
import numpy as np
I
islam_amin 已提交
19 20 21 22
import mindspore.dataset as ds
import mindspore.dataset.transforms.vision.c_transforms as c_vision
from mindspore import log as logger
from util import visualize_list, save_and_check_md5, \
I
islam_amin 已提交
23
    config_get_set_seed, config_get_set_num_parallel_workers, diff_mse
I
islam_amin 已提交
24 25 26 27 28 29 30

GENERATE_GOLDEN = False

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"


I
islam_amin 已提交
31
def test_random_posterize_op_c(plot=False, run_golden=False):
I
islam_amin 已提交
32
    """
I
islam_amin 已提交
33 34
    Test RandomPosterize in C transformations (uses assertion on mse as using md5 could have jpeg decoding
    inconsistencies)
I
islam_amin 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    """
    logger.info("test_random_posterize_op_c")

    original_seed = config_get_set_seed(55)
    original_num_parallel_workers = config_get_set_num_parallel_workers(1)

    # define map operations
    transforms1 = [
        c_vision.Decode(),
        c_vision.RandomPosterize((1, 8))
    ]

    #  First dataset
    data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    data1 = data1.map(input_columns=["image"], operations=transforms1)
    #  Second dataset
    data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    data2 = data2.map(input_columns=["image"], operations=[c_vision.Decode()])

    image_posterize = []
    image_original = []
    for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
        image1 = item1["image"]
        image2 = item2["image"]
        image_posterize.append(image1)
        image_original.append(image2)

I
islam_amin 已提交
62 63 64 65 66 67
    # check mse as md5 can be inconsistent.
    # mse = 2.9668956 is calculated from
    # a thousand runs of diff_mse(np.array(image_original), np.array(image_posterize)) that all produced the same mse.
    # allow for an error of 0.0000005
    assert abs(2.9668956 - diff_mse(np.array(image_original), np.array(image_posterize))) <= 0.0000005

I
islam_amin 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80
    if run_golden:
        # check results with md5 comparison
        filename = "random_posterize_01_result_c.npz"
        save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)

    if plot:
        visualize_list(image_original, image_posterize)

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


I
islam_amin 已提交
81
def test_random_posterize_op_fixed_point_c(plot=False, run_golden=True):
I
islam_amin 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    """
    Test RandomPosterize in C transformations with fixed point
    """
    logger.info("test_random_posterize_op_c")

    # define map operations
    transforms1 = [
        c_vision.Decode(),
        c_vision.RandomPosterize(1)
    ]

    #  First dataset
    data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    data1 = data1.map(input_columns=["image"], operations=transforms1)
    #  Second dataset
    data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
    data2 = data2.map(input_columns=["image"], operations=[c_vision.Decode()])

    image_posterize = []
    image_original = []
    for item1, item2 in zip(data1.create_dict_iterator(), data2.create_dict_iterator()):
        image1 = item1["image"]
        image2 = item2["image"]
        image_posterize.append(image1)
        image_original.append(image2)

    if run_golden:
        # check results with md5 comparison
        filename = "random_posterize_fixed_point_01_result_c.npz"
        save_and_check_md5(data1, filename, generate_golden=GENERATE_GOLDEN)

    if plot:
        visualize_list(image_original, image_posterize)


def test_random_posterize_exception_bit():
    """
    Test RandomPosterize: out of range input bits and invalid type
    """
    logger.info("test_random_posterize_exception_bit")
    # Test max > 8
    try:
        _ = c_vision.RandomPosterize((1, 9))
    except ValueError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
        assert str(e) == "Input is not within the required interval of (1 to 8)."
    # Test min < 1
    try:
        _ = c_vision.RandomPosterize((0, 7))
    except ValueError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
        assert str(e) == "Input is not within the required interval of (1 to 8)."
    # Test max < min
    try:
        _ = c_vision.RandomPosterize((8, 1))
    except ValueError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
        assert str(e) == "Input is not within the required interval of (1 to 8)."
    # Test wrong type (not uint8)
    try:
        _ = c_vision.RandomPosterize(1.1)
    except TypeError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
        assert str(e) == "Argument bits with value 1.1 is not of type (<class 'list'>, <class 'tuple'>, <class 'int'>)."
    # Test wrong number of bits
    try:
        _ = c_vision.RandomPosterize((1, 1, 1))
    except TypeError as e:
        logger.info("Got an exception in DE: {}".format(str(e)))
        assert str(e) == "Size of bits should be a single integer or a list/tuple (min, max) of length 2."


if __name__ == "__main__":
I
islam_amin 已提交
155 156
    test_random_posterize_op_c(plot=False, run_golden=False)
    test_random_posterize_op_fixed_point_c(plot=False)
I
islam_amin 已提交
157
    test_random_posterize_exception_bit()