"src/vscode:/vscode.git/clone" did not exist on "9dd6085b0ed49a90c8c2ec4297158d464c911c53"
test_transforms_processing.py 42.1 KB
Newer Older
1
2
3
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import os.path as osp
4
from unittest.mock import Mock
5
6
7
8
9

import numpy as np
import pytest

import mmcv
10
from mmcv.transforms import (TRANSFORMS, Normalize, Pad, RandomFlip,
Mashiro's avatar
Mashiro committed
11
                             RandomResize, Resize, TestTimeAug)
12
from mmcv.transforms.base import BaseTransform
13
14
15
16
17
18
19
20
21
22

try:
    import torch
except ModuleNotFoundError:
    torch = None
else:
    import torchvision

from numpy.testing import assert_array_almost_equal, assert_array_equal
from PIL import Image
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58


class TestNormalize:

    def test_normalize(self):
        img_norm_cfg = dict(
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.12, 57.375],
            to_rgb=True)
        transform = Normalize(**img_norm_cfg)
        results = dict()
        img = mmcv.imread(
            osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
        original_img = copy.deepcopy(img)
        results['img'] = img
        results = transform(results)
        mean = np.array(img_norm_cfg['mean'])
        std = np.array(img_norm_cfg['std'])
        converted_img = (original_img[..., ::-1] - mean) / std
        assert np.allclose(results['img'], converted_img)

    def test_repr(self):
        img_norm_cfg = dict(
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.12, 57.375],
            to_rgb=True)
        transform = Normalize(**img_norm_cfg)
        assert repr(transform) == ('Normalize(mean=[123.675 116.28  103.53 ], '
                                   'std=[58.395 57.12  57.375], to_rgb=True)')


