• 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"""
15Testing FiveCrop in DE
16"""
17import pytest
18import numpy as np
19
20import mindspore.dataset as ds
21import mindspore.dataset.transforms.py_transforms
22import mindspore.dataset.vision.py_transforms as vision
23from mindspore import log as logger
24from util import visualize_list, save_and_check_md5
25
26DATA_DIR = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
27SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
28
29GENERATE_GOLDEN = False
30
31def test_five_crop_op(plot=False):
32    """
33    Test FiveCrop
34    """
35    logger.info("test_five_crop")
36
37    # First dataset
38    data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
39    transforms_1 = [
40        vision.Decode(),
41        vision.ToTensor(),
42    ]
43    transform_1 = mindspore.dataset.transforms.py_transforms.Compose(transforms_1)
44    data1 = data1.map(operations=transform_1, input_columns=["image"])
45
46    # Second dataset
47    data2 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
48    transforms_2 = [
49        vision.Decode(),
50        vision.FiveCrop(200),
51        lambda *images: np.stack([vision.ToTensor()(image) for image in images])  # 4D stack of 5 images
52    ]
53    transform_2 = mindspore.dataset.transforms.py_transforms.Compose(transforms_2)
54    data2 = data2.map(operations=transform_2, input_columns=["image"])
55
56    num_iter = 0
57    for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1, output_numpy=True),
58                            data2.create_dict_iterator(num_epochs=1, output_numpy=True)):
59        num_iter += 1
60        image_1 = (item1["image"].transpose(1, 2, 0) * 255).astype(np.uint8)
61        image_2 = item2["image"]
62
63        logger.info("shape of image_1: {}".format(image_1.shape))
64        logger.info("shape of image_2: {}".format(image_2.shape))
65
66        logger.info("dtype of image_1: {}".format(image_1.dtype))
67        logger.info("dtype of image_2: {}".format(image_2.dtype))
68        if plot:
69            visualize_list(np.array([image_1]*5), (image_2 * 255).astype(np.uint8).transpose(0, 2, 3, 1))
70
71        # The output data should be of a 4D tensor shape, a stack of 5 images.
72        assert len(image_2.shape) == 4
73        assert image_2.shape[0] == 5
74
75
76def test_five_crop_error_msg():
77    """
78    Test FiveCrop error message.
79    """
80    logger.info("test_five_crop_error_msg")
81
82    data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
83    transforms = [
84        vision.Decode(),
85        vision.FiveCrop(200),
86        vision.ToTensor()
87    ]
88    transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
89    data = data.map(operations=transform, input_columns=["image"])
90
91    with pytest.raises(RuntimeError) as info:
92        for _ in data:
93            pass
94    error_msg = "TypeError: __call__() takes 2 positional arguments but 6 were given"
95
96    # error msg comes from ToTensor()
97    assert error_msg in str(info.value)
98
99
100def test_five_crop_md5():
101    """
102    Test FiveCrop with md5 check
103    """
104    logger.info("test_five_crop_md5")
105
106    # First dataset
107    data = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"], shuffle=False)
108    transforms = [
109        vision.Decode(),
110        vision.FiveCrop(100),
111        lambda *images: np.stack([vision.ToTensor()(image) for image in images])  # 4D stack of 5 images
112    ]
113    transform = mindspore.dataset.transforms.py_transforms.Compose(transforms)
114    data = data.map(operations=transform, input_columns=["image"])
115    # Compare with expected md5 from images
116    filename = "five_crop_01_result.npz"
117    save_and_check_md5(data, filename, generate_golden=GENERATE_GOLDEN)
118
119
120if __name__ == "__main__":
121    test_five_crop_op(plot=True)
122    test_five_crop_error_msg()
123    test_five_crop_md5()
124