test_random_crop_and_resize_with_bbox.py 9.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 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 RandomCropAndResizeWithBBox op in DE
"""
import numpy as np
import mindspore.dataset as ds
N
nhussain 已提交
20
import mindspore.dataset.vision.c_transforms as c_vision
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

from mindspore import log as logger
from util import visualize_with_bounding_boxes, InvalidBBoxType, check_bad_bbox, \
    config_get_set_seed, config_get_set_num_parallel_workers, save_and_check_md5

GENERATE_GOLDEN = False

# Updated VOC dataset with correct annotations - DATA_DIR
DATA_DIR_VOC = "../data/dataset/testVOC2012_2"
# COCO dataset - DATA_DIR, ANNOTATION_DIR
DATA_DIR_COCO = ["../data/dataset/testCOCO/train/", "../data/dataset/testCOCO/annotations/train.json"]


def test_random_resized_crop_with_bbox_op_c(plot_vis=False):
    """
    Prints images and bboxes side by side with and without RandomResizedCropWithBBox Op applied,
    tests with MD5 check, expected to pass
    """
    logger.info("test_random_resized_crop_with_bbox_op_c")

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

    # Load dataset
Z
Zirui Wu 已提交
45 46
    dataVoc1 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
    dataVoc2 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
47 48 49 50

    test_op = c_vision.RandomResizedCropWithBBox((256, 512), (0.5, 0.5), (0.5, 0.5))

    # map to apply ops
X
xiefangqi 已提交
51 52
    dataVoc2 = dataVoc2.map(input_columns=["image", "bbox"],
                            output_columns=["image", "bbox"],
N
nhussain 已提交
53
                            column_order=["image", "bbox"],
54 55 56 57 58 59 60
                            operations=[test_op])

    filename = "random_resized_crop_with_bbox_01_c_result.npz"
    save_and_check_md5(dataVoc2, filename, generate_golden=GENERATE_GOLDEN)

    unaugSamp, augSamp = [], []

61
    for unAug, Aug in zip(dataVoc1.create_dict_iterator(num_epochs=1), dataVoc2.create_dict_iterator(num_epochs=1)):
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        unaugSamp.append(unAug)
        augSamp.append(Aug)

    if plot_vis:
        visualize_with_bounding_boxes(unaugSamp, augSamp)

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


def test_random_resized_crop_with_bbox_op_coco_c(plot_vis=False):
    """
    Prints images and bboxes side by side with and without RandomResizedCropWithBBox Op applied,
    Testing with Coco dataset
    """
    logger.info("test_random_resized_crop_with_bbox_op_coco_c")
    # load dataset
    dataCoco1 = ds.CocoDataset(DATA_DIR_COCO[0], annotation_file=DATA_DIR_COCO[1], task="Detection",
                               decode=True, shuffle=False)

    dataCoco2 = ds.CocoDataset(DATA_DIR_COCO[0], annotation_file=DATA_DIR_COCO[1], task="Detection",
                               decode=True, shuffle=False)

    test_op = c_vision.RandomResizedCropWithBBox((512, 512), (0.5, 1), (0.5, 1))

    dataCoco2 = dataCoco2.map(input_columns=["image", "bbox"],
                              output_columns=["image", "bbox"],
N
nhussain 已提交
90
                              column_order=["image", "bbox"],
91 92 93 94
                              operations=[test_op])

    unaugSamp, augSamp = [], []

95
    for unAug, Aug in zip(dataCoco1.create_dict_iterator(num_epochs=1), dataCoco2.create_dict_iterator(num_epochs=1)):
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        unaugSamp.append(unAug)
        augSamp.append(Aug)

    if plot_vis:
        visualize_with_bounding_boxes(unaugSamp, augSamp, "bbox")


def test_random_resized_crop_with_bbox_op_edge_c(plot_vis=False):
    """
    Prints images and bboxes side by side with and without RandomResizedCropWithBBox Op applied,
    tests on dynamically generated edge case, expected to pass
    """
    logger.info("test_random_resized_crop_with_bbox_op_edge_c")

    # Load dataset
Z
Zirui Wu 已提交
111 112
    dataVoc1 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
    dataVoc2 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
113 114 115 116

    test_op = c_vision.RandomResizedCropWithBBox((256, 512), (0.5, 0.5), (0.5, 0.5))

    # maps to convert data into valid edge case data
X
xiefangqi 已提交
117 118
    dataVoc1 = dataVoc1.map(input_columns=["image", "bbox"],
                            output_columns=["image", "bbox"],
N
nhussain 已提交
119
                            column_order=["image", "bbox"],
120 121 122
                            operations=[lambda img, bboxes: (img, np.array([[0, 0, img.shape[1], img.shape[0]]]).astype(bboxes.dtype))])

    # Test Op added to list of Operations here
X
xiefangqi 已提交
123 124
    dataVoc2 = dataVoc2.map(input_columns=["image", "bbox"],
                            output_columns=["image", "bbox"],
N
nhussain 已提交
125
                            column_order=["image", "bbox"],
126 127 128 129
                            operations=[lambda img, bboxes: (img, np.array([[0, 0, img.shape[1], img.shape[0]]]).astype(bboxes.dtype)), test_op])

    unaugSamp, augSamp = [], []

130
    for unAug, Aug in zip(dataVoc1.create_dict_iterator(num_epochs=1), dataVoc2.create_dict_iterator(num_epochs=1)):
131 132 133 134 135 136 137 138 139 140 141 142 143 144
        unaugSamp.append(unAug)
        augSamp.append(Aug)

    if plot_vis:
        visualize_with_bounding_boxes(unaugSamp, augSamp)


def test_random_resized_crop_with_bbox_op_invalid_c():
    """
    Tests RandomResizedCropWithBBox on invalid constructor parameters, expected to raise ValueError
    """
    logger.info("test_random_resized_crop_with_bbox_op_invalid_c")

    # Load dataset, only Augmented Dataset as test will raise ValueError
Z
Zirui Wu 已提交
145
    dataVoc2 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
146 147 148 149 150 151

    try:
        # If input range of scale is not in the order of (min, max), ValueError will be raised.
        test_op = c_vision.RandomResizedCropWithBBox((256, 512), (1, 0.5), (0.5, 0.5))

        # map to apply ops
X
xiefangqi 已提交
152 153
        dataVoc2 = dataVoc2.map(input_columns=["image", "bbox"],
                                output_columns=["image", "bbox"],
N
nhussain 已提交
154
                                column_order=["image", "bbox"],
155 156
                                operations=[test_op])

157
        for _ in dataVoc2.create_dict_iterator(num_epochs=1):
158 159 160 161
            break

    except ValueError as err:
        logger.info("Got an exception in DE: {}".format(str(err)))
N
nhussain 已提交
162
        assert "Input is not within the required interval of (0 to 16777216)." in str(err)
163 164 165 166 167 168 169 170


def test_random_resized_crop_with_bbox_op_invalid2_c():
    """
     Tests RandomResizedCropWithBBox Op on invalid constructor parameters, expected to raise ValueError
    """
    logger.info("test_random_resized_crop_with_bbox_op_invalid2_c")
    # Load dataset # only loading the to AugDataset as test will fail on this
Z
Zirui Wu 已提交
171
    dataVoc2 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
172 173 174 175 176 177

    try:
        # If input range of ratio is not in the order of (min, max), ValueError will be raised.
        test_op = c_vision.RandomResizedCropWithBBox((256, 512), (1, 1), (1, 0.5))

        # map to apply ops
X
xiefangqi 已提交
178 179
        dataVoc2 = dataVoc2.map(input_columns=["image", "bbox"],
                                output_columns=["image", "bbox"],
N
nhussain 已提交
180
                                column_order=["image", "bbox"],
181 182
                                operations=[test_op])

183
        for _ in dataVoc2.create_dict_iterator(num_epochs=1):
184 185 186 187
            break

    except ValueError as err:
        logger.info("Got an exception in DE: {}".format(str(err)))
N
nhussain 已提交
188
        assert "Input is not within the required interval of (0 to 16777216)." in str(err)
189 190 191 192 193 194 195 196 197


def test_random_resized_crop_with_bbox_op_bad_c():
    """
    Test RandomCropWithBBox op with invalid bounding boxes, expected to catch multiple errors.
    """
    logger.info("test_random_resized_crop_with_bbox_op_bad_c")
    test_op = c_vision.RandomResizedCropWithBBox((256, 512), (0.5, 0.5), (0.5, 0.5))

Z
Zirui Wu 已提交
198
    data_voc2 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
199
    check_bad_bbox(data_voc2, test_op, InvalidBBoxType.WidthOverflow, "bounding boxes is out of bounds of the image")
Z
Zirui Wu 已提交
200
    data_voc2 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
201
    check_bad_bbox(data_voc2, test_op, InvalidBBoxType.HeightOverflow, "bounding boxes is out of bounds of the image")
Z
Zirui Wu 已提交
202
    data_voc2 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
203
    check_bad_bbox(data_voc2, test_op, InvalidBBoxType.NegativeXY, "min_x")
Z
Zirui Wu 已提交
204
    data_voc2 = ds.VOCDataset(DATA_DIR_VOC, task="Detection", usage="train", shuffle=False, decode=True)
205 206 207 208
    check_bad_bbox(data_voc2, test_op, InvalidBBoxType.WrongShape, "4 features")


if __name__ == "__main__":
X
xiefangqi 已提交
209 210 211
    test_random_resized_crop_with_bbox_op_c(plot_vis=False)
    test_random_resized_crop_with_bbox_op_coco_c(plot_vis=False)
    test_random_resized_crop_with_bbox_op_edge_c(plot_vis=False)
212 213 214
    test_random_resized_crop_with_bbox_op_invalid_c()
    test_random_resized_crop_with_bbox_op_invalid2_c()
    test_random_resized_crop_with_bbox_op_bad_c()