class TestResize:

    def test_resize(self):
        data_info = dict(
            img=np.random.random((1333, 800, 3)),
59
            gt_seg_map=np.random.random((1333, 800, 3)),
60
61
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
90
91
92
93
94
95
96
97
98
99
100
101
            gt_bboxes=np.array([[0, 0, 112, 112]]),
            gt_keypoints=np.array([[[20, 50, 1]]]))

        with pytest.raises(AssertionError):
            transform = Resize(scale=None, scale_factor=None)
        with pytest.raises(TypeError):
            transform = Resize(scale_factor=[])
        # test scale is int
        transform = Resize(scale=2000)
        results = transform(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (2000, 2000)
        assert results['scale_factor'] == (2000 / 800, 2000 / 1333)

        # test scale is tuple
        transform = Resize(scale=(2000, 2000))
        results = transform(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (2000, 2000)
        assert results['scale_factor'] == (2000 / 800, 2000 / 1333)

        # test scale_factor is float
        transform = Resize(scale_factor=2.0)
        results = transform(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (2666, 1600)
        assert results['scale_factor'] == (2.0, 2.0)

        # test scale_factor is tuple
        transform = Resize(scale_factor=(1.5, 2))
        results = transform(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (2666, 1200)
        assert results['scale_factor'] == (1.5, 2)

        # test keep_ratio is True
        transform = Resize(scale=(2000, 2000), keep_ratio=True)
        results = transform(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (2000, 1200)
        assert results['scale_factor'] == (1200 / 800, 2000 / 1333)

        # test resize_bboxes/seg/kps
        transform = Resize(scale_factor=(1.5, 2))
        results = transform(copy.deepcopy(data_info))
        assert (results['gt_bboxes'] == np.array([[0, 0, 168, 224]])).all()
        assert (results['gt_keypoints'] == np.array([[[30, 100, 1]]])).all()
102
        assert results['gt_seg_map'].shape[:2] == (2666, 1200)
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

        # test clip_object_border = False
        data_info = dict(
            img=np.random.random((300, 400, 3)),
            gt_bboxes=np.array([[200, 150, 600, 450]]))
        transform = Resize(scale=(200, 150), clip_object_border=False)
        results = transform(data_info)
        assert (results['gt_bboxes'] == np.array([100, 75, 300, 225])).all()

    def test_repr(self):
        transform = Resize(scale=(2000, 2000), keep_ratio=True)
        assert repr(transform) == ('Resize(scale=(2000, 2000), '
                                   'scale_factor=None, keep_ratio=True, '
                                   'clip_object_border=True), backend=cv2), '
                                   'interpolation=bilinear)')


class TestPad:

    def test_pad(self):
        # test size and size_divisor are both set
        with pytest.raises(AssertionError):
            Pad(size=(10, 10), size_divisor=2)

        # test size and size_divisor are both None
        with pytest.raises(AssertionError):
            Pad(size=None, size_divisor=None)

        # test size and pad_to_square are both None
        with pytest.raises(AssertionError):
            Pad(size=(10, 10), pad_to_square=True)

        # test pad_val is not int or tuple
        with pytest.raises(AssertionError):
            Pad(size=(10, 10), pad_val=[])

        # test padding_mode is not 'constant', 'edge', 'reflect' or 'symmetric'
        with pytest.raises(AssertionError):
            Pad(size=(10, 10), padding_mode='edg')

        data_info = dict(
            img=np.random.random((1333, 800, 3)),
145
            gt_seg_map=np.random.random((1333, 800, 3)),
146
147
148
            gt_bboxes=np.array([[0, 0, 112, 112]]),
            gt_keypoints=np.array([[[20, 50, 1]]]))

149
        # test pad img / gt_seg_map with size
150
151
152
        trans = Pad(size=(1200, 2000))
        results = trans(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (2000, 1200)
153
        assert results['gt_seg_map'].shape[:2] == (2000, 1200)
154

155
        # test pad img/gt_seg_map with size_divisor
156
157
158
        trans = Pad(size_divisor=11)
        results = trans(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (1342, 803)
159
        assert results['gt_seg_map'].shape[:2] == (1342, 803)
160

161
        # test pad img/gt_seg_map with pad_to_square
162
163
164
        trans = Pad(pad_to_square=True)
        results = trans(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (1333, 1333)
165
        assert results['gt_seg_map'].shape[:2] == (1333, 1333)
166

167
        # test pad img/gt_seg_map with pad_to_square and size_divisor
168
169
170
        trans = Pad(pad_to_square=True, size_divisor=11)
        results = trans(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (1342, 1342)
171
        assert results['gt_seg_map'].shape[:2] == (1342, 1342)
172

173
        # test pad img/gt_seg_map with pad_to_square and size_divisor
174
175
176
        trans = Pad(pad_to_square=True, size_divisor=11)
        results = trans(copy.deepcopy(data_info))
        assert results['img'].shape[:2] == (1342, 1342)
177
        assert results['gt_seg_map'].shape[:2] == (1342, 1342)
178
179
180
181
182
183
184
185

        # test padding_mode
        new_img = np.ones((1333, 800, 3))
        data_info['img'] = new_img
        trans = Pad(pad_to_square=True, padding_mode='edge')
        results = trans(copy.deepcopy(data_info))
        assert (results['img'] == np.ones((1333, 1333, 3))).all()

liukuikun's avatar
liukuikun committed
186
187
188
189
190
191
192
        # test pad_val is dict
        # test rgb image, size=(2000, 2000)
        trans = Pad(
            size=(2000, 2000),
            pad_val=dict(img=(12, 12, 12), seg=(10, 10, 10)))
        results = trans(copy.deepcopy(data_info))
        assert (results['img'][1333:2000, 800:2000, :] == 12).all()
193
        assert (results['gt_seg_map'][1333:2000, 800:2000, :] == 10).all()
liukuikun's avatar
liukuikun committed
194
195
196
197

        trans = Pad(size=(2000, 2000), pad_val=dict(img=(12, 12, 12)))
        results = trans(copy.deepcopy(data_info))
        assert (results['img'][1333:2000, 800:2000, :] == 12).all()
198
        assert (results['gt_seg_map'][1333:2000, 800:2000, :] == 255).all()
liukuikun's avatar
liukuikun committed
199
200
201
202
203
204
205

        # test rgb image, pad_to_square=True
        trans = Pad(
            pad_to_square=True,
            pad_val=dict(img=(12, 12, 12), seg=(10, 10, 10)))
        results = trans(copy.deepcopy(data_info))
        assert (results['img'][:, 800:1333, :] == 12).all()
206
        assert (results['gt_seg_map'][:, 800:1333, :] == 10).all()
liukuikun's avatar
liukuikun committed
207
208
209
210

        trans = Pad(pad_to_square=True, pad_val=dict(img=(12, 12, 12)))
        results = trans(copy.deepcopy(data_info))
        assert (results['img'][:, 800:1333, :] == 12).all()
211
        assert (results['gt_seg_map'][:, 800:1333, :] == 255).all()
liukuikun's avatar
liukuikun committed
212
213
214
215
216
217

        # test pad_val is int
        # test rgb image
        trans = Pad(size=(2000, 2000), pad_val=12)
        results = trans(copy.deepcopy(data_info))
        assert (results['img'][1333:2000, 800:2000, :] == 12).all()
218
        assert (results['gt_seg_map'][1333:2000, 800:2000, :] == 255).all()
liukuikun's avatar
liukuikun committed
219
220
        # test gray image
        new_img = np.random.random((1333, 800))
221
        data_info['img'] = new_img
liukuikun's avatar
liukuikun committed
222
        new_semantic_seg = np.random.random((1333, 800))
223
        data_info['gt_seg_map'] = new_semantic_seg
liukuikun's avatar
liukuikun committed
224
        trans = Pad(size=(2000, 2000), pad_val=12)
225
        results = trans(copy.deepcopy(data_info))
liukuikun's avatar
liukuikun committed
226
        assert (results['img'][1333:2000, 800:2000] == 12).all()
227
        assert (results['gt_seg_map'][1333:2000, 800:2000] == 255).all()
228
229
230
231
232
233

    def test_repr(self):
        trans = Pad(pad_to_square=True, size_divisor=11, padding_mode='edge')
        assert repr(trans) == (
            'Pad(size=None, size_divisor=11, pad_to_square=True, '
            "pad_val={'img': 0, 'seg': 255}), padding_mode=edge)")
234
235


236
237
238
239
240
241
242
243
244
245
246
247
248
class TestCenterCrop:

    @classmethod
    def setup_class(cls):
        img = mmcv.imread(
            osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
        cls.original_img = copy.deepcopy(img)
        seg = np.random.randint(0, 19, (300, 400)).astype(np.uint8)
        cls.gt_semantic_map = copy.deepcopy(seg)

    @staticmethod
    def reset_results(results, original_img, gt_semantic_map):
        results['img'] = copy.deepcopy(original_img)
249
        results['gt_seg_map'] = copy.deepcopy(gt_semantic_map)
250
251
252
253
        results['gt_bboxes'] = np.array([[0, 0, 210, 160],
                                         [200, 150, 400, 300]])
        results['gt_keypoints'] = np.array([[[20, 50, 1]], [[200, 150, 1]],
                                            [[300, 225, 1]]])
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
        return results

    @pytest.mark.skipif(
        condition=torch is None, reason='No torch in current env')
    def test_error(self):
        # test assertion if size is smaller than 0
        with pytest.raises(AssertionError):
            transform = dict(type='CenterCrop', crop_size=-1)
            TRANSFORMS.build(transform)

        # test assertion if size is tuple but one value is smaller than 0
        with pytest.raises(AssertionError):
            transform = dict(type='CenterCrop', crop_size=(224, -1))
            TRANSFORMS.build(transform)

        # test assertion if size is tuple and len(size) < 2
        with pytest.raises(AssertionError):
            transform = dict(type='CenterCrop', crop_size=(224, ))
            TRANSFORMS.build(transform)

        # test assertion if size is tuple len(size) > 2
        with pytest.raises(AssertionError):
            transform = dict(type='CenterCrop', crop_size=(224, 224, 3))
            TRANSFORMS.build(transform)

    def test_repr(self):
        # test repr
        transform = dict(type='CenterCrop', crop_size=224)
        center_crop_module = TRANSFORMS.build(transform)
        assert isinstance(repr(center_crop_module), str)

    def test_transform(self):
        results = {}
        self.reset_results(results, self.original_img, self.gt_semantic_map)

        # test CenterCrop when size is int
        transform = dict(type='CenterCrop', crop_size=224)
        center_crop_module = TRANSFORMS.build(transform)
        results = center_crop_module(results)
293
        assert results['img_shape'] == (224, 224)
294
        assert (results['img'] == self.original_img[38:262, 88:312, ...]).all()
295
296
        assert (results['gt_seg_map'] == self.gt_semantic_map[38:262,
                                                              88:312]).all()
297
298
299
300
301
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 122, 122], [112, 112, 224,
                                                     224]])).all()
        assert np.equal(
            results['gt_keypoints'],
302
            np.array([[[0, 12, 0]], [[112, 112, 1]], [[212, 187, 1]]])).all()
303
304
305
306
307
308
309

        # test CenterCrop when size is tuple
        transform = dict(type='CenterCrop', crop_size=(224, 224))
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
310
        assert results['img_shape'] == (224, 224)
311
        assert (results['img'] == self.original_img[38:262, 88:312, ...]).all()
312
313
        assert (results['gt_seg_map'] == self.gt_semantic_map[38:262,
                                                              88:312]).all()
314
315
316
317
318
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 122, 122], [112, 112, 224,
                                                     224]])).all()
        assert np.equal(
            results['gt_keypoints'],
319
            np.array([[[0, 12, 0]], [[112, 112, 1]], [[212, 187, 1]]])).all()
320
321

        # test CenterCrop when crop_height != crop_width
322
        transform = dict(type='CenterCrop', crop_size=(224, 256))
323
324
325
326
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
327
        assert results['img_shape'] == (256, 224)
328
        assert (results['img'] == self.original_img[22:278, 88:312, ...]).all()
329
330
        assert (results['gt_seg_map'] == self.gt_semantic_map[22:278,
                                                              88:312]).all()
331
332
333
334
335
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 122, 138], [112, 128, 224,
                                                     256]])).all()
        assert np.equal(
            results['gt_keypoints'],
336
            np.array([[[0, 28, 0]], [[112, 128, 1]], [[212, 203, 1]]])).all()
337
338
339

        # test CenterCrop when crop_size is equal to img.shape
        img_height, img_width, _ = self.original_img.shape
340
        transform = dict(type='CenterCrop', crop_size=(img_width, img_height))
341
342
343
344
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
345
        assert results['img_shape'] == (300, 400)
346
        assert (results['img'] == self.original_img).all()
347
        assert (results['gt_seg_map'] == self.gt_semantic_map).all()
348
349
350
351
352
353
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 210, 160], [200, 150, 400,
                                                     300]])).all()
        assert np.equal(
            results['gt_keypoints'],
            np.array([[[20, 50, 1]], [[200, 150, 1]], [[300, 225, 1]]])).all()
354
355
356

        # test CenterCrop when crop_size is larger than img.shape
        transform = dict(
357
            type='CenterCrop', crop_size=(img_width * 2, img_height * 2))
358
359
360
361
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
362
        assert results['img_shape'] == (300, 400)
363
        assert (results['img'] == self.original_img).all()
364
        assert (results['gt_seg_map'] == self.gt_semantic_map).all()
365
366
367
368
369
370
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 210, 160], [200, 150, 400,
                                                     300]])).all()
        assert np.equal(
            results['gt_keypoints'],
            np.array([[[20, 50, 1]], [[200, 150, 1]], [[300, 225, 1]]])).all()
371
372
373
374

        # test with padding
        transform = dict(
            type='CenterCrop',
375
            crop_size=(img_width // 2, img_height * 2),
376
377
            auto_pad=True,
            pad_cfg=dict(type='Pad', padding_mode='constant', pad_val=12))
378
379
380
381
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
382
        assert results['img_shape'] == (600, 200)
383
        assert results['img'].shape[:2] == results['gt_seg_map'].shape
384
        assert (results['img'][300:600, 100:300, ...] == 12).all()
385
        assert (results['gt_seg_map'][300:600, 100:300] == 255).all()
386
387
388
389
390
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 110, 160], [100, 150, 200,
                                                     300]])).all()
        assert np.equal(
            results['gt_keypoints'],
391
            np.array([[[0, 50, 0]], [[100, 150, 1]], [[200, 225, 0]]])).all()
392
393
394

        transform = dict(
            type='CenterCrop',
395
            crop_size=(img_width // 2, img_height * 2),
396
397
398
399
400
            auto_pad=True,
            pad_cfg=dict(
                type='Pad',
                padding_mode='constant',
                pad_val=dict(img=13, seg=33)))
401
402
403
404
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
405
        assert results['img_shape'] == (600, 200)
406
        assert (results['img'][300:600, 100:300, ...] == 13).all()
407
        assert (results['gt_seg_map'][300:600, 100:300] == 33).all()
408
409
410
411
412
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 110, 160], [100, 150, 200,
                                                     300]])).all()
        assert np.equal(
            results['gt_keypoints'],
413
            np.array([[[0, 50, 0]], [[100, 150, 1]], [[200, 225, 0]]])).all()
414
415
416

        # test CenterCrop when crop_width is smaller than img_width
        transform = dict(
417
            type='CenterCrop', crop_size=(img_width // 2, img_height))
418
419
420
421
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
422
        assert results['img_shape'] == (img_height, img_width // 2)
423
        assert (results['img'] == self.original_img[:, 100:300, ...]).all()
424
425
        assert (results['gt_seg_map'] == self.gt_semantic_map[:,
                                                              100:300]).all()
426
427
428
429
430
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 110, 160], [100, 150, 200,
                                                     300]])).all()
        assert np.equal(
            results['gt_keypoints'],
431
            np.array([[[0, 50, 0]], [[100, 150, 1]], [[200, 225, 0]]])).all()
432
433
434

        # test CenterCrop when crop_height is smaller than img_height
        transform = dict(
435
            type='CenterCrop', crop_size=(img_width, img_height // 2))
436
437
438
439
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
440
        assert results['img_shape'] == (img_height // 2, img_width)
441
        assert (results['img'] == self.original_img[75:225, ...]).all()
442
443
        assert (results['gt_seg_map'] == self.gt_semantic_map[75:225,
                                                              ...]).all()
444
445
446
447
448
        assert np.equal(results['gt_bboxes'],
                        np.array([[0, 0, 210, 85], [200, 75, 400,
                                                    150]])).all()
        assert np.equal(
            results['gt_keypoints'],
449
            np.array([[[20, 0, 0]], [[200, 75, 1]], [[300, 150, 0]]])).all()
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468

    @pytest.mark.skipif(
        condition=torch is None, reason='No torch in current env')
    def test_torchvision_compare(self):
        # compare results with torchvision
        results = {}
        transform = dict(type='CenterCrop', crop_size=224)
        center_crop_module = TRANSFORMS.build(transform)
        results = self.reset_results(results, self.original_img,
                                     self.gt_semantic_map)
        results = center_crop_module(results)
        center_crop_module = torchvision.transforms.CenterCrop(size=224)
        pil_img = Image.fromarray(self.original_img)
        pil_seg = Image.fromarray(self.gt_semantic_map)
        cropped_img = center_crop_module(pil_img)
        cropped_img = np.array(cropped_img)
        cropped_seg = center_crop_module(pil_seg)
        cropped_seg = np.array(cropped_seg)
        assert np.equal(results['img'], cropped_img).all()
469
        assert np.equal(results['gt_seg_map'], cropped_seg).all()
470
471
472
473
474
475


class TestRandomGrayscale:

    @classmethod
    def setup_class(cls):
476
        cls.img = (np.random.rand(10, 10, 3) * 255).astype(np.uint8)
477
478
479
480
481
482
483

    def test_repr(self):
        # test repr
        transform = dict(
            type='RandomGrayscale',
            prob=1.,
            channel_weights=(0.299, 0.587, 0.114),
484
            keep_channels=True)
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
        random_gray_scale_module = TRANSFORMS.build(transform)
        assert isinstance(repr(random_gray_scale_module), str)

    def test_error(self):
        # test invalid argument
        transform = dict(type='RandomGrayscale', prob=2)
        with pytest.raises(AssertionError):
            TRANSFORMS.build(transform)

    def test_transform(self):
        results = dict()
        # test rgb2gray, return the grayscale image with prob = 1.
        transform = dict(
            type='RandomGrayscale',
            prob=1.,
            channel_weights=(0.299, 0.587, 0.114),
501
            keep_channels=True)
502
503
504
505

        random_gray_scale_module = TRANSFORMS.build(transform)
        results['img'] = copy.deepcopy(self.img)
        img = random_gray_scale_module(results)['img']
506
507
508
        computed_gray = (self.img[:, :, 0] * 0.299 +
                         self.img[:, :, 1] * 0.587 +
                         self.img[:, :, 2] * 0.114).astype(np.uint8)
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
        for i in range(img.shape[2]):
            assert_array_almost_equal(img[:, :, i], computed_gray, decimal=4)
        assert img.shape == (10, 10, 3)

        # test rgb2gray, return the original image with p=0.
        transform = dict(type='RandomGrayscale', prob=0.)
        random_gray_scale_module = TRANSFORMS.build(transform)
        results['img'] = copy.deepcopy(self.img)
        img = random_gray_scale_module(results)['img']
        assert_array_equal(img, self.img)
        assert img.shape == (10, 10, 3)

        # test image with one channel
        transform = dict(type='RandomGrayscale', prob=1.)
        results['img'] = self.img[:, :, 0:1]
        random_gray_scale_module = TRANSFORMS.build(transform)
        img = random_gray_scale_module(results)['img']
        assert_array_equal(img, self.img[:, :, 0:1])
        assert img.shape == (10, 10, 1)


530
@TRANSFORMS.register_module()
531
class MockPackTaskInputs(BaseTransform):
532
533
534
535
536

    def __init__(self) -> None:
        super().__init__()

    def transform(self, results):
537
538
        packed_results = dict(inputs=results['img'], data_sample=Mock())
        return packed_results
539
540


541
542
543
544
545
546
547
548
549
class TestMultiScaleFlipAug:

    @classmethod
    def setup_class(cls):
        cls.img = mmcv.imread(
            osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
        cls.original_img = copy.deepcopy(cls.img)

    def test_error(self):
550
        # test assertion if scales is not tuple or list of tuple
551
552
        with pytest.raises(AssertionError):
            transform = dict(
553
                type='MultiScaleFlipAug', scales=[1333, 800], transforms=[])
554
555
556
557
558
559
            TRANSFORMS.build(transform)

        # test assertion if flip_direction is not str or list of str
        with pytest.raises(AssertionError):
            transform = dict(
                type='MultiScaleFlipAug',
560
                scales=[(1333, 800)],
561
562
563
564
565
566
567
568
569
570
                flip_direction=1,
                transforms=[])
            TRANSFORMS.build(transform)

    @pytest.mark.skipif(
        condition=torch is None, reason='No torch in current env')
    def test_multi_scale_flip_aug(self):
        # test with empty transforms
        transform = dict(
            type='MultiScaleFlipAug',
571
            transforms=[dict(type='MockPackTaskInputs')],
572
            scales=[(1333, 800), (800, 600), (640, 480)],
573
            allow_flip=True,
574
575
576
577
            flip_direction=['horizontal', 'vertical', 'diagonal'])
        multi_scale_flip_aug_module = TRANSFORMS.build(transform)
        results = dict()
        results['img'] = copy.deepcopy(self.original_img)
578
579
        packed_results = multi_scale_flip_aug_module(results)
        assert len(packed_results['inputs']) == 12
580

581
        # test with allow_flip=False
582
583
        transform = dict(
            type='MultiScaleFlipAug',
584
            transforms=[dict(type='MockPackTaskInputs')],
585
            scales=[(1333, 800), (800, 600), (640, 480)],
586
            allow_flip=False,
587
588
589
590
            flip_direction=['horizontal', 'vertical', 'diagonal'])
        multi_scale_flip_aug_module = TRANSFORMS.build(transform)
        results = dict()
        results['img'] = copy.deepcopy(self.original_img)
591
592
        packed_results = multi_scale_flip_aug_module(results)
        assert len(packed_results['inputs']) == 3
593
594
595
596
597
598
599
600
601
602

        # test with transforms
        img_norm_cfg = dict(
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.12, 57.375],
            to_rgb=True)
        transforms_cfg = [
            dict(type='Normalize', **img_norm_cfg),
            dict(type='Pad', size_divisor=32),
            dict(type='ImageToTensor', keys=['img']),
603
            dict(type='MockPackTaskInputs')
604
605
606
607
        ]
        transform = dict(
            type='MultiScaleFlipAug',
            transforms=transforms_cfg,
608
            scales=[(1333, 800), (800, 600), (640, 480)],
609
            allow_flip=True,
610
611
612
613
            flip_direction=['horizontal', 'vertical', 'diagonal'])
        multi_scale_flip_aug_module = TRANSFORMS.build(transform)
        results = dict()
        results['img'] = copy.deepcopy(self.original_img)
614
615
        packed_results = multi_scale_flip_aug_module(results)
        assert len(packed_results['inputs']) == 12
616
617
618
619
620
621
622
623
624
625

        # test with scale_factor
        img_norm_cfg = dict(
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.12, 57.375],
            to_rgb=True)
        transforms_cfg = [
            dict(type='Normalize', **img_norm_cfg),
            dict(type='Pad', size_divisor=32),
            dict(type='ImageToTensor', keys=['img']),
626
            dict(type='MockPackTaskInputs')
627
628
629
630
631
        ]
        transform = dict(
            type='MultiScaleFlipAug',
            transforms=transforms_cfg,
            scale_factor=[0.5, 1., 2.],
632
            allow_flip=True,
633
634
635
636
            flip_direction=['horizontal', 'vertical', 'diagonal'])
        multi_scale_flip_aug_module = TRANSFORMS.build(transform)
        results = dict()
        results['img'] = copy.deepcopy(self.original_img)
637
638
        packed_results = multi_scale_flip_aug_module(results)
        assert len(packed_results['inputs']) == 12
639
640
641
642
643
644
645
646
647
648

        # test no resize
        img_norm_cfg = dict(
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.12, 57.375],
            to_rgb=True)
        transforms_cfg = [
            dict(type='Normalize', **img_norm_cfg),
            dict(type='Pad', size_divisor=32),
            dict(type='ImageToTensor', keys=['img']),
649
            dict(type='MockPackTaskInputs')
650
651
652
653
        ]
        transform = dict(
            type='MultiScaleFlipAug',
            transforms=transforms_cfg,
654
            allow_flip=True,
655
656
657
658
            flip_direction=['horizontal', 'vertical', 'diagonal'])
        multi_scale_flip_aug_module = TRANSFORMS.build(transform)
        results = dict()
        results['img'] = copy.deepcopy(self.original_img)
659
660
        packed_results = multi_scale_flip_aug_module(results)
        assert len(packed_results['inputs']) == 4
661
662


663
class TestRandomChoiceResize:
664
665
666
667
668
669
670
671
672

    @classmethod
    def setup_class(cls):
        cls.img = mmcv.imread(
            osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
        cls.original_img = copy.deepcopy(cls.img)

    def reset_results(self, results):
        results['img'] = copy.deepcopy(self.original_img)
673
        results['gt_seg_map'] = copy.deepcopy(self.original_img)
674
675
676
677

    def test_repr(self):
        # test repr
        transform = dict(
678
            type='RandomChoiceResize', scales=[(1333, 800), (1333, 600)])
679
680
681
682
683
684
        random_multiscale_resize = TRANSFORMS.build(transform)
        assert isinstance(repr(random_multiscale_resize), str)

    def test_error(self):
        # test assertion if size is smaller than 0
        with pytest.raises(AssertionError):
685
            transform = dict(type='RandomChoiceResize', scales=[0.5, 1, 2])
686
687
688
689
690
            TRANSFORMS.build(transform)

    def test_random_multiscale_resize(self):
        results = dict()
        # test with one scale
691
        transform = dict(type='RandomChoiceResize', scales=[(1333, 800)])
692
693
694
695
696
697
698
        random_multiscale_resize = TRANSFORMS.build(transform)
        self.reset_results(results)
        results = random_multiscale_resize(results)
        assert results['img'].shape == (800, 1333, 3)

        # test with multi scales
        _scale_choice = [(1333, 800), (1333, 600)]
699
        transform = dict(type='RandomChoiceResize', scales=_scale_choice)
700
701
702
703
704
705
706
707
        random_multiscale_resize = TRANSFORMS.build(transform)
        self.reset_results(results)
        results = random_multiscale_resize(results)
        assert (results['img'].shape[1],
                results['img'].shape[0]) in _scale_choice

        # test keep_ratio
        transform = dict(
708
            type='RandomChoiceResize',
709
            scales=[(900, 600)],
710
711
            resize_type='Resize',
            keep_ratio=True)
712
713
714
715
716
717
718
719
720
721
        random_multiscale_resize = TRANSFORMS.build(transform)
        self.reset_results(results)
        _input_ratio = results['img'].shape[0] / results['img'].shape[1]
        results = random_multiscale_resize(results)
        _output_ratio = results['img'].shape[0] / results['img'].shape[1]
        assert_array_almost_equal(_input_ratio, _output_ratio)

        # test clip_object_border
        gt_bboxes = [[200, 150, 600, 450]]
        transform = dict(
722
            type='RandomChoiceResize',
723
            scales=[(200, 150)],
724
725
            resize_type='Resize',
            clip_object_border=True)
726
727
728
729
730
731
732
733
734
        random_multiscale_resize = TRANSFORMS.build(transform)
        self.reset_results(results)
        results['gt_bboxes'] = np.array(gt_bboxes)
        results = random_multiscale_resize(results)
        assert results['img'].shape == (150, 200, 3)
        assert np.equal(results['gt_bboxes'], np.array([[100, 75, 200,
                                                         150]])).all()

        transform = dict(
735
            type='RandomChoiceResize',
736
            scales=[(200, 150)],
737
738
            resize_type='Resize',
            clip_object_border=False)
739
740
741
742
743
744
745
746
747
        random_multiscale_resize = TRANSFORMS.build(transform)
        self.reset_results(results)
        results['gt_bboxes'] = np.array(gt_bboxes)
        results = random_multiscale_resize(results)
        assert results['img'].shape == (150, 200, 3)
        assert np.equal(results['gt_bboxes'], np.array([[100, 75, 300,
                                                         225]])).all()


748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
class TestRandomFlip:

    def test_init(self):

        # prob is float
        TRANSFORMS = RandomFlip(0.1)
        assert TRANSFORMS.prob == 0.1

        # prob is None
        with pytest.raises(ValueError):
            TRANSFORMS = RandomFlip(None)
            assert TRANSFORMS.prob is None

        # prob is a list
        TRANSFORMS = RandomFlip([0.1, 0.2], ['horizontal', 'vertical'])
        assert len(TRANSFORMS.prob) == 2
        assert len(TRANSFORMS.direction) == 2

        # direction is an invalid type
        with pytest.raises(ValueError):
            TRANSFORMS = RandomFlip(0.1, 1)

        # prob is an invalid type
        with pytest.raises(ValueError):
            TRANSFORMS = RandomFlip('0.1')

    def test_transform(self):

        results = {
            'img': np.random.random((224, 224, 3)),
            'gt_bboxes': np.array([[0, 1, 100, 101]]),
            'gt_keypoints': np.array([[[100, 100, 1.0]]]),
780
781
782
            # seg map flip is irrelative with image, so there is no requirement
            # that gt_set_map of test data matches image.
            'gt_seg_map': np.array([[0, 1], [2, 3]])
783
784
785
786
787
788
789
        }

        # horizontal flip
        TRANSFORMS = RandomFlip([1.0], ['horizontal'])
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
        assert (results_update['gt_bboxes'] == np.array([[124, 1, 224,
                                                          101]])).all()
790
791
        assert (results_update['gt_seg_map'] == np.array([[1, 0], [3,
                                                                   2]])).all()
792

793
        # diagonal flip
794
795
796
797
        TRANSFORMS = RandomFlip([1.0], ['diagonal'])
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
        assert (results_update['gt_bboxes'] == np.array([[124, 123, 224,
                                                          223]])).all()
798
799
        assert (results_update['gt_seg_map'] == np.array([[3, 2], [1,
                                                                   0]])).all()
800
801
802
803
804
805

        # vertical flip
        TRANSFORMS = RandomFlip([1.0], ['vertical'])
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
        assert (results_update['gt_bboxes'] == np.array([[0, 123, 100,
                                                          223]])).all()
806
807
        assert (results_update['gt_seg_map'] == np.array([[2, 3], [0,
                                                                   1]])).all()
808
809
810
811
812
813

        # horizontal flip when direction is None
        TRANSFORMS = RandomFlip(1.0)
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
        assert (results_update['gt_bboxes'] == np.array([[124, 1, 224,
                                                          101]])).all()
814
815
816
817
818
819
820
821
822
823
        assert (results_update['gt_seg_map'] == np.array([[1, 0], [3,
                                                                   2]])).all()

        # horizontal flip and swap label pair
        TRANSFORMS = RandomFlip([1.0], ['horizontal'],
                                swap_seg_labels=[[0, 1]])
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
        assert (results_update['gt_seg_map'] == np.array([[0, 1], [3,
                                                                   2]])).all()
        assert results_update['swap_seg_labels'] == [[0, 1]]
824
825
826
827
828

        TRANSFORMS = RandomFlip(0.0)
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
        assert (results_update['gt_bboxes'] == np.array([[0, 1, 100,
                                                          101]])).all()
829
830
        assert (results_update['gt_seg_map'] == np.array([[0, 1], [2,
                                                                   3]])).all()
831
832
833
834

        # flip direction is invalid in bbox flip
        with pytest.raises(ValueError):
            TRANSFORMS = RandomFlip(1.0)
835
836
            results_update = TRANSFORMS._flip_bbox(results['gt_bboxes'],
                                                   (224, 224), 'invalid')
837
838
839
840

        # flip direction is invalid in keypoints flip
        with pytest.raises(ValueError):
            TRANSFORMS = RandomFlip(1.0)
841
842
843
844
845
846
847
848
            results_update = TRANSFORMS._flip_keypoints(
                results['gt_keypoints'], (224, 224), 'invalid')

        # swap pair is invalid
        with pytest.raises(AssertionError):
            TRANSFORMS = RandomFlip(1.0, swap_seg_labels='invalid')
            results_update = TRANSFORMS._flip_seg_map(results['gt_seg_map'],
                                                      'horizontal')
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886

    def test_repr(self):
        TRANSFORMS = RandomFlip(0.1)
        TRANSFORMS_str = str(TRANSFORMS)
        assert isinstance(TRANSFORMS_str, str)


class TestRandomResize:

    def test_init(self):
        TRANSFORMS = RandomResize(
            (224, 224),
            (1.0, 2.0),
        )
        assert TRANSFORMS.scale == (224, 224)

    def test_repr(self):
        TRANSFORMS = RandomResize(
            (224, 224),
            (1.0, 2.0),
        )
        TRANSFORMS_str = str(TRANSFORMS)
        assert isinstance(TRANSFORMS_str, str)

    def test_transform(self):

        # choose target scale from init when override is True
        results = {}
        TRANSFORMS = RandomResize((224, 224), (1.0, 2.0))
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
        assert results_update['scale'][0] >= 224 and results_update['scale'][
            0] <= 448
        assert results_update['scale'][1] >= 224 and results_update['scale'][
            1] <= 448

        # keep ratio is True
        results = {
            'img': np.random.random((224, 224, 3)),
887
            'gt_seg_map': np.random.random((224, 224, 3)),
888
889
890
            'gt_bboxes': np.array([[0, 0, 112, 112]]),
            'gt_keypoints': np.array([[[112, 112]]])
        }
891

892
893
894
        TRANSFORMS = RandomResize((224, 224), (1.0, 2.0),
                                  resize_type='Resize',
                                  keep_ratio=True)
895
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
896
897
898
899
        assert 224 <= results_update['img_shape'][0]
        assert 448 >= results_update['img_shape'][0]
        assert 224 <= results_update['img_shape'][1]
        assert 448 >= results_update['img_shape'][1]
900
901
902
903
904
        assert results_update['keep_ratio']
        assert results['gt_bboxes'][0][2] >= 112
        assert results['gt_bboxes'][0][2] <= 112

        # keep ratio is False
905
906
907
        TRANSFORMS = RandomResize((224, 224), (1.0, 2.0),
                                  resize_type='Resize',
                                  keep_ratio=False)
908
909
910
911
912
        results_update = TRANSFORMS.transform(copy.deepcopy(results))

        # choose target scale from init when override is False and scale is a
        # list of tuples
        results = {}
913
        TRANSFORMS = RandomResize([(224, 448), (112, 224)],
914
915
                                  resize_type='Resize',
                                  keep_ratio=True)
916
        results_update = TRANSFORMS.transform(copy.deepcopy(results))
YuanLiuuuuuu's avatar
YuanLiuuuuuu committed
917
918
919
920
        assert results_update['scale'][1] >= 224 and results_update['scale'][
            1] <= 448
        assert results_update['scale'][0] >= 112 and results_update['scale'][
            0] <= 224
921
922
923
924
925

        # the type of scale is invalid in init
        with pytest.raises(NotImplementedError):
            results = {}
            TRANSFORMS = RandomResize([(224, 448), [112, 224]],
926
927
                                      resize_type='Resize',
                                      keep_ratio=True)
928
            results_update = TRANSFORMS.transform(copy.deepcopy(results))
Mashiro's avatar
Mashiro committed
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014


class TestTestTimeAug:

    def test_init(self):
        subroutines = [[
            dict(type='Resize', scale=(1333, 800), keep_ratio=True),
            dict(type='Resize', scale=(1333, 400), keep_ratio=True)
        ], [
            dict(type='RandomFlip', prob=1.),
            dict(type='RandomFlip', prob=0.)
        ], [dict(type='Normalize', mean=(0, 0, 0), std=(1, 1, 1))]]

        tta_transform = TestTimeAug(subroutines)
        subroutines = tta_transform.subroutines
        assert len(subroutines) == 4

        assert isinstance(subroutines[0].transforms[0], Resize)
        assert isinstance(subroutines[0].transforms[1], RandomFlip)
        assert isinstance(subroutines[0].transforms[2], Normalize)
        assert isinstance(subroutines[1].transforms[0], Resize)
        assert isinstance(subroutines[1].transforms[1], RandomFlip)
        assert isinstance(subroutines[1].transforms[2], Normalize)

    def test_transform(self):
        results = {
            'img': np.random.random((224, 224, 3)),
            'gt_bboxes': np.array([[0, 1, 100, 101]]),
            'gt_keypoints': np.array([[[100, 100, 1.0]]]),
            'gt_seg_map': np.random.random((224, 224, 3))
        }
        input_results = copy.deepcopy(results)
        transforms = [[
            dict(type='Resize', scale=(1333, 800), keep_ratio=True),
            dict(type='Resize', scale=(1333, 400), keep_ratio=True)
        ], [
            dict(type='RandomFlip', prob=0.),
            dict(type='RandomFlip', prob=1.)
        ], [dict(type='Normalize', mean=(0, 0, 0), std=(1, 1, 1))]]

        tta_transform = TestTimeAug(transforms)
        results = tta_transform.transform(results)
        assert len(results['img']) == 4

        resize1 = tta_transform.subroutines[0].transforms[0]
        resize2 = tta_transform.subroutines[2].transforms[0]
        flip1 = tta_transform.subroutines[0].transforms[1]
        flip2 = tta_transform.subroutines[1].transforms[1]
        normalize = tta_transform.subroutines[0].transforms[2]
        target_results = [
            normalize.transform(
                flip1.transform(
                    resize1.transform(copy.deepcopy(input_results)))),
            normalize.transform(
                flip2.transform(
                    resize1.transform(copy.deepcopy(input_results)))),
            normalize.transform(
                flip1.transform(
                    resize2.transform(copy.deepcopy(input_results)))),
            normalize.transform(
                flip2.transform(
                    resize2.transform(copy.deepcopy(input_results)))),
        ]

        assert np.allclose(target_results[0]['img'], results['img'][0])
        assert np.allclose(target_results[1]['img'], results['img'][1])
        assert np.allclose(target_results[2]['img'], results['img'][2])
        assert np.allclose(target_results[3]['img'], results['img'][3])

    def test_repr(self):
        transforms = [[
            dict(type='Resize', scale=(1333, 800), keep_ratio=True),
            dict(type='Resize', scale=(1333, 400), keep_ratio=True)
        ], [
            dict(type='RandomFlip', prob=0.),
            dict(type='RandomFlip', prob=1.)
        ], [dict(type='Normalize', mean=(0, 0, 0), std=(1, 1, 1))]]

        tta_transform = TestTimeAug(transforms)
        repr_str = repr(tta_transform)
        repr_str_list = repr_str.split('\n')
        assert repr_str_list[0] == 'TestTimeAugtransforms='
        assert repr_str_list[1] == 'Compose('
        assert repr_str_list[2].startswith('    Resize(scale=(1333, 800)')
        assert repr_str_list[3].startswith('    RandomFlip(prob=0.0')
        assert repr_str_list[4].startswith('    Normalize(mean=[0. 0. 0.]')